diff --git a/orchestrator/client/runner.py b/orchestrator/client/runner.py index debfd05..a3e3135 100755 --- a/orchestrator/client/runner.py +++ b/orchestrator/client/runner.py @@ -13,12 +13,22 @@ --gates: the installed gates script, e.g. ~/.claude/skills/kvb-check-gate/scripts/gates.py; optional, gate changes need it. + --operator: the installed operator script, e.g. + ~/.claude/skills/kvb-org-operator/scripts/operator.py; optional, + without it no row closes done after exit 0. --once: handle the queued jobs once and exit. +Environment: + SHELL: the operator's shell, else the login shell of the runner's uid. + Returns: Runs as the operator, outside any sandbox, every operator command a - pinned passkey signed in the Agent Orchestrator: exactly the signed text, with bash - in the signed directory, each signature once and before its expiry. + pinned passkey signed in the Agent Orchestrator: exactly the signed + text, as `$SHELL -ic ` like `operator.py run`, in the signed + directory, each signature once and before its expiry. After exit 0 it + runs `operator.py checked ` the same way and reports whether the + row's check passes on this host; the hub keeps the row open unless it + does. Runs every signed task change (priority pin, status, dependency or WSJF estimate; a board batch is one job per change) as `python3 -I -B ` from / without a shell, after checking the @@ -45,6 +55,8 @@ import collections import contextlib import json import os +import pwd +import shlex import signal import stat import subprocess @@ -72,6 +84,7 @@ SAFE_PATH = "/usr/bin:/bin" TASK_JOB = "task" TASK_LIMIT = 30.0 GATE_JOB = "gate" +OPERATOR = "operator/" REFUSED = "refused: no valid operator signature for this command" UNREGISTERED = "refused: this runner was started without --rasci and --council; reinstall its unit with make orchestrator-runner" UNGATED = "refused: this runner was started without --gates; reinstall its unit with make orchestrator-runner" @@ -82,6 +95,12 @@ class Register(NamedTuple): council: Path +class Host(NamedTuple): + shell: str + operator: Path | None + council: Path | None + + def call(base: str, path: str, payload: dict | None) -> dict: headers = dict(hub_api.GUARD) data = None @@ -229,16 +248,44 @@ def council_refusal(council: Path) -> str | None: return None -def execute(job: dict, report: Callable[[dict], None]) -> int: +def checked(job: dict, host: Host) -> bool | None: """Args: - job: the claimed and verified job with command and directory. - report: called with {"output", "code", "refused"}; code None while - the command runs. + job: an operator command that exited 0, its task operator/. + host: the operator's shell, operator.py and council. Returns: - The exit code. + Whether the row's check passes on this host, from `operator.py + checked ` in the operator's shell as `operator.py run` sees it; + None without --operator, for a task whose slug signing.TASK does not + match, or when that call cannot tell. """ - return spawn(["bash", "-c", job["command"]], job["directory"], None, report) + task = job.get("task") + if host.operator is None or not isinstance(task, str) or not task.startswith(OPERATOR) or not signing.TASK.fullmatch(task.removeprefix(OPERATOR)): + return None + council = [f"AGENTS_COUNCIL_ROOT={host.council}"] if host.council else [] + command = shlex.join(["env", *council, sys.executable, "-I", "-B", str(host.operator), "checked", task.removeprefix(OPERATOR)]) + try: + code = subprocess.run([host.shell, "-ic", command], cwd="/", stdin=subprocess.DEVNULL, capture_output=True, timeout=TASK_LIMIT, check=False, start_new_session=True).returncode + except (OSError, subprocess.TimeoutExpired): + return None + return {0: True, 1: False}.get(code) + + +def execute(job: dict, host: Host, report: Callable[[dict], None]) -> int: + """Args: + job: the claimed and verified job with task, command and directory. + host: the operator's shell, operator.py and council. + report: called with {"output", "code", "refused"}; code None while + the command runs; after exit 0 also "checked" from checked(). + + Returns: + The exit code of `$SHELL -ic ` in the signed directory. + """ + + def final(result: dict) -> None: + report({**result, "checked": checked(job, host)} if result["code"] == 0 else result) + + return spawn([host.shell, "-ic", job["command"]], job["directory"], None, final) def change(job: dict, register: Register, report: Callable[[dict], None]) -> int: @@ -338,7 +385,7 @@ def sender(base: str, job_id: str) -> Callable[[dict], None]: return send -def cycle(base: str, trust: verifier.Trust, register: Register | None, gates: Path | None = None) -> None: +def cycle(base: str, trust: verifier.Trust, register: Register | None, gates: Path | None, host: Host) -> None: for job in call(base, "/api/runner/jobs", None)["jobs"]: try: claimed = call(base, f"/api/runner/{job['id']}/claim", {}) @@ -359,7 +406,7 @@ def cycle(base: str, trust: verifier.Trust, register: Register | None, gates: Pa elif kind == GATE_JOB: gate(claimed, gates, send) else: - execute(claimed, send) + execute(claimed, host, send) def main() -> int: @@ -371,11 +418,13 @@ def main() -> int: parser.add_argument("--rasci", type=Path) parser.add_argument("--council", type=Path) parser.add_argument("--gates", type=Path) + parser.add_argument("--operator", type=Path) parser.add_argument("--once", action="store_true") args = parser.parse_args() base = hub_api.base_url(args.port) trust = verifier.Trust(approvers=args.approvers, replay=args.replay, origin=signing.origin_of(args.port)) register = Register(rasci=args.rasci, council=args.council) if args.rasci and args.council else None + host = Host(shell=os.environ.get("SHELL") or pwd.getpwuid(os.geteuid()).pw_shell, operator=args.operator, council=args.council) rules, told = staged_diff.rules_root(), "" while True: try: @@ -386,7 +435,7 @@ def main() -> int: print(f"runner: no merge previews: {error}", file=sys.stderr) told = str(error) try: - cycle(base, trust, register, args.gates) + cycle(base, trust, register, args.gates, host) except (OSError, ValueError, KeyError, TypeError): pass if args.once: diff --git a/orchestrator/kvb_orchestrator/jobs.py b/orchestrator/kvb_orchestrator/jobs.py index 8ad17f1..5ef56c3 100644 --- a/orchestrator/kvb_orchestrator/jobs.py +++ b/orchestrator/kvb_orchestrator/jobs.py @@ -14,7 +14,6 @@ CONSOLE = ("id", "status", "code", "output", "created_ts", "started", "finished" TASK_JOB = "task" GATE_JOB = "gate" CHANGES = (TASK_JOB, GATE_JOB) -USAGE = 2 def runner_job(job: dict) -> dict: @@ -79,11 +78,19 @@ class Jobs: return runner_job(job) def report(self, job_id: str, body: bytes) -> dict: + """Args: + body: {"output", "code", "refused"}, and "checked" on an operator + command's final report after exit 0: whether its row's check + passed on the host, null when the runner could not tell. + """ payload = decode(body) - expect(payload, ("output", "code", "refused")) + expect(payload, ("output", "code", "refused", "checked") if "checked" in payload else ("output", "code", "refused")) output, code, refused = bounded(payload, "output", RUN_OUTPUT), payload["code"], payload["refused"] + checked = payload.get("checked") if not isinstance(refused, bool) or (code is not None and (isinstance(code, bool) or not isinstance(code, int))): raise ToolError("code must be a whole number or null and refused true or false") + if checked is not None and not isinstance(checked, bool): + raise ToolError("checked must be true, false or null") record = self.jobs.get(job_id) if record is None: raise Missing(job_id) @@ -96,18 +103,23 @@ class Jobs: job, changed = self.jobs.transition(job_id, "running", {"status": status, "code": code, "output": output, "finished": time.time()}) if not changed: raise Conflict({"id": job_id, "status": job["status"]}) - runs = self.close_row(job, status, code) + runs = self.close_row(job, status, code, checked is True) tail = "\n".join(output.splitlines()[-20:]) self.log.add({"kind": "run", "title": f"{status}: {job['command'][:200]}", "text": tail, "ref": {"job": job_id, "task": job["task"], "code": code, "status": status}}) told = self.tell_applied(job) if job.get("kind") == TASK_JOB else [] return {"id": job_id, "status": status, "code": code, "runs": runs, "told": told} - def close_row(self, job: dict, status: str, code: int | None) -> list[dict]: - """Returns: + def close_row(self, job: dict, status: str, code: int | None, checked: bool) -> list[dict]: + """Args: + checked: whether the runner saw the row's check pass on the host + after exit 0; the hub cannot read the host's repos, PATH and + installed dirs itself. + + Returns: The operator.py runs that report the end of an operator command - job on its row: `ran` on exit 0, then an older operator.py's - `done` when `ran` is its usage error; `failed` on any other exit; - none for a refused job or a task or gate change. + job on its row: `ran` on exit 0, with --check-failed unless + checked, so the row stays open; `failed` on any other exit; none + for a refused job or a task or gate change. """ if job.get("kind") in CHANGES or status not in ("done", "failed"): return [] @@ -116,7 +128,4 @@ class Jobs: if status == "failed": why = f"killed by signal {-code}" if code < 0 else f"exit {code}" return [self.scripts.run(OPERATOR_SCRIPT, ["failed", *shown, "--why", why])] - runs = [self.scripts.run(OPERATOR_SCRIPT, ["ran", *shown])] - if runs[0]["code"] == USAGE: - runs.append(self.scripts.run(OPERATOR_SCRIPT, ["done", slug])) - return runs + return [self.scripts.run(OPERATOR_SCRIPT, ["ran", *shown] if checked else ["ran", *shown, "--check-failed"])] diff --git a/orchestrator/systemd/kvb-orchestrator-runner.service b/orchestrator/systemd/kvb-orchestrator-runner.service index 9ae0159..57a0bae 100644 --- a/orchestrator/systemd/kvb-orchestrator-runner.service +++ b/orchestrator/systemd/kvb-orchestrator-runner.service @@ -5,7 +5,7 @@ Description=Agent Orchestrator runner: runs the operator commands a pinned passk Type=simple Environment=PATH=/usr/bin:/bin EnvironmentFile=%h/.local/share/kvb-orchestrator/.env -ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/runner.py --port ${KVB_ORCHESTRATOR_PORT} --interval 2 --approvers %h/.config/kvb-orchestrator/approvers.json --replay %h/.local/state/kvb-orchestrator-approvals/runner.json --rasci %h/.claude/skills/kvb-org-rasci/scripts/rasci.py --council ${KVB_ORCHESTRATOR_COUNCIL} --gates %h/.claude/skills/kvb-check-gate/scripts/gates.py +ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/runner.py --port ${KVB_ORCHESTRATOR_PORT} --interval 2 --approvers %h/.config/kvb-orchestrator/approvers.json --replay %h/.local/state/kvb-orchestrator-approvals/runner.json --rasci %h/.claude/skills/kvb-org-rasci/scripts/rasci.py --council ${KVB_ORCHESTRATOR_COUNCIL} --gates %h/.claude/skills/kvb-check-gate/scripts/gates.py --operator %h/.claude/skills/kvb-org-operator/scripts/operator.py Restart=always RestartSec=5 diff --git a/skills/kvb-org-operator/run.md b/skills/kvb-org-operator/run.md index dbf75db..68e4749 100644 --- a/skills/kvb-org-operator/run.md +++ b/skills/kvb-org-operator/run.md @@ -36,7 +36,9 @@ check passed ()"), or `done` ("... marked done by "). `add` under the same slug reopens the row and clears `cancelled` and `failed`. -The hub's runner reports through `ran` and `failed`, as the same calls: -exit 0 closes the row from any status but done, whatever its check; exit -130 and signals count as failures. Any agent of the same user can forge `ran`, `failed` or +The hub's runner runs the command as `$SHELL -ic` too and reports through +`ran` and `failed`, as the same calls: after exit 0 it runs `checked` on +the host, and the row closes from any status but done only when that +passes; otherwise `ran --check-failed` keeps it open. Exit 130 and signals +count as failures. Any agent of the same user can forge `ran`, `failed` or `done`: the register and the radio are writable by every agent already. diff --git a/skills/kvb-org-operator/scripts/operator.py b/skills/kvb-org-operator/scripts/operator.py index 74ffdf5..25f8108 100755 --- a/skills/kvb-org-operator/scripts/operator.py +++ b/skills/kvb-org-operator/scripts/operator.py @@ -85,11 +85,14 @@ Args: done [--session ]: mark a row done, whatever its check, with a message unless it was done; a stale `failed` or `cancelled` goes as in ran. Without a session the caller is Operator. - ran --command "" --dir : the hub's report of a job - that exited 0: the row set done from every status but done and - whatever its check, which the hub cannot run without the host's - repos, PATH and installed dirs; a stale `failed` or `cancelled` - goes. + ran --command "" --dir [--check-failed]: the hub's + report of a job that exited 0: the row set done from every status + but done, or with --check-failed (the runner's `checked` on the host + did not pass) kept open with a message like run's; a stale `failed` + or `cancelled` goes. + checked : exit 0 when the row's check passes here as run would + close it, 1 when it does not, 2 for a slug the register lacks; the + hub's runner calls it on the host after a job's exit 0. failed --why "" --command "" --dir : the hub's report of a job that failed: the row set stopped with why and no output lines under `failed`, sent as a message like a failure in run. @@ -792,11 +795,20 @@ def settle(rasci: ModuleType, row: dict, status: str | None, fields: dict, statu return addressees(holders, None) -def succeeded(rasci: ModuleType, row: dict, hub: bool) -> str: +def holds(row: dict) -> bool: + """Returns: + Whether the row's check passes here; manual and an unreadable check + pass at once. + """ + check = "manual" if problem(row["check"]) else row["check"] + return check == "manual" or passed(check) + + +def succeeded(rasci: ModuleType, row: dict, hub: bool, complete: bool) -> str: """Args: - hub: the hub's report: the row closes whatever its check and from - every status but done; else only while open and once its check - passes (manual: at once). + hub: the hub's report: the row closes from every status but done; + else only while open. + complete: whether its check passed where the command ran. Returns: What an exit 0 did: the row as shown set done, or kept open while @@ -806,7 +818,6 @@ def succeeded(rasci: ModuleType, row: dict, hub: bool) -> str: """ name = visible(row["task"], "") check = "manual" if problem(row["check"]) else row["check"] - complete = hub or check == "manual" or passed(check) statuses = tuple(status for status in rasci.STATUSES if status != "done") if hub else OPEN agents = settle(rasci, row, "done" if complete else None, {}, statuses) if agents is None: @@ -1065,7 +1076,7 @@ def cmd_run(rasci: ModuleType, args: argparse.Namespace) -> int: elif code != 0: print(failure(rasci, row, f"exit {code}", shared(lines, typed))) else: - print(succeeded(rasci, row, False)) + print(succeeded(rasci, row, False, holds(row))) return 0 @@ -1097,10 +1108,22 @@ def ran_row(rasci: ModuleType, args: argparse.Namespace) -> dict: def cmd_ran(rasci: ModuleType, args: argparse.Namespace) -> int: - print(succeeded(rasci, ran_row(rasci, args), True)) + print(succeeded(rasci, ran_row(rasci, args), True, not args.check_failed)) return 0 +def cmd_checked(rasci: ModuleType, args: argparse.Namespace) -> int: + """Returns: + 0 when the row's check passes here, the way run closes a row after + exit 0; 1 when it does not; exit 2 for a task the register lacks. + """ + task = task_of(rasci, args.slug) + entry = rasci.load().get(task) + if entry is None: + fail(f"{task}: not in the register") + return 0 if holds({"check": entry.get("check") or "manual"}) else 1 + + def cmd_failed(rasci: ModuleType, args: argparse.Namespace) -> int: why = visible(" ".join(args.why.split()), "") if not why: @@ -1142,6 +1165,11 @@ def main() -> int: for flag in flags: p.add_argument(flag, required=True) p.set_defaults(func=func) + if name == "ran": + p.add_argument("--check-failed", action="store_true") + p = sub.add_parser("checked") + p.add_argument("slug") + p.set_defaults(func=cmd_checked) args = parser.parse_args() return args.func(module("rasci", RASCI), args) diff --git a/tests/hub_case.py b/tests/hub_case.py index 4bf4ed5..6131adb 100644 --- a/tests/hub_case.py +++ b/tests/hub_case.py @@ -19,6 +19,8 @@ from hub_support import ( GIT_ENV, HOST_STATE, HUB, + LOGIN_SHELL, + OPERATOR, OPTIONS, PAGE, RASCI, @@ -53,8 +55,11 @@ class HubCase(unittest.TestCase): self.offices = base / "state" / "offices" self.approvers = base / "config" / "approvers.json" self.replay = base / "replay" + self.shell = base / "login-shell" for path in (self.pages, self.state, self.outside, self.projects, self.tree_file.parent, self.timers, self.kept): path.mkdir() + self.shell.write_text(LOGIN_SHELL, encoding="utf-8") + self.shell.chmod(0o755) silence = mock.patch.object(server.Handler, "log_message") silence.start() self.addCleanup(silence.stop) @@ -198,8 +203,8 @@ class HubCase(unittest.TestCase): def run_runner(self, register: bool = True, council: Path | None = None) -> None: trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json")] flags = ["--rasci", str(RASCI), "--council", str(council or self.council)] if register else [] - command = [sys.executable, str(RUNNER), "--port", str(self.port), "--interval", "0.1", *trust, *flags, "--once"] - done = subprocess.run(command, capture_output=True, text=True, timeout=60, check=False) + command = [sys.executable, str(RUNNER), "--port", str(self.port), "--interval", "0.1", *trust, *flags, "--operator", str(OPERATOR), "--once"] + done = subprocess.run(command, capture_output=True, text=True, timeout=60, check=False, env={**os.environ, "SHELL": str(self.shell), "AGENTS_COUNCIL_ROOT": str(council or self.council)}) self.assertEqual(done.returncode, 0, done.stderr) def settle(self, check: Callable[[], bool]) -> None: diff --git a/tests/hub_support.py b/tests/hub_support.py index 47daea0..9ae425b 100644 --- a/tests/hub_support.py +++ b/tests/hub_support.py @@ -24,6 +24,8 @@ CLIENT = HUB / "client" / "permission_hook.py" RUNNER = HUB / "client" / "runner.py" APPROVAL = HUB / "client" / "approval.py" RASCI = REPO_ROOT / "skills" / "kvb-org-rasci" / "scripts" / "rasci.py" +OPERATOR = REPO_ROOT / "skills" / "kvb-org-operator" / "scripts" / "operator.py" +LOGIN_SHELL = '#!/bin/sh\n[ "$1" = -ic ] || exit 97\nexec /bin/sh -c "$2"\n' SPEC = importlib.util.spec_from_file_location("kvb_orchestrator_server", HUB / "server.py") server = importlib.util.module_from_spec(SPEC) sys.modules[SPEC.name] = server diff --git a/tests/test_hub_console.py b/tests/test_hub_console.py index 4de2b6f..271c232 100644 --- a/tests/test_hub_console.py +++ b/tests/test_hub_console.py @@ -107,47 +107,48 @@ class TestHubConsole(HubCase): fields = {"task": "operator/greet", "command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "status": "running", "proof": None} jobs = [ self.httpd.hub.jobs.add({**fields, **extra, "code": None, "output": "", "created_ts": time.time(), "started": time.time(), "finished": None, "dismissed": False}) - for extra in ({}, {}, {}, {}, {}, {"kind": "gate", "argv": []}) + for extra in ({}, {}, {}, {}, {}, {}, {}, {"kind": "gate", "argv": []}) ] reports = ( - {"output": "token-42\n", "code": 0, "refused": False}, {"output": "token-42\n", "code": 3, "refused": False}, + {"output": "token-42\n", "code": 0, "refused": False, "checked": True}, {"output": "", "code": 0, "refused": False, "checked": False}, + {"output": "", "code": 0, "refused": False}, {"output": "token-42\n", "code": 3, "refused": False}, {"output": "", "code": -9, "refused": False}, {"output": "", "code": 130, "refused": False}, {"output": "token-42\n", "code": None, "refused": True}, {"output": "", "code": 1, "refused": False}, ) answers = [self.runner(f"/api/runner/{job['id']}/report", report) for job, report in zip(jobs, reports)] self.assertEqual([(status, body["status"], len(body["runs"])) for status, body in answers], [ - (200, "done", 1), (200, "failed", 1), (200, "failed", 1), (200, "failed", 1), (200, "refused", 0), (200, "failed", 0), + (200, "done", 1), (200, "done", 1), (200, "done", 1), (200, "failed", 1), (200, "failed", 1), (200, "failed", 1), (200, "refused", 0), (200, "failed", 0), ]) shown = ["greet", f"--command={COMMAND}", f"--dir={self.outside}"] self.assertEqual(self.scripts.calls, [ (skill_scripts.OPERATOR_SCRIPT, ["ran", *shown]), + (skill_scripts.OPERATOR_SCRIPT, ["ran", *shown, "--check-failed"]), + (skill_scripts.OPERATOR_SCRIPT, ["ran", *shown, "--check-failed"]), (skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", "exit 3"]), (skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", "killed by signal 9"]), (skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", "exit 130"]), ]) self.assertNotIn("token-42", json.dumps(self.scripts.calls)) - def test_an_older_installed_operator_without_ran_still_closes_the_row_through_done(self): + def test_a_ran_the_installed_operator_refuses_never_falls_back_to_done(self): self.register("queued") fields = {"task": "operator/greet", "command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "status": "running", "proof": None} - jobs = [ - self.httpd.hub.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": time.time(), "finished": None, "dismissed": False}) - for _ in range(2) - ] - self.scripts.code = 2 - done = self.runner(f"/api/runner/{jobs[0]['id']}/report", {"output": "", "code": 0, "refused": False})[1] - failed = self.runner(f"/api/runner/{jobs[1]['id']}/report", {"output": "", "code": 1, "refused": False})[1] - shown = ["greet", f"--command={COMMAND}", f"--dir={self.outside}"] - self.assertEqual(self.scripts.calls, [ - (skill_scripts.OPERATOR_SCRIPT, ["ran", *shown]), - (skill_scripts.OPERATOR_SCRIPT, ["done", "greet"]), - (skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", "exit 1"]), - ]) - self.assertEqual((len(done["runs"]), len(failed["runs"])), (2, 1)) - self.scripts.code = 1 job = self.httpd.hub.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": time.time(), "finished": None, "dismissed": False}) - self.runner(f"/api/runner/{job['id']}/report", {"output": "", "code": 0, "refused": False}) - self.assertEqual(self.scripts.calls[-1], (skill_scripts.OPERATOR_SCRIPT, ["ran", *shown])) + self.scripts.code = 2 + done = self.runner(f"/api/runner/{job['id']}/report", {"output": "", "code": 0, "refused": False, "checked": False})[1] + shown = ["greet", f"--command={COMMAND}", f"--dir={self.outside}"] + self.assertEqual(self.scripts.calls, [(skill_scripts.OPERATOR_SCRIPT, ["ran", *shown, "--check-failed"])]) + self.assertEqual(len(done["runs"]), 1) + + def test_a_report_with_a_checked_other_than_true_false_or_null_is_refused(self): + self.register("queued") + fields = {"task": "operator/greet", "command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "status": "running", "proof": None} + job = self.httpd.hub.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": time.time(), "finished": None, "dismissed": False}) + for checked in ("yes", 1, [True]): + with self.subTest(checked=checked): + self.assertEqual(self.runner(f"/api/runner/{job['id']}/report", {"output": "", "code": 0, "refused": False, "checked": checked})[0], 400) + self.assertEqual(self.runner(f"/api/runner/{job['id']}/report", {"output": "", "code": 0, "refused": False, "checked": None})[1]["status"], "done") + self.assertEqual(self.scripts.calls[-1][1][-1], "--check-failed") def test_jobs_from_before_the_console_stay_out_of_the_inbox(self): self.register("done") diff --git a/tests/test_hub_executors.py b/tests/test_hub_executors.py index aa87bba..2e8b0c3 100644 --- a/tests/test_hub_executors.py +++ b/tests/test_hub_executors.py @@ -107,22 +107,54 @@ class TestHubExecutors(HubCase): self.approvers.unlink() job = {"task": "operator/greet", "command": command, "directory": str(self.outside), "proof": proof} self.assertIn("no key is pinned", runner.refusal(job, self.trust("other"), time.time())) - reports = [] - self.assertEqual(runner.execute({"command": "exit 3", "directory": str(self.outside)}, reports.append), 3) + reports, host = [], runner.Host(shell=str(self.shell), operator=None, council=None) + self.assertEqual(runner.execute({"command": "exit 3", "directory": str(self.outside)}, host, reports.append), 3) self.assertEqual(reports[-1], {"output": "", "code": 3, "refused": False}) + self.assertEqual(runner.execute({"command": "true", "directory": str(self.outside)}, host, reports.append), 0) + self.assertEqual(reports[-1], {"output": "", "code": 0, "refused": False, "checked": None}) + self.assertEqual(runner.execute({"command": "true", "directory": str(self.outside)}, host._replace(shell=str(self.outside)), reports.append), 127) + + def test_the_runner_keeps_a_row_open_whose_check_fails_on_the_host_after_exit_0(self): + command = "echo pushed" + register = {"operator/push": {"title": command, "workdir": str(self.outside), "description": "push", "check": f"absent:{self.outside}", "status": "queued", "roles": {}}} + self.write_council({"rasci.json": register}) + digest = hashlib.sha256(command.encode()).hexdigest() + signer = self.pin() + push = [self.entry("operator", "operator/push", "", digest)] + with mock.patch.object(batches, "UNDO", 0.05): + self.assertEqual(self.approve(push, self.signed(push, signer))[0], 202) + self.settle(lambda: self.runner_jobs() != []) + self.run_runner() + job = self.snapshot()["jobs"][-1] + self.assertEqual((job["status"], job["code"], job["output"]), ("done", 0, "pushed\n")) + self.assertEqual(self.scripts.calls[-1], (skill_scripts.OPERATOR_SCRIPT, ["ran", "push", f"--command={command}", f"--dir={self.outside}", "--check-failed"])) + host = runner.Host(shell=str(self.shell), operator=hub_support.OPERATOR, council=self.council) + self.assertIs(runner.checked({"task": "operator/push"}, host), False) + self.assertIsNone(runner.checked({"task": "operator/missing"}, host)) + self.assertIsNone(runner.checked({"task": "operator/push"}, host._replace(shell=str(self.outside / "no-shell")))) + marking = self.outside / "marking-shell" + marking.write_text('#!/bin/sh\ntouch "$0.ran"\n', encoding="utf-8") + marking.chmod(0o700) + for task in ("operator/x\\'\"; id #", "operator/Push", "review/push", "push", None): + with self.subTest(task=task): + self.assertIsNone(runner.checked({"task": task}, host._replace(shell=str(marking)))) + self.assertFalse(marking.with_name("marking-shell.ran").exists()) + self.write_council({"rasci.json": {"operator/push": {**register["operator/push"], "check": "manual"}}}) + self.assertIs(runner.checked({"task": "operator/push"}, host), True) def test_the_runner_closes_the_output_pipe_on_every_path(self): popen, spawned = subprocess.Popen, [] job = {"command": "echo hi; sleep 0.3", "directory": str(self.outside)} + host = runner.Host(shell=str(self.shell), operator=None, council=None) def spawn(*args: object, **kwargs: object) -> subprocess.Popen: spawned.append(popen(*args, **kwargs)) return spawned[-1] with mock.patch.object(subprocess, "Popen", spawn), mock.patch.object(runner, "BEAT", 0.05): - self.assertEqual(runner.execute(job, [].append), 0) + self.assertEqual(runner.execute(job, host, [].append), 0) self.assertTrue(spawned[0].stdout.closed) - self.assertRaises(RuntimeError, runner.execute, job, mock.Mock(side_effect=RuntimeError("the hub is gone"))) + self.assertRaises(RuntimeError, runner.execute, job, host, mock.Mock(side_effect=RuntimeError("the hub is gone"))) self.settle(lambda: spawned[1].stdout.closed) self.assertEqual(spawned[1].wait(10), 0) diff --git a/tests/test_operator.py b/tests/test_operator.py index b3c48d1..faa770b 100644 --- a/tests/test_operator.py +++ b/tests/test_operator.py @@ -1016,6 +1016,20 @@ class TestOperator(unittest.TestCase): with self.subTest(args=args): self.assertEqual(self._as(None, *args).returncode, 2) + def test_checked_answers_the_host_check_and_ran_with_check_failed_keeps_the_row_open(self): + self._add("open", self.base, "true", "r", f"absent:{self.base}") + self._add("gone", self.base, "true", "r", f"absent:{self.base / 'nothing'}") + self._add("man", self.base, "true", "r", "manual") + codes = {slug: self._as(None, "checked", slug).returncode for slug in ("open", "gone", "man", "missing")} + self.assertEqual(codes, {"open": 1, "gone": 0, "man": 0, "missing": 2}) + shown = ("--command", "true", "--dir", str(self.base)) + kept = self._as(None, "ran", "open", *shown, "--check-failed") + self.assertEqual(kept.returncode, 0, kept.stderr) + self.assertIn(f"but absent:{self.base} does not pass yet; the row stays open", kept.stdout) + self.assertIn("operator/open", self._open()) + self.assertEqual(self._as(None, "ran", "open", *shown).returncode, 0) + self.assertNotIn("operator/open", self._open()) + def test_the_hub_runner_calls_the_stored_session_with_ran_and_failed_even_when_its_channel_says_post(self): radio = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py" chosen = subprocess.run([sys.executable, str(radio), "feedback", "set", "post"], capture_output=True, text=True, env=self.env, check=False) @@ -1031,7 +1045,7 @@ class TestOperator(unittest.TestCase): "from kvb_orchestrator.jobs import Jobs\n" "from kvb_orchestrator.skill_scripts import Scripts\n" "hub = types.SimpleNamespace(scripts=Scripts(Path(sys.argv[2]), Path(sys.argv[3]), Path(sys.argv[4])))\n" - "print(json.dumps([Jobs.close_row(hub, job, status, code) for job, status, code in json.loads(sys.argv[5])]))\n" + "print(json.dumps([Jobs.close_row(hub, job, status, code, True) for job, status, code in json.loads(sys.argv[5])]))\n" ) jobs = [ [{"task": "operator/go", "command": "true", "directory": str(self.base)}, "done", 0],