diff --git a/CHANGELOG.md b/CHANGELOG.md index 3401736..b17d29e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ - Tests are type-checked by mypy as well; 14 test modules still sit on the ignore list until they are typed. - git, Cline CLI and lms output are decoded as UTF-8 with replacement, so the dashboard's agent status and autopilot survive any text on a non-UTF-8 locale code page. - The dashboard's Settings tab has a "Start Iris in the tray at login" switch that writes or removes the Startup-folder entry (`/api/startup`); an installer build answers that it manages its own entry. +- When `agents.toml` names a nightshift command, the dashboard's Repos tab shows the active run above the repo list (done and blocked counts, current item and minutes on it, last gate check); `/api/agents` carries it as a `nightshift` key. ## 1.0.0 (release date): steady, safer and measured diff --git a/README.md b/README.md index 4f581bb..523a701 100644 --- a/README.md +++ b/README.md @@ -346,7 +346,7 @@ The page polls every 3 seconds and has eleven tabs: name and age only (it stats files but never reads them). - Activity: the last 50 journal entries newest first with tier and outcome chips, plus today's request, confirmation, refusal and error counts. Autopilot outcomes appear here with their own badge. -- Repos: branch, last commit and its age, uncommitted files, BLOCKED.md and STUCK flags per agent repo, stuck repos first. +- Repos: branch, last commit and its age, uncommitted files, BLOCKED.md and STUCK flags per agent repo, stuck repos first. When `agents.toml` sets `nightshift_command` (how to call nightshift) and `nightshift_runs` (the folders that hold its run dirs), one line above the list shows the active run: done and blocked counts, current item and minutes on it, last gate check. - Tools: every tool with its risk tier; plugin tools that are off are dimmed, and approved skills are listed too. - Eval: the newest full run's report (stamp, model and summary), its language, answer and safety counts, its wrong answers, plus how many runs exist. diff --git a/iris/agents.py b/iris/agents.py index 23930ff..9c747b8 100644 --- a/iris/agents.py +++ b/iris/agents.py @@ -10,10 +10,12 @@ from __future__ import annotations +import json import os import subprocess import time import tomllib +from collections.abc import Callable from dataclasses import dataclass, field from pathlib import Path @@ -24,6 +26,7 @@ DEFAULT_WORKTREES = [str(Path.home() / ".cline" / "worktrees")] DEFAULT_STUCK_MINUTES = 60 GIT_TIMEOUT = 10 # seconds; a repo on a spinning disk must not hang the voice loop +NIGHTSHIFT_TIMEOUT = 20 # seconds; a hung status call must not hang the agents view either def _default_repos() -> list[str]: @@ -74,6 +77,8 @@ class Config: repos: list[str] = field(default_factory=_default_repos) worktrees: list[str] = field(default_factory=lambda: list(DEFAULT_WORKTREES)) stuck_minutes: int = DEFAULT_STUCK_MINUTES + nightshift_command: list[str] = field(default_factory=list) # empty = the active-run glance is off + nightshift_runs: list[str] = field(default_factory=list) # folders that hold run dirs (a run.toml inside) def load_config(path: Path | str | None = None) -> Config: @@ -91,6 +96,10 @@ def load_config(path: Path | str | None = None) -> Config: cfg.worktrees = [str(x) for x in data["worktrees"]] if isinstance(data.get("stuck_minutes"), (int, float)) and data["stuck_minutes"] > 0: cfg.stuck_minutes = int(data["stuck_minutes"]) + if isinstance(data.get("nightshift_command"), list): + cfg.nightshift_command = [str(x) for x in data["nightshift_command"]] + if isinstance(data.get("nightshift_runs"), list): + cfg.nightshift_runs = [str(x) for x in data["nightshift_runs"]] return cfg @@ -154,6 +163,74 @@ def repo_status(repo: Path | str, stuck_minutes: int = DEFAULT_STUCK_MINUTES, no return status +def _newest_run_dir(runs: list[str]) -> Path | None: + """The most recently active nightshift run dir under the folders in `runs`. + + A run dir is a folder with a run.toml; activity means its .gate/supervise.jsonl exists, and the + newest such file wins so several runs can share one notes folder. + """ + best: tuple[float, Path] | None = None + for root in runs: + base = Path(root) + if not base.is_dir(): + continue + for child in sorted(base.iterdir()): + gate_file = child / ".gate" / "supervise.jsonl" + if not (child.is_dir() and (child / "run.toml").is_file() and gate_file.is_file()): + continue + mtime = gate_file.stat().st_mtime + if best is None or mtime > best[0]: + best = (mtime, child) + return best[1] if best else None + + +def nightshift_run( + cfg: Config | None = None, + run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run, +) -> dict[str, object] | None: + """The active nightshift run as one dict for the agents view; None when the feature is off. + + Runs ` status --json ` on the most recently touched run dir and maps + its JSON to the fields the view shows. Any failure (no runs, non-zero exit, bad JSON, timeout) + comes back as {"error": ""} instead of raising: this is a read-only glance, and Iris + never starts, stops or changes a run. + """ + cfg = cfg or load_config() + if not cfg.nightshift_command: + return None + run_dir = _newest_run_dir(cfg.nightshift_runs) + if run_dir is None: + return {"error": "no nightshift runs found"} + cmd = [*cfg.nightshift_command, "status", "--json", str(run_dir)] + try: + proc = run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", + timeout=NIGHTSHIFT_TIMEOUT, check=False) + except subprocess.TimeoutExpired as exc: + return {"error": f"nightshift status timed out after {exc.timeout} seconds"} + except (OSError, subprocess.SubprocessError) as exc: + return {"error": f"nightshift status failed: {exc}"} + if proc.returncode != 0: + last = (proc.stderr or "nightshift status failed").strip().splitlines()[-1] + return {"error": last} + try: + data = json.loads(proc.stdout) + done = len(data["done"]) if isinstance(data.get("done"), list) else 0 + blocked = len(data["blocked"]) if isinstance(data.get("blocked"), list) else 0 + return { + "name": str(data["name"]), + "done": done, + "total": int(data["total"]), + "blocked": blocked, + "next_item": data["next_item"], + "next_title": data["next_title"], + "current_minutes": data["current_minutes"], + "gate": str(data["gate"]), + "dir": str(run_dir), + } + except (KeyError, TypeError, ValueError) as exc: + return {"error": f"bad nightshift status JSON: {exc}"} + + def agents_status(config: Path | str | None = None) -> str: """Status of every watched agent repo: branch, last commit and age, uncommitted files, BLOCKED.md.""" cfg = load_config(config) diff --git a/iris/agents.toml b/iris/agents.toml index 4b5dcbf..e1bab53 100644 --- a/iris/agents.toml +++ b/iris/agents.toml @@ -5,8 +5,14 @@ # repos explicit repo roots, for example ["C:/code/my-app", "D:/work/api"] # worktrees roots that contain Cline worktrees: each / that is a git repo is added, # so a new worktree shows up in the status without editing this file (default ~/.cline/worktrees) +# nightshift_command how to call nightshift, for example ["W:/nightshift/.venv/Scripts/python.exe", "-m", "nightshift"]; +# empty = the active-run glance is off (the default) +# nightshift_runs folders that hold run dirs (a run dir has a run.toml), for example ["W:/Opus-notes"] repos = [] # Minutes without a commit, together with uncommitted changes, that count as STUCK. stuck_minutes = 60 + +nightshift_command = [] +nightshift_runs = [] diff --git a/iris/dashboard/__init__.py b/iris/dashboard/__init__.py index 332f87e..ac82a45 100644 --- a/iris/dashboard/__init__.py +++ b/iris/dashboard/__init__.py @@ -6,7 +6,8 @@ /api/system CPU %, RAM used/total, per-GPU load, VRAM and temperature, with a five-minute history for the sparklines /api/agents one row per watched repo (branch, last commit and age, uncommitted - count, BLOCKED.md, STUCK), stuck rows first; cached 30 s + count, BLOCKED.md, STUCK), stuck rows first; when agents.toml names a nightshift command the payload + also carries its active run's status; cached 30 s /api/runs one progress row per watched repo that has a PROGRESS-*.md file: item counts and whether the run is done; not-done runs first, then by name; cached 30 s /api/lmstudio every model LM Studio knows, with its state (loaded or not) and type @@ -124,7 +125,7 @@ def system_payload() -> dict[str, Any]: def agents_payload() -> dict[str, Any]: """One structured row per watched repo; the stuck ones come first.""" - from iris.agents import discover, load_config, repo_status + from iris.agents import discover, load_config, nightshift_run, repo_status cfg = load_config() rows = [] @@ -136,7 +137,11 @@ def agents_payload() -> dict[str, Any]: "uncommitted": s.uncommitted, "blocked": s.blocked, "stuck": s.stuck, "error": s.error}) rows.sort(key=lambda r: 0 if r["stuck"] else 1) # stuck first, stable otherwise - return {"rows": rows} + payload: dict[str, Any] = {"rows": rows} + ns = nightshift_run(cfg) # the active-run glance; None when agents.toml names no command + if ns is not None: + payload["nightshift"] = ns + return payload def runs_payload() -> dict[str, Any]: diff --git a/iris/dashboard/index.html b/iris/dashboard/index.html index a81747b..b487e46 100644 --- a/iris/dashboard/index.html +++ b/iris/dashboard/index.html @@ -65,6 +65,7 @@ .b-stuck{color:#f85149;background:rgba(248,81,73,.14)} .b-blocked{color:#d29922;background:rgba(210,153,34,.14)} .a-err{color:#8a9099;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:170px} +.ns-line{color:#8a9099;font-size:11px;padding:2px 8px 6px;border-bottom:1px solid #23262c} /* lm studio */ .lm-head{display:flex;align-items:center;gap:8px;margin-bottom:6px} @@ -567,6 +568,19 @@

