From 491bb3ea62bf159edb644835b4db282809542fea Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Tue, 24 Nov 2026 11:48:50 +0100 Subject: [PATCH 01/13] feat(execution): put a run's jobs into the workspace its request names A run started by POST /run goes into the open workspace. A client other than the builder, a command in a shell, has no open workspace of its own: it would add its jobs to whatever workspace a person has open in the pages, and to open its own first it would have to change theirs. POST /run takes an optional `workspace`, a workspace's name. The run's jobs go into that workspace through adopt_roots(into=...), the path the Launches page's "add to a workspace" takes, and a workspace of that name is made when there is none. The open workspace keeps its roots and stays open. The run's record names the workspace: a restart puts the run back into it. A value that is not a workspace's name is refused and nothing starts. The builder sends no `workspace`, and its runs go into the open workspace as before. The test fakes of adopt_runs take the new argument. --- app/ui_tests/test_agents.py | 6 ++--- app/ui_tests/test_harbor_routes.py | 2 +- app/ui_tests/test_prerequisites_route.py | 2 +- app/ui_tests/test_run_routes.py | 27 ++++++++++++++++++- app/web/execute.py | 33 ++++++++++++++---------- app/web/shared.py | 9 ++++--- 6 files changed, 57 insertions(+), 22 deletions(-) diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index 66833375f..86289dda1 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -48,7 +48,7 @@ def start(plan): self.started.append(plan) return SimpleNamespace(jobs=str(self.tmp / "runs" / plan.name / "jobs"), summary=lambda: {}) self.stack.enter_context(patch.object(execution, "start", start)) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() def test_capability_source_retains_pin_and_install_details(self): @@ -379,7 +379,7 @@ def start(plan): self.started.append(plan) return SimpleNamespace(jobs=str(self.tmp / "runs" / plan.name / "jobs"), summary=lambda: {"id": plan.name + "-1"}) self.stack.enter_context(patch.object(execution, "start", start)) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() r = self.client.get("/new-run"); self.addCleanup(r.close) self.schema = json.loads(re.search(r'', r.get_data(as_text=True), re.S).group(1)) @@ -469,7 +469,7 @@ def start(plan): self.started.append(plan) return SimpleNamespace(jobs=str(self.tmp / "runs" / plan.name / "jobs"), summary=lambda: {"id": plan.name}) self.stack.enter_context(patch.object(execution, "start", start)) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() def get(self, url): diff --git a/app/ui_tests/test_harbor_routes.py b/app/ui_tests/test_harbor_routes.py index f8fb04d69..5cd11c6cd 100644 --- a/app/ui_tests/test_harbor_routes.py +++ b/app/ui_tests/test_harbor_routes.py @@ -40,7 +40,7 @@ def start(plan): self.started.append(plan) return SimpleNamespace(jobs=str(self.tmp / "runs" / plan.name / "jobs"), summary=lambda: {"id": plan.name + "-1", "state": "preparing"}) self.stack.enter_context(patch.object(execution, "start", start)) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() r = self.client.get("/new-run"); self.addCleanup(r.close) with self.client.session_transaction() as s: diff --git a/app/ui_tests/test_prerequisites_route.py b/app/ui_tests/test_prerequisites_route.py index 22f724a03..1a64b8cb0 100644 --- a/app/ui_tests/test_prerequisites_route.py +++ b/app/ui_tests/test_prerequisites_route.py @@ -29,7 +29,7 @@ def setUp(self): self.started = [] self.stack.enter_context(patch.object(execution, "start", lambda plan: self.started.append(plan) or SimpleNamespace( jobs=str(self.tmp), summary=lambda: {"id": "x", "state": "preparing"}))) - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: None)) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": None)) self.client = web.app.test_client() r = self.client.get("/new-run"); self.addCleanup(r.close) with self.client.session_transaction() as s: diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index cd25e91f1..5efc350dd 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -79,7 +79,7 @@ def run(argv, timeout=600, stdin=None, stop=None): return 0, "" self.stack.enter_context(patch.object(execution, "subprocess_run", run)) self.stack.enter_context(patch.object(execution, "docker_here", lambda sh, needs="": None)) # docker answers here, as the probe says it does there - self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs: self.adopted.extend(ex.jobs for ex in runs))) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into="": self.adopted.extend(ex.jobs for ex in runs))) self.adopted = [] self.client = web.app.test_client() r = self.client.get("/new-run"); self.addCleanup(r.close) @@ -518,6 +518,31 @@ def test_an_old_record_with_no_workspace_open_gets_one_as_before(self): self.assertEqual(again.roots, [self.jobs]) self.assertEqual(workspace.load(self.home, self.ws.name).roots, self.held + [self.jobs]) # added when it started, left as it is + def test_a_run_posted_with_a_workspace_goes_into_it_and_the_open_one_stays_open(self): + """``workspace``: the run's jobs go into that workspace, made under that name when there is none; the open + one keeps its roots and stays open; the record names it for a restart. A name that is not one starts nothing.""" + def post(name, into): + r = self.client.post("/run", data=json.dumps({"name": name, "script": "", "where": "local", "workspace": into, + "parts": [{"id": "a", "label": "a", "script": "echo a"}]}), + content_type="application/json", headers={"Origin": "http://localhost", "X-CSRF-Token": self.csrf}); self.addCleanup(r.close) + if r.status_code == 200: + execution.EXECUTIONS[r.json["id"]].thread.join(10) + return r + first, second = (str(self.tmp / "runs" / n / "jobs") for n in ("q1", "q2")) + self.assertEqual(post("q1", "planner").status_code, 200) + made = workspace.load(self.home, "planner") + self.assertEqual((made.label, made.roots), ("planner", [first])) + self.assertEqual(web.shared.STATE["workspace"].name, self.ws.name) + self.assertEqual(workspace.load(self.home, self.ws.name).roots, self.held + [self.jobs]) + self.assertEqual(json.loads((self.tmp / "runs" / "q1" / "run.json").read_text())["workspace"], "planner") + self.assertEqual(post("q2", "planner").status_code, 200) # one there already: added to + self.assertEqual(workspace.load(self.home, "planner").roots, [first, second]) + before = sorted(w.name for w in workspace.list_all(self.home)) + r = post("q3", "Not a name") + self.assertEqual((r.status_code, r.json), (400, {"ok": False, "error": "A workspace's name is lowercase letters, digits and dashes."})) + self.assertFalse((self.tmp / "runs" / "q3").exists()) + self.assertEqual(sorted(w.name for w in workspace.list_all(self.home)), before) + class Credentials(unittest.TestCase): def test_a_run_on_openai_is_given_openais_endpoint(self): diff --git a/app/web/execute.py b/app/web/execute.py index 7cc557dfe..a8158bd27 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -6,7 +6,7 @@ import re import time from flask import abort, jsonify, request, url_for -from nullius import execution, hosts, prerequisites, prices, providers, settings +from nullius import execution, hosts, prerequisites, prices, providers, settings, workspace from nullius.harbor import source as harbor_source from nullius.standard.backends import boat from nullius.standard.pages import recipe as standard_recipe @@ -18,7 +18,10 @@ @app.route("/run", methods=["POST"]) def run_start(): """Start a plan. The builder posts the recipe; - the target is this machine or one of the Settings' hosts. Same guards + the target is this machine or one of the Settings' hosts. ``workspace``: + the workspace its jobs go into, made under that name when there is none, + in place of the open one (``nullius recipes launch`` sends it; the + builder does not). Same guards as every mutation: form token, same origin, and a loopback client - running is writing to a machine.""" shared._require_csrf() @@ -26,8 +29,11 @@ def run_start(): abort(403, description="Runs are started from a browser on the application host only.") body = request.get_json(silent=True) or {} recipe = body.get("recipe") if isinstance(body.get("recipe"), dict) else {} + into = body.get("workspace") or "" + if into and (not isinstance(into, str) or workspace.slug(into) != into): + return jsonify(ok=False, error="A workspace's name is lowercase letters, digits and dashes."), 400 if recipe.get("harness") == standard_recipe.HARNESS: - return _start_standard(recipe) + return _start_standard(recipe, into) where = str(body.get("where") or "local") host = None if where != "local": @@ -64,7 +70,7 @@ def run_start(): parts=[{"id": re.sub(r"[^A-Za-z0-9_.-]", "_", str(p.get("id") or "")), "label": str(p.get("label") or ""), "script": str(p.get("script") or "")} for p in (body.get("parts") or []) if isinstance(p, dict)], recipe=recipe) - return _start(plan) + return _start(plan, into) def credentials_for(provider, endpoint=None) -> dict: @@ -120,10 +126,10 @@ def standard_plans(recipe: dict, out: dict, known) -> tuple: return plans, "" -def _start_standard(recipe: dict): +def _start_standard(recipe: dict, into: str = ""): """The standard: compiled here from its definitions; on this machine, a host, or split over several - one run per machine, every - one checked before any starts.""" + one checked before any starts. ``into``: the workspace its jobs go into (``begin``).""" if len(json.dumps(recipe)) > 200_000: return jsonify(ok=False, error="the recipe is too large to keep with the run"), 400 out = standard_recipe.compile(recipe, docker_unusable=docker_problem, boat_unusable=boat.unusable, @@ -138,8 +144,8 @@ def _start_standard(recipe: dict): if problem: return jsonify(ok=False, error=problem), 400 if len(plans) == 1: - return _start(plans[0]) - started, problem, status = begin(plans) + return _start(plans[0], into) + started, problem, status = begin(plans, into) if problem: return jsonify(ok=False, error=problem), status return jsonify(ok=True, open=url_for("index", view="launch"), runs=[ex.summary() for ex in started], @@ -190,9 +196,10 @@ def docker_problem(): return prerequisites.docker_here() -def begin(plans: list) -> tuple: +def begin(plans: list, into: str = "") -> tuple: """Start ``plans``, each checked before any starts: (the runs, "", 200), or - ([], why not, its status) and nothing started.""" + ([], why not, its status) and nothing started. ``into``: the workspace + their jobs go into, the open one when empty (``shared.adopt_runs``).""" for plan in plans: problem = plan.check() if problem: @@ -204,12 +211,12 @@ def begin(plans: list) -> tuple: started = [execution.start(plan) for plan in plans] # The job lands (or is mirrored) under runs//jobs: the workspace # reads it from now on. - shared.adopt_runs(started) + shared.adopt_runs(started, into) return started, "", 200 -def _start(plan: execution.Plan): - started, problem, status = begin([plan]) +def _start(plan: execution.Plan, into: str = ""): + started, problem, status = begin([plan], into) if problem: return jsonify(ok=False, error=problem), status summary, jobs = started[0].summary(), plan.jobs diff --git a/app/web/shared.py b/app/web/shared.py index a47855ad2..4d67b10d5 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -342,10 +342,13 @@ def adopt_roots(roots, label="", new=False, into=""): return ws -def adopt_runs(runs): +def adopt_runs(runs, into=""): """Runs just started: their jobs into a workspace as ``adopt_roots`` puts - them, each record naming it for a restart to put them back.""" - ws = adopt_roots([ex.jobs for ex in runs]) + them - ``into``, made under that name when there is none, the open one + left as it is - each record naming it for a restart to put them back.""" + if into and workspace.load(WS_HOME, into) is None: + workspace.create(WS_HOME, [], into) + ws = adopt_roots([ex.jobs for ex in runs], into=into) for ex in runs: ex.file_under(ws.name) From ed9bb770238a6fc39b339a95305646ffc23099b6 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Tue, 24 Nov 2026 11:52:23 +0100 Subject: [PATCH 02/13] feat(builder): launch a saved recipe from a shell as the builder's Run does A person launches a run from the builder: Run sends the recipe to the server, which starts it here or on a host, files its jobs under a workspace and follows it as a launch the pages show live. From a shell there was no way to do the same. `nullius standard run` runs in the shell's own process and writes its jobs there; the server neither follows nor lists it, and only one process can follow a runs folder. `nullius recipes launch ` sends the requests the builder sends to the Nullius server on this machine: GET /new-run for the builder's data and its form token, POST /new-run/runner for the compile the Review step shows, POST /new-run/prerequisites for what each machine lacks, then POST /run. The server compiles the recipe again and starts the plan: a launch from the shell and one from the page are the same launch. The recipe is a saved one, by its name or id, or a recipe file. `--where` replaces the recipe's machines, `--workspace` names the workspace the launch goes into, `--yes` answers the question Run asks before a run of every unit, and `--wait` returns when the launch has ended. It prints the launch's key, each run's jobs folder and its job pages. `nullius recipes list` lists the saved recipes. A Harbor recipe is refused: its plan is made by the page's script, and it runs by the script its Review step generates. --- app/nullius/cli.py | 2 + app/nullius/recipes/cli.py | 213 ++++++++++++++++++++++++++++++++++ app/tests/test_unified_cli.py | 3 +- app/ui_tests/test_agents.py | 39 +++++++ 4 files changed, 256 insertions(+), 1 deletion(-) create mode 100644 app/nullius/recipes/cli.py diff --git a/app/nullius/cli.py b/app/nullius/cli.py index aa9609093..fc65da26a 100644 --- a/app/nullius/cli.py +++ b/app/nullius/cli.py @@ -18,6 +18,7 @@ "flags": "write a run's task flags", "import": "import ATIF or OpenTelemetry output", "standard": "inspect and run standard definitions", + "recipes": "list saved recipes, launch one as the builder's Run", "workspace": "manage workspaces", "paths": "show persistent storage locations", "prices": "show and update model prices", @@ -29,6 +30,7 @@ "flags": "nullius.runs.flags_cli", "import": "nullius.importers.cli", "standard": "nullius.standard.cli", + "recipes": "nullius.recipes.cli", "workspace": "nullius.workspace_cli", "paths": "nullius.paths", "prices": "nullius.prices", diff --git a/app/nullius/recipes/cli.py b/app/nullius/recipes/cli.py new file mode 100644 index 000000000..ca6ff9421 --- /dev/null +++ b/app/nullius/recipes/cli.py @@ -0,0 +1,213 @@ +"""The builder's saved recipes from a shell, and a recipe launched as the builder's Run launches it. + + nullius recipes list [--json] + nullius recipes launch [--where MACHINE]... [--workspace NAME] [--server URL] [--yes] [--wait] [--json] + +``list`` reads the saved recipes (``store.listing``) and writes nothing. + +``launch`` sends a recipe of the Nullius standard to the Nullius server running on this machine, as the builder's +Run sends it: the builder's data (``GET /new-run``, which holds the form token), the compile its Review step shows +(``POST /new-run/runner``), what each machine lacks (``POST /new-run/prerequisites``), then ``POST /run``. The +server makes the launch and follows it, as one it started from the page: one process follows a runs folder +(``execution``), and the pages list the runs it follows. The recipe is a saved one, by its name or its id, or a +recipe file as the builder exports it. + +The exit codes are the contract in ``docs/cli/exit-codes.md``: 0 done, 2 usage, 3 no such recipe, 4 refused (by the +compile, a machine, the question Run asks, the server, or a launch that ended otherwise than done with ``--wait``). +""" +from __future__ import annotations + +import argparse +import datetime +import http.cookiejar +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +from nullius import execution +from nullius.recipes import store + +EXIT_OK, EXIT_NOT_FOUND, EXIT_REFUSED = 0, 3, 4 +STANDARD = "standard" +SCHEMA = re.compile(r'', re.S) +POLL_SECONDS = 5.0 + + +class Refused(Exception): + """Why nothing more is sent: one line.""" + + +class Server: + """The Nullius server at ``url``, asked as a page asks it: one session (its cookie), its origin, the form token + the builder's data holds.""" + + def __init__(self, url: str, timeout: float = 60.0): + self.url = url.rstrip("/") + self.timeout = timeout + self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) + self.token = "" + + def send(self, method: str, path: str, body=None) -> tuple: + """(status, the answer's text).""" + headers = {"Origin": self.url, **({"X-CSRF-Token": self.token} if self.token else {})} + data = None if body is None else json.dumps(body).encode() + if data is not None: + headers["Content-Type"] = "application/json" + req = urllib.request.Request(self.url + path, data=data, method=method, headers=headers) + try: + with self.opener.open(req, timeout=self.timeout) as r: + return r.status, r.read().decode("utf-8", "replace") + except urllib.error.HTTPError as e: + return e.code, e.read().decode("utf-8", "replace") + except (urllib.error.URLError, OSError) as e: + raise Refused(f"no Nullius server answers at {self.url}: {getattr(e, 'reason', e)}") from None + + def json(self, method: str, path: str, body=None) -> tuple: + status, text = self.send(method, path, body) + try: + return status, json.loads(text) + except ValueError: + raise Refused(f"{method} {path}: HTTP {status}, not a JSON answer") from None + + +def default_server() -> str: + """The server ``nullius serve`` starts here: its port from saved settings or the environment, else 5057.""" + return f"http://127.0.0.1:{os.environ.get('APP_PORT') or 5057}" + + +def find(ref: str) -> dict: + """The recipe ``ref`` names: a recipe file (one recipe, or a saved recipe's file), else a saved recipe by its + name, its id or its recipe's name. ``LookupError`` when there is none.""" + if os.path.isfile(ref): + with open(ref, encoding="utf-8") as f: + got = json.load(f) + if isinstance(got, list) and len(got) == 1: + got = got[0] + got = got.get("recipe") if isinstance(got, dict) and isinstance(got.get("recipe"), dict) else got + if not isinstance(got, dict): + raise Refused(f"{ref} holds no single recipe") + return got + for item in store.listing(): + if ref in (item.get("id"), item.get("name"), item["recipe"].get("name")): + return item["recipe"] + raise LookupError(f"no saved recipe or recipe file {ref}") + + +def launch(server: Server, recipe: dict, where=None, into: str = "", yes: bool = False, now=None) -> dict: + """Send ``recipe`` as the builder's Run does; the server's answer to ``POST /run``, with ``review``, the rows of + the Review step, and ``launch``, the launch's key. ``Refused`` when the builder would not start it.""" + if (recipe.get("harness") or "harbor") != STANDARD: + raise Refused("a Harbor recipe runs by the script its Review step generates: docs/builder.md") + status, text = server.send("GET", "/new-run") + found = SCHEMA.search(text) if status == 200 else None + if not found: + raise Refused(f"{server.url} is not a Nullius server (GET /new-run: HTTP {status})") + data = json.loads(found.group(1)) + if not data.get("local"): + raise Refused(f"{server.url} starts runs for a client on its own machine only") + server.token = data.get("csrf") or "" + # each Run is a new job: the recipe's name and the second (command-builder.js, startRun) + stamp = (now or datetime.datetime.now()).strftime("%m%d-%H%M%S") + recipe = dict(recipe, name=f"{recipe.get('name') or ''}-{stamp}", **({"where": where[0] if len(where) == 1 else list(where)} if where else {})) + _, out = server.json("POST", "/new-run/runner", {"recipe": recipe}) + if out.get("errors"): + raise Refused(" ".join(e.get("message", "") for e in out["errors"])) + if out.get("confirm") and not yes: + raise Refused(f"Run asks first: {out['confirm']} --yes answers yes") + _, pre = server.json("POST", "/new-run/prerequisites", {"recipe": recipe, "provider": recipe.get("provider") or ""}) + if not pre.get("ready"): + lacks = [f"{m.get('label')}: {r.get('label')}" + (f" ({r['detail']})" if r.get("detail") else "") + for m in pre.get("machines") or [] for r in m.get("rows") or [] if r.get("state") == "missing"] + raise Refused("a machine lacks what the run needs: " + ("; ".join(lacks + list(pre.get("errors") or [])) or "see Review")) + body = {"name": recipe["name"], "where": recipe.get("where") or "local", "recipe": recipe, **({"workspace": into} if into else {})} + status, got = server.json("POST", "/run", body) + if not got.get("ok"): + raise Refused(got.get("error") or f"POST /run: HTTP {status}") + return dict(got, review=out.get("review") or [], launch=f"run:{got['id']}") + + +def wait(server: Server, run_ids, every: float = POLL_SECONDS) -> dict: + """{run id: its summary} once none of the runs is alive (``GET /run/``, the route the page polls).""" + ended = {} + while True: + for rid in run_ids: + if rid not in ended: + status, s = server.json("GET", f"/run/{urllib.parse.quote(rid)}") + if status != 200: + raise Refused(f"GET /run/{rid}: HTTP {status}") + if s.get("state") not in execution.ALIVE: + ended[rid] = {k: v for k, v in s.items() if k != "log"} + if len(ended) == len(run_ids): + return ended + time.sleep(every) + + +def _list(a) -> int: + items = store.listing() + if a.json: + json.dump(items, sys.stdout, indent=1, ensure_ascii=False) + sys.stdout.write("\n") + return EXIT_OK + for x in items: + r = x["recipe"] + print(f"{x['name']}\t{x['id']}\t{r.get('harness') or 'harbor'}\t{r.get('benchmark') or ''}\t{x.get('saved', '')}") + return EXIT_OK + + +def _launch(a) -> int: + try: + recipe = find(a.recipe) + except LookupError as e: + print(e, file=sys.stderr) + return EXIT_NOT_FOUND + except (OSError, ValueError, Refused) as e: + print(e, file=sys.stderr) + return EXIT_REFUSED + server = Server(a.server or default_server()) + try: + got = launch(server, recipe, a.where, a.workspace or "", a.yes) + runs = got.get("runs") or [got] + ended = wait(server, [r["id"] for r in runs]) if a.wait else {} + except Refused as e: + print(e, file=sys.stderr) + return EXIT_REFUSED + page = server.url + "/job/{}" + (f"?workspace={urllib.parse.quote(a.workspace)}" if a.workspace else "") + if a.json: + json.dump(dict(got, **({"ended": ended} if a.wait else {})), sys.stdout, indent=1, ensure_ascii=False) + sys.stdout.write("\n") + else: + print(f"launch {got['launch']}") + for r in runs: + print(f"run {r['id']} on {r.get('host')}: {(ended.get(r['id']) or r).get('state')}") + print(f" jobs {r.get('jobs')}") + for j in r.get("job_ids") or []: + print(f" job {j} {page.format(urllib.parse.quote(j))}") + return EXIT_REFUSED if any(s.get("state") != "done" for s in ended.values()) else EXIT_OK + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="nullius recipes", description=__doc__.split("\n\n")[0], + epilog="exit codes: 0 done, 2 usage, 3 no such recipe, 4 refused") + sub = ap.add_subparsers(dest="cmd", required=True) + ls = sub.add_parser("list", help="the saved recipes: name, id, runner, benchmark, when saved") + ls.add_argument("--json", action="store_true", help="one JSON document: the saved recipes as stored") + la = sub.add_parser("launch", help="launch a recipe of the standard on the server here, as the builder's Run") + la.add_argument("recipe", help="a saved recipe's name or id, or a recipe file (JSON)") + la.add_argument("--where", action="append", metavar="MACHINE", + help="local, the server's machine, or a host's entry in Settings, in place of the recipe's Where (repeatable: one shard each)") + la.add_argument("--workspace", metavar="NAME", help="the workspace the launch goes into, made when there is none (default: the open one, as Run)") + la.add_argument("--server", metavar="URL", help="the Nullius server on this machine (default http://127.0.0.1:APP_PORT, else 5057)") + la.add_argument("--yes", action="store_true", help="answer yes to the question Run asks before a run of every unit") + la.add_argument("--wait", action="store_true", help="return when the launch has ended; exit 4 when it ended otherwise than done") + la.add_argument("--json", action="store_true", help="one JSON document: the server's answer to the launch") + a = ap.parse_args(argv) + return {"list": _list, "launch": _launch}[a.cmd](a) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/app/tests/test_unified_cli.py b/app/tests/test_unified_cli.py index 804ac9456..8b30b1da7 100644 --- a/app/tests/test_unified_cli.py +++ b/app/tests/test_unified_cli.py @@ -81,13 +81,14 @@ def find_spec(self, fullname, *args): env=self.env, capture_output=True, text=True) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(set(json.loads(result.stdout)), {"atif", "otel"}) - for command in ("runs", "compare", "standard", "workspace", "paths"): + for command in ("runs", "compare", "standard", "workspace", "paths", "recipes"): result = self.run_cli(command, "--help") self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("usage:", result.stdout) def test_errors_keep_the_delegated_exit_status(self): self.assertEqual(self.run_cli("import", str(self.root / "missing")).returncode, 3) + self.assertEqual(self.run_cli("recipes", "launch", "missing").returncode, 3) self.assertEqual(self.run_cli("runs", "unknown").returncode, 2) self.assertEqual(self.run_cli("unknown").returncode, 2) diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index 86289dda1..8644a426f 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -451,6 +451,45 @@ def test_run_refuses_a_host_a_misfit_and_an_unset_provider(self): self.assertIn(why, r.get_json()["error"]) self.assertEqual(self.started, []) + def test_recipes_launch_starts_the_plan_run_starts_into_the_workspace_it_names(self): + """`nullius recipes launch` asks the server what the builder asks it: a saved recipe, on a host, starts the + plan Run starts for the same recipe, into the workspace named; the launch's key is printed. Run's question is + refused without --yes and a recipe that is not there exits 3, nothing started.""" + import contextlib, datetime, io + from nullius import prerequisites + from nullius.recipes import cli as recipes, store + client, into = self.client, [] + class Here(recipes.Server): # the server, through the test client + def send(self, method, path, body=None): + r = client.open(path, method=method, headers={"Origin": "http://localhost", **({"X-CSRF-Token": self.token} if self.token else {})}, + **({} if body is None else {"data": json.dumps(body), "content_type": "application/json"})) + try: + return r.status_code, r.get_data(as_text=True) + finally: + r.close() + self.stack.enter_context(patch.dict(os.environ, {"NULLIUS_HOME": str(self.tmp / "home")})) + self.stack.enter_context(patch.object(recipes, "Server", Here)) + self.stack.enter_context(patch.object(prerequisites, "check_host", lambda host, needs, setups=None, standard=False: [])) + self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into_="": into.append(into_))) + store.save(self.recipe(name="fake", title="fake on two")) + got = recipes.launch(Here("http://localhost"), store.listing()[0]["recipe"], ["me@bench"], "planner", now=datetime.datetime(2026, 1, 1, 12, 0, 0)) + self.assertEqual((got["launch"], into), ("run:fake-0101-120000-1", ["planner"])) + self.assertEqual(self.post("/run", {"name": "fake-0101-120000", "where": "me@bench", "recipe": self.recipe(where="me@bench", title="fake on two")}).get_json()["ok"], True) + shell, page = self.started + self.assertEqual(shell.to_dict(), page.to_dict()) # the same launch + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(recipes.main(["launch", "fake on two", "--server", "http://localhost"]), 0) + self.assertRegex(out.getvalue(), r"^launch run:fake-\d{4}-\d{6}-1\n") + self.assertEqual(into[-1], "") # no workspace named: the open one, as Run + self.started.clear() + store.save(self.recipe(name="every", title="every unit", limit="")) + with contextlib.redirect_stderr(io.StringIO()) as err: + self.assertEqual(recipes.main(["launch", "every unit", "--server", "http://localhost"]), 4) + self.assertEqual(recipes.main(["launch", "nowhere", "--server", "http://localhost"]), 3) + self.assertIn("--yes answers yes", err.getvalue()) + self.assertEqual(self.started, []) + class StandardPieces(unittest.TestCase): """What the pages say of the standard beyond a pair: an agent's options, From c5c627c7da1f4eb7a5364edfd9a2529f51ffeafd Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Tue, 24 Nov 2026 11:53:06 +0100 Subject: [PATCH 03/13] docs(builder): the recipes command, and the builder's Run covered from a shell A page of its own for `nullius recipes list` and `launch`, beside `standard run`: what each takes, that `launch` needs the server running here and sends the builder's requests, what it refuses and prints, and how the result is read. The table of pages from a shell moves `/new-run` and its Run from "No command yet" to "Covered", says that `standard run` runs in the shell while `recipes launch` goes through the server, and adds `/recipes`. The CLI index, the site's navigation, the builder's Run rules, the exit codes' Writes row and the running rule name the command. --- .claude/rules/running.md | 3 ++- app/site/mkdocs.yml | 1 + docs/builder.md | 1 + docs/cli/README.md | 1 + docs/cli/exit-codes.md | 2 +- docs/cli/pages.md | 5 +++-- docs/cli/recipes.md | 44 ++++++++++++++++++++++++++++++++++++++++ 7 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 docs/cli/recipes.md diff --git a/.claude/rules/running.md b/.claude/rules/running.md index a1c0187c4..7902d8090 100644 --- a/.claude/rules/running.md +++ b/.claude/rules/running.md @@ -1,7 +1,8 @@ ## What this repository runs Nullius reads run output and runs a benchmark only on an explicit **Run** -from the builder's Review step: a **Nullius standard** recipe +from the builder's Review step, or `nullius recipes launch`, which sends a +saved standard recipe to the server as Run does: a **Nullius standard** recipe (`docs/standard.md`) or a **Harbor** recipe, on this machine or a Settings host (`nullius/execution.py`). A benchmark's own scripts run as its Original setup. diff --git a/app/site/mkdocs.yml b/app/site/mkdocs.yml index 2e465487d..f752d5931 100644 --- a/app/site/mkdocs.yml +++ b/app/site/mkdocs.yml @@ -104,6 +104,7 @@ nav: - Task flags: cli/flags.md - Definitions: cli/definitions.md - Run a benchmark: cli/run.md + - Launch a recipe: cli/recipes.md - Prove a benchmark: cli/prove.md - Conform an agent or a capability: cli/conform.md - Fidelity: cli/fidelity.md diff --git a/docs/builder.md b/docs/builder.md index e4c9d8674..f3fe3886b 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -107,6 +107,7 @@ and Delete work only from a browser on the application host. | Delete launch | Once every run of the launch has ended. Deletes each run's `//` (a shard per machine included), every job of the launch, their judgements in every workspace, and each run's copy on its host when ticked. A run still going is refused: stop it first. A launch with jobs from elsewhere has no Delete | | Restart of Nullius | Reattaches; the job goes back into the workspace it started in, under the name a rename gave it, while that workspace exists, without opening it. The workspace open before the restart opens again. One process follows a runs folder: a second `nullius serve` on it stops with a message | | Cannot run from the page | Generated tasks and custom agents are not supported by Run | +| From a shell | `nullius recipes launch ` sends a saved recipe of the standard to the server as Run does: [Launch a recipe](cli/recipes.md) | | Refused | Reads *refused* on the runs page, with why; the job was never written | | Files | `//`: script, log, `run.json`, `jobs/`; default `runs/` under the user data directory (`nullius paths`) | diff --git a/docs/cli/README.md b/docs/cli/README.md index 533fd34c2..b59ba65cd 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -15,6 +15,7 @@ From a source checkout, replace `nullius` with | [Task flags](flags.md) | `nullius flags list`, `set`, `accept`, `remove`, `copy`, `import`, `feasibility` | | [Definitions](definitions.md) | `nullius standard list`, `check`, `fit`, `pins`, `new` | | [Run a benchmark](run.md) | `nullius standard run` | +| [Launch a recipe](recipes.md) | `nullius recipes list`, `launch` | | [Prove a benchmark](prove.md) | `nullius standard prove` | | [Conform an agent or a capability](conform.md) | `nullius standard conform` | | [Fidelity](fidelity.md) | `nullius standard fidelity` | diff --git a/docs/cli/exit-codes.md b/docs/cli/exit-codes.md index c3762671d..8f8eef7d3 100644 --- a/docs/cli/exit-codes.md +++ b/docs/cli/exit-codes.md @@ -24,7 +24,7 @@ A refusal is one line on stderr, nothing partial written; the standard's command | Streams | stdout for output, stderr for diagnostics; `--json` is one document | | Job id | The job directory's name, everywhere | | Secrets | Read commands make no model call and never print credentials. Job content is redacted | -| Writes | Reads write nothing, open no socket; import under `-o`; the standard its jobs, and a user definition on `new`, `prove`, `conform`, `fidelity`; migration writes only with `--apply`; `flags` writes only the job's `failure-analysis.json` | +| Writes | Reads write nothing, open no socket; import under `-o`; the standard its jobs, and a user definition on `new`, `prove`, `conform`, `fidelity`; migration writes only with `--apply`; `flags` writes only the job's `failure-analysis.json`; `recipes launch` writes nothing here and asks the server on this machine, which starts the run |
diff --git a/docs/cli/pages.md b/docs/cli/pages.md index 7caed9c28..e6ec5f418 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -19,7 +19,9 @@ Each page's command, or why there is none. | `/agents`, `/capabilities` | `nullius standard list` includes agents, capabilities and their proven ports | | A benchmark's *Prove it* | `nullius standard prove KEY` ([Prove](prove.md)) | | *Prove its ports* | `nullius standard conform KEY` ([Conform](conform.md)) | -| `/run` | `nullius standard run` per dataset and choice, `--shard I/N` per machine ([Run](run.md)) | +| `/run` | `nullius standard run` per dataset and choice, `--shard I/N` per machine, in the shell ([Run](run.md)) | +| `/new-run`, its Run | `nullius recipes launch [--where MACHINE] [--workspace NAME]`, through the server ([Launch a recipe](recipes.md)) | +| `/recipes` | `nullius recipes list [--json]` | ## While the app runs @@ -40,7 +42,6 @@ Each page's command, or why there is none. | `/judge/…` | `judge.cli job --confirm` | | Rename or delete a workspace | `nullius workspace rename`, `nullius workspace delete --yes` | | Unlink a workspace's root, delete its folder | `workspace.forget`, `execution.delete`; today `POST /workspaces//roots/unlink` and `/roots/delete` | -| `/new-run` | `recipes.cli`; today `POST /new-run/runner` | | Delete a launch | `execution.delete`; today `POST /launch//delete` | | `/launches`, add a launch to a workspace | today `POST /launch//add` | diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md new file mode 100644 index 000000000..e579a93e2 --- /dev/null +++ b/docs/cli/recipes.md @@ -0,0 +1,44 @@ +# Launch a recipe + +A saved recipe of the standard, launched from a shell as the builder's **Run** launches it. + +```bash title="Recipes" +nullius recipes list [--json] +nullius recipes launch [--where MACHINE]... [--workspace NAME] [--server URL] [--yes] [--wait] [--json] +``` + +```bash title="Examples" +nullius recipes launch "OSWorld1 nop" --where gpu-box --workspace trials +nullius recipes launch recipe.json --wait --json +``` + +| Argument | Meaning | +| --- | --- | +| `` | A saved recipe by its name or id ([Saved recipes](../builder.md#saved-recipes-and-drafts)), or a recipe file as the builder exports it | +| `--where MACHINE` | `local`, the server's machine, or a host's entry in Settings, in place of the recipe's *Where*; repeated, one shard each | +| `--workspace NAME` | The workspace the launch goes into, made when there is none; the open workspace stays open. Default: the open one, as Run | +| `--server URL` | The Nullius server on this machine (default `http://127.0.0.1:` and `APP_PORT`, else 5057) | +| `--yes` | Answers the question Run asks before a run of every unit | +| `--wait` | Returns when the launch has ended; exits 4 when it ended otherwise than done | +| `--json` | The server's answer as one document | + +| Rule | Detail | +| --- | --- | +| The server | `launch` needs `nullius serve` running here: the server starts the launch and follows it, as one started from the page. `nullius standard run` runs in the shell instead ([Run a benchmark](run.md)) | +| What it sends | The builder's requests: `GET /new-run`, `POST /new-run/runner`, `POST /new-run/prerequisites`, `POST /run` | +| Refused | An error of the compile, a machine missing a prerequisite, the question without `--yes`, a Harbor recipe: nothing starts | +| The name | The recipe's name and the second, as each Run names a new job | +| What it prints | `launch run:`, the launch's key; per run its machine, its state, its jobs folder and its job pages | +| The result | `nullius runs show `: [Read jobs](read-jobs.md) | + +
+ +- [Run builder](../builder.md) + + The recipe and its Run. + +- [Pages from a shell](pages.md) + + The other pages' commands. + +
From 7cd578085cc3b89464789635776de9900ba31386 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Tue, 24 Nov 2026 12:00:43 +0100 Subject: [PATCH 04/13] fix(builder): end a launch's --wait when a run pauses on its question A run of several agents pauses when a part fails and asks, on its page, whether to go on with the next one. `--wait` waited for the run to end and a paused run never ends until someone answers on the page: a caller in a shell, a script or an agent, waited for ever. `--wait` now returns when no run of the launch is going: each has ended or is paused. A paused run is printed with its state and the command exits 4, as for a run that ended otherwise than done. The wait asks each run's state until it stops going and does not ask an ended run again. --- app/nullius/recipes/cli.py | 9 ++++---- app/tests/test_recipes_cli.py | 43 +++++++++++++++++++++++++++++++++++ docs/cli/recipes.md | 2 +- 3 files changed, 49 insertions(+), 5 deletions(-) create mode 100644 app/tests/test_recipes_cli.py diff --git a/app/nullius/recipes/cli.py b/app/nullius/recipes/cli.py index ca6ff9421..7a6ae105d 100644 --- a/app/nullius/recipes/cli.py +++ b/app/nullius/recipes/cli.py @@ -13,7 +13,7 @@ recipe file as the builder exports it. The exit codes are the contract in ``docs/cli/exit-codes.md``: 0 done, 2 usage, 3 no such recipe, 4 refused (by the -compile, a machine, the question Run asks, the server, or a launch that ended otherwise than done with ``--wait``). +compile, a machine, the question Run asks, the server, or with ``--wait`` a launch that ended otherwise than done or paused). """ from __future__ import annotations @@ -132,7 +132,8 @@ def launch(server: Server, recipe: dict, where=None, into: str = "", yes: bool = def wait(server: Server, run_ids, every: float = POLL_SECONDS) -> dict: - """{run id: its summary} once none of the runs is alive (``GET /run/``, the route the page polls).""" + """{run id: its summary} once none of the runs is going (``GET /run/``, the route the page polls): each has + ended, or is paused on the question the page answers, which a shell cannot.""" ended = {} while True: for rid in run_ids: @@ -140,7 +141,7 @@ def wait(server: Server, run_ids, every: float = POLL_SECONDS) -> dict: status, s = server.json("GET", f"/run/{urllib.parse.quote(rid)}") if status != 200: raise Refused(f"GET /run/{rid}: HTTP {status}") - if s.get("state") not in execution.ALIVE: + if s.get("state") not in execution.ALIVE or s.get("state") == "paused": ended[rid] = {k: v for k, v in s.items() if k != "log"} if len(ended) == len(run_ids): return ended @@ -203,7 +204,7 @@ def main(argv=None) -> int: la.add_argument("--workspace", metavar="NAME", help="the workspace the launch goes into, made when there is none (default: the open one, as Run)") la.add_argument("--server", metavar="URL", help="the Nullius server on this machine (default http://127.0.0.1:APP_PORT, else 5057)") la.add_argument("--yes", action="store_true", help="answer yes to the question Run asks before a run of every unit") - la.add_argument("--wait", action="store_true", help="return when the launch has ended; exit 4 when it ended otherwise than done") + la.add_argument("--wait", action="store_true", help="return when the launch has ended or paused on a question; exit 4 unless it ended done") la.add_argument("--json", action="store_true", help="one JSON document: the server's answer to the launch") a = ap.parse_args(argv) return {"list": _list, "launch": _launch}[a.cmd](a) diff --git a/app/tests/test_recipes_cli.py b/app/tests/test_recipes_cli.py new file mode 100644 index 000000000..262ec019b --- /dev/null +++ b/app/tests/test_recipes_cli.py @@ -0,0 +1,43 @@ +"""`nullius recipes launch --wait`: it asks each run's state until none is going, and a run paused on the page's +question ends the wait as an end does.""" +from __future__ import annotations + +import unittest +from unittest.mock import patch + +from nullius.recipes import cli + + +class Scripted(cli.Server): + """A server whose ``GET /run/`` answers the states given for that run, one per call, the last one kept.""" + def __init__(self, states): + super().__init__("http://localhost") + self.states, self.asked = {k: list(v) for k, v in states.items()}, [] + + def send(self, method, path, body=None): + rid = path.rsplit("/", 1)[1] + self.asked.append(rid) + left = self.states[rid] + state = left.pop(0) if len(left) > 1 else left[0] + return 200, '{"id": "%s", "state": "%s", "log": ["a line"]}' % (rid, state) + + +class Wait(unittest.TestCase): + def test_it_waits_until_no_run_is_going_and_a_pause_ends_it(self): + server = Scripted({"a": ["preparing", "running", "done"], "b": ["running", "paused"]}) + with patch.object(cli.time, "sleep", lambda s: None): + ended = cli.wait(server, ["a", "b"]) + self.assertEqual({k: v["state"] for k, v in ended.items()}, {"a": "done", "b": "paused"}) + self.assertNotIn("log", ended["a"]) + self.assertEqual(server.asked, ["a", "b", "a", "b", "a"]) # an ended run is not asked again + + def test_a_route_that_does_not_answer_the_run_refuses(self): + class Gone(cli.Server): + def send(self, method, path, body=None): + return 404, "{}" + with self.assertRaises(cli.Refused): + cli.wait(Gone("http://localhost"), ["a"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md index e579a93e2..56e323ef8 100644 --- a/docs/cli/recipes.md +++ b/docs/cli/recipes.md @@ -19,7 +19,7 @@ nullius recipes launch recipe.json --wait --json | `--workspace NAME` | The workspace the launch goes into, made when there is none; the open workspace stays open. Default: the open one, as Run | | `--server URL` | The Nullius server on this machine (default `http://127.0.0.1:` and `APP_PORT`, else 5057) | | `--yes` | Answers the question Run asks before a run of every unit | -| `--wait` | Returns when the launch has ended; exits 4 when it ended otherwise than done | +| `--wait` | Returns when the launch has ended, or paused on the question its page asks; exits 4 unless it ended done | | `--json` | The server's answer as one document | | Rule | Detail | From 0d48c1b82484d4a5a8d7b36b4cc2519df1b2593d Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Tue, 24 Nov 2026 12:03:09 +0100 Subject: [PATCH 05/13] test(execution): name the workspace of the launch tests after what it holds The two tests of a launch into a named workspace called it after a role. They call it "trials", as the command's page does in its example. --- app/ui_tests/test_agents.py | 4 ++-- app/ui_tests/test_run_routes.py | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index 8644a426f..a9294959d 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -472,8 +472,8 @@ def send(self, method, path, body=None): self.stack.enter_context(patch.object(prerequisites, "check_host", lambda host, needs, setups=None, standard=False: [])) self.stack.enter_context(patch.object(web.shared, "adopt_runs", lambda runs, into_="": into.append(into_))) store.save(self.recipe(name="fake", title="fake on two")) - got = recipes.launch(Here("http://localhost"), store.listing()[0]["recipe"], ["me@bench"], "planner", now=datetime.datetime(2026, 1, 1, 12, 0, 0)) - self.assertEqual((got["launch"], into), ("run:fake-0101-120000-1", ["planner"])) + got = recipes.launch(Here("http://localhost"), store.listing()[0]["recipe"], ["me@bench"], "trials", now=datetime.datetime(2026, 1, 1, 12, 0, 0)) + self.assertEqual((got["launch"], into), ("run:fake-0101-120000-1", ["trials"])) self.assertEqual(self.post("/run", {"name": "fake-0101-120000", "where": "me@bench", "recipe": self.recipe(where="me@bench", title="fake on two")}).get_json()["ok"], True) shell, page = self.started self.assertEqual(shell.to_dict(), page.to_dict()) # the same launch diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 5efc350dd..22f6a2a81 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -529,14 +529,14 @@ def post(name, into): execution.EXECUTIONS[r.json["id"]].thread.join(10) return r first, second = (str(self.tmp / "runs" / n / "jobs") for n in ("q1", "q2")) - self.assertEqual(post("q1", "planner").status_code, 200) - made = workspace.load(self.home, "planner") - self.assertEqual((made.label, made.roots), ("planner", [first])) + self.assertEqual(post("q1", "trials").status_code, 200) + made = workspace.load(self.home, "trials") + self.assertEqual((made.label, made.roots), ("trials", [first])) self.assertEqual(web.shared.STATE["workspace"].name, self.ws.name) self.assertEqual(workspace.load(self.home, self.ws.name).roots, self.held + [self.jobs]) - self.assertEqual(json.loads((self.tmp / "runs" / "q1" / "run.json").read_text())["workspace"], "planner") - self.assertEqual(post("q2", "planner").status_code, 200) # one there already: added to - self.assertEqual(workspace.load(self.home, "planner").roots, [first, second]) + self.assertEqual(json.loads((self.tmp / "runs" / "q1" / "run.json").read_text())["workspace"], "trials") + self.assertEqual(post("q2", "trials").status_code, 200) # one there already: added to + self.assertEqual(workspace.load(self.home, "trials").roots, [first, second]) before = sorted(w.name for w in workspace.list_all(self.home)) r = post("q3", "Not a name") self.assertEqual((r.status_code, r.json), (400, {"ok": False, "error": "A workspace's name is lowercase letters, digits and dashes."})) From 83e806ffc1ad0734965db1d755e6db124d44a610 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 11:27:43 +0100 Subject: [PATCH 06/13] docs(builder): keep the launch command's docs to what a reader acts on The project's writing rules now keep guarantees, requirements and refusals in docs/ and drop mechanism, and state each fact on one page. The command's page no longer lists the requests it sends, and its server row says only that a launch needs the server and that `standard run` does not. The builder's page drops its row for the command: the table of pages from a shell already pairs Run with it. The exit codes' Writes row and the running rule say the same in fewer words. --- .claude/rules/running.md | 4 ++-- docs/builder.md | 1 - docs/cli/exit-codes.md | 2 +- docs/cli/recipes.md | 3 +-- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/.claude/rules/running.md b/.claude/rules/running.md index 7902d8090..b4e9f8999 100644 --- a/.claude/rules/running.md +++ b/.claude/rules/running.md @@ -1,8 +1,8 @@ ## What this repository runs Nullius reads run output and runs a benchmark only on an explicit **Run** -from the builder's Review step, or `nullius recipes launch`, which sends a -saved standard recipe to the server as Run does: a **Nullius standard** recipe +from the builder's Review step, or `nullius recipes launch`, the same from a +shell: a **Nullius standard** recipe (`docs/standard.md`) or a **Harbor** recipe, on this machine or a Settings host (`nullius/execution.py`). A benchmark's own scripts run as its Original setup. diff --git a/docs/builder.md b/docs/builder.md index f3fe3886b..e4c9d8674 100644 --- a/docs/builder.md +++ b/docs/builder.md @@ -107,7 +107,6 @@ and Delete work only from a browser on the application host. | Delete launch | Once every run of the launch has ended. Deletes each run's `//` (a shard per machine included), every job of the launch, their judgements in every workspace, and each run's copy on its host when ticked. A run still going is refused: stop it first. A launch with jobs from elsewhere has no Delete | | Restart of Nullius | Reattaches; the job goes back into the workspace it started in, under the name a rename gave it, while that workspace exists, without opening it. The workspace open before the restart opens again. One process follows a runs folder: a second `nullius serve` on it stops with a message | | Cannot run from the page | Generated tasks and custom agents are not supported by Run | -| From a shell | `nullius recipes launch ` sends a saved recipe of the standard to the server as Run does: [Launch a recipe](cli/recipes.md) | | Refused | Reads *refused* on the runs page, with why; the job was never written | | Files | `//`: script, log, `run.json`, `jobs/`; default `runs/` under the user data directory (`nullius paths`) | diff --git a/docs/cli/exit-codes.md b/docs/cli/exit-codes.md index 8f8eef7d3..405624e88 100644 --- a/docs/cli/exit-codes.md +++ b/docs/cli/exit-codes.md @@ -24,7 +24,7 @@ A refusal is one line on stderr, nothing partial written; the standard's command | Streams | stdout for output, stderr for diagnostics; `--json` is one document | | Job id | The job directory's name, everywhere | | Secrets | Read commands make no model call and never print credentials. Job content is redacted | -| Writes | Reads write nothing, open no socket; import under `-o`; the standard its jobs, and a user definition on `new`, `prove`, `conform`, `fidelity`; migration writes only with `--apply`; `flags` writes only the job's `failure-analysis.json`; `recipes launch` writes nothing here and asks the server on this machine, which starts the run | +| Writes | Reads write nothing, open no socket; import under `-o`; the standard its jobs, and a user definition on `new`, `prove`, `conform`, `fidelity`; migration writes only with `--apply`; `flags` writes only the job's `failure-analysis.json`; `recipes launch` writes nothing: the server here starts the run |
diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md index 56e323ef8..34b686754 100644 --- a/docs/cli/recipes.md +++ b/docs/cli/recipes.md @@ -24,8 +24,7 @@ nullius recipes launch recipe.json --wait --json | Rule | Detail | | --- | --- | -| The server | `launch` needs `nullius serve` running here: the server starts the launch and follows it, as one started from the page. `nullius standard run` runs in the shell instead ([Run a benchmark](run.md)) | -| What it sends | The builder's requests: `GET /new-run`, `POST /new-run/runner`, `POST /new-run/prerequisites`, `POST /run` | +| The server | `launch` needs `nullius serve` running here; `nullius standard run` runs without it ([Run a benchmark](run.md)) | | Refused | An error of the compile, a machine missing a prerequisite, the question without `--yes`, a Harbor recipe: nothing starts | | The name | The recipe's name and the second, as each Run names a new job | | What it prints | `launch run:`, the launch's key; per run its machine, its state, its jobs folder and its job pages | From de00426a9a884a136d6d534acfa89061d74b9ebf Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 11:27:54 +0100 Subject: [PATCH 07/13] feat(builder): show a launch's review from a shell and start nothing `nullius recipes launch` could only launch. To see what a recipe would start, where, and whether the server would accept it, a caller had to open the builder's Review step. `--dry-run` sends what the Review step sends, the compile and the check of what each machine lacks. It prints the rows the Review step shows, each machine's missing needs and the notes, then stops before POST /run: no launch, no job folder, no workspace. It exits 0 when Run would start the launch and 4, with the reason, when the launch would be refused. With `--json` it prints the compile's answer with the machines' answer and the refusal. The name is the one `standard traces` gives its option that writes nothing. The launch and the dry run share one review. A launch now asks the machines before it refuses on Run's question, as the Review step does, and refuses a `--workspace` that is not a workspace's name with the server's own words. --- app/nullius/recipes/cli.py | 82 ++++++++++++++++++++++++++++--------- app/ui_tests/test_agents.py | 16 +++++++- docs/cli/pages.md | 2 +- docs/cli/recipes.md | 3 +- 4 files changed, 80 insertions(+), 23 deletions(-) diff --git a/app/nullius/recipes/cli.py b/app/nullius/recipes/cli.py index 7a6ae105d..d93c68fa5 100644 --- a/app/nullius/recipes/cli.py +++ b/app/nullius/recipes/cli.py @@ -1,7 +1,7 @@ """The builder's saved recipes from a shell, and a recipe launched as the builder's Run launches it. nullius recipes list [--json] - nullius recipes launch [--where MACHINE]... [--workspace NAME] [--server URL] [--yes] [--wait] [--json] + nullius recipes launch [--where MACHINE]... [--workspace NAME] [--server URL] [--yes] [--wait | --dry-run] [--json] ``list`` reads the saved recipes (``store.listing``) and writes nothing. @@ -10,10 +10,12 @@ (``POST /new-run/runner``), what each machine lacks (``POST /new-run/prerequisites``), then ``POST /run``. The server makes the launch and follows it, as one it started from the page: one process follows a runs folder (``execution``), and the pages list the runs it follows. The recipe is a saved one, by its name or its id, or a -recipe file as the builder exports it. +recipe file as the builder exports it. ``--dry-run`` stops before ``POST /run`` and prints what the Review step +shows: nothing starts, no job or workspace is made. -The exit codes are the contract in ``docs/cli/exit-codes.md``: 0 done, 2 usage, 3 no such recipe, 4 refused (by the -compile, a machine, the question Run asks, the server, or with ``--wait`` a launch that ended otherwise than done or paused). +The exit codes are the contract in ``docs/cli/exit-codes.md``: 0 done (with ``--dry-run``: Run would start it), 2 usage, +3 no such recipe, 4 refused (by the compile, a machine, the question Run asks, the server, or with ``--wait`` a launch +that ended otherwise than done or paused). """ from __future__ import annotations @@ -29,7 +31,7 @@ import urllib.parse import urllib.request -from nullius import execution +from nullius import execution, workspace from nullius.recipes import store EXIT_OK, EXIT_NOT_FOUND, EXIT_REFUSED = 0, 3, 4 @@ -98,9 +100,10 @@ def find(ref: str) -> dict: raise LookupError(f"no saved recipe or recipe file {ref}") -def launch(server: Server, recipe: dict, where=None, into: str = "", yes: bool = False, now=None) -> dict: - """Send ``recipe`` as the builder's Run does; the server's answer to ``POST /run``, with ``review``, the rows of - the Review step, and ``launch``, the launch's key. ``Refused`` when the builder would not start it.""" +def review(server: Server, recipe: dict, where=None, into: str = "", yes: bool = False, now=None) -> tuple: + """What the builder's Review step shows for ``recipe``, nothing started: (the recipe as Run sends it, the answer + to ``POST /new-run/runner`` with ``prerequisites``, the answer to ``POST /new-run/prerequisites``, and + ``refused``, why Run would not start it, else "").""" if (recipe.get("harness") or "harbor") != STANDARD: raise Refused("a Harbor recipe runs by the script its Review step generates: docs/builder.md") status, text = server.send("GET", "/new-run") @@ -115,20 +118,30 @@ def launch(server: Server, recipe: dict, where=None, into: str = "", yes: bool = stamp = (now or datetime.datetime.now()).strftime("%m%d-%H%M%S") recipe = dict(recipe, name=f"{recipe.get('name') or ''}-{stamp}", **({"where": where[0] if len(where) == 1 else list(where)} if where else {})) _, out = server.json("POST", "/new-run/runner", {"recipe": recipe}) - if out.get("errors"): - raise Refused(" ".join(e.get("message", "") for e in out["errors"])) - if out.get("confirm") and not yes: - raise Refused(f"Run asks first: {out['confirm']} --yes answers yes") - _, pre = server.json("POST", "/new-run/prerequisites", {"recipe": recipe, "provider": recipe.get("provider") or ""}) - if not pre.get("ready"): - lacks = [f"{m.get('label')}: {r.get('label')}" + (f" ({r['detail']})" if r.get("detail") else "") - for m in pre.get("machines") or [] for r in m.get("rows") or [] if r.get("state") == "missing"] - raise Refused("a machine lacks what the run needs: " + ("; ".join(lacks + list(pre.get("errors") or [])) or "see Review")) + pre = {"machines": [], "ready": False, "errors": []} # an error of the compile: no machine is asked + if not out.get("errors"): + _, pre = server.json("POST", "/new-run/prerequisites", {"recipe": recipe, "provider": recipe.get("provider") or ""}) + lacks = [f"{m.get('label')}: {r.get('label')}" + (f" ({r['detail']})" if r.get("detail") else "") + for m in pre.get("machines") or [] for r in m.get("rows") or [] if r.get("state") == "missing"] + why = ("A workspace's name is lowercase letters, digits and dashes." if into and workspace.slug(into) != into + else " ".join(e.get("message", "") for e in out["errors"]) if out.get("errors") + else f"Run asks first: {out['confirm']} --yes answers yes" if out.get("confirm") and not yes + else "" if pre.get("ready") + else "a machine lacks what the run needs: " + ("; ".join(lacks + list(pre.get("errors") or [])) or "see Review")) + return recipe, dict(out, prerequisites=pre, refused=why) + + +def launch(server: Server, recipe: dict, where=None, into: str = "", yes: bool = False, now=None) -> dict: + """Send ``recipe`` as the builder's Run does; the server's answer to ``POST /run``, with ``review``, the rows of + the Review step, and ``launch``, the launch's key. ``Refused`` when the builder would not start it.""" + recipe, seen = review(server, recipe, where, into, yes, now) + if seen["refused"]: + raise Refused(seen["refused"]) body = {"name": recipe["name"], "where": recipe.get("where") or "local", "recipe": recipe, **({"workspace": into} if into else {})} status, got = server.json("POST", "/run", body) if not got.get("ok"): raise Refused(got.get("error") or f"POST /run: HTTP {status}") - return dict(got, review=out.get("review") or [], launch=f"run:{got['id']}") + return dict(got, review=seen.get("review") or [], launch=f"run:{got['id']}") def wait(server: Server, run_ids, every: float = POLL_SECONDS) -> dict: @@ -170,6 +183,8 @@ def _launch(a) -> int: print(e, file=sys.stderr) return EXIT_REFUSED server = Server(a.server or default_server()) + if a.dry_run: + return _dry_run(server, recipe, a) try: got = launch(server, recipe, a.where, a.workspace or "", a.yes) runs = got.get("runs") or [got] @@ -191,6 +206,33 @@ def _launch(a) -> int: return EXIT_REFUSED if any(s.get("state") != "done" for s in ended.values()) else EXIT_OK +def _dry_run(server: Server, recipe: dict, a) -> int: + """What Run would launch, as the Review step shows it; exit 0 when Run would start it.""" + try: + _, seen = review(server, recipe, a.where, a.workspace or "", a.yes) + except Refused as e: + print(e, file=sys.stderr) + return EXIT_REFUSED + pre = seen["prerequisites"] + if a.json: + json.dump(seen, sys.stdout, indent=1, ensure_ascii=False) + sys.stdout.write("\n") + else: + for _, label, value in seen.get("review") or []: + print(f"{label}: {value}") + for m in pre.get("machines") or []: + lacks = [f"{r.get('label')} {r.get('state')}" + (f" ({r['detail']})" if r.get("detail") else "") + for r in m.get("rows") or [] if r.get("state") != "ok"] + print(f"Prerequisites, {m.get('label')}: {'; '.join(lacks) or 'ready'}") + for note in (seen.get("notes") or []) + (pre.get("notes") or []): + print(f"Note: {note}") + print("Not launched: --dry-run") + if seen["refused"]: + print(seen["refused"], file=sys.stderr) + return EXIT_REFUSED + return EXIT_OK + + def main(argv=None) -> int: ap = argparse.ArgumentParser(prog="nullius recipes", description=__doc__.split("\n\n")[0], epilog="exit codes: 0 done, 2 usage, 3 no such recipe, 4 refused") @@ -204,7 +246,9 @@ def main(argv=None) -> int: la.add_argument("--workspace", metavar="NAME", help="the workspace the launch goes into, made when there is none (default: the open one, as Run)") la.add_argument("--server", metavar="URL", help="the Nullius server on this machine (default http://127.0.0.1:APP_PORT, else 5057)") la.add_argument("--yes", action="store_true", help="answer yes to the question Run asks before a run of every unit") - la.add_argument("--wait", action="store_true", help="return when the launch has ended or paused on a question; exit 4 unless it ended done") + ends = la.add_mutually_exclusive_group() + ends.add_argument("--wait", action="store_true", help="return when the launch has ended or paused on a question; exit 4 unless it ended done") + ends.add_argument("--dry-run", action="store_true", help="print what the Review step shows and launch nothing; exit 0 when Run would start it") la.add_argument("--json", action="store_true", help="one JSON document: the server's answer to the launch") a = ap.parse_args(argv) return {"list": _list, "launch": _launch}[a.cmd](a) diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index a9294959d..f33dbcf12 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -453,8 +453,9 @@ def test_run_refuses_a_host_a_misfit_and_an_unset_provider(self): def test_recipes_launch_starts_the_plan_run_starts_into_the_workspace_it_names(self): """`nullius recipes launch` asks the server what the builder asks it: a saved recipe, on a host, starts the - plan Run starts for the same recipe, into the workspace named; the launch's key is printed. Run's question is - refused without --yes and a recipe that is not there exits 3, nothing started.""" + plan Run starts for the same recipe, into the workspace named; the launch's key is printed. --dry-run prints the + Review step's rows and starts nothing. Run's question is refused without --yes and a recipe that is not there + exits 3, nothing started.""" import contextlib, datetime, io from nullius import prerequisites from nullius.recipes import cli as recipes, store @@ -482,10 +483,21 @@ def send(self, method, path, body=None): self.assertEqual(recipes.main(["launch", "fake on two", "--server", "http://localhost"]), 0) self.assertRegex(out.getvalue(), r"^launch run:fake-\d{4}-\d{6}-1\n") self.assertEqual(into[-1], "") # no workspace named: the open one, as Run + held = (list(self.started), list(into)) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(recipes.main(["launch", "fake on two", "--dry-run", "--workspace", "dry", "--server", "http://localhost"]), 0) + self.assertEqual(recipes.main(["launch", "fake on two", "--dry-run", "--json", "--server", "http://localhost"]), 0) + shown, doc = out.getvalue().split("Not launched: --dry-run\n") + self.assertRegex(shown, r"^Benchmark: .*\nRunner: Nullius\n(.*\n)*Scope: first 2 .*\n(.*\n)*Prerequisites, this machine: ready\n") + self.assertEqual((json.loads(doc)["refused"], json.loads(doc)["prerequisites"]["ready"]), ("", True)) + self.assertEqual((self.started, into), held) # no run, no workspace self.started.clear() store.save(self.recipe(name="every", title="every unit", limit="")) with contextlib.redirect_stderr(io.StringIO()) as err: self.assertEqual(recipes.main(["launch", "every unit", "--server", "http://localhost"]), 4) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(recipes.main(["launch", "every unit", "--dry-run", "--server", "http://localhost"]), 4) + self.assertIn("\nScope: all ", out.getvalue()) self.assertEqual(recipes.main(["launch", "nowhere", "--server", "http://localhost"]), 3) self.assertIn("--yes answers yes", err.getvalue()) self.assertEqual(self.started, []) diff --git a/docs/cli/pages.md b/docs/cli/pages.md index e6ec5f418..8567d1751 100644 --- a/docs/cli/pages.md +++ b/docs/cli/pages.md @@ -20,7 +20,7 @@ Each page's command, or why there is none. | A benchmark's *Prove it* | `nullius standard prove KEY` ([Prove](prove.md)) | | *Prove its ports* | `nullius standard conform KEY` ([Conform](conform.md)) | | `/run` | `nullius standard run` per dataset and choice, `--shard I/N` per machine, in the shell ([Run](run.md)) | -| `/new-run`, its Run | `nullius recipes launch [--where MACHINE] [--workspace NAME]`, through the server ([Launch a recipe](recipes.md)) | +| `/new-run`: its Review, its Run | `nullius recipes launch [--dry-run]`, through the server ([Launch a recipe](recipes.md)) | | `/recipes` | `nullius recipes list [--json]` | ## While the app runs diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md index 34b686754..7c860f980 100644 --- a/docs/cli/recipes.md +++ b/docs/cli/recipes.md @@ -4,7 +4,7 @@ A saved recipe of the standard, launched from a shell as the builder's **Run** l ```bash title="Recipes" nullius recipes list [--json] -nullius recipes launch [--where MACHINE]... [--workspace NAME] [--server URL] [--yes] [--wait] [--json] +nullius recipes launch [--where MACHINE]... [--workspace NAME] [--server URL] [--yes] [--wait | --dry-run] [--json] ``` ```bash title="Examples" @@ -20,6 +20,7 @@ nullius recipes launch recipe.json --wait --json | `--server URL` | The Nullius server on this machine (default `http://127.0.0.1:` and `APP_PORT`, else 5057) | | `--yes` | Answers the question Run asks before a run of every unit | | `--wait` | Returns when the launch has ended, or paused on the question its page asks; exits 4 unless it ended done | +| `--dry-run` | Prints what the Review step shows and stops; exits 0 when Run would start it | | `--json` | The server's answer as one document | | Rule | Detail | From d9d5dcca01497e4bceefd7926ff4461361362361 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:05:30 +0100 Subject: [PATCH 08/13] fix(execution): refuse unsafe launch workspace destinations --- app/ui_tests/test_run_routes.py | 26 ++++++++++++++++++++++++++ app/web/execute.py | 5 +++++ docs/cli/recipes.md | 1 + 3 files changed, 32 insertions(+) diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 22f6a2a81..3032a4681 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -173,6 +173,32 @@ def test_a_name_still_running_or_used_before_is_refused_and_nothing_starts(self) self.assertEqual((dict(execution.EXECUTIONS), self.adopted), ({}, [])) # nothing started, the free name included self.assertFalse((self.tmp / "runs" / "fresh").exists()) + def test_a_launch_refuses_a_linked_workspace_before_starting(self): + home = self.tmp / "workspaces" + home.mkdir() + outside = self.tmp / "outside" + outside.mkdir() + inside = home / "inside" + inside.mkdir() + linked = home / "trials" + run = SimpleNamespace(jobs=str(self.tmp / "runs" / "launch" / "jobs"), summary=lambda: {"id": "launch"}) + with patch.object(web.shared, "WS_HOME", str(home)), patch.object(execution, "start", return_value=run) as start: + for target in (outside, inside, self.tmp / "absent"): + with self.subTest(target=target): + linked.symlink_to(target, target_is_directory=True) + try: + r = self.post({"name": "launch", "script": "true", "workspace": "trials"}) + self.assertEqual(r.status_code, 400) + self.assertIn("symbolic link", r.json["error"]) + start.assert_not_called() + self.assertFalse((target / "workspace.json").exists()) + finally: + linked.unlink() + runs, problem, status = web.execute.begin([], "../outside") + self.assertEqual((runs, status), ([], 400)) + self.assertIn("inside the workspaces folder", problem) + start.assert_not_called() + def test_a_single_run_opens_its_job_page_before_harbor_writes_the_job(self): r = self.post({"name": "tau3-x3", "script": "true", "where": "local", "jobs": [{"name": "tau3-x3", "agent": "oracle", "dataset": "tau3-x3"}]}) self.assertEqual(r.status_code, 200, r.get_data(as_text=True)); self.assertEqual(r.json["open"], "/job/tau3-x3") diff --git a/app/web/execute.py b/app/web/execute.py index a8158bd27..d2c868d10 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -200,6 +200,11 @@ def begin(plans: list, into: str = "") -> tuple: """Start ``plans``, each checked before any starts: (the runs, "", 200), or ([], why not, its status) and nothing started. ``into``: the workspace their jobs go into, the open one when empty (``shared.adopt_runs``).""" + if into: + dest = os.path.join(shared.WS_HOME, into) + home = os.path.realpath(shared.WS_HOME) + if os.path.islink(dest) or os.path.commonpath([home, os.path.realpath(dest)]) != home: + return [], "A launch workspace must be inside the workspaces folder and cannot be a symbolic link.", 400 for plan in plans: problem = plan.check() if problem: diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md index 7c860f980..f4cb35dcc 100644 --- a/docs/cli/recipes.md +++ b/docs/cli/recipes.md @@ -27,6 +27,7 @@ nullius recipes launch recipe.json --wait --json | --- | --- | | The server | `launch` needs `nullius serve` running here; `nullius standard run` runs without it ([Run a benchmark](run.md)) | | Refused | An error of the compile, a machine missing a prerequisite, the question without `--yes`, a Harbor recipe: nothing starts | +| Workspace path | Launch refuses a symbolic link or a destination outside the workspaces folder before starting | | The name | The recipe's name and the second, as each Run names a new job | | What it prints | `launch run:`, the launch's key; per run its machine, its state, its jobs folder and its job pages | | The result | `nullius runs show `: [Read jobs](read-jobs.md) | From 3ae315d05b436e7ab21293cb7f8e7790a9733e9d Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:05:30 +0100 Subject: [PATCH 09/13] fix(builder): resolve saved recipes by exact id and name --- app/nullius/recipes/cli.py | 12 ++++++++---- app/tests/test_recipes_cli.py | 36 ++++++++++++++++++++++++++++++++++- docs/cli/recipes.md | 2 +- 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/app/nullius/recipes/cli.py b/app/nullius/recipes/cli.py index d93c68fa5..9e6da474b 100644 --- a/app/nullius/recipes/cli.py +++ b/app/nullius/recipes/cli.py @@ -84,7 +84,7 @@ def default_server() -> str: def find(ref: str) -> dict: """The recipe ``ref`` names: a recipe file (one recipe, or a saved recipe's file), else a saved recipe by its - name, its id or its recipe's name. ``LookupError`` when there is none.""" + id, display name or internal name, in that order. ``LookupError`` when there is none.""" if os.path.isfile(ref): with open(ref, encoding="utf-8") as f: got = json.load(f) @@ -94,9 +94,13 @@ def find(ref: str) -> dict: if not isinstance(got, dict): raise Refused(f"{ref} holds no single recipe") return got - for item in store.listing(): - if ref in (item.get("id"), item.get("name"), item["recipe"].get("name")): - return item["recipe"] + items = store.listing() + for key in ("id", "name", "internal"): + matches = [item for item in items if ref == (item["recipe"].get("name") if key == "internal" else item.get(key))] + if len(matches) > 1: + raise Refused(f"ambiguous recipe {ref!r}: " + "; ".join(f"{x.get('name')!r} ({x.get('id')})" for x in matches)) + if matches: + return matches[0]["recipe"] raise LookupError(f"no saved recipe or recipe file {ref}") diff --git a/app/tests/test_recipes_cli.py b/app/tests/test_recipes_cli.py index 262ec019b..39582f17b 100644 --- a/app/tests/test_recipes_cli.py +++ b/app/tests/test_recipes_cli.py @@ -2,10 +2,44 @@ question ends the wait as an end does.""" from __future__ import annotations +import io +import os +import tempfile import unittest +from contextlib import redirect_stderr from unittest.mock import patch -from nullius.recipes import cli +from nullius.recipes import cli, store + + +class Selection(unittest.TestCase): + def test_exact_id_then_display_name_then_internal_name(self): + with tempfile.TemporaryDirectory() as home, patch.dict(os.environ, {"NULLIUS_HOME": home}), \ + patch.object(store.time, "strftime", side_effect=["2000-01-01", "2000-01-02", "2000-01-03"]): + first = store.save({"version": 1, "harness": "standard", "name": "quick-check", "title": "quick-check", "limit": 1}) + second = store.save({"version": 1, "harness": "standard", "name": "quick-check", "title": "Quick check", "limit": 2}) + third = store.save({"version": 1, "harness": "standard", "name": "other", "title": first["id"]}) + self.assertEqual(cli.find("quick-check"), first["recipe"]) + self.assertEqual(cli.find("Quick check"), second["recipe"]) + self.assertEqual(cli.find(first["id"]), first["recipe"]) + self.assertEqual(cli.find("other"), third["recipe"]) + + def test_ambiguity_at_any_step_lists_the_matches_and_launches_nothing(self): + for key in ("id", "name", "internal"): + items = [{"id": "a", "name": "First", "recipe": {"name": "first"}}, + {"id": "b", "name": "Second", "recipe": {"name": "second"}}] + for item in items: + if key == "internal": + item["recipe"]["name"] = "match" + else: + item[key] = "match" + with self.subTest(key=key), patch.object(store, "listing", return_value=items), \ + patch.object(cli, "Server") as server, redirect_stderr(io.StringIO()) as err: + self.assertEqual(cli.main(["launch", "match"]), 4) + self.assertIn("ambiguous recipe", err.getvalue()) + for item in items: + self.assertIn(f"{item['name']!r} ({item['id']})", err.getvalue()) + server.assert_not_called() class Scripted(cli.Server): diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md index f4cb35dcc..e3680767e 100644 --- a/docs/cli/recipes.md +++ b/docs/cli/recipes.md @@ -14,7 +14,7 @@ nullius recipes launch recipe.json --wait --json | Argument | Meaning | | --- | --- | -| `` | A saved recipe by its name or id ([Saved recipes](../builder.md#saved-recipes-and-drafts)), or a recipe file as the builder exports it | +| `` | A recipe file, or an exact saved id, display name, then internal name; ambiguous matches are listed and refused | | `--where MACHINE` | `local`, the server's machine, or a host's entry in Settings, in place of the recipe's *Where*; repeated, one shard each | | `--workspace NAME` | The workspace the launch goes into, made when there is none; the open workspace stays open. Default: the open one, as Run | | `--server URL` | The Nullius server on this machine (default `http://127.0.0.1:` and `APP_PORT`, else 5057) | From 1337df4db9f38a56095f5553b0047e571113486e Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:05:30 +0100 Subject: [PATCH 10/13] fix(builder): share the provider gate with recipe previews --- app/nullius/recipes/cli.py | 1 + app/tests/test_recipes_cli.py | 19 ++++++++++++++++++- app/ui_tests/test_agents.py | 21 +++++++++++++++++++++ app/web/builder.py | 3 ++- app/web/execute.py | 8 ++++++-- docs/cli/recipes.md | 2 +- 6 files changed, 49 insertions(+), 5 deletions(-) diff --git a/app/nullius/recipes/cli.py b/app/nullius/recipes/cli.py index 9e6da474b..2f35e858f 100644 --- a/app/nullius/recipes/cli.py +++ b/app/nullius/recipes/cli.py @@ -129,6 +129,7 @@ def review(server: Server, recipe: dict, where=None, into: str = "", yes: bool = for m in pre.get("machines") or [] for r in m.get("rows") or [] if r.get("state") == "missing"] why = ("A workspace's name is lowercase letters, digits and dashes." if into and workspace.slug(into) != into else " ".join(e.get("message", "") for e in out["errors"]) if out.get("errors") + else out["provider_error"] if out.get("provider_error") else f"Run asks first: {out['confirm']} --yes answers yes" if out.get("confirm") and not yes else "" if pre.get("ready") else "a machine lacks what the run needs: " + ("; ".join(lacks + list(pre.get("errors") or [])) or "see Review")) diff --git a/app/tests/test_recipes_cli.py b/app/tests/test_recipes_cli.py index 39582f17b..a29cf1588 100644 --- a/app/tests/test_recipes_cli.py +++ b/app/tests/test_recipes_cli.py @@ -3,10 +3,11 @@ from __future__ import annotations import io +import json import os import tempfile import unittest -from contextlib import redirect_stderr +from contextlib import redirect_stderr, redirect_stdout from unittest.mock import patch from nullius.recipes import cli, store @@ -42,6 +43,22 @@ def test_ambiguity_at_any_step_lists_the_matches_and_launches_nothing(self): server.assert_not_called() +class Review(unittest.TestCase): + def test_dry_run_uses_the_servers_provider_refusal(self): + for refusal, code in (("Set the provider key in Settings.", 4), ("", 0)): + answers = [(200, ''), + (200, json.dumps({"errors": [], "provider_error": refusal})), + (200, '{"machines": [], "ready": true}')] + with self.subTest(refusal=refusal), patch.object(cli, "find", return_value={"harness": "standard"}), \ + patch.object(cli.Server, "send", side_effect=answers) as send, \ + redirect_stdout(io.StringIO()) as out, redirect_stderr(io.StringIO()) as err: + self.assertEqual(cli.main(["launch", "saved", "--dry-run", "--json"]), code) + self.assertEqual(json.loads(out.getvalue())["refused"], refusal) + self.assertEqual(err.getvalue().strip(), refusal) + self.assertEqual([(c.args[0], c.args[1]) for c in send.call_args_list], + [("GET", "/new-run"), ("POST", "/new-run/runner"), ("POST", "/new-run/prerequisites")]) + + class Scripted(cli.Server): """A server whose ``GET /run/`` answers the states given for that run, one per call, the last one kept.""" def __init__(self, states): diff --git a/app/ui_tests/test_agents.py b/app/ui_tests/test_agents.py index f33dbcf12..4a1f7514c 100644 --- a/app/ui_tests/test_agents.py +++ b/app/ui_tests/test_agents.py @@ -501,6 +501,27 @@ def send(self, method, path, body=None): self.assertEqual(recipes.main(["launch", "nowhere", "--server", "http://localhost"]), 3) self.assertIn("--yes answers yes", err.getvalue()) self.assertEqual(self.started, []) + saved = store.save(self.recipe(name="missing-key", title="missing key", provider="openrouter")) + with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(recipes.main(["launch", "missing key", "--dry-run", "--json", "--server", "http://localhost"]), 4) + refused = self.post("/run", {"recipe": saved["recipe"]}) + self.assertEqual(refused.status_code, 400) + self.assertEqual(json.loads(out.getvalue())["refused"], refused.get_json()["error"]) + self.assertIn("OPENROUTER_API_KEY", json.loads(out.getvalue())["refused"]) + self.assertEqual(self.started, []) + + def test_review_and_run_allow_a_keyless_recipe_without_a_provider_key(self): + compiler = web.execute.standard_recipe + catalogue = compiler._all() + catalogue["benchmark"][0]["controls"] = {"nop": {"source": "nullius", "from": "Nothing runs."}} + recipe = self.recipe(other="nop", provider="openrouter", model="") + with patch.object(compiler, "_all", return_value=catalogue): + self.assertTrue(compiler.compile(recipe)["keyless"]) + review = self.post("/new-run/runner", {"recipe": recipe}).get_json() + self.assertEqual((review["errors"], review["provider_error"]), ([], "")) + run = self.post("/run", {"recipe": recipe}) + self.assertTrue(run.get_json()["ok"], run.get_json()) + self.assertTrue(self.started[0].keyless) class StandardPieces(unittest.TestCase): diff --git a/app/web/builder.py b/app/web/builder.py index ff63fd008..d28c52f93 100644 --- a/app/web/builder.py +++ b/app/web/builder.py @@ -230,7 +230,8 @@ def _standard_compile(recipe: dict) -> dict: out = standard_recipe.compile(recipe, docker_unusable=execute.docker_problem, boat_unusable=boat.unusable, boat_size_problem=execute.boat_size_problem, unpriced=execute.unpriced) # served_models: each model field's model as the run sends it, which Served by lists the providers of - return {k: out[k] for k in ("errors", "notes", "review", "jobs", "confirm", "served_models")} + return {**{k: out[k] for k in ("errors", "notes", "review", "jobs", "confirm", "served_models")}, + "provider_error": execute.standard_provider_problem(recipe, out) if not out["errors"] else ""} @app.route("/new-run/prerequisites", methods=["POST"]) diff --git a/app/web/execute.py b/app/web/execute.py index d2c868d10..3c536f316 100644 --- a/app/web/execute.py +++ b/app/web/execute.py @@ -136,8 +136,7 @@ def _start_standard(recipe: dict, into: str = ""): boat_size_problem=boat_size_problem, unpriced=unpriced) if out["errors"]: return jsonify(ok=False, error=" ".join(e["message"] for e in out["errors"])), 400 - # a run of controls calls no model: it is handed no key, so none need be set - missing = "" if out.get("keyless") else provider_problem(recipe.get("provider"), recipe.get("endpoint")) + missing = standard_provider_problem(recipe, out) if missing: return jsonify(ok=False, error=missing), 400 plans, problem = standard_plans(recipe, out, {h.entry for h in _hosts()}) @@ -152,6 +151,11 @@ def _start_standard(recipe: dict, into: str = ""): **started[0].summary()) +def standard_provider_problem(recipe: dict, out: dict) -> str: + """The provider refusal shared by Review and Run; a keyless run needs no provider key.""" + return "" if out.get("keyless") else provider_problem(recipe.get("provider"), recipe.get("endpoint")) + + _PRICED = {"at": float("-inf"), "rows": {}} diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md index e3680767e..d67235cf6 100644 --- a/docs/cli/recipes.md +++ b/docs/cli/recipes.md @@ -20,7 +20,7 @@ nullius recipes launch recipe.json --wait --json | `--server URL` | The Nullius server on this machine (default `http://127.0.0.1:` and `APP_PORT`, else 5057) | | `--yes` | Answers the question Run asks before a run of every unit | | `--wait` | Returns when the launch has ended, or paused on the question its page asks; exits 4 unless it ended done | -| `--dry-run` | Prints what the Review step shows and stops; exits 0 when Run would start it | +| `--dry-run` | Prints Review and checks Run's provider key requirement, including its keyless exemption; exits 0 when Run would start it | | `--json` | The server's answer as one document | | Rule | Detail | From 5bbea582d2a59fba1ff3ac36d9331eec4ac7ef34 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:05:30 +0100 Subject: [PATCH 11/13] fix(web): create launch workspaces as unopened --- app/nullius/workspace.py | 4 ++-- app/tests/test_workspace.py | 17 +++++++++++++++++ app/ui_tests/test_run_routes.py | 16 ++++++++++++++++ app/web/shared.py | 2 +- docs/cli/recipes.md | 2 +- 5 files changed, 37 insertions(+), 4 deletions(-) diff --git a/app/nullius/workspace.py b/app/nullius/workspace.py index 5479fd3a1..958ac364e 100644 --- a/app/nullius/workspace.py +++ b/app/nullius/workspace.py @@ -177,13 +177,13 @@ def _free(name: str, taken) -> str: return next(c for c in (f"{name[:NAME_MAX - len(str(i)) - 1].rstrip('-')}-{i}" for i in range(2, 1000)) if c not in taken) -def create(home_dir: str, roots, label: str = "") -> Workspace: +def create(home_dir: str, roots, label: str = "", *, opened: bool = True) -> Workspace: taken = {ws.name for ws in list_all(home_dir)} name = slug(label) name = _free(name, taken) if name else random_name(taken) now = _now() ws = Workspace(name=name, label=label.strip() or name, roots=list(roots), - created=now, opened=now, dir=os.path.join(home_dir, name)) + created=now, opened=now if opened else "", closed=not opened, dir=os.path.join(home_dir, name)) save(ws) return ws diff --git a/app/tests/test_workspace.py b/app/tests/test_workspace.py index ad8533950..a7ca94220 100644 --- a/app/tests/test_workspace.py +++ b/app/tests/test_workspace.py @@ -183,6 +183,23 @@ def test_last_open_is_the_latest_unless_the_user_closed_it(self): workspace.touch(b) self.assertEqual(workspace.last_open(self.home).name, "b") + def test_an_unopened_workspace_is_remembered_only_after_it_is_opened(self): + a = workspace.create(self.home, [], "destination", opened=False) + self.assertEqual((a.opened, a.closed), ("", True)) + self.assertIsNone(workspace.last_open(self.home)) + with patch.object(workspace, "_now", return_value="2000-01-01T00:00:00+00:00"): + b = workspace.create(self.home, [], "existing") + c = workspace.create(self.home, [], "another", opened=False) + self.assertEqual((workspace.load(self.home, c.name).opened, c.closed), ("", True)) + self.assertEqual(workspace.last_open(self.home).name, b.name) + b.closed = True + workspace.save(b) + self.assertIsNone(workspace.last_open(self.home)) + workspace.touch(a) + self.assertTrue(a.opened) + self.assertFalse(a.closed) + self.assertEqual(workspace.last_open(self.home).name, a.name) + class Holding(unittest.TestCase): def test_each_folder_lists_the_workspaces_with_a_root_in_it(self): diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index 3032a4681..2f1172fc0 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -426,6 +426,22 @@ def test_the_workspace_left_open_opens_again(self): self.root.rmdir() # roots gone: it opens as the open action does self.assertEqual(self.restart().roots, [str(self.root)]) + def test_a_launch_destination_does_not_replace_the_workspace_reopened(self): + with patch.object(workspace, "_now", return_value="2000-01-01T00:00:00+00:00"): + ws = workspace.create(self.home, [str(self.root)], label="existing") + web.shared.open_workspace(ws) + filed = [] + run = SimpleNamespace(jobs=str(self.tmp / "runs" / "launch" / "jobs"), file_under=filed.append) + web.shared.adopt_runs([run], "destination") + destination = workspace.load(self.home, "destination") + self.assertEqual((destination.opened, destination.closed), ("", True)) + self.assertEqual((destination.roots, filed), ([run.jobs], ["destination"])) + self.assertIs(web.shared.STATE["workspace"], ws) + self.assertEqual(self.restart().name, ws.name) + web.shared.open_workspace(destination) + self.assertTrue(workspace.load(self.home, destination.name).opened) + self.assertEqual(self.restart().name, destination.name) + def test_a_second_server_on_the_runs_folder_stops_with_one_line(self): refused = execution.Followed("another Nullius follows the runs in /r: stop it before starting this one") with patch.object(execution, "restore", side_effect=refused), self.assertRaises(SystemExit) as end: diff --git a/app/web/shared.py b/app/web/shared.py index 4d67b10d5..a297bd705 100644 --- a/app/web/shared.py +++ b/app/web/shared.py @@ -347,7 +347,7 @@ def adopt_runs(runs, into=""): them - ``into``, made under that name when there is none, the open one left as it is - each record naming it for a restart to put them back.""" if into and workspace.load(WS_HOME, into) is None: - workspace.create(WS_HOME, [], into) + workspace.create(WS_HOME, [], into, opened=False) ws = adopt_roots([ex.jobs for ex in runs], into=into) for ex in runs: ex.file_under(ws.name) diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md index d67235cf6..257a6b935 100644 --- a/docs/cli/recipes.md +++ b/docs/cli/recipes.md @@ -16,7 +16,7 @@ nullius recipes launch recipe.json --wait --json | --- | --- | | `` | A recipe file, or an exact saved id, display name, then internal name; ambiguous matches are listed and refused | | `--where MACHINE` | `local`, the server's machine, or a host's entry in Settings, in place of the recipe's *Where*; repeated, one shard each | -| `--workspace NAME` | The workspace the launch goes into, made when there is none; the open workspace stays open. Default: the open one, as Run | +| `--workspace NAME` | The launch destination, made unopened when missing; the open workspace still reopens after restart. Default: the open one, as Run | | `--server URL` | The Nullius server on this machine (default `http://127.0.0.1:` and `APP_PORT`, else 5057) | | `--yes` | Answers the question Run asks before a run of every unit | | `--wait` | Returns when the launch has ended, or paused on the question its page asks; exits 4 unless it ended done | From e46554ac065dc410d950c3ca93a2bee298157e7f Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:05:30 +0100 Subject: [PATCH 12/13] test(builder): exercise recipe launch waiting through the command --- app/tests/test_recipes_cli.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/app/tests/test_recipes_cli.py b/app/tests/test_recipes_cli.py index a29cf1588..b73b5ff97 100644 --- a/app/tests/test_recipes_cli.py +++ b/app/tests/test_recipes_cli.py @@ -66,6 +66,16 @@ def __init__(self, states): self.states, self.asked = {k: list(v) for k, v in states.items()}, [] def send(self, method, path, body=None): + if (method, path) == ("GET", "/new-run"): + return 200, '' + if (method, path) == ("POST", "/new-run/runner"): + return 200, '{"errors": []}' + if (method, path) == ("POST", "/new-run/prerequisites"): + return 200, '{"machines": [], "ready": true}' + if (method, path) == ("POST", "/run"): + return 200, json.dumps({"ok": True, "id": "a", "runs": [ + {"id": rid, "host": "local", "jobs": f"jobs/{rid}", "state": "preparing"} for rid in self.states]}) + assert method == "GET" and path.startswith("/run/"), (method, path) rid = path.rsplit("/", 1)[1] self.asked.append(rid) left = self.states[rid] @@ -74,6 +84,19 @@ def send(self, method, path, body=None): class Wait(unittest.TestCase): + def test_the_command_waits_and_prints_the_terminal_states_and_exit_code(self): + for state, code in (("done", 0), ("paused", 4), ("failed", 4), ("stopped", 4)): + server = Scripted({"a": ["preparing", "running", "done"], "b": ["running", state]}) + with self.subTest(state=state), patch.object(cli, "find", return_value={"harness": "standard", "name": "saved"}), \ + patch.object(cli, "Server", return_value=server), patch.object(cli.time, "sleep") as sleep, \ + redirect_stdout(io.StringIO()) as out: + result = cli.main(["launch", "saved", "--wait"]) + self.assertEqual(server.asked, ["a", "b", "a", "b", "a"]) + self.assertEqual(sleep.call_count, 2) + self.assertEqual(out.getvalue().splitlines(), ["launch run:a", "run a on local: done", " jobs jobs/a", + f"run b on local: {state}", " jobs jobs/b"]) + self.assertEqual(result, code) + def test_it_waits_until_no_run_is_going_and_a_pause_ends_it(self): server = Scripted({"a": ["preparing", "running", "done"], "b": ["running", "paused"]}) with patch.object(cli.time, "sleep", lambda s: None): From 12b1a399d6101680331ec508a3f5e4a58483ee97 Mon Sep 17 00:00:00 2001 From: Pierre Leca Date: Wed, 25 Nov 2026 12:05:57 +0100 Subject: [PATCH 13/13] docs(builder): keep the launch command's rows to what a reader acts on The fixes before this one make the earlier rows of --workspace and --dry-run true again: they come back as they were. The order in which a saved recipe is matched, and the check behind a refused workspace, are the code's; a reader needs only that a shared name and a linked workspace folder are refused. --- docs/cli/recipes.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/cli/recipes.md b/docs/cli/recipes.md index 257a6b935..a97b60001 100644 --- a/docs/cli/recipes.md +++ b/docs/cli/recipes.md @@ -14,20 +14,19 @@ nullius recipes launch recipe.json --wait --json | Argument | Meaning | | --- | --- | -| `` | A recipe file, or an exact saved id, display name, then internal name; ambiguous matches are listed and refused | +| `` | A saved recipe by its id or name ([Saved recipes](../builder.md#saved-recipes-and-drafts)), or a recipe file as the builder exports it; a name several share is refused | | `--where MACHINE` | `local`, the server's machine, or a host's entry in Settings, in place of the recipe's *Where*; repeated, one shard each | -| `--workspace NAME` | The launch destination, made unopened when missing; the open workspace still reopens after restart. Default: the open one, as Run | +| `--workspace NAME` | The workspace the launch goes into, made when there is none; the open workspace stays open. Default: the open one, as Run | | `--server URL` | The Nullius server on this machine (default `http://127.0.0.1:` and `APP_PORT`, else 5057) | | `--yes` | Answers the question Run asks before a run of every unit | | `--wait` | Returns when the launch has ended, or paused on the question its page asks; exits 4 unless it ended done | -| `--dry-run` | Prints Review and checks Run's provider key requirement, including its keyless exemption; exits 0 when Run would start it | +| `--dry-run` | Prints what the Review step shows and stops; exits 0 when Run would start it | | `--json` | The server's answer as one document | | Rule | Detail | | --- | --- | | The server | `launch` needs `nullius serve` running here; `nullius standard run` runs without it ([Run a benchmark](run.md)) | -| Refused | An error of the compile, a machine missing a prerequisite, the question without `--yes`, a Harbor recipe: nothing starts | -| Workspace path | Launch refuses a symbolic link or a destination outside the workspaces folder before starting | +| Refused | An error of the compile, a machine missing a prerequisite, the question without `--yes`, a Harbor recipe, a workspace folder that is a link: nothing starts | | The name | The recipe's name and the second, as each Run names a new job | | What it prints | `launch run:`, the launch's key; per run its machine, its state, its jobs folder and its job pages | | The result | `nullius runs show `: [Read jobs](read-jobs.md) |