diff --git a/README.md b/README.md index 80391ee..51beed2 100644 --- a/README.md +++ b/README.md @@ -102,8 +102,8 @@ its limits are. | `sisi plan brief` / `sisi plan --record FILE` / `sisi plan` / `sisi plan --done\|--fail ID "…"` | The dependency graph of a piece of work, recorded before any delegation: `\| node \| class \| needs \| branch \| files \| check \| why \|`, one join every node reaches; refused on a cycle, a missing need, a shared branch, or overlapping files between nodes that can run at once. Prints the waves to dispatch together. `sisi pick --node ID` gives the worker and a header for the brief; the hook denies a lead's delegation outside the plan, out of order, unpicked, or without its own worktree, and the end of a turn sends the lead back while ready nodes wait. `sisi judge` closes or reopens the node. A `sisi chore:` brief (models research, plan brief) needs no plan. `"enforce": false` turns denials into reminders | | `sisi models` / `sisi models research [--record FILE]` | The workers table: at most one row per provider (the plan or account a call draws on) per class, the one whose published allowance goes furthest, with its source and quota windows (`5h: N req; week: N req`); the wheel picks a plan less the more of its windows sisi's own delegations have used (never below 5%); research is redone every 3 days by a hard worker. (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it | | `sisi models offered [--record FILE]` | Save the host's raw offered-model list from stdin and print the chore to match it against the table; `--record FILE` saves the harness's wheel so `sisi pick` only returns models this harness offers | -| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest] [--node ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first, `--newest` the newest, and `--node ID` closes or reopens the job running that plan node | -| `sisi judge WORKER extend MINUTES "" [--newest] [--node ID]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest, or the job for `--node ID`) gets MINUTES more from now, and its late fault clears | +| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest] [--node ID \| --chore ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first (and if another open job has `--node`/`--chore`, a note names the closed job and the remaining ones with their targeting flags), `--newest` the newest, `--node ID` closes or reopens the job running that plan node, and `--chore ID` closes that chore job | +| `sisi judge WORKER extend MINUTES "" [--newest] [--node ID \| --chore ID]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest, or the job for `--node ID` / `--chore ID`) gets MINUTES more from now, and its late fault clears | | `sisi direct "…"` | Allow more direct tool calls this turn, with the reason | ## Where things live diff --git a/sisi/cli.py b/sisi/cli.py index a6c0161..d2a56e1 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -41,10 +41,10 @@ Delegation sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME] the wheel gives you one worker for a ready plan node (or of a class, for a `sisi chore:` brief); one pick, one delegation - sisi judge WORKER good|bad|out WHY | extend MINUTES WHY [--newest] [--node ID] + sisi judge WORKER good|bad|out WHY | extend MINUTES WHY [--newest] [--node ID | --chore ID] how a delegation went (`out` with the provider's own message when it hit a limit: sisi tries it again by itself), or give a running job more time; - --node ID names the job itself when one worker runs two plan nodes + --node ID or --chore ID names the job itself when a worker runs several sisi direct REASON allow yourself more direct tool calls this turn, with the reason Setting up diff --git a/sisi/hooks.py b/sisi/hooks.py index 29b21e0..1d0593d 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -194,7 +194,10 @@ def watch(p): notes += stop + soft screen_brief_without_look(brief) and notes.append(NOLOOK) s.update(probe) # the pick this delegation spent, if any - chore is None or s["chores"].pop(chore) + cid = s["chores"].pop(chore)[3] if chore is not None else None + if (c := probe.get("claimed")) and cid: + k, m = "%s %r" % c, s.get("meta") if isinstance(s.get("meta"), dict) else {} + s["meta"] = {**m, k: {**(m.get(k) if isinstance(m.get(k), dict) else {}), "chore": cid}} if node and probe.get("claimed"): from . import plan plan.start(s, node, *probe["claimed"]) @@ -295,5 +298,7 @@ def gate(p, for_subagent=False): return 0 s["blocks"] = s.get("blocks", 0) + 1 demand and s.setdefault("retro_demanded", time.time()) + if unjudged := models.unjudged(s): + reason += "\nsisi: unjudged jobs: " + ", ".join(unjudged) print(json.dumps({"decision": "block", "reason": say(reason)})) return 0 diff --git a/sisi/models.py b/sisi/models.py index 265de28..67498c9 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -236,6 +236,30 @@ def overdue(s): return list(by_w.items()) +def _job_info(s, w, t): + """(tag, flag, hhmm) for the open job of worker w started at t: tag is `node X`, `chore Y` or empty.""" + meta = s["meta"] if isinstance(s.get("meta"), dict) else {} + m = meta.get("%s %r" % (w, t)) + m = m if isinstance(m, dict) else {} + nid = m.get("node") or next((k for k, v in ((s.get("plan") or {}).get("state") or {}).items() + if isinstance(v, dict) and v.get("st") == "running" and v.get("worker") == w and v.get("since") == t), None) + cid, hhmm = m.get("chore"), time.strftime("%H:%M", time.localtime(t)) + if nid: return "node %s" % nid, "--node %s" % nid, hhmm + if cid: return "chore %s" % cid, "--chore %s" % cid, hhmm + return "", "", hhmm + + +def unjudged(s): + """['WORKER (node X | chore Y, started HH:MM)', ...] for the open jobs in `s["starts"]`, oldest first.""" + starts, jobs = s.get("starts") if isinstance(s.get("starts"), dict) else {}, [] + for w, v in starts.items(): + for t in (v if isinstance(v, list) else ()): + if type(t) in (int, float) and math.isfinite(t): + tag, _, hhmm = _job_info(s, w, t) + jobs.append((t, "%s (%sstarted %s)" % (w, tag + ", " if tag else "", hhmm))) + return [text for _, text in sorted(jobs)] + + def waiting(s): """A delegation of this piece of work is open: started and not yet judged.""" return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values()) @@ -476,10 +500,11 @@ def sync_late(s, cwd, sid, add=True): def judge(args, cwd=None): - """`sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID] | extend MINUTES "" [--newest] [--node ID]`. - Without --node a verdict closes the worker's oldest open job (--newest: its newest); with --node, the job that runs that plan node.""" + """`sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "" [--newest] [--node ID | --chore ID]`. + Without --node/--chore a verdict closes the worker's oldest open job (--newest: its newest); with --node, the job that runs that + plan node; with --chore, the job started under that chore id.""" from . import retro # not at the top: hooks import this module and must stay quick - args, newest, minutes, note, node = [a for a in args if a != "--newest"], "--newest" in args, None, "", None + args, newest, minutes, note, node, chore, warn = [a for a in args if a != "--newest"], "--newest" in args, None, "", None, None, "" if "--minutes" in args: i = args.index("--minutes") v, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:] @@ -487,10 +512,13 @@ def judge(args, cwd=None): if "--node" in args: # the plan node whose job is judged: one worker may run several i = args.index("--node") node, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:] + if "--chore" in args: # the chore whose job is judged + i = args.index("--chore") + chore, args = (args[i + 1:i + 2] or [""])[0].lower(), args[:i] + args[i + 2:] ext = len(args) == 4 and args[1] == "extend" and minutes is None and re.fullmatch(r"[1-9]\d{0,3}|10000", args[2]) if not args or not args[0].strip() or not (ext or (len(args) == 3 and args[1] in ("good", "bad", "out") and minutes != 0)) or len(args[-1].split()) < 3 \ - or (node is not None and not re.fullmatch(r"[a-z0-9-]{1,30}", node)): - print('usage: sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID] | extend MINUTES "" [--newest] [--node ID]') + or (node is not None and not re.fullmatch(r"[a-z0-9-]{1,30}", node)) or chore == "" or (node is not None and chore is not None): + print('usage: sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "" [--newest] [--node ID | --chore ID]') return 1 wrows = rows(wheel()[0]) # a worker's wheel row wins over its table row (the list is the truth), and is counted once trows = wrows + [r for r in rows(store.read(table())) if short(r[0]) not in {short(x[0]) for x in wrows}] @@ -516,6 +544,14 @@ def judge(args, cwd=None): return print("sisi judge: node %s is not a job %s is running here, so --node names nothing. Nothing was changed." % (node, wkey)) or 1 cand = v["since"] if type(v.get("since")) in (int, float) and v["since"] in open_ else None not ext and cand is not None and open_.remove(cand) + elif chore is not None: # --chore: the job started under this chore id + meta = s["meta"] if isinstance(s.get("meta"), dict) else {} + cand = next((t for t in open_ if isinstance(m := meta.get("%s %r" % (wkey, t)), dict) and m.get("chore") == chore), None) + if cand is None: + infos = [_job_info(s, wkey, t) for t in open_ if type(t) in (int, float) and math.isfinite(t)] + jobs = ["%s (started %s)" % (tag, hhmm) if tag else "started %s" % hhmm for tag, _, hhmm in infos] + return print("sisi judge: chore %s is not an open job for %s (open: %s). Nothing was changed." % (chore, wkey, ", ".join(jobs) or "none")) or 1 + if not ext: open_.remove(cand) else: cand = (open_.pop(-1 if newest else 0) if not ext else open_[-1 if newest else 0]) if open_ else None if ext and not newest: # the job that is late, not just the oldest open one @@ -527,6 +563,13 @@ def judge(args, cwd=None): m[k], s["meta"] = {**(m[k] if isinstance(m.get(k), dict) else {}), "limit": lim, "extended": now, "reason": retro.clean(args[3])}, m isinstance(s.get("reminded"), list) and s.__setitem__("reminded", [x for x in s["reminded"] if x != [wkey, cand]]) return sync_late(s, cwd, sid, False) or print("extended %s limit to %d min." % (wkey, lim)) or 0 + if ok_t and node is None and chore is None and open_: # no target named: say which job closed when it could have been another + tag, flag, hhmm = _job_info(s, wkey, cand) + others = [_job_info(s, wkey, t) for t in open_ if type(t) in (int, float) and math.isfinite(t)] + if flag or any(f for _, f, _ in others): + closed = "%s (started %s)" % (tag, hhmm) if tag else "started %s" % hhmm + left = ", ".join("%s (started %s, %s)" % (k, h, f) if f else "started %s" % h for k, f, h in others) + warn = "closed %s; still open: %s" % (closed, left) isinstance(s.get("meta"), dict) and s["meta"].pop("%s %r" % (wkey, cand), None) if node is not None: s["plan"]["state"][node] = {"st": "done", "evidence": "judged good"} if args[1] == "good" else {"st": "failed", "why": "judged " + args[1]} # as plan.judged moves the node its job started elif s.get("plan"): from . import plan; plan.judged(s, wkey, cand, args[1]) @@ -535,7 +578,7 @@ def judge(args, cwd=None): minutes = minutes or max(1, int((now - began) / 60)) note = " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(began)), len(open_)) sync_late(s, cwd, sid, False) - elif ext or node is not None: return print("sisi judge: no open job for %s." % args[0]) or 1 + elif ext or node is not None or chore is not None: return print("sisi judge: no open job for %s." % args[0]) or 1 iso = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t)) rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1], "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)), @@ -547,6 +590,7 @@ def judge(args, cwd=None): store.append(log, json.dumps(rec, sort_keys=True)) ok = store.commit("delegation judged", log) print("%s%s" % ("recorded: %d min%s." % (minutes, note) if minutes else "recorded, not timed.", "" if ok else " (store commit failed)")) + if warn: print(warn) return 0 diff --git a/tests/test_judge_chore.py b/tests/test_judge_chore.py new file mode 100644 index 0000000..ca7bf44 --- /dev/null +++ b/tests/test_judge_chore.py @@ -0,0 +1,183 @@ +"""Tests for `sisi judge --chore ID`, multi-job warnings, and stop-gate unjudged job lines. +Black-box CLI tests in a temporary home and store.""" +import glob, hashlib, json, os, re, shutil, subprocess, sys, tempfile, time, unittest + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +REAL_HOME = os.path.expanduser("~") +HEADER = "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n" +ALPHA = "| alpha | host subagent model `alpha` | routine | free | quick | |\n" +BETA = "| beta | host subagent model `beta` | routine | free | quick | |\n" + + +def tree(): + """A fingerprint of the product tree, so a test that writes into it is caught.""" + out = hashlib.sha1() + for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))): + if os.path.isfile(p): + with open(p, "rb") as f: + out.update(p.encode() + f.read()) + return out.hexdigest() + + +class JudgeChore(unittest.TestCase): + def setUp(self): + before = tree() + self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) + book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md") + mine = self.read(book) if os.path.exists(book) else None + self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, + "a test wrote the person's own rules file")) + self.tmp = tempfile.mkdtemp(prefix="sisi-test-") + self.addCleanup(shutil.rmtree, self.tmp, True) + self.data = os.path.join(self.tmp, "data") + os.makedirs(self.data) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": True}})) + self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, SISI_STATE=os.path.join(self.tmp, "state"), + SISI_LIB=os.path.join(self.tmp, "lib"), CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude")) + for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME", + "CLAUDE_CODE_ENTRYPOINT"): + self.env.pop(name, None) + self.proj = os.path.join(self.tmp, "proj") + os.makedirs(self.proj) + subprocess.run(["git", "init", "-q"], cwd=self.proj, check=True, capture_output=True) + self.write(os.path.join(self.data, "models.md"), HEADER + ALPHA + BETA) + os.makedirs(os.path.join(self.data, "offered"), exist_ok=True) + self.write(os.path.join(self.data, "offered", "unknown.txt"), + "listed %s by harness unknown\nalpha\nbeta\n" % time.strftime("%Y-%m-%dT%H:%M:%S")) + self.hook("tick") + self.hook("prompt", prompt="work on the project") + rc, out, err = self.sisi("done", "--goal", "ship the chore judging fix cleanly", + "--check", "chore judging tests pass cleanly", + "--next", "run the full suite next") + self.assertEqual(rc, 0, out + err) + + def read(self, *parts): + with open(os.path.join(*parts), encoding="utf-8") as f: + return f.read() + + def write(self, path, text): + with open(path, "w", encoding="utf-8") as f: + f.write(text) + return path + + def sisi(self, *args, sid="s1", stdin=""): + env = dict(self.env, SISI_SESSION_ID=sid) + r = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi")] + list(args), cwd=self.proj, + env=env, input=stdin, capture_output=True, text=True) + return r.returncode, r.stdout, r.stderr + + def hook(self, cmd, sid="s1", **payload): + body = json.dumps({"session_id": sid, "cwd": self.proj, **payload}) + return self.sisi(cmd, sid=sid, stdin=body) + + def tool(self, name, sid="s1", tool_input=None): + return self.hook("watch", sid=sid, hook_event_name="PreToolUse", tool_name=name, tool_input=tool_input or {}) + + def state(self, sid="s1"): + return json.loads(self.read(self.tmp, "state", "core-sessions", sid + ".json")) + + def outcomes(self): + path = os.path.join(self.data, "outcomes.jsonl") + return [json.loads(l) for l in self.read(path).splitlines() if l.strip()] if os.path.exists(path) else [] + + def start_chore(self, *cmd, worker="alpha"): + rc, brief, err = self.sisi(*cmd) + self.assertEqual(rc, 0, brief + err) + m = re.match(r"sisi chore: .+? ([0-9a-f]{8})\b", brief.splitlines()[0]) + self.assertIsNotNone(m, brief) + cid = m.group(1) + rc_p, out_p, err_p = self.sisi("pick", "routine", "--not", "beta" if worker == "alpha" else "alpha") + self.assertEqual(rc_p, 0, out_p + err_p) + prompt = "%s\nRun `sisi chore show %s` and do what it says." % (brief.splitlines()[0], cid) + rc_t, out_t, err_t = self.tool("Agent", tool_input={"model": worker, "prompt": prompt}) + self.assertEqual((rc_t, out_t), (0, ""), out_t + err_t) + return cid + + def test_1_judge_chore_closes_only_named_chore_and_refuses_unknown(self): + cid1 = self.start_chore("plan", "brief") + time.sleep(0.02) + cid2 = self.start_chore("models", "research") + starts = self.state()["starts"]["alpha"] + self.assertEqual(len(starts), 2) + t1, t2 = starts + + before_state, before_out = self.state(), self.outcomes() + for bad in (("good", "finished the chore cleanly", "--chore", "deadbeef"), + ("extend", "30", "needs more time here", "--chore", "deadbeef")): + rc, out, _ = self.sisi("judge", "alpha", *bad) + self.assertEqual(rc, 1, out) + self.assertEqual(len(out.strip().splitlines()), 1, out) + self.assertIn(cid1, out) + self.assertIn(cid2, out) + rc_missing, out_missing, _ = self.sisi("judge", "alpha", "good", "finished the chore cleanly", "--chore") + self.assertEqual(rc_missing, 1, out_missing) + self.assertEqual((self.state(), self.outcomes()), (before_state, before_out)) + + rc_ext, out_ext, _ = self.sisi("judge", "alpha", "extend", "30", "needs more time here", "--chore", cid2) + self.assertEqual(rc_ext, 0, out_ext) + self.assertIn("extended alpha limit to 30 min.", out_ext) + self.assertEqual(self.state()["meta"]["alpha %r" % t2].get("limit"), 30) + self.assertIsNone(self.state()["meta"]["alpha %r" % t1].get("limit")) + + rc_j, out_j, _ = self.sisi("judge", "alpha", "good", "models research finished cleanly", "--chore", cid2) + self.assertEqual(rc_j, 0, out_j) + self.assertEqual(self.state()["starts"]["alpha"], [t1]) + self.assertEqual(self.outcomes()[-1]["started"], time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t2))) + + rc_again, out_again, _ = self.sisi("judge", "alpha", "good", "trying to judge closed chore", "--chore", cid2) + self.assertEqual(rc_again, 1, out_again) + self.assertEqual(len(out_again.strip().splitlines()), 1, out_again) + self.assertIn(cid1, out_again) + + rc_j1, out_j1, _ = self.sisi("judge", "alpha", "good", "plan brief finished cleanly", "--chore", cid1) + self.assertEqual(rc_j1, 0, out_j1) + self.assertEqual(self.state()["starts"]["alpha"], []) + + def test_2_judge_without_flag_warns_with_closed_and_open_targets(self): + cid1 = self.start_chore("plan", "brief") + time.sleep(0.02) + cid2 = self.start_chore("models", "research") + t1, t2 = self.state()["starts"]["alpha"] + + rc, out, _ = self.sisi("judge", "alpha", "good", "oldest chore finished cleanly") + self.assertEqual(rc, 0, out) + self.assertEqual(self.state()["starts"]["alpha"], [t2]) + lines = out.strip().splitlines() + self.assertEqual(len(lines), 2, out) + self.assertIn("job started %s" % time.strftime("%H:%M", time.localtime(t1)), lines[0]) + self.assertIn(cid1, lines[1]) + self.assertIn(cid2, lines[1]) + self.assertIn("--chore " + cid2, lines[1]) + + def test_3_stop_gate_lists_unjudged_jobs_on_one_line_without_blocking_on_them(self): + graph = ("| node | class | needs | branch | files | check | why |\n|---|---|---|---|---|---|---|\n" + "| a | routine | - | feat-a | sisi/a.py | test a passes | exact spec |\n" + "| join | lead | a | - | - | suite passes | lead joins |\n") + rc, out, _ = self.sisi("plan", "--record", self.write(os.path.join(self.tmp, "plan.md"), graph)) + self.assertEqual(rc, 0, out) + rc_p, out_p, _ = self.sisi("pick", "--node", "a", "--not", "beta") + self.assertEqual(rc_p, 0, out_p) + self.assertEqual(self.tool("Agent", tool_input={"model": "alpha", "prompt": "sisi node: a\nDo node a."})[1], "") + cid = self.start_chore("models", "research", worker="beta") + ta = self.state()["starts"]["alpha"][0] + tb = self.state()["starts"]["beta"][0] + + # Open checks while workers run: stop gate does not block on unjudged jobs. + self.assertEqual(self.hook("gate")[1], "") + + # When the stop gate already blocks (e.g. changed files + passed checks, no retro yet), + # it appends one line listing unjudged jobs in WORKER (node X | chore Y, started HH:MM) form. + self.tool("Edit") + self.assertEqual(self.sisi("done", "--pass", "1", "chore judging tests pass cleanly")[0], 0) + rc_g, out_g, _ = self.hook("gate") + self.assertEqual(rc_g, 0, out_g) + doc = json.loads(out_g) + self.assertEqual(doc["decision"], "block") + extra_lines = [l for l in doc["reason"].splitlines() if "alpha (" in l or "beta (" in l] + self.assertEqual(len(extra_lines), 1, doc["reason"]) + self.assertIn("alpha (node a, started %s)" % time.strftime("%H:%M", time.localtime(ta)), extra_lines[0]) + self.assertIn("beta (chore %s, started %s)" % (cid, time.strftime("%H:%M", time.localtime(tb))), extra_lines[0]) + + +if __name__ == "__main__": + unittest.main()