Files
sisi/tests/test_judge_chore.py
T

184 lines
9.8 KiB
Python

"""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()