diff --git a/skills/kvb-git-hotfix/scripts/hotfix.py b/skills/kvb-git-hotfix/scripts/hotfix.py index 63a3d82..71f788a 100755 --- a/skills/kvb-git-hotfix/scripts/hotfix.py +++ b/skills/kvb-git-hotfix/scripts/hotfix.py @@ -624,11 +624,20 @@ def set_status(rasci: ModuleType, row: dict, status: str) -> None: rasci.apply_status(row, final) +def known(rasci: ModuleType) -> dict[str, dict]: + """Returns: + The register over its archive: rasci.py archives a task done or + stopped for more than a week, and a hotfix there is still this + skill's to adopt or move on. + """ + return {**rasci.load(rasci.ARCHIVE), **rasci.load()} + + def cmd_add(rasci: ModuleType, args: argparse.Namespace) -> int: task = task_of(rasci, args.slug) repo = clone(args.repo) common, origin = identity(repo) - adoptable(task, rasci.load().get(task), args.branch, (common, origin)) + adoptable(task, known(rasci).get(task), args.branch, (common, origin)) entry = { "common_dir": common, "origin": origin, @@ -644,7 +653,7 @@ def cmd_add(rasci: ModuleType, args: argparse.Namespace) -> int: council = module("council", rasci.COUNCIL) sid, _ = council.caller(args.session) author = council.live_sessions().get(sid) or sid - with rasci.database() as tasks: + with rasci.database(task) as tasks: row = adoptable(task, tasks.get(task), entry["branch"], (common, origin)) entry = {**row, **entry, "roles": authored(row.get("roles") or {}, author)} set_status(rasci, entry, REGISTER_STATUS[args.status]) @@ -700,7 +709,7 @@ def cmd_update(rasci: ModuleType, args: argparse.Namespace) -> int: pr = number(args.pr) if args.status == "merged" and args.sha is None: fail("--status merged needs --sha, the commit as it sits on the default branch") - entry = rasci.load().get(task) + entry = known(rasci).get(task) if entry is None or "stage" not in entry: fail(f"{task}: no hotfix in the register; record it with add") fields: dict = {} @@ -710,7 +719,7 @@ def cmd_update(rasci: ModuleType, args: argparse.Namespace) -> int: fields["sha"] = landed(where, args.sha, args.default) if args.status == "merged" else commit(where, args.sha) if pr is not None: fields["pr"] = pr - with rasci.database() as tasks: + with rasci.database(task) as tasks: entry = tasks.get(task) if entry is None or "stage" not in entry: fail(f"{task}: no hotfix in the register; record it with add") diff --git a/skills/kvb-org-organize/scripts/hooks.py b/skills/kvb-org-organize/scripts/hooks.py index e9bc5fd..fc323cb 100755 --- a/skills/kvb-org-organize/scripts/hooks.py +++ b/skills/kvb-org-organize/scripts/hooks.py @@ -68,7 +68,7 @@ def handle(script: str, sub: str, raw: str) -> tuple[int, str, str]: code = module.main() except SystemExit as stop: code = exit_code(stop) - except Exception: + except Exception: # noqa: BLE001 import traceback traceback.print_exc() diff --git a/skills/kvb-org-rasci/SKILL.md b/skills/kvb-org-rasci/SKILL.md index db25c88..7f7eb75 100644 --- a/skills/kvb-org-rasci/SKILL.md +++ b/skills/kvb-org-rasci/SKILL.md @@ -6,7 +6,7 @@ description: > --- The register is the organisation's single point of truth: every agent -records what it works on; claims, queue, handover and reports run over it. `${CLAUDE_SKILL_DIR}/scripts/rasci.py` keeps it in +records what it works on. `${CLAUDE_SKILL_DIR}/scripts/rasci.py` keeps it in `/rasci.json`. A `kvb-org-organize` claim enters its task by itself (holder as R and A, `running`, start, workdir, branch); its release sets `done` and the end, or `stopped` while a key result is still open. @@ -17,6 +17,8 @@ rasci.py kr add "" | met | open | rm rasci.py role "" rasci.py get rasci.py rm +rasci.py keep +rasci.py prune --since ... rasci.py show [--wide] [--all] [--gaps] rasci.py artifacts [--ended] [--task ] [--worker ] rasci.py estimate "" --value --complexity @@ -40,10 +42,8 @@ published). `done` is refused while one is open; a task ended short of them is - **R Responsible**: does the task: the claim holder, or the subagent it runs. - **A Accountable**: exactly one; takes the final decision. The claim holder, unless the operator decides. -- **S Supportive**: helps carry it out: a peer's fix, the chair's grant, a - runner. -- **C Consulted**: asked before acting: line representatives, lineage - owners, the operator on a pending decision. +- **S Supportive**: helps carry it out: a fix, a grant, a runner. +- **C Consulted**: asked before acting, e.g. the operator on a decision. - **I Informed**: kept informed, without a say. `-` clears a party; the operator is the party `Operator`. @@ -53,7 +53,7 @@ published). `done` is refused while one is open; a task ended short of them is - On start, `set` title, objective, description, priority and worker, `kr add` every key result, and `role` every party beyond R and A; update the status on each change. -- Artifacts share this table and follow the `kvb-org-artefacts` skill: +- Artifacts follow the `kvb-org-artefacts` skill: record each one when it appears, drop it once deleted. Add every script or tool the task ran (`--tool`): `tools` ranks them for `kvb-dream`. - Priority is the rank of the `kvb-org-wsjf` skill: an operator's pin @@ -63,7 +63,9 @@ published). `done` is refused while one is open; a task ended short of them is recorded alone, replaces the median. - `--after ` records that a task follows another (a Gantt arrow); an unknown task and a cycle are refused. -- Write only your own rows; another session's task belongs to that session. +- Write only your own rows. +- Until a hub prune's Sécurité deadline, `keep` (or any change) holds a + listed task open; the rest end `stopped`. - Read `show` or `get` instead of asking a peer what it works on; `--wide` adds OKR, artifacts, times and every letter. Both cap at the top 30 open tasks; `--all` lists every task. Tasks ended over 7 days ago move to diff --git a/skills/kvb-org-rasci/scripts/rasci.py b/skills/kvb-org-rasci/scripts/rasci.py index a33ac7a..14f7502 100755 --- a/skills/kvb-org-rasci/scripts/rasci.py +++ b/skills/kvb-org-rasci/scripts/rasci.py @@ -8,6 +8,15 @@ Environment: work/ and cluster/ claim of the council there. The operator's agent order (`agents order`) lies beside it in /agent-order.json, apart from every task row: it breaks ties of equal task priority only. + `prune` reads the active entries of /queue.json. + +Args: + keep : set an open task's register change time to now and + nothing else, so a pending stale task prune keeps it. + prune --since ...: under the register lock set every + listed task stopped that is open, has no active queue job and no + register change after ; print `stopped ` or + `kept : ` per task. A second run stops nothing more. Exit codes: 0 done, 2 usage error. @@ -90,6 +99,7 @@ ARCHIVE = ROOT / "rasci-archive.json" ARCHIVE_AFTER = datetime.timedelta(days=7) LOCK = ROOT / "rasci.lock" AGENT_ORDER = ROOT / "agent-order.json" +QUEUE = ROOT / "queue.json" def load(path: Path = DB) -> dict[str, dict]: @@ -613,6 +623,76 @@ def cmd_rm(args: argparse.Namespace) -> int: return 0 +def change_time(row: dict) -> float | None: + try: + moment = datetime.datetime.fromisoformat(row["updated"]) + except (KeyError, TypeError, ValueError): + return None + return moment.timestamp() if moment.tzinfo is not None else None + + +def queue_running() -> set[str]: + """Returns: + The tasks of the active entries of /queue.json; none without + the file. An unreadable or malformed file fails, so a prune never + stops a task whose queue job it cannot see. + """ + try: + data = json.loads(nofollow.read_text(ROOT, QUEUE)) + except FileNotFoundError: + return set() + except (OSError, ValueError, RecursionError): + fail(f"{QUEUE} cannot be read; prune changes nothing while the running queue jobs are unknown") + entries = data.get("entries") if isinstance(data, dict) else None + if not isinstance(entries, list): + fail(f"{QUEUE} holds no entries list; prune changes nothing while the running queue jobs are unknown") + return {entry.get("task") for entry in entries if isinstance(entry, dict) and entry.get("status") == "active"} + + +def kept_why(task: str, entry: dict | None, running: set[str], since: int) -> str | None: + """Returns: + Why prune keeps the task: not in the register, already ended, an + active queue job, no change time, or a change after since; None + when it sets the task stopped. + """ + if entry is None: + return "not in the register" + if entry.get("status") in ENDED: + return f"already {entry['status']}" + if task in running: + return "a queue job runs for it" + changed = change_time(entry) + if changed is None: + return "no register change time" + return f"changed at {entry['updated']}, after the prune list" if changed > since else None + + +def cmd_keep(args: argparse.Namespace) -> int: + check_task(args.task) + with database() as tasks: + entry = tasks.get(args.task) + if entry is None or entry.get("status") in ENDED: + fail(f"{args.task}: no open task in the register; only an open one can be kept") + entry["updated"] = stamp() + print(f"kept {args.task}: its register change time is now, so a pending prune keeps it") + return 0 + + +def cmd_prune(args: argparse.Namespace) -> int: + for task in args.tasks: + check_task(task) + lines = [] + with database() as tasks: + running = queue_running() + for task in dict.fromkeys(args.tasks): + why = kept_why(task, tasks.get(task), running, args.since) + if why is None: + apply_status(tasks[task], "stopped") + lines.append(f"stopped {task}" if why is None else f"kept {task}: {why}") + print("\n".join(lines)) + return 0 + + def holders(row: dict, letter: str, width: int) -> str: parties = sorted(row["roles"], key=lambda p: (p != OPERATOR, p.lower())) return cell(", ".join(p for p in parties if letter in row["roles"][p]), width) @@ -697,10 +777,14 @@ def main() -> int: p.add_argument("party") p.add_argument("letters") p.set_defaults(func=cmd_role) - for name, func in (("get", cmd_get), ("rm", cmd_rm)): + for name, func in (("get", cmd_get), ("rm", cmd_rm), ("keep", cmd_keep)): p = sub.add_parser(name) p.add_argument("task") p.set_defaults(func=func) + p = sub.add_parser("prune") + p.add_argument("--since", type=int, required=True) + p.add_argument("tasks", nargs="+") + p.set_defaults(func=cmd_prune) p = sub.add_parser("show") p.add_argument("--all", action="store_true") p.add_argument("--wide", action="store_true") diff --git a/tests/test_hotfix.py b/tests/test_hotfix.py index 6c5af75..8408e0a 100644 --- a/tests/test_hotfix.py +++ b/tests/test_hotfix.py @@ -352,7 +352,8 @@ class TestHotfix(unittest.TestCase): self.assertNotEqual(row["end"], old) self.rasci("set", "hotfix/closed", "--status", "done", "--end", old) self.out("add", "closed", *self.flags({"--branch": "fix/db", "--sha": self.fix, "--status": "merged"})) - self.assertEqual(self.rows()["hotfix/closed"]["end"], old) + archived = json.loads((self.root / "rasci-archive.json").read_text(encoding="utf-8")) + self.assertEqual(("hotfix/closed" in self.rows(), archived["hotfix/closed"]["end"]), (False, old)) def test_pending_reports_missing_and_open_hotfixes_of_the_repository(self): expected = [ diff --git a/tests/test_lean_output.py b/tests/test_lean_output.py index 790c27d..f66f5a0 100644 --- a/tests/test_lean_output.py +++ b/tests/test_lean_output.py @@ -33,7 +33,7 @@ class Scratch(unittest.TestCase): class TestRegisterTable(Scratch): def show(self, roles: dict[str, str], results: list[dict], *args: str) -> list[str]: root = self.base / "council" - root.mkdir() + root.mkdir(exist_ok=True) rows = { f"work/t{n:03d}": {"title": f"T{n}", "prio": n, "roles": roles, "key_results": results} for n in range(1, OPEN_ROWS + 1) @@ -59,8 +59,11 @@ class TestRegisterTable(Scratch): def test_gaps_name_only_the_shown_rows(self): lines = self.show({}, []) self.assertEqual(lines[-2], f"{OPEN_ROWS - 30} more (show --all)") - self.assertIn("work/t030 has 0 A", lines[-1]) - self.assertNotIn("work/t031", lines[-1]) + self.assertRegex(lines[-1], r"^gaps: \d+ \(show --gaps\)$") + listed = [line for line in self.show({}, [], "--gaps") if line.startswith("gap: ")] + self.assertTrue(any("work/t030 has 0 A" in line for line in listed), listed) + self.assertFalse(any("work/t031" in line for line in listed), listed) + self.assertEqual(lines[-1], f"gaps: {len(listed)} (show --gaps)") class TestMemoryBudget(Scratch): diff --git a/tests/test_rasci_prune.py b/tests/test_rasci_prune.py new file mode 100644 index 0000000..c591354 --- /dev/null +++ b/tests/test_rasci_prune.py @@ -0,0 +1,118 @@ +"""Exercise requirement 075: rasci.py keep touches a task's change time, rasci.py prune stops only the unkept listed tasks.""" + +from __future__ import annotations + +import datetime +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +RASCI = REPO_ROOT / "skills" / "kvb-org-rasci" / "scripts" / "rasci.py" +OLD = "2026-11-01T08:00:00+00:00" +SINCE = int(datetime.datetime.fromisoformat("2026-11-20T00:00:00+00:00").timestamp()) + + +def row(status: str, updated: str, **fields: object) -> dict: + return {"roles": {"Docs": "RA"}, "status": status, "updated": updated, "title": "t", **fields} + + +class TestRasciPrune(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.home = Path(self.tmp.name) / "home" + self.root = Path(self.tmp.name) / "council" + self.home.mkdir() + self.root.mkdir() + self.write({ + "work/stale": row("queued", OLD), + "work/blocked": row("blocked", OLD), + "work/fresh": row("running", "2026-11-25T08:00:00+00:00"), + "work/queued-job": row("running", OLD), + "work/done": row("done", OLD, end=OLD), + "work/other": row("queued", OLD), + }) + + def write(self, tasks: dict) -> None: + (self.root / "rasci.json").write_text(json.dumps(tasks), encoding="utf-8") + + def tasks(self) -> dict: + return json.loads((self.root / "rasci.json").read_text(encoding="utf-8")) + + def run_rasci(self, *args: str) -> subprocess.CompletedProcess: + env = {"PATH": "/usr/bin:/bin", "HOME": str(self.home), "AGENTS_COUNCIL_ROOT": str(self.root)} + return subprocess.run([sys.executable, str(RASCI), *args], capture_output=True, text=True, env=env, cwd=self.tmp.name, check=False, timeout=120) + + def queue(self, entries: list[dict]) -> None: + (self.root / "queue.json").write_text(json.dumps({"seq": len(entries), "entries": entries}), encoding="utf-8") + + def test_keep_moves_only_the_change_time_of_an_open_task(self): + before = self.tasks()["work/stale"] + done = self.run_rasci("keep", "work/stale") + self.assertEqual(done.returncode, 0, done.stderr) + after = self.tasks()["work/stale"] + self.assertGreater(datetime.datetime.fromisoformat(after["updated"]), datetime.datetime.fromisoformat(OLD)) + self.assertEqual({key: value for key, value in after.items() if key != "updated"}, {key: value for key, value in before.items() if key != "updated"}) + + def test_keep_refuses_an_unknown_or_ended_task_and_writes_nothing(self): + before = (self.root / "rasci.json").read_bytes() + for task in ("work/missing", "work/done"): + with self.subTest(task=task): + done = self.run_rasci("keep", task) + self.assertEqual(done.returncode, 2) + self.assertIn("no open task", done.stderr) + self.assertEqual((self.root / "rasci.json").read_bytes(), before) + + def test_prune_stops_the_unchanged_open_listed_tasks_and_reports_every_other_as_kept(self): + self.queue([{"id": "test-1", "task": "work/queued-job", "status": "active"}, {"id": "test-2", "task": "work/stale", "status": "waiting"}]) + done = self.run_rasci("prune", "--since", str(SINCE), "work/stale", "work/blocked", "work/fresh", "work/queued-job", "work/done", "work/missing") + self.assertEqual(done.returncode, 0, done.stderr) + lines = done.stdout.splitlines() + self.assertEqual(lines[:2], ["stopped work/stale", "stopped work/blocked"]) + self.assertTrue(lines[2].startswith("kept work/fresh: changed at 2026-11-25T08:00:00+00:00"), lines) + self.assertEqual(lines[3:], ["kept work/queued-job: a queue job runs for it", "kept work/done: already done", "kept work/missing: not in the register"]) + tasks = self.tasks() + self.assertEqual({task: tasks[task]["status"] for task in tasks}, {"work/stale": "stopped", "work/blocked": "stopped", "work/fresh": "running", "work/queued-job": "running", "work/other": "queued"}) + self.assertIn("end", tasks["work/stale"]) + archived = json.loads((self.root / "rasci-archive.json").read_text(encoding="utf-8")) + self.assertEqual(archived["work/done"]["status"], "done") + + def test_a_task_kept_after_the_list_was_taken_stays_open(self): + self.assertEqual(self.run_rasci("keep", "work/stale").returncode, 0) + done = self.run_rasci("prune", "--since", str(SINCE), "work/stale", "work/other") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue(done.stdout.startswith("kept work/stale: changed at "), done.stdout) + self.assertEqual((self.tasks()["work/stale"]["status"], self.tasks()["work/other"]["status"]), ("queued", "stopped")) + + def test_a_task_never_listed_is_never_changed(self): + before = self.tasks()["work/other"] + self.assertEqual(self.run_rasci("prune", "--since", str(SINCE), "work/stale").returncode, 0) + self.assertEqual(self.tasks()["work/other"], before) + + def test_a_second_prune_stops_nothing_more(self): + first = self.run_rasci("prune", "--since", str(SINCE), "work/stale") + snapshot = self.tasks() + second = self.run_rasci("prune", "--since", str(SINCE), "work/stale") + self.assertEqual((first.stdout, second.stdout), ("stopped work/stale\n", "kept work/stale: already stopped\n")) + self.assertEqual(self.tasks(), snapshot) + + def test_an_unreadable_queue_file_fails_and_stops_nothing(self): + before = (self.root / "rasci.json").read_bytes() + (self.root / "queue.json").write_text("{not json", encoding="utf-8") + done = self.run_rasci("prune", "--since", str(SINCE), "work/stale") + self.assertEqual(done.returncode, 2) + self.assertIn("running queue jobs are unknown", done.stderr) + self.assertEqual((self.root / "rasci.json").read_bytes(), before) + + def test_prune_refuses_an_invalid_slug_or_a_missing_since(self): + self.assertEqual(self.run_rasci("prune", "--since", str(SINCE), "Not A Slug").returncode, 2) + self.assertEqual(self.run_rasci("prune", "work/stale").returncode, 2) + self.assertEqual(self.tasks()["work/stale"]["status"], "queued") + + +if __name__ == "__main__": + unittest.main()