Settings

body.appendChild(el("div", "empty", d && d.error ? d.error : "no data yet")); return; } + if (d.nightshift){ // the active nightshift run, when agents.toml names a command; above the repo list + const n = d.nightshift; + let line; + if (n.error){ + line = n.error; // already says what happened ("no nightshift runs found", ...) + } else { + const on = n.next_item != null ? "on " + n.next_item + " " + (n.next_title || "") : "complete"; + const mins = n.current_minutes != null ? " for " + n.current_minutes + " min" : ""; + line = "nightshift " + n.name + ": " + n.done + "/" + n.total + " done, " + n.blocked + + " blocked, " + on + mins + ", last check " + n.gate; + } + body.appendChild(el("div", "ns-line", line)); + } const head = el("div", "arow a-head"); ["repo", "branch", "last commit", "uncommitted", ""].forEach(h => { head.appendChild(el("span", null, h)); diff --git a/tests/test_agents.py b/tests/test_agents.py index 6230072..964694b 100644 --- a/tests/test_agents.py +++ b/tests/test_agents.py @@ -1,5 +1,6 @@ """Tests for the read-only agent manager, against temporary git repos (no real repos touched).""" +import json import os import subprocess import time @@ -255,6 +256,7 @@ def test_shipped_config_is_an_empty_example(): shipped = Path(__file__).resolve().parents[1] / "iris" / "agents.toml" cfg = load_config(shipped) assert cfg.repos == [] and cfg.stuck_minutes == 60 + assert cfg.nightshift_command == [] and cfg.nightshift_runs == [] # the glance is off out of the box def test_repos_come_from_the_env_var(monkeypatch, tmp_path): @@ -283,3 +285,192 @@ def test_age_is_spoken_in_readable_units(): assert _age(12 * 60) == "12 minutes" and _age(2 * 3600) == "2 hours" assert _age(3 * 86400) == "3 days" and _age(2 * 86400 * 365) == "2 years" assert _age(None) == "a while" + + +class _StatusProc: + """A stand-in for subprocess.run's result; the fake runner hands one of these back.""" + + def __init__(self, returncode=0, stdout="", stderr=""): + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + + +def _status_json() -> str: + """The same JSON nightshift status --json prints (see _status_payload in the nightshift cli).""" + return json.dumps({ + "name": "qwen92", + "total": 2, + "done": [1], + "blocked": [], + "next_item": 2, + "next_title": "dashboard: show it on the agents view", + "current_minutes": 7, + "gate": "pass", + "commits": [{"hash": "abc1234", "subject": "Q1: agents: read the active nightshift run"}], + "events": [], + }) + + +def make_run_dir(root: Path, name: str, *, minutes_ago: float = 0) -> Path: + """A nightshift run dir: a folder with a run.toml and .gate/supervise.jsonl. + + `minutes_ago` backdates the supervise file so 'most recently touched' is deterministic. + """ + d = root / name + (d / ".gate").mkdir(parents=True) + (d / "run.toml").write_text("[run]\nname = \"test\"\n", encoding="utf-8") + gate_file = d / ".gate" / "supervise.jsonl" + gate_file.write_text("{}\n", encoding="utf-8") + stamp = time.time() - minutes_ago * 60 + os.utime(gate_file, (stamp, stamp)) + return d + + +def test_nightshift_run_is_off_by_default(tmp_path): + calls: list[list[str]] = [] + + def fake(*args, **kwargs): + calls.append(args[0]) + return _StatusProc(stdout=_status_json()) + + assert agents.nightshift_run(Config(nightshift_command=[], nightshift_runs=[str(tmp_path)]), run=fake) is None + assert calls == [] # the command never runs when the feature is off + + +def test_config_reads_the_nightshift_keys(tmp_path): + loaded = load_config(write_config(tmp_path, repos=[], worktrees=[])) # no nightshift keys at all + assert loaded.nightshift_command == [] and loaded.nightshift_runs == [] + p = tmp_path / "ns.toml" + p.write_text('nightshift_command = ["W:/ns/python.exe", "-m", "nightshift"]\n' + 'nightshift_runs = ["W:/Opus-notes"]\n', encoding="utf-8") + loaded = load_config(p) + assert loaded.nightshift_command == ["W:/ns/python.exe", "-m", "nightshift"] + assert loaded.nightshift_runs == ["W:/Opus-notes"] + + +def test_nightshift_run_picks_the_most_recently_touched_run(tmp_path): + make_run_dir(tmp_path, "old-run", minutes_ago=90) + new = make_run_dir(tmp_path, "new-run") # touched just now + argvs: list[list[str]] = [] + + def fake(*args, **kwargs): + argvs.append(args[0]) + return _StatusProc(stdout=_status_json()) + + out = agents.nightshift_run(Config(nightshift_command=["ns"], nightshift_runs=[str(tmp_path)]), run=fake) + assert out is not None and "error" not in out + assert out["dir"] == str(new) # the newer supervise.jsonl wins, not the folder name + assert argvs[0] == ["ns", "status", "--json", str(new)] + + +def test_nightshift_run_maps_the_status_fields(tmp_path): + run_dir = make_run_dir(tmp_path, "qwen92") + + def fake(*args, **kwargs): + return _StatusProc(stdout=_status_json()) + + out = agents.nightshift_run(Config(nightshift_command=["ns"], nightshift_runs=[str(tmp_path)]), run=fake) + assert out == { + "name": "qwen92", + "done": 1, + "total": 2, + "blocked": 0, + "next_item": 2, + "next_title": "dashboard: show it on the agents view", + "current_minutes": 7, + "gate": "pass", + "dir": str(run_dir), + } + + +def test_nightshift_run_counts_done_and_blocked_items(tmp_path): + make_run_dir(tmp_path, "qwen92") + payload = json.dumps({"name": "done-run", "total": 5, "done": [1, 2], "blocked": [3, 4], + "next_item": None, "next_title": None, "current_minutes": None, "gate": "fail"}) + + def fake(*args, **kwargs): + return _StatusProc(stdout=payload) + + out = agents.nightshift_run(Config(nightshift_command=["ns"], nightshift_runs=[str(tmp_path)]), run=fake) + assert out is not None and "error" not in out + assert out["done"] == 2 and out["blocked"] == 2 # counts, not the raw lists + assert out["next_item"] is None and out["next_title"] is None and out["current_minutes"] is None + assert out["gate"] == "fail" + + +def test_nightshift_run_argv_is_exactly_command_plus_status_json_and_dir(tmp_path): + run_dir = make_run_dir(tmp_path, "qwen92") + seen: dict[str, object] = {} + + def fake(*args, **kwargs): + seen["argv"] = args[0] + seen.update(kwargs) + return _StatusProc(stdout=_status_json()) + + agents.nightshift_run(Config(nightshift_command=["W:/ns/python.exe", "-m", "nightshift"], + nightshift_runs=[str(tmp_path)]), run=fake) + assert seen["argv"] == ["W:/ns/python.exe", "-m", "nightshift", "status", "--json", str(run_dir)] + assert seen["capture_output"] is True and seen["text"] is True + assert seen["encoding"] == "utf-8" and seen["errors"] == "replace" + assert seen["timeout"] == 20 + + +def test_nightshift_run_reports_when_no_runs_exist(tmp_path): + (tmp_path / "not-a-run").mkdir() # a folder without run.toml is not a run dir + bare = make_run_dir(tmp_path, "no-gate") + (bare / ".gate" / "supervise.jsonl").unlink() # a run dir nobody has touched yet: skipped + calls: list[list[str]] = [] + + def fake(*args, **kwargs): + calls.append(args[0]) + return _StatusProc(stdout=_status_json()) + + runs = [str(tmp_path), str(tmp_path / "missing")] # a missing root is skipped too + out = agents.nightshift_run(Config(nightshift_command=["ns"], nightshift_runs=runs), run=fake) + assert isinstance(out, dict) and set(out) == {"error"} + assert "no nightshift runs" in str(out["error"]) + assert calls == [] # nothing to ask, so the command never runs + + +def test_nightshift_run_reports_a_non_zero_exit(tmp_path): + make_run_dir(tmp_path, "qwen92") + + def fake(*args, **kwargs): + return _StatusProc(returncode=1, stderr="boom: first line\nthe last line\n") + + out = agents.nightshift_run(Config(nightshift_command=["ns"], nightshift_runs=[str(tmp_path)]), run=fake) + assert out == {"error": "the last line"} + + +def test_nightshift_run_reports_bad_json(tmp_path): + make_run_dir(tmp_path, "qwen92") + + def fake(*args, **kwargs): + return _StatusProc(stdout="{oops") + + out = agents.nightshift_run(Config(nightshift_command=["ns"], nightshift_runs=[str(tmp_path)]), run=fake) + assert isinstance(out, dict) and set(out) == {"error"} + assert "JSON" in str(out["error"]) + + +def test_nightshift_run_reports_a_timeout(tmp_path): + make_run_dir(tmp_path, "qwen92") + + def fake(*args, **kwargs): + raise subprocess.TimeoutExpired(cmd="ns", timeout=20) + + out = agents.nightshift_run(Config(nightshift_command=["ns"], nightshift_runs=[str(tmp_path)]), run=fake) + assert isinstance(out, dict) and set(out) == {"error"} + assert "timed out" in str(out["error"]) + + +def test_nightshift_run_reports_a_missing_command(tmp_path): + make_run_dir(tmp_path, "qwen92") + + def fake(*args, **kwargs): + raise FileNotFoundError("ns not found") + + out = agents.nightshift_run(Config(nightshift_command=["ns"], nightshift_runs=[str(tmp_path)]), run=fake) + assert isinstance(out, dict) and set(out) == {"error"} + assert "failed" in str(out["error"]) diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 40214f1..044c9f5 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -457,6 +457,39 @@ def test_api_agents_stuck_rows_first(tmp_path, monkeypatch): assert rows[0]["uncommitted"] == 1 and rows[0]["branch"] == "main" +def test_agents_payload_has_no_nightshift_key_when_the_feature_is_off(tmp_path, monkeypatch): + import iris.agents as agents_mod + from tests.test_agents import make_repo, write_config + + repo = make_repo(tmp_path, "fresh") + monkeypatch.setattr(agents_mod, "CONFIG", write_config(tmp_path, repos=[str(repo)], worktrees=[])) + + assert "nightshift" not in agents_payload() # no nightshift_command in agents.toml: the glance is off + + +def test_agents_payload_carries_the_nightshift_run_when_configured(tmp_path, monkeypatch): + import iris.agents as agents_mod + from tests.test_agents import make_repo + + repo = make_repo(tmp_path, "fresh") + cfg = tmp_path / "agents.toml" + lines = [f"repos = [{str(repo)!r}]".replace("'", '"'), # repr doubles the backslashes: valid TOML on Windows + 'worktrees = []', "stuck_minutes = 60", + 'nightshift_command = ["python", "-m", "nightshift"]', + 'nightshift_runs = ["C:/runs"]'] + cfg.write_text("\n".join(lines) + "\n", encoding="utf-8") + monkeypatch.setattr(agents_mod, "CONFIG", cfg) + + fake = {"name": "qwen92", "done": 1, "total": 2, "blocked": 0, "next_item": 2, + "next_title": "dashboard: show it on the agents view", "current_minutes": 7, + "gate": "pass", "dir": "C:/runs/qwen92"} + monkeypatch.setattr(agents_mod, "nightshift_run", lambda cfg=None: fake) + + data = agents_payload() + assert data["nightshift"] == fake # the runner's result, untouched; the rows are still there + assert [r["name"] for r in data["rows"]] == ["fresh"] + + @pytest.fixture(scope="module") def runs_repos(tmp_path_factory): """alpha and zeta are not done, beta is done, gamma has no PROGRESS file at all. Built once for both /api/runs