diff --git a/README.md b/README.md index 9dc5dd0..950e9f0 100644 --- a/README.md +++ b/README.md @@ -474,7 +474,7 @@ The hub page loads nothing from the network: its icons come from Bootstrap Icons The Agents view "Hierarchy" draws the council's formal offices as a collapsible organigram: the Operator above the chair; in line under the chair one unit per dimension with its domain chairs (`/`) and one for the presidents (`work/`); beside the chair, on a side branch, the staff positions: organisers (`cluster/`) and single-segment offices such as `stack-architecture`. Each box shows the office and its holder, so an agent with several offices appears in each of them. A dashed line marks an additional superior, read live from the `kvb-org-rasci` register: an open task whose R (or worker) holds an office and that names another office holder A or C links that holder's first office to the agent's office for the task (the office or claimed work named like the task, else the agent's first office); the chair adds none, its solid line already runs there. On a narrow screen the chart scrolls inside its own frame, never the page. The chair in every graph is the holder of the `chair` office, not a fixed name. Appointing, handing over or recalling an office there asks for the passkey signature; the hub writes a job (office, signed holder, successor session, work; no command) into `~/.local/state/kvb-orchestrator/offices/jobs`, and the `kvb-orchestrator-offices.path` user unit runs `client/offices.py` on the host, which verifies the signature, refuses a council directory others can write, a link on the path or a holder that changed since the signature. For a takeover or recall it moves the office aside and removes it only while the claim there still names the signed holder; an appoint or takeover then runs a plain `council.py claim ` for the successor by argv. council.py itself has no flag that overrides a live holder. The same view holds the operator's agent order as a drag list with up and down buttons: `rasci.py agents order` stores it in `agent-order.json` beside the register, where it breaks ties of equal task priority and orders the chair's grants without touching any task's `--prio` pin. -The Tasks tab (key 4, `#tasks/list`, `#tasks/board`, `#tasks/rasci`) shows the `kvb-org-rasci` register as a list, a board by status and a RASCI matrix; queue jobs from `council/queue.json` appear as "waiting for a grant", and the filter "Waits on Operator" is the inbox, which the Inbox entry under Stream opens: every pending review, ask, rule request, operator row and choice card, with no Choices column of its own. The Tasks toolbar is one row that wraps on narrow screens (views, filter, estimation, sort and business value, trend on the burn view), the status chips the second; every list row shows its ETA, and `#tasks/3d` draws the tasks and their dependencies on the 3D engine. Its "Request choices" dropdown has one button per channel, post and call to the agents ticked in it, newsletter, broadcast, pan-pan, Sécurité and mayday to all, that sends the fixed request "send me your open decisions as choices" without a text field, one passkey assertion over every recipient (`/api/choices/sign`, then `/api/choices`). Agents answer with `decision_request`, shown as choice cards, and a click on an option is the passkey-signed answer: after the 3 s undo the hub verifies the signature and posts the answer to the asking agent, whose `decision_wait` returns it as `message` and `answer` for `operator_message`. A task's sheet pins its priority (`rasci.py set --prio `) or sets and drops the operator's WSJF estimate (`rasci.py estimate Operator --value --complexity ` or `--drop`) after a passkey signature; the hub writes an argv-only job, and the runner, started with `--rasci --council `, verifies it like an operator command and runs `rasci.py` from `/` without a shell, killing it after 30 s. Agent order stays untouched. The install copies the fresh runner unit and restarts the runner when it is enabled, and only while the installed `council.py`, `nofollow.py` and `rasci.py` match this tree: otherwise it disables the runner and asks for `make install`. The runner unit pins `PATH` to `/usr/bin:/bin`, so a signed command names any other program by its full path; a runner started without `--rasci` and `--council` keeps running signed commands and refuses task changes, and so does one whose council is a symlink or another uid's. Each worktree in the tree file may carry `"flow": {"pull": [...], "push": [...], "source": "file"}` or `null`, which the Tree, the Chord edges, the detail panel and the matching task show; a malformed flow shows as `invalid`. Worktrees and tasks with open work (uncommitted, unpushed, unmerged, task not done) carry a warning bar. +The Tasks tab (key 4, `#tasks/list`, `#tasks/board`, `#tasks/rasci`) shows the `kvb-org-rasci` register as a list, a board by status and a RASCI matrix; queue jobs from `council/queue.json` appear as "waiting for a grant", and the filter "Waits on Operator" is the inbox, which the Inbox entry under Stream opens: every pending review, ask, rule request, operator row and choice card, with no Choices column of its own. The Tasks toolbar is one row that wraps on narrow screens (views, filter, estimation, sort and business value, trend on the burn view), the status chips the second; every list row shows its ETA, and `#tasks/3d` draws the tasks and their dependencies on the 3D engine. Its "Request choices" dropdown has one button per channel, post and call to the agents ticked in it, newsletter, broadcast, pan-pan, Sécurité and mayday to all, that sends the fixed request "send me your open decisions as choices" without a text field, one passkey assertion over every recipient (`/api/choices/sign`, then `/api/choices`). Agents answer with `decision_request`, shown as choice cards, and a click on an option is the passkey-signed answer: after the 3 s undo the hub verifies the signature and posts the answer to the asking agent, whose `decision_wait` returns it as `message` and `answer` for `operator_message`. A task's sheet pins its priority (`rasci.py set --prio `) or sets and drops the operator's WSJF estimate (`rasci.py estimate Operator --value --complexity ` or `--drop`) after a passkey signature; the hub writes an argv-only job, and the runner, started with `--rasci --council `, verifies it like an operator command and runs `rasci.py` from `/` without a shell, killing it after 30 s. Agent order stays untouched. The install copies the fresh runner unit and restarts the runner when it is enabled, and only while the installed `council.py`, `nofollow.py` and `rasci.py` match this tree: otherwise it disables the runner and asks for `make install`. The home install and `orchestrator.sh install`, `stop` and `runner` refuse while `~/.local/state/kvb-orchestrator/runner-job.json` names a live runner pid, which the runner keeps only while it runs a hub row, because stopping the runner kills that row; run them in a terminal once no row runs, never as a hub row. A starting runner has the hub fail every job an earlier runner left running back to its agent (`/api/runner/restart`). The runner unit pins `PATH` to `/usr/bin:/bin`, so a signed command names any other program by its full path; a runner started without `--rasci` and `--council` keeps running signed commands and refuses task changes, and so does one whose council is a symlink or another uid's. Each worktree in the tree file may carry `"flow": {"pull": [...], "push": [...], "source": "file"}` or `null`, which the Tree, the Chord edges, the detail panel and the matching task show; a malformed flow shows as `invalid`. Worktrees and tasks with open work (uncommitted, unpushed, unmerged, task not done) carry a warning bar. Without reinstalling the skills, `make orchestrator-install` installs, builds and starts only the hub, `make orchestrator-check` checks the installed hub (image, container, logs, HTTP, pinned keys, hook, runner, tree timer, disk; exit 1 on a failure), `make orchestrator-pin CREDENTIAL=` pins the passkey that "Register passkey" shows, `make orchestrator-runner` enables the runner service, and `make orchestrator-hook` registers the PermissionRequest hook in `~/.claude/settings.json`, replacing an earlier Agent Orchestrator entry and keeping the file mode, after a copy to `settings.json.before-kvb-orchestrator-hook` (Claude Code reads `~/.claude/settings.local.json` only in sessions started in the home directory). Agents that reach the Docker socket are root-equivalent: until the agent VMs of core requirement 093 isolate them, the signatures do not hold against such an agent. `make watch-check` shows whether the resource watch hook is stuck (running hooks, holders of the kept queue history, age of the stored stage). diff --git a/orchestrator/client/runner.py b/orchestrator/client/runner.py index 98f0e58..2c6ace0 100755 --- a/orchestrator/client/runner.py +++ b/orchestrator/client/runner.py @@ -6,6 +6,8 @@ --approvers: the pinned passkeys, e.g. ~/.config/kvb-orchestrator/approvers.json. --replay: the runner's replay store, outside the hub's reach, e.g. ~/.local/state/kvb-orchestrator-approvals/runner.json. + --state: the hub state dir, e.g. ~/.local/state/kvb-orchestrator, where + the runner keeps runner-job.json while a job runs. --rasci: the installed register script, e.g. ~/.claude/skills/kvb-org-rasci/scripts/rasci.py; optional. --council: the council directory holding rasci.json, the agents' @@ -44,8 +46,15 @@ Returns: every PREVIEW_SECONDS, it posts, for each open operator row that is a git merge of a full commit id (staged_diff.merge_of) whose HEAD differs from the preview the hub holds, staged_diff.merge_preview, which its Match card shows; such a - merge whose job names the previewed HEAD is refused once HEAD moved. The - exit code is 0. + merge whose job names the previewed HEAD is refused once HEAD moved. + At start, before its first cycle, it removes a leftover runner-job.json + and posts /api/runner/restart once, so the hub fails every job an + earlier runner left running; a failed post is printed to stderr. While + it runs a job it keeps runner-job.json, {pid, job, task, started} with + its own pid, written by rename with mode 0600 and removed when the job + ends, whatever the outcome; `orchestrator.sh idle` refuses an install + while that pid lives, and a job whose marker cannot be written is + refused. The exit code is 0. """ from __future__ import annotations @@ -77,6 +86,8 @@ import verifier LINES = 200 PREVIEWS = "/api/runner/previews" +RESTART = "/api/runner/restart" +MARKER = "runner-job.json" ERROR_LIMIT = 500 PREVIEW_FAILURES = (OSError, ValueError, staged_diff.DiffError) BEAT = 2.0 @@ -100,6 +111,7 @@ class Host(NamedTuple): shell: str operator: Path | None council: Path | None + marker: Path def call(base: str, path: str, payload: dict | None) -> dict: @@ -422,6 +434,42 @@ def sender(base: str, job_id: str) -> Callable[[dict], None]: return send +def mark(marker: Path, job: dict) -> str | None: + """Args: + marker: runner-job.json in the hub state dir. + job: the claimed job about to run, with id and task. + + Returns: + Why the job must not run: the marker that makes `orchestrator.sh + idle` refuse an install, which would stop the runner under the job, + cannot be written; None once it is written. + """ + try: + verifier.write_private(marker, {"pid": os.getpid(), "job": job["id"], "task": job["task"], "started": time.time()}) + except OSError as error: + return f"refused: the runner cannot write {marker}, which keeps an install from stopping it under this job: {error}" + return None + + +def refused(claimed: dict, trust: verifier.Trust, register: Register | None, gates: Path | None) -> str | None: + kind = claimed.get("kind") + if kind == TASK_JOB: + return UNREGISTERED if register is None else council_refusal(register.council) or task_refusal(claimed, trust, time.time()) + if kind == GATE_JOB: + return UNGATED if gates is None else gate_refusal(claimed, trust, time.time()) + return refusal(claimed, trust, time.time()) or moved(claimed) + + +def run(claimed: dict, register: Register | None, gates: Path | None, host: Host, send: Callable[[dict], None]) -> None: + kind = claimed.get("kind") + if kind == TASK_JOB: + change(claimed, register, send) + elif kind == GATE_JOB: + gate(claimed, gates, send) + else: + execute(claimed, host, send) + + 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: @@ -429,21 +477,36 @@ def cycle(base: str, trust: verifier.Trust, register: Register | None, gates: Pa except urllib.error.HTTPError: continue send = sender(base, claimed["id"]) - kind = claimed.get("kind") - if kind == TASK_JOB: - reason = UNREGISTERED if register is None else council_refusal(register.council) or task_refusal(claimed, trust, time.time()) - elif kind == GATE_JOB: - reason = UNGATED if gates is None else gate_refusal(claimed, trust, time.time()) - else: - reason = refusal(claimed, trust, time.time()) or moved(claimed) + reason = refused(claimed, trust, register, gates) or mark(host.marker, claimed) if reason is not None: send({"output": reason, "code": None, "refused": True}) - elif kind == TASK_JOB: - change(claimed, register, send) - elif kind == GATE_JOB: - gate(claimed, gates, send) - else: - execute(claimed, host, send) + continue + try: + run(claimed, register, gates, host, send) + finally: + host.marker.unlink(missing_ok=True) + + +def restart(base: str, marker: Path) -> None: + marker.unlink(missing_ok=True) + try: + call(base, RESTART, {}) + except (OSError, ValueError, TypeError) as error: + print(f"runner: the hub keeps the jobs an earlier runner left running: {error}", file=sys.stderr) + + +def post_previews(base: str, rules: Path | None, told: str) -> str: + """Returns: + The error this post failed with, printed unless it equals told, the + one printed last; "" once a post succeeds. + """ + try: + previews(base, rules) + except (OSError, ValueError, KeyError, TypeError) as error: + if str(error) != told: + print(f"runner: no merge previews: {error}", file=sys.stderr) + return str(error) + return "" def main() -> int: @@ -452,6 +515,7 @@ def main() -> int: parser.add_argument("--interval", type=float, required=True) parser.add_argument("--approvers", type=Path, required=True) parser.add_argument("--replay", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) parser.add_argument("--rasci", type=Path) parser.add_argument("--council", type=Path) parser.add_argument("--gates", type=Path) @@ -461,18 +525,13 @@ def main() -> int: 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) + host = Host(shell=os.environ.get("SHELL") or pwd.getpwuid(os.geteuid()).pw_shell, operator=args.operator, council=args.council, marker=args.state / MARKER) rules, told, previewed = staged_diff.rules_root(), "", None + restart(base, host.marker) while True: if previewed is None or time.monotonic() - previewed >= PREVIEW_SECONDS: previewed = time.monotonic() - try: - previews(base, rules) - told = "" - except (OSError, ValueError, KeyError, TypeError) as error: - if str(error) != told: - print(f"runner: no merge previews: {error}", file=sys.stderr) - told = str(error) + told = post_previews(base, rules, told) try: cycle(base, trust, register, args.gates, host) except (OSError, ValueError, KeyError, TypeError): diff --git a/orchestrator/kvb_orchestrator/handler.py b/orchestrator/kvb_orchestrator/handler.py index 78363f3..22277dd 100644 --- a/orchestrator/kvb_orchestrator/handler.py +++ b/orchestrator/kvb_orchestrator/handler.py @@ -29,6 +29,7 @@ BOARD = re.compile(r"/api/board/([a-z-]{1,32})") UPLOADS = "/api/uploads" MATCH_ROUTE = "/api/match" PREVIEWS_ROUTE = "/api/runner/previews" +RESTART_ROUTE = "/api/runner/restart" MATCH_POSTS = {"/api/match/stale": "match_stale", "/api/match/snapshot": "match_snapshot"} HOOK_POSTS = {"/api/asks": "ask", "/api/decisions": "question"} POSTS = (*HOOK_POSTS, UPLOADS, "/api/messages", *MATCH_POSTS) @@ -283,7 +284,9 @@ class Handler(Exchange): def runner(self, path: str, body: bytes) -> None: hub = self.server.hub route = RUNNER_ROUTE.fullmatch(path) - if route is None: + if path == RESTART_ROUTE: + self.answer(hub.restart_runner, HTTPStatus.OK) + elif route is None: self.answer(lambda: hub.record_preview(body), HTTPStatus.OK) elif route.group(2) == "claim": self.answer(lambda: hub.claim(route.group(1)), HTTPStatus.OK) @@ -303,7 +306,7 @@ class Handler(Exchange): return lambda body: self.answer(lambda: receive(body), HTTPStatus.OK if path in MATCH_POSTS else HTTPStatus.CREATED) self.send_text(HTTPStatus.FORBIDDEN, "forbidden: local POST with the X-Kvb-Orchestrator header and no foreign origin only") return None - if RUNNER_ROUTE.fullmatch(path) or path == PREVIEWS_ROUTE: + if RUNNER_ROUTE.fullmatch(path) or path in (PREVIEWS_ROUTE, RESTART_ROUTE): if self.client(): return lambda body: self.runner(path, body) self.send_text(HTTPStatus.FORBIDDEN, "forbidden: the runner calls with the X-Kvb-Orchestrator header and no origin only") diff --git a/orchestrator/kvb_orchestrator/jobs.py b/orchestrator/kvb_orchestrator/jobs.py index a30dd3c..1acc740 100644 --- a/orchestrator/kvb_orchestrator/jobs.py +++ b/orchestrator/kvb_orchestrator/jobs.py @@ -15,6 +15,7 @@ TASK_JOB = "task" GATE_JOB = "gate" CHANGES = (TASK_JOB, GATE_JOB) UNRUNNABLE = "The hub runner needs a command and an absolute directory, and this row lacks one; run it with operator.py run in a terminal." +RESTARTED = "the runner restarted while this job ran; run the row again" def runner_job(job: dict) -> dict: @@ -148,11 +149,39 @@ 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, 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}}) + return self.ended(job, checked is True) + + def restart_runner(self) -> dict: + """Returns: + {"failed": ids}: every running job, which the restart of the + runner killed, turned failed with RESTARTED as its output, code + None and finished now, its row closed like a failed run. + """ + failed = [] + for job in self.jobs.listed(): + record, changed = self.jobs.transition(job["id"], "running", {"status": "failed", "code": None, "output": RESTARTED, "finished": time.time()}) + if changed: + self.ended(record, False) + failed.append(job["id"]) + return {"failed": failed} + + def ended(self, job: dict, checked: bool) -> dict: + """Args: + job: a job that just left running, with its status, code and + output. + checked: as in close_row(). + + Returns: + {"id", "status", "code", "runs", "told"} after its row closed + (close_row()), the run went to the log and, for a task change, + its batch was told (tell_applied()). + """ + status, code = job["status"], job["code"] + runs = self.close_row(job, status, code, checked) + tail = "\n".join(job["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} + return {"id": job["id"], "status": status, "code": code, "runs": runs, "told": told} def close_row(self, job: dict, status: str, code: int | None, checked: bool) -> list[dict]: """Args: @@ -165,14 +194,16 @@ class Jobs: job on its row: `ran` on exit 0, with --check-failed unless checked, so the row stays open; `failed` with where the output stays, the job's console, never the output itself, on any other - exit; none for a refused job or a task or gate change. + exit and, why RESTARTED, on a failed job without code, which a + runner restart killed; none for a refused job or a task or gate + change. """ if job.get("kind") in CHANGES or status not in ("done", "failed"): return [] slug = job["task"].removeprefix(OPERATOR) shown = [slug, f"--command={job['command']}", f"--dir={job['directory']}"] if status == "failed": - why = f"killed by signal {-code}" if code < 0 else f"exit {code}" + why = RESTARTED if code is None else f"killed by signal {-code}" if code < 0 else f"exit {code}" where = f"the console of hub job {job['id']} under the row in Waits on Operator" return [self.scripts.run(OPERATOR_SCRIPT, ["failed", *shown, "--why", why, f"--where={where}"])] 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 57a0bae..63ad627 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 --operator %h/.claude/skills/kvb-org-operator/scripts/operator.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 --state %h/.local/state/kvb-orchestrator --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/scripts/install.sh b/scripts/install.sh index f589020..e9c9259 100644 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -43,6 +43,7 @@ migrate_council() { } status=0 if [[ "${TARGET}" == "${HOME}" ]]; then + bash "${REPO_ROOT}/scripts/orchestrator.sh" idle || exit 1 if ! python3 "${council_root}" preflight; then warn "skills: install refused before copying anything; the installed skills keep the earlier council root until the reasons above are gone." exit 1 diff --git a/scripts/orchestrator.sh b/scripts/orchestrator.sh index a7be7fa..dab2394 100644 --- a/scripts/orchestrator.sh +++ b/scripts/orchestrator.sh @@ -1,30 +1,37 @@ #!/usr/bin/env bash -# Usage: orchestrator.sh install | migrate | stop | start | check | pin | runner | hook -# install migrate, then copy orchestrator/ to ~/.local/share/kvb-orchestrator, -# write its .env, build and start the container, register the MCP -# server for Claude Code, build pkgmgr from the newest signed tag of -# PKGMGR_REPO and enable the tree timer and the cleanup path unit, -# enable the sessions timer and the offices path unit, enable the -# resources timer, the firewall path unit and timer; re-enable the -# runner and re-register the hook when the migration took them over; -# an enabled runner gets the fresh unit and a restart +# Usage: orchestrator.sh install | migrate | stop | start | check | pin | runner | hook | idle +# install refuse like idle, else migrate, then copy orchestrator/ to +# ~/.local/share/kvb-orchestrator, write its .env, build and start +# the container, register the MCP server for Claude Code, build +# pkgmgr from the newest signed tag of PKGMGR_REPO and enable the +# tree timer and the cleanup path unit, enable the sessions timer +# and the offices path unit, enable the resources timer, the +# firewall path unit and timer; re-enable the runner and +# re-register the hook when the migration took them over; an +# enabled runner gets the fresh unit and a restart # migrate move every trace of the earlier name to the kvb-orchestrator names # once: container, image, code, state, approvals, pinned keys, MCP # server, PermissionRequest hook, runner unit; a second run changes # nothing -# stop stop the container, the runner, the offices path unit and the -# resources timer, which write the council roots, keeping them -# enabled; exit 1 when the container does not stop +# stop refuse like idle, else stop the container, the runner, the +# offices path unit and the resources timer, which write the +# council roots, keeping them enabled; exit 1 when the container +# does not stop # start start them again, the units only while enabled # check image imports, container, logs, HTTP, pinned keys, hook, runner, # disk; exit 1 when a check fails # pin pin the credential blob the "Passkey registrieren" settings show -# runner install, enable and restart the runner user service; disable it -# and exit 1 while the installed council.py, nofollow.py, -# councilroot.py or rasci.py differ from this tree +# runner refuse like idle, else install, enable and restart the runner +# user service; disable it and exit 1 while the installed +# council.py, nofollow.py, councilroot.py or rasci.py differ from +# this tree # hook register the PermissionRequest hook in ~/.claude/settings.json, # replacing an earlier entry, keeping everything else and the file # mode, after a copy to settings.json.before-kvb-orchestrator-hook +# idle exit 1 with the hub row's task and job id while runner-job.json +# in ~/.local/state/kvb-orchestrator names a live pid, the runner +# running that row, which a stop of the runner would kill; exit 0 +# without the file or for a dead pid set -euo pipefail REPO_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)" @@ -323,6 +330,7 @@ offices_unit() { } install_all() { + idle || return 1 migrate || return 0 local hub=0 install_hub || hub=1 @@ -339,6 +347,7 @@ install_all() { } stop_all() { + idle || return 1 if [[ -f "${HUB}/compose.yml" ]] && command -v docker &>/dev/null; then docker compose --file "${HUB}/compose.yml" stop || return 1 fi @@ -362,7 +371,32 @@ runner_enabled() { has_systemd && [[ "$(systemctl --user is-enabled "${RUNNER}" 2>/dev/null || true)" == "enabled" ]] } +idle() { + python3 - "${STATE}/runner-job.json" <<'PY' +import json, os, sys +from pathlib import Path + + +def alive(pid): + try: + os.kill(pid, 0) + except (OSError, OverflowError): + return False + return True + + +try: + marker = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) + pid, job, task = int(marker["pid"]), marker["job"], marker["task"] +except (OSError, ValueError, KeyError, TypeError): + sys.exit(0) +if pid > 0 and alive(pid): + sys.exit(f"skills: a hub row runs ({task}, job {job}): the install would stop the runner and kill it; run the install in a terminal once no row runs") +PY +} + runner() { + idle || return 1 if ! has_systemd; then warn "skills: no systemd user session; the runner is off and approved operator commands wait." return 1 @@ -484,8 +518,9 @@ check) check ;; pin) pin "${2:-}" ;; runner) runner ;; hook) hook ;; +idle) idle ;; *) - warn "usage: orchestrator.sh install | migrate | stop | start | check | pin | runner | hook" + warn "usage: orchestrator.sh install | migrate | stop | start | check | pin | runner | hook | idle" exit 2 ;; esac diff --git a/tests/e2e/test_hub_inbox_e2e.py b/tests/e2e/test_hub_inbox_e2e.py index c4fa72e..938c611 100644 --- a/tests/e2e/test_hub_inbox_e2e.py +++ b/tests/e2e/test_hub_inbox_e2e.py @@ -60,7 +60,7 @@ class TestHubInbox(base.OrchestratorE2ECase): def test_chromium_runs_a_command_into_its_console_denies_by_call_and_accepts_a_rule(self): self.inbox_work() signer = self.pin() - trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json")] + trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json"), "--state", str(self.state)] def run_jobs() -> None: if any(job["status"] == "queued" for job in self.httpd.hub.jobs.listed()): diff --git a/tests/hub_case.py b/tests/hub_case.py index 27e8585..3d9287d 100644 --- a/tests/hub_case.py +++ b/tests/hub_case.py @@ -208,7 +208,7 @@ class HubCase(unittest.TestCase): return json.loads(body)["jobs"] def run_runner(self, register: bool = True, council: Path | None = None) -> None: - trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json")] + trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json"), "--state", str(self.state)] 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, "--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)}) diff --git a/tests/test_hub_console.py b/tests/test_hub_console.py index c360dc9..65aa02c 100644 --- a/tests/test_hub_console.py +++ b/tests/test_hub_console.py @@ -165,6 +165,33 @@ class TestHubConsole(HubCase): ]) self.assertNotIn("token-42", json.dumps(self.scripts.calls)) + def test_a_runner_restart_fails_every_running_job_and_closes_its_row_like_a_failed_run(self): + self.register("queued") + now = time.time() + fields = {"task": "operator/greet", "command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "proof": None, "code": None, "output": "line 1\n", "created_ts": now, "finished": None, "dismissed": False} + command = self.httpd.hub.jobs.add({**fields, "status": "running", "started": now}) + gate = self.httpd.hub.jobs.add({**fields, "status": "running", "started": now, "kind": "gate", "argv": []}) + queued = self.httpd.hub.jobs.add({**fields, "status": "queued", "started": None}) + done = self.httpd.hub.jobs.add({**fields, "status": "done", "code": 0, "started": now, "finished": now}) + self.assertEqual(self.post_json("/api/runner/restart", {}, self.guard(self.host))[0], 403) + self.assertEqual(self.post_json("/api/runner/restart", {}, {"Host": self.host})[0], 403) + self.assertEqual(self.scripts.calls, []) + status, answer = self.runner("/api/runner/restart", {}) + self.assertEqual((status, sorted(answer["failed"])), (200, sorted([command["id"], gate["id"]]))) + for job in (command, gate): + with self.subTest(job=job["id"]): + stored = self.httpd.hub.jobs.get(job["id"]) + self.assertEqual((stored["status"], stored["code"], stored["output"]), ("failed", None, jobs.RESTARTED)) + self.assertGreaterEqual(stored["finished"], now) + self.assertEqual([self.httpd.hub.jobs.get(job["id"])["status"] for job in (queued, done)], ["queued", "done"]) + shown = ["greet", f"--command={COMMAND}", f"--dir={self.outside}"] + where = f"--where=the console of hub job {command['id']} under the row in Waits on Operator" + self.assertEqual(self.scripts.calls, [(skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", jobs.RESTARTED, where])]) + stored = json.loads((self.state / "jobs.json").read_text(encoding="utf-8")) + self.assertEqual({stored[job["id"]]["status"] for job in (command, gate)}, {"failed"}) + self.assertEqual(self.runner("/api/runner/restart", {}), (200, {"failed": []})) + self.assertEqual(len(self.scripts.calls), 1) + 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} diff --git a/tests/test_hub_executors.py b/tests/test_hub_executors.py index 2e8b0c3..9fbb9cc 100644 --- a/tests/test_hub_executors.py +++ b/tests/test_hub_executors.py @@ -107,7 +107,7 @@ 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, host = [], runner.Host(shell=str(self.shell), operator=None, council=None) + reports, host = [], runner.Host(shell=str(self.shell), operator=None, council=None, marker=self.state / runner.MARKER) 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) @@ -128,7 +128,7 @@ class TestHubExecutors(HubCase): 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) + host = runner.Host(shell=str(self.shell), operator=hub_support.OPERATOR, council=self.council, marker=self.state / runner.MARKER) 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")))) @@ -145,7 +145,7 @@ class TestHubExecutors(HubCase): 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) + host = runner.Host(shell=str(self.shell), operator=None, council=None, marker=self.state / runner.MARKER) def spawn(*args: object, **kwargs: object) -> subprocess.Popen: spawned.append(popen(*args, **kwargs)) diff --git a/tests/test_hub_gates.py b/tests/test_hub_gates.py index 605727c..70e1633 100644 --- a/tests/test_hub_gates.py +++ b/tests/test_hub_gates.py @@ -117,7 +117,7 @@ class TestRunnerGates(HubCase): self.db = self.home / ".local" / "state" / "agents-council" / "gates.db" def run_gates_runner(self, flags: list[str]) -> None: - trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json")] + trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json"), "--state", str(self.state)] 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, env={**os.environ, "HOME": str(self.home)}) self.assertEqual(done.returncode, 0, done.stderr) diff --git a/tests/test_hub_runner_restart.py b/tests/test_hub_runner_restart.py new file mode 100644 index 0000000..5cbdadc --- /dev/null +++ b/tests/test_hub_runner_restart.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import contextlib +import http.server +import io +import json +import os +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path +from unittest import mock + +from hub_support import LOGIN_SHELL, runner + +JOB = "0123456789abcdef" +FAILED = "fedcba9876543210" + + +class Answer(http.server.BaseHTTPRequestHandler): + def do_GET(self) -> None: + self.server.seen.append(("GET", self.path)) + self.reply(200, {"jobs": self.server.jobs} if self.path == "/api/runner/jobs" else {"rows": [], "reviews": []}) + + def do_POST(self) -> None: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + self.server.seen.append(("POST", self.path)) + if self.path == runner.RESTART: + self.reply(self.server.restart, {"failed": []}) + elif self.path.endswith("/claim"): + self.reply(200, next(job for job in self.server.jobs if f"/{job['id']}/" in self.path)) + else: + self.server.reports.append((self.path.split("/")[3], body)) + self.reply(200, {}) + + def reply(self, status: int, payload: dict) -> None: + data = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *_args: object) -> None: + return + + +class FakeHub(http.server.ThreadingHTTPServer): + def __init__(self, jobs: list[dict], restart: int) -> None: + """Args: + jobs: what /api/runner/jobs lists and each claim hands out. + restart: the HTTP status /api/runner/restart answers. + """ + super().__init__(("127.0.0.1", 0), Answer) + self.jobs = jobs + self.restart = restart + self.seen: list[tuple[str, str]] = [] + self.reports: list[tuple[str, dict]] = [] + + +class TestRunnerRestart(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.base = Path(tmp.name) + self.state = self.base / "state" + self.state.mkdir() + self.marker = self.state / runner.MARKER + self.shell = self.base / "login-shell" + self.shell.write_text(LOGIN_SHELL, encoding="utf-8") + self.shell.chmod(0o755) + self.host = runner.Host(shell=str(self.shell), operator=None, council=None, marker=self.marker) + self.trust = runner.verifier.Trust(approvers=self.base / "approvers.json", replay=self.base / "replay.json", origin="http://localhost:1") + + def hub(self, jobs: list[dict], restart: int) -> FakeHub: + hub = FakeHub(jobs, restart) + threading.Thread(target=hub.serve_forever, args=(0.05,), daemon=True).start() + self.addCleanup(hub.server_close) + self.addCleanup(hub.shutdown) + return hub + + def job(self, job_id: str, command: str) -> dict: + return {"id": job_id, "task": "operator/push", "command": command, "directory": str(self.base), "sha256": "", "proof": None} + + def start(self, hub: FakeHub) -> tuple[int, str]: + argv = ["runner", "--port", str(hub.server_address[1]), "--interval", "0.1", "--approvers", str(self.base / "approvers.json"), "--replay", str(self.base / "replay.json"), "--state", str(self.state), "--once"] + stderr = io.StringIO() + with mock.patch.object(sys, "argv", argv), contextlib.redirect_stderr(stderr): + code = runner.main() + return code, stderr.getvalue() + + def cycle(self, hub: FakeHub) -> None: + with mock.patch.object(runner, "refusal", return_value=None): + runner.cycle(runner.hub_api.base_url(hub.server_address[1]), self.trust, None, None, self.host) + + def finals(self, hub: FakeHub) -> dict[str, dict]: + return {job_id: body for job_id, body in hub.reports if body["code"] is not None or body["refused"]} + + def test_the_runner_drops_a_leftover_marker_and_has_the_hub_fail_the_earlier_jobs_before_its_first_cycle(self): + self.marker.write_text(json.dumps({"pid": os.getpid(), "job": JOB, "task": "operator/push", "started": 0}), encoding="utf-8") + hub = self.hub([], 200) + self.assertEqual(self.start(hub), (0, "")) + self.assertFalse(self.marker.exists()) + self.assertEqual(hub.seen[0], ("POST", runner.RESTART)) + self.assertEqual(hub.seen.count(("POST", runner.RESTART)), 1) + self.assertIn(("GET", "/api/runner/jobs"), hub.seen[1:]) + + def test_a_failed_restart_call_is_printed_once_and_the_runner_goes_on(self): + hub = self.hub([], 500) + code, stderr = self.start(hub) + self.assertEqual(code, 0) + self.assertEqual([line for line in stderr.splitlines() if "earlier runner" in line], ["runner: the hub keeps the jobs an earlier runner left running: HTTP Error 500: Internal Server Error"]) + self.assertIn(("GET", "/api/runner/jobs"), hub.seen) + + def test_the_runner_keeps_the_marker_while_a_job_runs_and_removes_it_whatever_the_outcome(self): + hub = self.hub([self.job(JOB, f'stat -c %a "{self.marker}" && cat "{self.marker}"'), self.job(FAILED, f'test -f "{self.marker}" && exit 3')], 200) + before = time.time() + self.cycle(hub) + finals = self.finals(hub) + self.assertEqual((finals[JOB]["code"], finals[FAILED]["code"]), (0, 3)) + mode, text = finals[JOB]["output"].split("\n", 1) + held = json.loads(text) + self.assertEqual((mode, held["pid"], held["job"], held["task"]), ("600", os.getpid(), JOB, "operator/push")) + self.assertTrue(before <= held["started"] <= time.time(), held) + self.assertFalse(self.marker.exists()) + seen = [] + + def broken(*_args: object) -> int: + seen.append(json.loads(self.marker.read_text(encoding="utf-8"))["job"]) + raise RuntimeError("the hub is gone") + + hub.jobs[:] = [self.job(JOB, "true")] + with mock.patch.object(runner, "execute", broken): + self.assertRaises(RuntimeError, self.cycle, hub) + self.assertEqual(seen, [JOB]) + self.assertFalse(self.marker.exists()) + + def test_a_job_whose_marker_cannot_be_written_is_refused_and_never_runs(self): + ran = self.base / "ran" + hub = self.hub([self.job(JOB, f'touch "{ran}"')], 200) + with mock.patch.object(runner.verifier, "write_private", side_effect=OSError("disk full")): + self.cycle(hub) + final = self.finals(hub)[JOB] + self.assertEqual((final["refused"], final["code"]), (True, None)) + self.assertTrue(final["output"].startswith(f"refused: the runner cannot write {self.marker}"), final["output"]) + self.assertIn("disk full", final["output"]) + self.assertFalse(ran.exists() or self.marker.exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_install.py b/tests/test_install.py index d13ecc1..b35d77d 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -29,6 +29,7 @@ COUNCIL_PARTS = ( "skills/kvb-org-organize/scripts/councilroot.py", "skills/kvb-org-organize/scripts/nofollow.py", "skills/kvb-org-organize/scripts/schedules.py", ) +RUNNING_JOB = "0123456789abcdef" AGENT_ROOTS = {"sandbox": {"filesystem": {"allowWrite": ["~/.local/state/agents-shared", "~/.local/state/agents-release/**"]}}} CGROUP_KILL = """ case "$*" in *try-restart*kvb-code-graph*) @@ -122,7 +123,8 @@ class TestInstall(unittest.TestCase): self.assertEqual(json.loads(config.read_text(encoding="utf-8")), {"mine": True}) self.assertIn(str(config), done.stderr) - def home_install(self, root: Path, binary: bool, config: bool = True, fail_now: bool = False, schedules: dict | None = None) -> tuple[subprocess.CompletedProcess, list[str], list[str]]: + def home_install(self, root: Path, binary: bool, config: bool = True, fail_now: bool = False, schedules: dict | None = None, + runner_job: dict | None = None) -> tuple[subprocess.CompletedProcess, list[str], list[str]]: repo, stubs, home = root / "repo", root / "bin", root / "home" (repo / "scripts").mkdir(parents=True) shutil.copy(INSTALL, repo / "scripts" / "install.sh") @@ -162,6 +164,10 @@ class TestInstall(unittest.TestCase): council = home / ".local" / "state" / "agents-shared" council.mkdir(parents=True, mode=0o700) (council / "schedules.json").write_text(json.dumps(schedules), encoding="utf-8") + if runner_job is not None: + hub_state = home / ".local" / "state" / "kvb-orchestrator" + hub_state.mkdir(parents=True) + (hub_state / "runner-job.json").write_text(json.dumps(runner_job), encoding="utf-8") env = {"PATH": str(stubs), "TARGET": str(home), "HOME": str(home), "AGENTS_COUNCIL_LEGACY": str(root / "legacy")} done = subprocess.run(["/bin/bash", str(repo / "scripts" / "install.sh")], env=env, capture_output=True, text=True, check=False) return done, read_lines(log), read_lines(cbm) @@ -246,6 +252,25 @@ class TestInstall(unittest.TestCase): self.assertIn("skills: git or python3 not found; skipped TokenEconomizer.", done.stderr) self.assertFalse((Path(tmp) / "home" / "Repositories").exists()) + def test_a_hub_row_the_runner_runs_stops_the_home_install_before_it_changes_anything(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + done, calls, _ = self.home_install(root, binary=True, runner_job={"pid": os.getpid(), "job": RUNNING_JOB, "task": "operator/push", "started": 0}) + self.assertEqual(done.returncode, 1, done.stderr) + self.assertIn(f"a hub row runs (operator/push, job {RUNNING_JOB}): the install would stop the runner and kill it; run the install in a terminal once no row runs", done.stderr) + self.assertEqual(calls, []) + self.assertFalse((root / "repo" / ".agents").exists() or (root / "home" / ".agents").exists() or (root / "home" / ".claude" / "skills").exists()) + + def test_a_marker_whose_runner_is_gone_lets_the_home_install_pass(self): + gone = subprocess.Popen(["true"]) + gone.wait() + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + done, _, _ = self.home_install(root, binary=True, runner_job={"pid": gone.pid, "job": RUNNING_JOB, "task": "operator/push", "started": 0}) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertNotIn("a hub row runs", done.stderr) + self.assertTrue((root / "home" / ".claude" / "skills" / "locked" / "SKILL.md").is_file()) + def test_reinstall_empties_the_skill_directories_in_place(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) diff --git a/tests/test_orchestrator_migration.py b/tests/test_orchestrator_migration.py index 8f527b7..44c7c35 100644 --- a/tests/test_orchestrator_migration.py +++ b/tests/test_orchestrator_migration.py @@ -230,6 +230,27 @@ class TestOrchestratorMigration(unittest.TestCase): self.assertEqual((units / f"{NEW}-runner.service").read_text(encoding="utf-8") == shipped, enabled) self.assertEqual(restart in calls, enabled) + def test_a_hub_row_the_runner_runs_makes_idle_stop_install_and_runner_refuse_before_any_call(self): + marker = self.home / ".local" / "state" / NEW / "runner-job.json" + job = {"job": "0123456789abcdef", "task": "operator/push", "started": 0} + self.write(marker, json.dumps({**job, "pid": os.getpid()}), 0o600) + before = snapshot(self.home) + for command in ("idle", "stop", "install", "runner"): + with self.subTest(command=command): + done = subprocess.run(["bash", str(SCRIPT), command], env=self.env, capture_output=True, text=True, timeout=120, check=False) + self.assertEqual(done.returncode, 1, done.stderr) + self.assertIn("a hub row runs (operator/push, job 0123456789abcdef): the install would stop the runner and kill it; run the install in a terminal once no row runs", done.stderr) + self.assertEqual(json.loads(self.state.read_text(encoding="utf-8"))["calls"], []) + self.assertEqual(snapshot(self.home), before) + gone = subprocess.Popen(["true"]) + gone.wait() + self.write(marker, json.dumps({**job, "pid": gone.pid}), 0o600) + passed = subprocess.run(["bash", str(SCRIPT), "idle"], env=self.env, capture_output=True, text=True, timeout=120, check=False) + self.assertEqual((passed.returncode, passed.stderr), (0, "")) + marker.unlink() + passed = subprocess.run(["bash", str(SCRIPT), "idle"], env=self.env, capture_output=True, text=True, timeout=120, check=False) + self.assertEqual((passed.returncode, passed.stderr), (0, "")) + def test_every_shipped_service_pins_the_path(self): units = sorted((REPO_ROOT / "orchestrator" / "systemd").glob("*.service")) self.assertIn(f"{NEW}-runner.service", [unit.name for unit in units])