diff --git a/.claude/rules/running.md b/.claude/rules/running.md index a1c0187c4..b4e9f8999 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`, 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/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..2f35e858f --- /dev/null +++ b/app/nullius/recipes/cli.py @@ -0,0 +1,263 @@ +"""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 | --dry-run] [--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. ``--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 (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 + +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, workspace +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 + 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) + 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 + 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}") + + +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") + 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}) + 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 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")) + 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=seen.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 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: + 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 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 + 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()) + 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] + 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 _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") + 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") + 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) + + +if __name__ == "__main__": + sys.exit(main()) 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/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/app/tests/test_recipes_cli.py b/app/tests/test_recipes_cli.py new file mode 100644 index 000000000..b73b5ff97 --- /dev/null +++ b/app/tests/test_recipes_cli.py @@ -0,0 +1,117 @@ +"""`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 io +import json +import os +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout +from unittest.mock import patch + +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 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): + super().__init__("http://localhost") + 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] + 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_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): + 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/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/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_agents.py b/app/ui_tests/test_agents.py index 66833375f..4a1f7514c 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)) @@ -451,6 +451,78 @@ 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. --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 + 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"], "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 + 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 + 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, []) + 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): """What the pages say of the standard beyond a pair: an agent's options, @@ -469,7 +541,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..2f1172fc0 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) @@ -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") @@ -400,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: @@ -518,6 +560,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", "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"], "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."})) + 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/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 7cc557dfe..3c536f316 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,32 +126,36 @@ 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, 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()}) 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], **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": {}} @@ -190,9 +200,15 @@ 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``).""" + 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: @@ -204,12 +220,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..a297bd705 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, 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/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..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` | +| 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/pages.md b/docs/cli/pages.md index 7caed9c28..8567d1751 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 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 @@ -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..a97b60001 --- /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 | --dry-run] [--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 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 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 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, 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) | + +
+ +- [Run builder](../builder.md) + + The recipe and its Run. + +- [Pages from a shell](pages.md) + + The other pages' commands. + +