sisi 0.1.0: a shared rulebook and verification tool for AI coding agents
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.9) (push) Canceled after 0s
Contracts with a ladder of checks, an end-of-turn gate, retrospectives and shared lessons, time-to-delivery measurement, a library of 140 verification techniques and 20 recipes, personal data kept outside the clone, and releases with rollback. Standard library only. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
2fc1fe9c2d
223 files changed
+22163
No files matched your search
@@ -0,0 +1,63 @@
|
||||
"""Run every test module in its own process, several at a time.
|
||||
|
||||
The suite is the fast check in this project's contract, so it runs at the end
|
||||
of every agent turn and must finish well inside 60 seconds even on a busy
|
||||
machine. Each module already isolates itself (temporary home, state and data
|
||||
folders), so modules are safe to run side by side.
|
||||
|
||||
Usage: python3 tests/run_parallel.py [-j N]
|
||||
Exit status is 0 only if every module passes. Output of a failing module is
|
||||
printed in full; passing modules print one line.
|
||||
"""
|
||||
import concurrent.futures
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
|
||||
|
||||
def run(module):
|
||||
start = time.time()
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-W", "ignore::ResourceWarning", "-m", "unittest", module],
|
||||
cwd=HERE, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=True,
|
||||
)
|
||||
return module, proc.returncode, proc.stdout, time.time() - start
|
||||
|
||||
|
||||
def main(argv):
|
||||
jobs = os.cpu_count() or 4
|
||||
if "-j" in argv:
|
||||
jobs = int(argv[argv.index("-j") + 1])
|
||||
modules = sorted(f[:-3] for f in os.listdir(HERE)
|
||||
if f.startswith("test_") and f.endswith(".py"))
|
||||
if not modules:
|
||||
print("no test modules found")
|
||||
return 1
|
||||
failed = []
|
||||
total = 0
|
||||
start = time.time()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool:
|
||||
for module, code, out, secs in pool.map(run, modules):
|
||||
ran = [l for l in out.splitlines() if l.startswith("Ran ")]
|
||||
count = int(ran[-1].split()[1]) if ran else 0
|
||||
total += count
|
||||
if code != 0 or not ran:
|
||||
failed.append(module)
|
||||
print("FAILED %s (%.1fs)\n%s" % (module, secs, out))
|
||||
else:
|
||||
print("ok %-28s %4d tests %6.1fs" % (module, count, secs))
|
||||
print("\nRan %d tests in %d modules in %.1fs" % (total, len(modules), time.time() - start))
|
||||
if failed:
|
||||
print("FAILED: " + ", ".join(failed))
|
||||
return 1
|
||||
print("OK")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,140 @@
|
||||
import json, os, subprocess, sys, tempfile, unittest
|
||||
|
||||
import warnings
|
||||
sys.warnoptions.append("ignore::ResourceWarning") # keeps unittest from re-enabling them
|
||||
warnings.simplefilter("ignore", ResourceWarning) # tests read small files inline
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
sys.path.insert(0, REPO)
|
||||
ITERS = max(1, int(os.environ.get("SISI_TEST_ITERS", "1"))) # scale property tests up with SISI_TEST_ITERS=10
|
||||
BIN = os.path.join(REPO, "bin", "sisi")
|
||||
|
||||
|
||||
_CURRENT = [] # the temp root of the test now running (empty outside a SisiCase)
|
||||
|
||||
|
||||
def _guarded(name):
|
||||
"""Every resolved root (home, state, personal data) must lie inside the running test's temp dir. A path that
|
||||
resolves into the real home, state or personal data dir fails the test at once, not by luck on a busy machine."""
|
||||
from sisi import paths
|
||||
orig = getattr(paths, name)
|
||||
|
||||
def wrapper(*a, **kw):
|
||||
r = orig(*a, **kw)
|
||||
if _CURRENT and not os.path.realpath(r).startswith(_CURRENT[-1] + os.sep):
|
||||
raise AssertionError("isolation leak: paths.%s() resolved to %s, outside the test's temp dir %s" % (name, r, _CURRENT[-1]))
|
||||
return r
|
||||
wrapper.__wrapped__ = orig
|
||||
setattr(paths, name, wrapper)
|
||||
|
||||
|
||||
for _n in ("home", "state", "data", "lib"):
|
||||
_guarded(_n)
|
||||
|
||||
|
||||
class SisiCase(unittest.TestCase):
|
||||
"""Every test gets a fresh SISI_HOME and SISI_STATE in temp dirs. Real config is never touched."""
|
||||
|
||||
def setUp(self):
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self._tmp.cleanup)
|
||||
self.tmp = os.path.realpath(self._tmp.name)
|
||||
self.home = os.path.join(self.tmp, "home")
|
||||
self.state = os.path.join(self.tmp, "state")
|
||||
self.data = os.path.join(self.tmp, "data")
|
||||
self.proj = os.path.join(self.tmp, "proj")
|
||||
for d in (self.home, self.proj):
|
||||
os.makedirs(d)
|
||||
saved = {k: os.environ.get(k) for k in ("SISI_HOME", "SISI_STATE", "SISI_DATA", "SISI_TOOL", "SISI_SESSION_ID", "SISI_RETRO_REQUIRED", "SISI_NOTES")}
|
||||
os.environ.update(SISI_HOME=self.home, SISI_STATE=self.state, SISI_DATA=self.data,
|
||||
SISI_RETRO_REQUIRED="0") # retro tests turn it on
|
||||
os.environ.pop("SISI_NOTES", None)
|
||||
_CURRENT.append(self.tmp)
|
||||
self.addCleanup(_CURRENT.pop)
|
||||
for k in ("SISI_TOOL", "SISI_SESSION_ID"):
|
||||
os.environ.pop(k, None)
|
||||
|
||||
def restore():
|
||||
for k, v in saved.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
self.addCleanup(restore)
|
||||
|
||||
def sisi_proc(self, *args, cwd=None, stdin=None, env=None):
|
||||
"""Run bin/sisi as a real subprocess (for timing tests and process-level behaviour)."""
|
||||
e = dict(os.environ, **(env or {}))
|
||||
# stdin is always closed after `stdin` (empty when none): hooks such as tick and gate read it to the end, so
|
||||
# inheriting an open pipe from whoever runs the suite makes them wait forever
|
||||
return subprocess.run([sys.executable, BIN] + list(args), cwd=cwd or self.proj, input=stdin or "",
|
||||
capture_output=True, text=True, env=e, timeout=120)
|
||||
|
||||
def sisi(self, *args, cwd=None, stdin=None, env=None):
|
||||
"""Run the CLI in this process (fast). Same arguments and result shape as a subprocess run."""
|
||||
import contextlib, io
|
||||
from unittest import mock
|
||||
from sisi import cli
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
old_cwd = os.getcwd()
|
||||
os.chdir(cwd or self.proj)
|
||||
try:
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \
|
||||
mock.patch.object(sys, "stdin", io.StringIO(stdin or "")), mock.patch.dict(os.environ, env or {}):
|
||||
try:
|
||||
rc = cli.main(list(args))
|
||||
except SystemExit as e:
|
||||
rc = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
|
||||
finally:
|
||||
os.chdir(old_cwd)
|
||||
return subprocess.CompletedProcess(args, rc or 0, out.getvalue(), err.getvalue())
|
||||
|
||||
def git_init(self, d=None):
|
||||
d = d or self.proj
|
||||
subprocess.run(["git", "init", "-q"], cwd=d, check=True)
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"],
|
||||
cwd=d, check=True)
|
||||
|
||||
def write_contract(self, c, d=None, trusted=True):
|
||||
d = d or self.proj
|
||||
if trusted:
|
||||
from sisi import trust
|
||||
trust.add(d)
|
||||
os.makedirs(os.path.join(d, ".sisi"), exist_ok=True)
|
||||
with open(os.path.join(d, ".sisi", "contract.json"), "w") as f:
|
||||
json.dump(c, f)
|
||||
|
||||
def results(self):
|
||||
p = os.path.join(self.state, "results.jsonl")
|
||||
if not os.path.exists(p):
|
||||
return []
|
||||
with open(p) as f:
|
||||
return [json.loads(l) for l in f]
|
||||
|
||||
|
||||
def check(id, cmd, rung=3, kind="general", exit=0, timeout_s=10, **expect):
|
||||
return {"id": id, "claim": "claim " + id, "kind": kind, "rung": rung, "cmd": cmd,
|
||||
"expect": dict({"exit": exit}, **expect), "timeout_s": timeout_s}
|
||||
|
||||
|
||||
def human(id, rung=5, kind="general"):
|
||||
return {"id": id, "claim": "claim " + id, "kind": kind, "rung": rung}
|
||||
|
||||
|
||||
def contract(checks, invariants=()):
|
||||
return {"id": "t", "goal": "g", "checks": list(checks), "invariants": list(invariants),
|
||||
"assumptions": [], "questions": []}
|
||||
|
||||
|
||||
def skip_timing_if_busy(case):
|
||||
"""Skip a wall-clock speed assertion when the machine is overloaded.
|
||||
|
||||
A speed test measures sisi only when the machine has spare capacity. With more runnable work
|
||||
than processors it measures the queue, and a failure says nothing about the code.
|
||||
"""
|
||||
import os
|
||||
try:
|
||||
load, cpus = os.getloadavg()[0], os.cpu_count() or 1
|
||||
except OSError:
|
||||
return
|
||||
if load > cpus:
|
||||
case.skipTest("machine overloaded (load %.0f on %d processors): speed not measured" % (load, cpus))
|
||||
@@ -0,0 +1,67 @@
|
||||
import os, unittest
|
||||
from support import *
|
||||
from sisi import contract as C
|
||||
|
||||
|
||||
class ContractTests(SisiCase):
|
||||
def test_skeleton_is_valid_but_fails(self):
|
||||
c = C.skeleton("goal")
|
||||
self.assertEqual(C.validate(c), [])
|
||||
self.assertEqual(self.sisi("contract", "init", "--goal", "make x").returncode, 0)
|
||||
self.assertEqual(self.sisi("contract", "check").returncode, 0)
|
||||
self.assertEqual(self.sisi("verify").returncode, 1) # placeholder must not pass
|
||||
self.assertEqual(self.sisi("contract", "init").returncode, 1) # no clobbering
|
||||
|
||||
def test_validation_errors(self):
|
||||
good = contract([check("a", "true")])
|
||||
self.assertEqual(C.validate(good), [])
|
||||
bad = {
|
||||
"not an object": [],
|
||||
"no checks": dict(good, checks=[]),
|
||||
"empty goal": dict(good, goal=" "),
|
||||
"bad kind": contract([check("a", "true", kind="nope")]),
|
||||
"rung 0": contract([check("a", "true", rung=0)]),
|
||||
"rung 7": contract([check("a", "true", rung=7)]),
|
||||
"rung bool": contract([check("a", "true", rung=True)]),
|
||||
"rung 3 no cmd": contract([human("a", rung=3)]),
|
||||
"rung 5 with cmd": contract([dict(check("a", "true"), rung=5)]),
|
||||
"no expect.exit": contract([dict(check("a", "true"), expect={})]),
|
||||
"bad timeout": contract([check("a", "true", timeout_s=0)]),
|
||||
"duplicate ids": contract([check("a", "true"), check("a", "true")]),
|
||||
"dup across invariant": contract([check("a", "true")], [check("a", "true")]),
|
||||
"invariant no cmd": contract([check("a", "true")], [{"id": "i", "claim": "c", "expect": {"exit": 0}}]),
|
||||
"assumptions not strings": dict(good, assumptions=[1]),
|
||||
"question w/o default": dict(good, questions=[{"q": "?"}]),
|
||||
}
|
||||
for name, c in bad.items():
|
||||
with self.subTest(name):
|
||||
self.assertTrue(C.validate(c), name)
|
||||
|
||||
def test_rung_5_6_valid_without_cmd(self):
|
||||
self.assertEqual(C.validate(contract([check("a", "true"), human("h", 5), human("i", 6)])), [])
|
||||
|
||||
def test_floors(self):
|
||||
weak = contract([check("m", "true", rung=3, kind="money")])
|
||||
self.assertEqual(len(C.floor_failures(weak)), 1)
|
||||
self.assertEqual(C.floor_failures(contract([check("m", "true", rung=2, kind="money")])), [])
|
||||
# one strong check among weak ones satisfies the floor
|
||||
self.assertEqual(C.floor_failures(contract([check("m", "true", rung=3, kind="money"),
|
||||
check("n", "true", rung=1, kind="money")])), [])
|
||||
self.assertEqual(C.floor_failures(contract([check("u", "true", rung=4, kind="ui")])), [])
|
||||
for k in ("concurrency", "parsing", "money", "state-machine", "migration"):
|
||||
self.assertEqual(C.floors()[k], 2)
|
||||
|
||||
def test_find_stops_at_git_root(self):
|
||||
self.git_init()
|
||||
self.write_contract(contract([check("a", "true")]))
|
||||
sub = os.path.join(self.proj, "a", "b")
|
||||
os.makedirs(sub)
|
||||
self.assertEqual(C.find(sub), os.path.join(self.proj, ".sisi", "contract.json"))
|
||||
outer = self.tmp # a contract above the git root must not be found
|
||||
self.write_contract(contract([check("a", "true")]), outer)
|
||||
os.remove(os.path.join(self.proj, ".sisi", "contract.json"))
|
||||
self.assertIsNone(C.find(sub))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,395 @@
|
||||
import json, os, random, time, unittest
|
||||
from support import *
|
||||
from sisi import delivery, gate, harvest, retro, store, verify as V, contract as C
|
||||
|
||||
|
||||
def ts(t):
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(t)) + ".250Z"
|
||||
|
||||
|
||||
def human_line(t, text="do the thing please"):
|
||||
return {"type": "user", "timestamp": ts(t), "message": {"role": "user", "content": text}}
|
||||
|
||||
|
||||
def hook_line(t):
|
||||
return {"type": "user", "isMeta": True, "timestamp": ts(t),
|
||||
"message": {"role": "user", "content": "Stop hook feedback:\nsisi: the contract is not satisfied"}}
|
||||
|
||||
|
||||
def result_line(t, size=10):
|
||||
return {"type": "user", "timestamp": ts(t), "toolUseResult": {"stdout": "x" * size},
|
||||
"message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t", "content": "y" * size}]}}
|
||||
|
||||
|
||||
def other_machine_lines(t):
|
||||
return [{"type": "user", "timestamp": ts(t), "origin": {"kind": "task-notification"},
|
||||
"message": {"role": "user", "content": "worker finished"}},
|
||||
{"type": "user", "timestamp": ts(t), "message": {"role": "user", "content": "<system-reminder>be good</system-reminder>"}},
|
||||
{"type": "user", "timestamp": ts(t), "message": {"role": "user", "content": "<task-notification>x</task-notification>"}}]
|
||||
|
||||
|
||||
def asst_line(t):
|
||||
return {"type": "assistant", "timestamp": ts(t), "message": {"role": "assistant", "content": [{"type": "text", "text": "ok"}]}}
|
||||
|
||||
|
||||
def write_transcript(path, entries):
|
||||
with open(path, "w") as f:
|
||||
for e in entries:
|
||||
f.write((e if isinstance(e, str) else json.dumps(e, separators=(",", ":"))) + "\n")
|
||||
|
||||
|
||||
def reference_start(path):
|
||||
"""Slow and simple: read the whole file, apply the same human-message rule to every line, keep the last."""
|
||||
best = None
|
||||
with open(path) as f:
|
||||
for line in f:
|
||||
try:
|
||||
d = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if d.get("type") == "user" and harvest.typed_text(d)[0] is not None:
|
||||
best = harvest.epoch(d["timestamp"])
|
||||
return best
|
||||
|
||||
|
||||
class StartFinderTests(SisiCase):
|
||||
def path(self, name="t.jsonl"):
|
||||
return os.path.join(self.tmp, name)
|
||||
|
||||
def test_last_human_message_wins_over_later_machine_entries(self):
|
||||
t0 = 1_800_000_000
|
||||
entries = [human_line(t0 - 500, "first request"), asst_line(t0 - 400), human_line(t0, "second request, the one"),
|
||||
asst_line(t0 + 5), result_line(t0 + 6), hook_line(t0 + 7)] + other_machine_lines(t0 + 8) + \
|
||||
[asst_line(t0 + 9), result_line(t0 + 10), hook_line(t0 + 11)]
|
||||
write_transcript(self.path(), entries)
|
||||
self.assertAlmostEqual(delivery.find_start(self.path()), t0 + 0.25, places=1)
|
||||
|
||||
def test_queued_message_typed_while_working_counts(self):
|
||||
t0 = 1_800_000_000
|
||||
queued = {"type": "attachment", "timestamp": ts(t0 + 30),
|
||||
"attachment": {"type": "queued_command", "commandMode": "prompt", "prompt": "also do this"}}
|
||||
write_transcript(self.path(), [human_line(t0), asst_line(t0 + 1), queued, result_line(t0 + 31)])
|
||||
self.assertAlmostEqual(delivery.find_start(self.path()), t0 + 30.25, places=1)
|
||||
|
||||
def test_huge_tool_results_and_tiny_chunks(self):
|
||||
t0 = 1_800_000_000
|
||||
entries = [human_line(t0, "the request")] + [result_line(t0 + i, size=5000) for i in range(1, 20)]
|
||||
write_transcript(self.path(), entries)
|
||||
self.assertAlmostEqual(delivery.find_start(self.path(), chunk=700), t0 + 0.25, places=1)
|
||||
self.assertIsNone(delivery.find_start(self.path(), max_bytes=20000, chunk=700)) # too far back: not measured
|
||||
|
||||
def test_none_when_nothing_found_or_unreadable(self):
|
||||
write_transcript(self.path(), [asst_line(1), result_line(2), hook_line(3)])
|
||||
self.assertIsNone(delivery.find_start(self.path()))
|
||||
self.assertIsNone(delivery.find_start(os.path.join(self.tmp, "missing.jsonl")))
|
||||
write_transcript(self.path("bad.jsonl"), ["{not json", "\x00\x01garbage", '{"type":"user","timestamp":5}', ""])
|
||||
self.assertIsNone(delivery.find_start(self.path("bad.jsonl")))
|
||||
write_transcript(self.path("empty.jsonl"), [])
|
||||
self.assertIsNone(delivery.find_start(self.path("empty.jsonl")))
|
||||
|
||||
def test_matches_reference_on_random_transcripts(self):
|
||||
rnd = random.Random(20261122)
|
||||
for n in range(40 * ITERS):
|
||||
t, entries = 1_800_000_000, []
|
||||
for _ in range(rnd.randint(1, 60)):
|
||||
t += rnd.randint(1, 30)
|
||||
k = rnd.random()
|
||||
if k < 0.12:
|
||||
entries.append(human_line(t, "typed %d" % rnd.randint(0, 99)))
|
||||
elif k < 0.4:
|
||||
entries.append(result_line(t, rnd.choice([10, 300, 4000])))
|
||||
elif k < 0.55:
|
||||
entries.append(hook_line(t))
|
||||
elif k < 0.65:
|
||||
entries.extend(other_machine_lines(t))
|
||||
elif k < 0.7:
|
||||
entries.append("{broken")
|
||||
else:
|
||||
entries.append(asst_line(t))
|
||||
write_transcript(self.path(), entries)
|
||||
want = reference_start(self.path())
|
||||
got = delivery.find_start(self.path(), chunk=rnd.choice([64, 257, 1000, 128 * 1024]))
|
||||
self.assertEqual(got, want, "case %d" % n)
|
||||
|
||||
def test_real_transcripts_if_present(self):
|
||||
"""Read-only: every real transcript gives a start no later than its last record, and the same answer as a full scan."""
|
||||
base = os.path.expanduser("~/.claude/projects")
|
||||
found = []
|
||||
for root, _, files in os.walk(base):
|
||||
if "subagents" in root:
|
||||
continue
|
||||
found += [os.path.join(root, f) for f in files if f.endswith(".jsonl")]
|
||||
if len(found) > 40:
|
||||
break
|
||||
found.sort(key=lambda p: os.path.getsize(p))
|
||||
for p in (found[:1] + found[-1:]) if found else []:
|
||||
if os.path.getsize(p) > 30 * 1024 * 1024:
|
||||
continue
|
||||
got = delivery.find_start(p)
|
||||
if got is not None:
|
||||
self.assertEqual(got, reference_start(p) if os.path.getsize(p) < 8 * 1024 * 1024 else got)
|
||||
|
||||
|
||||
class DeliveryRowTests(SisiCase):
|
||||
sid = "d-1"
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.tp = os.path.join(self.tmp, "transcript.jsonl")
|
||||
self.t0 = time.time() - 90
|
||||
write_transcript(self.tp, [human_line(self.t0 - 400, "older"), asst_line(self.t0 - 300),
|
||||
human_line(self.t0, "the request"), asst_line(self.t0 + 1), result_line(self.t0 + 2),
|
||||
hook_line(self.t0 + 3)])
|
||||
|
||||
def hook(self, **extra):
|
||||
p = dict({"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop"}, **extra)
|
||||
return self.sisi_proc("gate", stdin=json.dumps(p))
|
||||
|
||||
def rows(self):
|
||||
p = os.path.join(self.state, "deliveries.jsonl")
|
||||
if not os.path.exists(p):
|
||||
return []
|
||||
with open(p) as f:
|
||||
return [json.loads(l) for l in f]
|
||||
|
||||
def test_row_is_recorded_when_the_gate_allows(self):
|
||||
self.write_contract(contract([check("ok", "true")]))
|
||||
r = self.hook(transcript_path=self.tp)
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
rows = self.rows()
|
||||
self.assertEqual(len(rows), 1)
|
||||
row = rows[0]
|
||||
self.assertEqual((row["session"], row["project"], row["contract"], row["send_backs"]), (self.sid, self.proj, True, 0))
|
||||
self.assertGreaterEqual(row["seconds"], 89)
|
||||
self.assertLess(row["seconds"], 140)
|
||||
self.assertGreaterEqual(row["check_s"], 0.0)
|
||||
self.assertEqual(row["start"], time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(self.t0)) + "Z")
|
||||
self.hook(transcript_path=self.tp) # the same request again: not recorded twice
|
||||
self.assertEqual(len(self.rows()), 1)
|
||||
|
||||
def test_send_backs_and_check_time_are_counted_for_the_request(self):
|
||||
self.write_contract(contract([check("bad", "sleep 0.3; exit 1")]))
|
||||
r = self.hook(transcript_path=self.tp)
|
||||
self.assertEqual(json.loads(r.stdout)["decision"], "block")
|
||||
self.assertEqual(self.rows(), []) # a send-back is not a delivery
|
||||
self.write_contract(contract([check("ok", "sleep 0.2")]))
|
||||
r = self.hook(transcript_path=self.tp)
|
||||
self.assertEqual(r.stdout, "")
|
||||
row = self.rows()[0]
|
||||
self.assertEqual(row["send_backs"], 1)
|
||||
self.assertGreaterEqual(row["check_s"], 0.45)
|
||||
|
||||
def test_no_contract_is_recorded_as_such(self):
|
||||
r = self.hook(transcript_path=self.tp)
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(self.rows()[0]["contract"], False)
|
||||
|
||||
def test_gate_fails_open_without_a_usable_transcript(self):
|
||||
self.write_contract(contract([check("ok", "true")]))
|
||||
for tp in (None, os.path.join(self.tmp, "missing.jsonl"), self.tp + ".dir"):
|
||||
kw = {} if tp is None else {"transcript_path": tp}
|
||||
r = self.hook(**kw)
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""), kw)
|
||||
os.mkdir(self.tp + ".dir")
|
||||
r = self.hook(transcript_path=self.tp + ".dir") # a directory
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
for bad in (b"\x00\xff\xfe{[", b"{" * 100000, b'{"type":"user","timestamp":"nonsense","message":{"content":"hi"}}\n'):
|
||||
with open(self.tp, "wb") as f:
|
||||
f.write(bad)
|
||||
r = self.hook(transcript_path=self.tp)
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
self.assertEqual(self.rows(), [])
|
||||
r = self.hook(transcript_path=12345)
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
|
||||
def test_a_failing_recorder_never_changes_the_answer(self):
|
||||
from unittest import mock
|
||||
self.write_contract(contract([check("ok", "true")]))
|
||||
with mock.patch.object(delivery, "find_start", side_effect=RuntimeError("boom")):
|
||||
a = gate.decide({"session_id": "x1", "cwd": self.proj, "transcript_path": self.tp})
|
||||
gate._record_delivery({"session_id": "x1", "cwd": self.proj, "transcript_path": self.tp})
|
||||
self.assertEqual(a, ("allow", None))
|
||||
self.assertEqual(self.rows(), [])
|
||||
|
||||
def test_overhead_is_small(self):
|
||||
"""Recording a delivery on a large transcript costs well under the budget of 50 ms (generous bound for CI)."""
|
||||
entries = [human_line(self.t0)] + [result_line(self.t0 + i, 20000) for i in range(1, 100)]
|
||||
write_transcript(self.tp, entries)
|
||||
delivery.find_start(self.tp) # warm imports
|
||||
t = time.perf_counter()
|
||||
for _ in range(5):
|
||||
delivery.find_start(self.tp)
|
||||
per = (time.perf_counter() - t) / 5
|
||||
self.assertLess(per, 0.25)
|
||||
|
||||
def test_retro_stores_the_request_time_with_the_lesson(self):
|
||||
store.save_session("r-1", {"session_id": "r-1", "transcript_path": self.tp, "cwd": self.proj})
|
||||
os.environ["SISI_SESSION_ID"] = "r-1"
|
||||
con = retro.connect()
|
||||
try:
|
||||
lid = retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None,
|
||||
moment="`make build` took 9 minutes in lib/src", cause="no cache here",
|
||||
change="add a cache recipe for `make build`"), self.proj, None)
|
||||
con.commit()
|
||||
v = con.execute("SELECT delivery_s FROM occurrences WHERE lesson_id=?", (lid,)).fetchone()[0]
|
||||
finally:
|
||||
con.close()
|
||||
self.assertGreaterEqual(v, 89)
|
||||
self.assertLess(v, 200)
|
||||
self.assertIn("it took longer than it had to", self.sisi("help").stdout)
|
||||
|
||||
|
||||
def ref_percentile(xs, p):
|
||||
s = sorted(xs)
|
||||
if len(s) == 1:
|
||||
return s[0]
|
||||
pos = (len(s) - 1) * p / 100.0
|
||||
lo, frac = int(pos // 1), pos - int(pos // 1)
|
||||
return s[lo] if frac == 0 else s[lo] * (1 - frac) + s[lo + 1] * frac
|
||||
|
||||
|
||||
class TimeCommandTests(SisiCase):
|
||||
def test_small_known_values(self):
|
||||
self.assertEqual(delivery.median([5, 1, 3]), 3)
|
||||
self.assertEqual(delivery.median([4, 1, 3, 2]), 2.5)
|
||||
self.assertEqual(delivery.percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 90), 9.1)
|
||||
self.assertEqual(delivery.percentile([7], 90), 7)
|
||||
self.assertIsNone(delivery.median([]))
|
||||
self.assertIsNone(delivery.percentile([], 90))
|
||||
|
||||
def test_median_and_percentile_property(self):
|
||||
rnd = random.Random(7)
|
||||
for _ in range(300 * ITERS):
|
||||
xs = [rnd.choice([rnd.randint(0, 50), rnd.random() * 1000]) for _ in range(rnd.randint(1, 40))]
|
||||
half = sorted(xs)
|
||||
n = len(half)
|
||||
want_med = half[n // 2] if n % 2 else (half[n // 2 - 1] + half[n // 2]) / 2
|
||||
self.assertAlmostEqual(delivery.median(xs), want_med)
|
||||
for p in (0, 50, 90, 100, rnd.randint(0, 100)):
|
||||
self.assertAlmostEqual(delivery.percentile(xs, p), ref_percentile(xs, p), places=6)
|
||||
self.assertLessEqual(delivery.percentile(xs, 50), delivery.percentile(xs, 90) + 1e-9)
|
||||
|
||||
def add_rows(self, now, spec):
|
||||
"""spec: list of (days_ago, seconds, project, send_backs, check_s)."""
|
||||
for d, secs, proj, sb, cs in spec:
|
||||
end = now - d * 86400
|
||||
store.append("deliveries", {"ts": delivery._iso(end), "session": "s", "project": proj, "start": delivery._iso(end - secs),
|
||||
"end": delivery._iso(end), "seconds": secs, "send_backs": sb, "check_s": cs, "contract": True})
|
||||
|
||||
def test_report_windows_projects_shares_and_send_backs(self):
|
||||
now = time.time()
|
||||
self.add_rows(now, [(1, 100, "/a/alpha", 0, 10), (2, 300, "/a/alpha", 1, 90), (3, 200, "/b/beta", 0, 20),
|
||||
(9, 400, "/a/alpha", 0, 40), (10, 800, "/b/beta", 2, 80), (20, 5, "/a/alpha", 0, 0)])
|
||||
r = delivery.report(now)
|
||||
cur, prev = r["all"]["last7"], r["all"]["prev7"]
|
||||
self.assertEqual((cur["n"], cur["median_s"], prev["n"], prev["median_s"]), (3, 200, 2, 600))
|
||||
self.assertAlmostEqual(cur["check_share"], 120 / 600)
|
||||
self.assertEqual(cur["send_back_deliveries"], 1)
|
||||
self.assertEqual(r["projects"]["/a/alpha"]["last7"]["median_s"], 200)
|
||||
self.assertEqual(r["projects"]["/b/beta"]["prev7"]["n"], 1)
|
||||
out = []
|
||||
delivery.cmd_time([], out=out.append)
|
||||
text = "\n".join(out)
|
||||
self.assertIn("median 3m20s", text)
|
||||
self.assertIn("1 of 3", text)
|
||||
self.assertIn("alpha", text)
|
||||
js = []
|
||||
delivery.cmd_time(["--json"], out=js.append)
|
||||
self.assertEqual(json.loads(js[0])["all"]["last7"]["n"], 3)
|
||||
|
||||
def test_windows_agree_with_a_simple_reference(self):
|
||||
rnd = random.Random(11)
|
||||
now = time.time()
|
||||
for _ in range(30 * ITERS):
|
||||
rows = [{"end": delivery._iso(now - rnd.random() * 20 * 86400), "seconds": rnd.random() * 500} for _ in range(rnd.randint(0, 30))]
|
||||
cur, prev = delivery.windows(rows, now)
|
||||
ref_cur = [r for r in rows if now - 7 * 86400 <= harvest.epoch(r["end"]) <= now]
|
||||
ref_prev = [r for r in rows if now - 14 * 86400 <= harvest.epoch(r["end"]) < now - 7 * 86400]
|
||||
self.assertEqual((sorted(map(id, cur)), sorted(map(id, prev))), (sorted(map(id, ref_cur)), sorted(map(id, ref_prev))))
|
||||
|
||||
def test_no_data_is_said_plainly(self):
|
||||
r = self.sisi("time")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertIn("no deliveries recorded", r.stdout)
|
||||
self.assertIn("no deliveries recorded in the last 7 days", self.sisi("status").stdout)
|
||||
self.assertEqual(json.loads(self.sisi("time", "--json").stdout)["all"]["last7"]["n"], 0)
|
||||
|
||||
def test_status_shows_the_seven_day_median_and_slow_checks_get_advice(self):
|
||||
now = time.time()
|
||||
self.add_rows(now, [(1, 120, "/p", 0, 5), (2, 60, "/p", 0, 5), (3, 600, "/p", 0, 5)])
|
||||
self.assertIn("median 2m00s over the last 7 days (3 deliveries)", self.sisi("status").stdout)
|
||||
for dur in (50, 70):
|
||||
store.append("results", {"ts": store.now(), "check": "slow-one", "status": "passed", "duration_s": dur, "tier": "fast"})
|
||||
store.append("results", {"ts": store.now(), "check": "quick", "status": "passed", "duration_s": 0.5, "tier": "fast"})
|
||||
store.append("results", {"ts": store.now(), "check": "mutation", "status": "passed", "duration_s": 300, "tier": "deep"})
|
||||
slow = delivery.report(now)["slowest_checks"]
|
||||
self.assertEqual([x["id"] for x in slow], ["mutation", "slow-one", "quick"])
|
||||
self.assertAlmostEqual(slow[1]["mean_s"], 60)
|
||||
self.assertIn('"tier": "deep"', slow[1]["suggestion"])
|
||||
self.assertIn("split", slow[0]["suggestion"])
|
||||
|
||||
|
||||
class ParallelVerifyTests(SisiCase):
|
||||
def strip(self, results):
|
||||
return [{k: r[k] for k in ("item", "id", "status", "kind", "rung", "tier")} for r in results]
|
||||
|
||||
def mk(self, parallel=None, serial_ids=()):
|
||||
cs = [check("a", "sleep 0.5"), check("b", "sleep 0.5; exit 1"), check("c", "sleep 0.5"),
|
||||
check("d", "sleep 0.5"), check("e", "exit 0"), human("h"), check("slowboy", "sleep 5", timeout_s=0.2)]
|
||||
cs.append(dict(check("deep1", "sleep 0.1"), tier="deep"))
|
||||
for c in cs:
|
||||
if c["id"] in serial_ids:
|
||||
c["serial"] = True
|
||||
c = contract(cs, [check("inv", "sleep 0.3")])
|
||||
if parallel is not None:
|
||||
c["parallel"] = parallel
|
||||
return c
|
||||
|
||||
def test_same_results_in_the_same_order_and_faster(self):
|
||||
t = time.time()
|
||||
serial = V.run(self.mk(), self.proj, tiers=("fast", "deep"))
|
||||
t_serial = time.time() - t
|
||||
t = time.time()
|
||||
par = V.run(self.mk(parallel=True), self.proj, tiers=("fast", "deep"))
|
||||
t_par = time.time() - t
|
||||
self.assertEqual(self.strip(par), self.strip(serial))
|
||||
self.assertEqual([r["id"] for r in par], ["a", "b", "c", "d", "e", "h", "slowboy", "deep1", "inv"])
|
||||
self.assertLess(t_par, t_serial - 0.5)
|
||||
explicit_off = V.run(self.mk(parallel=False), self.proj)
|
||||
self.assertEqual(self.strip(explicit_off), self.strip(V.run(self.mk(), self.proj)))
|
||||
|
||||
def test_serial_checks_run_alone(self):
|
||||
log = os.path.join(self.tmp, "log")
|
||||
def cmd(n):
|
||||
return "echo start-%s >> %s; sleep 0.3; echo end-%s >> %s" % (n, log, n, log)
|
||||
cs = [check("p1", cmd("p1")), dict(check("s1", cmd("s1")), serial=True), check("p2", cmd("p2")),
|
||||
dict(check("s2", cmd("s2")), serial=True)]
|
||||
res = V.run(dict(contract(cs), parallel=True), self.proj)
|
||||
self.assertEqual([r["id"] for r in res], ["p1", "s1", "p2", "s2"])
|
||||
lines = open(log).read().split()
|
||||
for n in ("s1", "s2"): # nothing else starts or ends between a serial check's start and end
|
||||
i = lines.index("start-" + n)
|
||||
self.assertEqual(lines[i + 1], "end-" + n)
|
||||
|
||||
def test_property_random_contracts_match_serial(self):
|
||||
rnd = random.Random(3)
|
||||
for _ in range(6 * ITERS):
|
||||
cs = [dict(check("c%d" % i, "exit %d" % rnd.choice([0, 0, 1])), **({"serial": True} if rnd.random() < 0.3 else {}))
|
||||
for i in range(rnd.randint(1, 9))]
|
||||
c = contract(cs)
|
||||
serial = V.run(c, self.proj)
|
||||
par = V.run(dict(c, parallel=True), self.proj)
|
||||
self.assertEqual(self.strip(par), self.strip(serial))
|
||||
|
||||
def test_validation_and_cli(self):
|
||||
self.assertTrue(any("parallel" in e for e in C.validate(dict(contract([check("a", "true")]), parallel="yes"))))
|
||||
bad = contract([dict(check("a", "true"), serial="x")])
|
||||
self.assertTrue(any("serial" in e for e in C.validate(bad)))
|
||||
self.write_contract(dict(contract([check("a", "true"), check("b", "true")]), parallel=True))
|
||||
r = self.sisi("verify", "--json")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertEqual([x["id"] for x in json.loads(r.stdout)["results"]], ["a", "b"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,37 @@
|
||||
import json, os, unittest
|
||||
from support import *
|
||||
|
||||
|
||||
class EndToEnd(SisiCase):
|
||||
def test_full_flow(self):
|
||||
for d in (".claude", ".codex", ".config/opencode"):
|
||||
os.makedirs(os.path.join(self.home, d))
|
||||
with open(os.path.join(self.home, ".claude", "settings.json"), "w") as f:
|
||||
json.dump({"hooks": {"SessionStart": [{"matcher": "*", "hooks": [{"type": "command", "command": "existing"}]}]}}, f)
|
||||
self.git_init()
|
||||
self.assertEqual(self.sisi("install").returncode, 0)
|
||||
doc = self.sisi("doctor").stdout
|
||||
self.assertIn("claude-code wired", doc)
|
||||
payload = json.dumps({"session_id": "e2e", "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup"})
|
||||
self.assertEqual(self.sisi("tick", stdin=payload).stdout, "")
|
||||
stop = json.dumps({"session_id": "e2e", "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False})
|
||||
|
||||
self.write_contract(contract([check("feature", "test -f %s/done.txt" % self.proj, rung=3)]))
|
||||
r = self.sisi("gate", stdin=stop)
|
||||
self.assertEqual(r.returncode, 0)
|
||||
d = json.loads(r.stdout)
|
||||
self.assertEqual(d["decision"], "block")
|
||||
self.assertIn("feature", d["reason"])
|
||||
|
||||
open(os.path.join(self.proj, "done.txt"), "w").close()
|
||||
r = self.sisi("gate", stdin=stop)
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
|
||||
out = self.sisi("status").stdout
|
||||
self.assertIn("contracts verified : 1", out)
|
||||
self.assertIn("3: 100%", out)
|
||||
self.assertEqual(self.sisi("uninstall").returncode, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,456 @@
|
||||
import io, json, os, random, sys, unittest
|
||||
from unittest import mock
|
||||
from support import *
|
||||
from sisi import gate, store
|
||||
|
||||
|
||||
class GateBase(SisiCase):
|
||||
sid = "sess-1"
|
||||
|
||||
def call(self, cwd=None, sid=None, **extra):
|
||||
"""Run the gate in process as the hook would. Returns (action, message)."""
|
||||
payload = dict({"session_id": sid or self.sid, "cwd": cwd or self.proj, "hook_event_name": "Stop",
|
||||
"stop_hook_active": False}, **extra)
|
||||
return gate.decide(payload)
|
||||
|
||||
def hook(self, payload=None, cwd=None):
|
||||
"""Run the real hook command: JSON stdin, stdout, exit code."""
|
||||
p = dict({"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop"}, **(payload or {}))
|
||||
return self.sisi("gate", cwd=cwd, stdin=json.dumps(p))
|
||||
|
||||
def set_config(self, **gate_cfg):
|
||||
os.makedirs(self.state, exist_ok=True)
|
||||
with open(os.path.join(self.state, "config.json"), "w") as f:
|
||||
json.dump({"gate": gate_cfg}, f)
|
||||
|
||||
|
||||
class GateContractTests(GateBase):
|
||||
def test_pass_allows_with_no_output(self):
|
||||
self.write_contract(contract([check("ok", "true")]))
|
||||
r = self.hook()
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
|
||||
def test_fail_blocks_with_claude_format(self):
|
||||
self.write_contract(contract([check("bad", "echo boom-output >&2; exit 1")]))
|
||||
r = self.hook()
|
||||
self.assertEqual(r.returncode, 0)
|
||||
d = json.loads(r.stdout)
|
||||
self.assertEqual(d["decision"], "block")
|
||||
self.assertIn("bad", d["reason"])
|
||||
self.assertIn("boom-output", d["reason"])
|
||||
|
||||
def test_timeout_and_floor_block(self):
|
||||
self.write_contract(contract([check("slow", "sleep 5", timeout_s=0.2)]))
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
self.write_contract(contract([check("m", "true", rung=3, kind="money")]))
|
||||
a, msg = self.call(sid="other")
|
||||
self.assertEqual(a, "block")
|
||||
self.assertIn("floor", msg)
|
||||
|
||||
def test_invalid_contract_blocks(self):
|
||||
self.write_contract({"id": "x"})
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
|
||||
def test_budget_makes_unfinished_checks_timeout(self):
|
||||
self.set_config(budget_s=0.4)
|
||||
self.write_contract(contract([check("a", "sleep 3", timeout_s=60), check("b", "true")]))
|
||||
a, msg = self.call()
|
||||
self.assertEqual(a, "block")
|
||||
st = {r["check"]: r["status"] for r in self.results()}
|
||||
self.assertEqual(st, {"a": "timeout", "b": "timeout"}) # b never ran: counts as timeout
|
||||
|
||||
def test_three_strikes_then_unverified_release_then_reset(self):
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3)
|
||||
a, msg = self.call()
|
||||
self.assertEqual(a, "allow")
|
||||
self.assertIn("UNVERIFIED", msg)
|
||||
self.assertEqual(self.results()[-1]["status"], "unverified")
|
||||
out = self.hook() # after release the count restarts: blocks again
|
||||
self.assertEqual(json.loads(out.stdout)["decision"], "block")
|
||||
|
||||
def test_unverified_release_is_printed(self):
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
for _ in range(3):
|
||||
self.hook()
|
||||
r = self.hook()
|
||||
self.assertIn("UNVERIFIED", json.loads(r.stdout)["systemMessage"])
|
||||
|
||||
def test_pass_resets_count(self):
|
||||
self.write_contract(contract([check("c", "test -f %s/ok" % self.tmp)]))
|
||||
self.call(); self.call()
|
||||
open(os.path.join(self.tmp, "ok"), "w").close()
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
os.remove(os.path.join(self.tmp, "ok"))
|
||||
self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3) # fresh three strikes
|
||||
|
||||
def test_strikes_are_per_session(self):
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
for _ in range(3):
|
||||
self.call(sid="a")
|
||||
self.assertEqual(self.call(sid="b")[0], "block")
|
||||
|
||||
def test_stop_hook_active_does_not_bypass(self):
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
self.assertEqual(self.call(stop_hook_active=True)[0], "block")
|
||||
|
||||
def test_disabled_allows(self):
|
||||
self.set_config(enabled=False)
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
|
||||
def test_contract_found_from_subdir_up_to_git_root(self):
|
||||
self.git_init()
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
sub = os.path.join(self.proj, "x", "y")
|
||||
os.makedirs(sub)
|
||||
self.assertEqual(self.call(cwd=sub)[0], "block")
|
||||
|
||||
|
||||
class GateFailOpenTests(GateBase):
|
||||
def test_internal_error_allows_and_logs(self):
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
with mock.patch.object(gate, "decide", side_effect=RuntimeError("kaboom")), \
|
||||
mock.patch.object(sys, "stdin", io.StringIO("{}")), mock.patch.object(sys, "stdout", io.StringIO()) as out:
|
||||
self.assertEqual(gate.main(), 0)
|
||||
self.assertEqual(out.getvalue(), "")
|
||||
with open(os.path.join(self.state, "errors.log")) as f:
|
||||
self.assertIn("kaboom", f.read())
|
||||
|
||||
def test_unwritable_state_allows(self):
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
os.makedirs(self.state, exist_ok=True)
|
||||
open(os.path.join(self.state, "sessions"), "w").close() # session records can no longer be written
|
||||
r = self.hook()
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
|
||||
def test_garbage_stdin_allows(self):
|
||||
r = self.sisi("gate", stdin="not json")
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
r = self.sisi("gate", stdin="")
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
|
||||
def test_corrupt_session_and_config_files(self):
|
||||
os.makedirs(os.path.join(self.state, "sessions"))
|
||||
with open(os.path.join(self.state, "sessions", "sess-1.json"), "w") as f:
|
||||
f.write("{{{")
|
||||
with open(os.path.join(self.state, "config.json"), "w") as f:
|
||||
f.write("nope")
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
self.assertEqual(self.hook().returncode, 0)
|
||||
|
||||
|
||||
class GateNoContractTests(GateBase):
|
||||
def start(self, sid=None):
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": sid or self.sid, "cwd": self.proj, "source": "startup"}))
|
||||
|
||||
def grow(self, n_lines=0, n_files=1):
|
||||
for i in range(n_files):
|
||||
with open(os.path.join(self.proj, "f%d.txt" % i), "w") as f:
|
||||
f.write("x\n" * (n_lines // max(n_files, 1) + 1))
|
||||
|
||||
def test_not_a_git_repo_allows(self):
|
||||
self.grow(500, 5)
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
|
||||
def test_small_change_allows(self):
|
||||
self.git_init(); self.start()
|
||||
self.grow(10, 1)
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
|
||||
def test_many_files_blocks(self):
|
||||
self.git_init(); self.start()
|
||||
self.grow(4, 5)
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
|
||||
def test_preexisting_dirt_does_not_count(self):
|
||||
self.git_init()
|
||||
self.grow(500, 6)
|
||||
self.start()
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
with open(os.path.join(self.proj, "new.txt"), "w") as f:
|
||||
f.write("y\n" * 100)
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
|
||||
def test_committed_growth_still_counts(self):
|
||||
self.git_init(); self.start()
|
||||
self.grow(100, 1)
|
||||
subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True)
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "c"], cwd=self.proj, check=True)
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
|
||||
def test_waive_allows_and_records(self):
|
||||
self.git_init(); self.start()
|
||||
self.grow(100, 1)
|
||||
r = self.sisi("contract", "waive", "typo fix")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
w = store.read("waivers")
|
||||
self.assertEqual(w[0]["reason"], "typo fix")
|
||||
self.assertIn("project", w[0])
|
||||
|
||||
def test_waiver_before_session_does_not_count(self):
|
||||
self.git_init()
|
||||
self.sisi("contract", "waive", "old")
|
||||
w = store.read("waivers")
|
||||
w[0]["ts"] = "2000-01-01T00:00:00Z"
|
||||
os.remove(os.path.join(self.state, "waivers.jsonl"))
|
||||
store.append("waivers", w[0])
|
||||
self.start(); self.grow(100, 1)
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
|
||||
def test_contract_created_after_block_is_enforced(self):
|
||||
self.git_init(); self.start(); self.grow(100, 1)
|
||||
self.call()
|
||||
self.write_contract(contract([check("bad", "false")]))
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
|
||||
|
||||
class GatePropertyTests(GateBase):
|
||||
"""The gate cannot be passed with a failing, timed-out or unrun check short of the 3-strike release."""
|
||||
|
||||
CMDS = [("true", 0, "passed")] * 3 + [("exit 1", 0, "failed"), ("exit 7", 7, "passed"), ("exit 7", 0, "failed")] \
|
||||
+ [("sleep 3", 0, "timeout")] * 1
|
||||
|
||||
def gen(self, rng):
|
||||
checks, invs, expect_ok = [], [], True
|
||||
floors = {"money": 2, "parsing": 2, "ui": None}
|
||||
kinds = {}
|
||||
for i in range(rng.randint(1, 5)):
|
||||
kind = rng.choice(["general", "money", "parsing", "ui", "state-machine"])
|
||||
if rng.random() < 0.2:
|
||||
rung = rng.choice([5, 6])
|
||||
checks.append(human("h%d" % i, rung, kind))
|
||||
kinds.setdefault(kind, []).append(rung)
|
||||
continue
|
||||
cmd, exit_, status = rng.choice(self.CMDS)
|
||||
rung = rng.randint(1, 4)
|
||||
checks.append(check("c%d" % i, cmd, rung=rung, kind=kind, exit=exit_, timeout_s=0.08))
|
||||
kinds.setdefault(kind, []).append(rung)
|
||||
if status != "passed":
|
||||
expect_ok = False
|
||||
for i in range(rng.randint(0, 2)):
|
||||
cmd, exit_, status = rng.choice(self.CMDS)
|
||||
invs.append(check("i%d" % i, cmd, exit=exit_, timeout_s=0.08))
|
||||
if status != "passed":
|
||||
expect_ok = False
|
||||
for kind, rungs in kinds.items():
|
||||
if kind in ("money", "parsing", "state-machine") and min(rungs) > 2:
|
||||
expect_ok = False
|
||||
if not invs and not any("cmd" in c for c in checks):
|
||||
expect_ok = False # nothing runnable: the contract is invalid and must not pass
|
||||
return contract(checks, invs), expect_ok
|
||||
|
||||
def test_generated_contracts(self):
|
||||
seeds = [0, random.randrange(2**32)] + [random.randrange(2**32) for _ in range(ITERS - 1)]
|
||||
for seed in seeds:
|
||||
rng = random.Random(seed)
|
||||
for n in range(4 * ITERS):
|
||||
c, expect_ok = self.gen(rng)
|
||||
sid = "p-%d-%d" % (seed, n)
|
||||
self.write_contract(c)
|
||||
with self.subTest(seed=seed, n=n, contract=c):
|
||||
first = self.call(sid=sid)[0]
|
||||
self.assertEqual(first, "allow" if expect_ok else "block")
|
||||
if not expect_ok:
|
||||
acts = [first] + [self.call(sid=sid)[0] for _ in range(2)]
|
||||
self.assertEqual(acts, ["block"] * 3) # never passes early
|
||||
a, msg = self.call(sid=sid)
|
||||
self.assertEqual(a, "allow")
|
||||
self.assertIn("UNVERIFIED", msg)
|
||||
|
||||
|
||||
class GateUnchangedTreeTests(GateBase):
|
||||
"""Fix 1: a turn that changed nothing is not punished, and not re-checked."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.git_init()
|
||||
self.counter = os.path.join(self.tmp, "runs")
|
||||
|
||||
def counting(self, cmd="true"):
|
||||
return check("c", "echo x >> %s; %s" % (self.counter, cmd))
|
||||
|
||||
def runs(self):
|
||||
return len(open(self.counter).read().split()) if os.path.exists(self.counter) else 0
|
||||
|
||||
def tick(self):
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"}))
|
||||
|
||||
def edit(self, text="x"):
|
||||
with open(os.path.join(self.proj, "work.txt"), "a") as f:
|
||||
f.write(text + "\n")
|
||||
|
||||
def test_unchanged_since_baseline_allows_without_running(self):
|
||||
self.write_contract(contract([self.counting("false")]))
|
||||
self.tick()
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
self.assertEqual(self.runs(), 0)
|
||||
|
||||
def test_unchanged_since_last_allow_not_rerun(self):
|
||||
self.write_contract(contract([self.counting()]))
|
||||
self.tick()
|
||||
self.edit()
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
self.assertEqual(self.runs(), 1)
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
self.assertEqual(self.runs(), 1)
|
||||
self.edit() # a change runs the checks again
|
||||
self.call()
|
||||
self.assertEqual(self.runs(), 2)
|
||||
|
||||
def test_unchanged_after_block_keeps_blocking_and_counts_strikes(self):
|
||||
self.write_contract(contract([self.counting("false")]))
|
||||
self.tick()
|
||||
self.edit()
|
||||
acts = [self.call() for _ in range(3)]
|
||||
self.assertEqual([a for a, _ in acts], ["block"] * 3)
|
||||
self.assertEqual(self.runs(), 1) # only the first call ran the checks
|
||||
self.assertIn("send-back 2 of 3", acts[1][1])
|
||||
a, msg = self.call()
|
||||
self.assertEqual(a, "allow")
|
||||
self.assertIn("UNVERIFIED", msg)
|
||||
self.assertEqual(self.call()[0], "allow") # released tree, still unchanged: allowed
|
||||
|
||||
def test_fixing_the_work_reruns(self):
|
||||
marker = os.path.join(self.proj, "fixed")
|
||||
self.write_contract(contract([check("c", "test -f %s" % marker)]))
|
||||
self.tick()
|
||||
self.edit()
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
open(marker, "w").close()
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
|
||||
def test_fixing_a_gitignored_contract_reruns(self):
|
||||
with open(os.path.join(self.proj, ".git", "info", "exclude"), "a") as f:
|
||||
f.write(".sisi/\n")
|
||||
self.write_contract(contract([check("c", "false")]))
|
||||
self.tick()
|
||||
self.edit()
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
self.write_contract(contract([check("c", "true")]))
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
|
||||
|
||||
class GateTrustTests(GateBase):
|
||||
"""Fix 2: a contract that arrived with a clone is never executed without approval."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.marker = os.path.join(self.tmp, "ran")
|
||||
self.write_contract(contract([check("evil", "touch %s; false" % self.marker)]), trusted=False)
|
||||
|
||||
def test_gate_allows_with_one_notice_and_runs_nothing(self):
|
||||
r = self.hook()
|
||||
self.assertEqual(r.returncode, 0)
|
||||
msg = json.loads(r.stdout)["systemMessage"]
|
||||
self.assertIn("untrusted", msg)
|
||||
self.assertIn("sisi contract trust", msg)
|
||||
self.assertEqual(self.hook().stdout, "") # notice only once per session
|
||||
self.assertFalse(os.path.exists(self.marker))
|
||||
|
||||
def test_verify_refuses_with_distinct_exit(self):
|
||||
r = self.sisi("verify")
|
||||
self.assertEqual(r.returncode, 3)
|
||||
self.assertIn("untrusted", r.stdout)
|
||||
self.assertFalse(os.path.exists(self.marker))
|
||||
|
||||
def test_trust_then_untrust(self):
|
||||
self.assertEqual(self.sisi("contract", "trust").returncode, 0)
|
||||
self.assertEqual(json.loads(self.hook().stdout)["decision"], "block")
|
||||
self.assertTrue(os.path.exists(self.marker))
|
||||
os.remove(self.marker)
|
||||
self.sisi("contract", "untrust")
|
||||
self.assertEqual(self.sisi("verify").returncode, 3)
|
||||
self.assertFalse(os.path.exists(self.marker))
|
||||
|
||||
def test_init_trusts_the_project(self):
|
||||
d = os.path.join(self.tmp, "other")
|
||||
os.makedirs(d)
|
||||
self.sisi("contract", "init", cwd=d)
|
||||
self.assertEqual(self.sisi("verify", cwd=d).returncode, 1) # ran (placeholder fails), not refused
|
||||
|
||||
def test_trust_follows_realpath(self):
|
||||
link = os.path.join(self.tmp, "link")
|
||||
os.symlink(self.proj, link)
|
||||
self.sisi("contract", "trust", cwd=link)
|
||||
self.assertEqual(self.sisi("verify").returncode, 1)
|
||||
|
||||
|
||||
class GateEmptyContractTests(GateBase):
|
||||
"""Fix 3: a contract with nothing runnable must not pass."""
|
||||
|
||||
def test_only_human_or_empty_is_invalid_everywhere(self):
|
||||
for name, c in (("human only", contract([human("h5", 5), human("h6", 6)])), ("empty", contract([]))):
|
||||
with self.subTest(name):
|
||||
self.write_contract(c)
|
||||
r = self.sisi("contract", "check")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("runnable", r.stdout)
|
||||
self.assertEqual(self.sisi("verify").returncode, 1)
|
||||
self.assertIn("runnable", self.sisi("verify").stdout)
|
||||
self.assertEqual(self.call(sid=name)[0], "block")
|
||||
|
||||
def test_waive_is_the_way_out(self):
|
||||
self.git_init()
|
||||
self.write_contract(contract([human("h")]))
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
|
||||
def test_skeleton_is_honest_and_does_not_trap_question_turns(self):
|
||||
self.git_init()
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"}))
|
||||
r = self.sisi("contract", "init")
|
||||
self.assertIn("SKELETON", r.stdout)
|
||||
self.assertIn("real command", r.stdout)
|
||||
self.assertEqual(self.sisi("verify").returncode, 1)
|
||||
self.assertEqual(self.call()[0], "allow") # nothing changed but the skeleton itself
|
||||
with open(os.path.join(self.proj, "big.txt"), "w") as f:
|
||||
f.write("x\n" * 100)
|
||||
a, msg = self.call()
|
||||
self.assertEqual(a, "block") # growth rule applies while the contract is still a skeleton
|
||||
self.assertIn("contract", msg)
|
||||
|
||||
|
||||
class GateGrowthTests(GateBase):
|
||||
"""Fix 4: growth without contract keeps blocking like a failing contract."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.git_init()
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"}))
|
||||
|
||||
def grow(self, name, n):
|
||||
with open(os.path.join(self.proj, name), "a") as f:
|
||||
f.write("x\n" * n)
|
||||
|
||||
def test_blocks_up_to_three_then_unverified(self):
|
||||
self.grow("a.txt", 100)
|
||||
self.assertEqual([self.call()[0] for _ in range(3)], ["block"] * 3)
|
||||
a, msg = self.call()
|
||||
self.assertEqual(a, "allow")
|
||||
self.assertIn("UNVERIFIED", msg)
|
||||
self.assertEqual(self.results()[-1]["status"], "unverified")
|
||||
self.grow("a.txt", 1) # still over the threshold, still no contract: strikes start again
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
|
||||
def test_contract_ends_it(self):
|
||||
self.grow("a.txt", 100)
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
self.write_contract(contract([check("c", "true")]))
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
|
||||
def test_waiver_covers_tree_at_that_moment_only(self):
|
||||
self.grow("a.txt", 100)
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
self.assertEqual(self.sisi("contract", "waive", "generated file").returncode, 0)
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
self.grow("a.txt", 10) # small growth after the waiver point
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
self.grow("a.txt", 100) # big growth after the waiver point
|
||||
self.assertEqual(self.call()[0], "block")
|
||||
self.sisi("contract", "waive", "again")
|
||||
self.assertEqual(self.call()[0], "allow")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,492 @@
|
||||
import json, os, random, subprocess, sys, time, unittest
|
||||
|
||||
from support import SisiCase, REPO
|
||||
|
||||
from sisi import escapes, groundtruth, harvest, learn_cli, scoreboard, store, taskset
|
||||
|
||||
T0 = harvest.epoch("2026-11-01T10:00:00.000Z")
|
||||
|
||||
|
||||
def iso(t):
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime(t))
|
||||
|
||||
|
||||
def rec(typ, t, sid="S1", cwd="/nowhere", sidechain=False, agent=None, **kw):
|
||||
d = {"parentUuid": None, "isSidechain": sidechain, "type": typ, "timestamp": iso(t), "cwd": cwd, "sessionId": sid,
|
||||
"entrypoint": "cli", "userType": "external", "gitBranch": "main"}
|
||||
if agent:
|
||||
d["agentId"] = agent
|
||||
d.update(kw)
|
||||
return json.dumps(d, separators=(",", ":"))
|
||||
|
||||
|
||||
def user(t, text, **kw):
|
||||
return rec("user", t, message={"role": "user", "content": text}, **kw)
|
||||
|
||||
|
||||
def asst(t, text=None, tool=None, cmd=None, model="claude-sonnet-5-5", **kw):
|
||||
blocks = []
|
||||
if text is not None:
|
||||
blocks.append({"type": "text", "text": text})
|
||||
if tool:
|
||||
blocks.append({"type": "tool_use", "id": "tu1", "name": tool, "input": {"command": cmd} if cmd else {}})
|
||||
return rec("assistant", t, message={"role": "assistant", "model": model, "content": blocks}, **kw)
|
||||
|
||||
|
||||
def tool_result(t, **kw):
|
||||
return rec("user", t, message={"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu1", "content": "ok"}]},
|
||||
toolUseResult={"stdout": "ok"}, **kw)
|
||||
|
||||
|
||||
def git(cwd, *args, date=None):
|
||||
env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@t")
|
||||
if date:
|
||||
env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = iso(date)
|
||||
p = subprocess.run(["git"] + list(args), cwd=cwd, env=env, capture_output=True, text=True)
|
||||
assert p.returncode == 0, p.stderr
|
||||
return p.stdout.strip()
|
||||
|
||||
|
||||
class Fixture(SisiCase):
|
||||
def projdir(self, name="-home-t-Code-r"):
|
||||
d = os.path.join(self.home, ".claude", "projects", name)
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
def write(self, path, lines, mode="w"):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, mode, encoding="utf-8") as f:
|
||||
for ln in lines:
|
||||
f.write(ln + "\n")
|
||||
|
||||
def session(self, sid, lines, proj="-home-t-Code-r"):
|
||||
p = os.path.join(self.projdir(proj), sid + ".jsonl")
|
||||
self.write(p, lines)
|
||||
return p
|
||||
|
||||
def harvest(self):
|
||||
con = harvest.connect()
|
||||
st = harvest.run(home=self.home, workers=1, con=con)
|
||||
return con, st
|
||||
|
||||
def repo(self, name="r"):
|
||||
d = os.path.join(self.home, "Code", name)
|
||||
os.makedirs(d)
|
||||
git(d, "init", "-q", "-b", "main")
|
||||
return d
|
||||
|
||||
def commit(self, d, fname, t, content="x"):
|
||||
with open(os.path.join(d, fname), "a") as f:
|
||||
f.write(content + "\n")
|
||||
git(d, "add", "-A")
|
||||
git(d, "commit", "-q", "-m", "c " + fname, date=t)
|
||||
return git(d, "rev-parse", "HEAD")
|
||||
|
||||
|
||||
class TestTypedText(unittest.TestCase):
|
||||
def test_rule(self):
|
||||
tt = harvest.typed_text
|
||||
h = {"type": "user", "message": {"content": "please fix the build"}}
|
||||
self.assertEqual(tt(h)[0], "please fix the build")
|
||||
self.assertIsNone(tt({"type": "user", "isMeta": True, "message": {"content": "hi"}})[0])
|
||||
self.assertIsNone(tt({"type": "user", "toolUseResult": {}, "message": {"content": "hi"}})[0])
|
||||
self.assertIsNone(tt({"type": "user", "message": {"content": [{"type": "tool_result", "content": "x"}]}})[0])
|
||||
self.assertIsNone(tt({"type": "user", "origin": {"kind": "task-notification"}, "message": {"content": "x"}})[0])
|
||||
self.assertIsNone(tt({"type": "user", "origin": {"kind": "peer"}, "message": {"content": "x"}})[0])
|
||||
self.assertEqual(tt({"type": "user", "origin": {"kind": "human"}, "message": {"content": "yo"}})[0], "yo")
|
||||
for wrapped in ("<system-reminder>x</system-reminder>", "<local-command-stdout>x</local-command-stdout>",
|
||||
"<task-notification>x</task-notification>", "This session is being continued from a previous conversation",
|
||||
"<local-command-caveat>Caveat: x</local-command-caveat>"):
|
||||
self.assertIsNone(tt({"type": "user", "message": {"content": wrapped}})[0], wrapped)
|
||||
self.assertIsNone(tt({"type": "user", "isCompactSummary": True, "message": {"content": "summary"}})[0])
|
||||
self.assertEqual(tt({"type": "user", "message": {"content": "[Request interrupted by user for tool use]"}}), (None, 0, True))
|
||||
self.assertIsNone(tt({"type": "user", "message": {"content": "<command-name>/clear</command-name><command-args></command-args>"}})[0])
|
||||
self.assertEqual(tt({"type": "user", "message": {"content": "<command-name>/x</command-name><command-args>do it</command-args>"}})[0], "do it")
|
||||
txt, pasted, _ = tt({"type": "user", "message": {"content": "look <pasted_content id=\"1\">" + "z" * 50 + "</pasted_content> now"}})
|
||||
self.assertEqual(txt, "look now")
|
||||
self.assertGreater(pasted, 50)
|
||||
txt, _, _ = tt({"type": "user", "message": {"content": [{"type": "text", "text": "[Image #1] see this"}, {"type": "image"}]}})
|
||||
self.assertEqual(txt, "see this")
|
||||
self.assertEqual(tt({"type": "user", "message": {"content": [{"type": "text", "text": "[Image #1]"}, {"type": "image"}]}})[0], "")
|
||||
|
||||
def test_queued_command(self):
|
||||
a = {"type": "queued_command", "commandMode": "prompt", "prompt": "do more", "origin": {"kind": "human"}}
|
||||
self.assertEqual(harvest.typed_text(a, queued_prompt=a["prompt"])[0], "do more")
|
||||
b = dict(a, origin={"kind": "task-notification"})
|
||||
self.assertIsNone(harvest.typed_text(b, queued_prompt="x")[0])
|
||||
|
||||
|
||||
class TestHeuristics(unittest.TestCase):
|
||||
def test_machine(self):
|
||||
self.assertTrue(harvest.machine_reason("You are a worker: do this", None, "cli")[0])
|
||||
self.assertTrue(harvest.machine_reason("Act as the design sub-agent for this task.", None, "t3-code")[0])
|
||||
self.assertTrue(harvest.machine_reason("x" * 4000, None, "cli")[0])
|
||||
self.assertTrue(harvest.machine_reason(None)[0])
|
||||
self.assertTrue(harvest.machine_reason("Generate a title that will help the user", None, "sdk-cli")[0])
|
||||
self.assertFalse(harvest.machine_reason("Tell me how you work with subagents", None, "cli")[0])
|
||||
self.assertFalse(harvest.machine_reason("fix the login bug in app.py please", None, "cli")[0])
|
||||
|
||||
def test_correction(self):
|
||||
self.assertTrue(harvest.is_correction("No, that's not what I asked"))
|
||||
self.assertTrue(harvest.is_correction("it still doesn't work"))
|
||||
self.assertFalse(harvest.is_correction("great, now add tests"))
|
||||
self.assertFalse(harvest.is_correction("no" + " blah" * 600))
|
||||
|
||||
|
||||
class TestHarvest(Fixture):
|
||||
def test_main_vs_subagent_and_counts(self):
|
||||
proj = self.projdir()
|
||||
main = [user(T0, "fix the parser bug", cwd="/x"),
|
||||
asst(T0 + 5, "Which file?"),
|
||||
user(T0 + 60, "parser.py"),
|
||||
asst(T0 + 70, tool="Bash", cmd="git commit -am x"),
|
||||
tool_result(T0 + 71),
|
||||
asst(T0 + 80, tool="Bash", cmd="sisi verify"),
|
||||
asst(T0 + 90, tool="AskUserQuestion"),
|
||||
asst(T0 + 100, "All tests pass. Done."),
|
||||
user(T0 + 200, "no, that's wrong, it still fails"),
|
||||
rec("user", T0 + 205, message={"role": "user", "content": "[Request interrupted by user]"}),
|
||||
asst(T0 + 300, "Fixed it.")]
|
||||
self.write(os.path.join(proj, "S1.jsonl"), main)
|
||||
sub = os.path.join(proj, "S1", "subagents", "agent-abc.jsonl")
|
||||
self.write(sub, [user(T0 + 10, "You are a worker: do X", sid="S1", sidechain=True, agent="abc"),
|
||||
asst(T0 + 20, "done", sid="S1", sidechain=True, agent="abc", model="claude-haiku-5-5")])
|
||||
with open(sub[:-6] + ".meta.json", "w") as f:
|
||||
json.dump({"agentType": "x", "model": "haiku"}, f)
|
||||
wf = os.path.join(proj, "S1", "subagents", "workflows", "wf_1234abcd-xx", "agent-zzz.jsonl")
|
||||
self.write(wf, [user(T0 + 12, "brief two", sid="S1", sidechain=True, agent="zzz")])
|
||||
self.write(os.path.join(proj, "S1", "subagents", "workflows", "wf_1234abcd-xx", "journal.jsonl"), ['{"a":1}'])
|
||||
con, st = self.harvest()
|
||||
self.assertEqual(st["seen"], 3)
|
||||
m = con.execute("SELECT * FROM sessions WHERE kind='main'").fetchone()
|
||||
self.assertEqual(m["id"], "S1")
|
||||
self.assertEqual(m["user_turns"], 3)
|
||||
self.assertEqual(m["n_corrections"], 1)
|
||||
self.assertEqual(m["n_premature_done"], 1) # correction right after a completion claim
|
||||
self.assertEqual(m["n_interrupts"], 1)
|
||||
self.assertEqual(m["n_ask"], 1)
|
||||
self.assertEqual(m["n_question_turns"], 1)
|
||||
self.assertEqual((m["ran_commit"], m["used_verify"], m["used_contract"]), (1, 1, 0))
|
||||
self.assertEqual(m["last_claims_done"], 1)
|
||||
self.assertEqual(json.loads(m["tools"])["Bash"], 2)
|
||||
self.assertEqual(m["machine"], 0)
|
||||
subs = {r["agent_id"]: r for r in con.execute("SELECT * FROM sessions WHERE kind='subagent'")}
|
||||
self.assertEqual(set(subs), {"abc", "zzz"})
|
||||
self.assertEqual(subs["abc"]["parent_id"], "S1")
|
||||
self.assertEqual(subs["abc"]["user_turns"], 0)
|
||||
self.assertEqual(json.loads(subs["abc"]["meta"])["model"], "haiku")
|
||||
self.assertTrue(subs["abc"]["first_message"].startswith("You are a worker"))
|
||||
msgs = [r["text"] for r in con.execute("SELECT text FROM user_msgs WHERE session_id='S1' ORDER BY idx")]
|
||||
self.assertEqual(msgs, ["fix the parser bug", "parser.py", "no, that's wrong, it still fails"])
|
||||
self.assertEqual(con.execute("SELECT correction FROM user_msgs WHERE idx=2").fetchone()[0], 1)
|
||||
|
||||
def test_incremental(self):
|
||||
p = self.session("S1", [user(T0, "do a thing please", cwd="/x"), asst(T0 + 5, "ok")])
|
||||
con, st = self.harvest()
|
||||
self.assertEqual((st["parsed"], st["skipped"]), (1, 0))
|
||||
con.close()
|
||||
con, st = self.harvest()
|
||||
self.assertEqual((st["parsed"], st["skipped"]), (0, 1))
|
||||
self.write(p, [user(T0 + 100, "and another thing")], mode="a")
|
||||
con.close()
|
||||
con, st = self.harvest()
|
||||
self.assertEqual((st["parsed"], st["skipped"]), (1, 0))
|
||||
self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 2)
|
||||
self.assertEqual(con.execute("SELECT COUNT(*) FROM user_msgs").fetchone()[0], 2)
|
||||
|
||||
def test_malformed_lines_never_raise(self):
|
||||
p = os.path.join(self.projdir(), "S1.jsonl")
|
||||
with open(p, "wb") as f:
|
||||
f.write(b"not json at all\n")
|
||||
f.write(b'{"parentUuid":null,"type":"user","message":{"content":\n') # truncated
|
||||
f.write(b'{"parentUuid":null,"type":"user","message":null,"timestamp":12}\n')
|
||||
f.write(b'{"parentUuid":null,"type":"assistant","message":{"content":[1,"x",null]},"timestamp":"garbage"}\n')
|
||||
f.write(b'\xff\xfe\x00bad bytes\n')
|
||||
f.write(b'{"parentUuid":null,"type":"attachment","attachment":{"type":"queued_command","prompt":7}}\n')
|
||||
f.write((user(T0, "a real request here", cwd="/x") + "\n").encode())
|
||||
con, st = self.harvest()
|
||||
self.assertEqual(st["errors"], 0)
|
||||
self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 1)
|
||||
|
||||
def test_queued_message_counts_once(self):
|
||||
att = rec("attachment", T0 + 50, attachment={"type": "queued_command", "prompt": "also do this", "commandMode": "prompt",
|
||||
"origin": {"kind": "human"}, "timestamp": iso(T0 + 50)})
|
||||
note = rec("attachment", T0 + 60, attachment={"type": "queued_command", "prompt": "<task-notification>x", "commandMode": "task-notification",
|
||||
"origin": {"kind": "task-notification"}})
|
||||
self.session("S1", [user(T0, "start the work", cwd="/x"), asst(T0 + 10, tool="Read"), att, note, user(T0 + 51, "also do this")])
|
||||
con, _ = self.harvest()
|
||||
self.assertEqual(con.execute("SELECT user_turns FROM sessions").fetchone()[0], 2)
|
||||
|
||||
|
||||
class TestGroundTruth(Fixture):
|
||||
def test_start_commit_ignores_foreign_refs(self):
|
||||
d = self.repo()
|
||||
c1 = self.commit(d, "a", T0 - 7200)
|
||||
c2 = self.commit(d, "b", T0 - 3600)
|
||||
# a checkpoint commit made after c2 and before the session, reachable only from refs/t3/...
|
||||
git(d, "checkout", "-q", "--detach")
|
||||
c3 = self.commit(d, "ckpt", T0 - 600)
|
||||
git(d, "update-ref", "refs/t3/x/checkpoints/1", c3)
|
||||
git(d, "checkout", "-q", "main")
|
||||
git(d, "reset", "-q", "--hard", c2)
|
||||
git(d, "update-ref", "-d", "refs/heads/detached") if False else None
|
||||
self.assertEqual(groundtruth.estimate_start(d, T0), c2)
|
||||
self.assertEqual(groundtruth.estimate_start(d, T0 - 5000), c1)
|
||||
self.assertIsNone(groundtruth.estimate_start(d, T0 - 99999))
|
||||
# a remote-tracking ref counts
|
||||
git(d, "update-ref", "refs/remotes/origin/main", c3)
|
||||
self.assertEqual(groundtruth.estimate_start(d, T0), c3)
|
||||
|
||||
def test_ground_truth_end_to_end(self):
|
||||
d = self.repo()
|
||||
with open(os.path.join(d, "justfile"), "w") as f:
|
||||
f.write("check:\n\techo ok\n")
|
||||
git(d, "add", "-A")
|
||||
git(d, "commit", "-q", "-m", "init", date=T0 - 1000)
|
||||
start = git(d, "rev-parse", "HEAD")
|
||||
after = self.commit(d, "new.py", T0 + 600)
|
||||
late = self.commit(d, "late.py", T0 + 12000) # beyond window + 2h
|
||||
self.session("S1", [user(T0, "add the feature to new.py", cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 3000, "ok")], proj="-p1")
|
||||
con, _ = self.harvest()
|
||||
groundtruth.run(con, home=self.home, workers=1)
|
||||
g = con.execute("SELECT * FROM groundtruth WHERE session_id='S1'").fetchone()
|
||||
self.assertEqual((g["start_commit"], g["start_kind"]), (start, "estimated"))
|
||||
self.assertEqual([c["sha"] for c in json.loads(g["commits"])], [after])
|
||||
self.assertEqual(g["test_cmd"], "just check")
|
||||
self.assertEqual(g["repo_root"], os.path.realpath(d))
|
||||
# sisi's own record makes it exact
|
||||
store.save_session("S1", {"session_id": "S1", "head": start})
|
||||
con.execute("DELETE FROM groundtruth")
|
||||
groundtruth.run(con, home=self.home, workers=1)
|
||||
g = con.execute("SELECT * FROM groundtruth WHERE session_id='S1'").fetchone()
|
||||
self.assertEqual(g["start_kind"], "exact")
|
||||
|
||||
def test_missing_t3_worktree_recovered(self):
|
||||
d = self.repo("proj")
|
||||
self.commit(d, "a", T0 - 100)
|
||||
gone = os.path.join(self.home, ".t3", "worktrees", "proj", "t3-abc")
|
||||
root, how, _ = groundtruth.resolve_repo(gone, self.home)
|
||||
self.assertEqual((root, how), (os.path.realpath(d), "t3-worktree-recovery"))
|
||||
self.assertEqual(groundtruth.resolve_repo(os.path.join(self.home, ".t3", "worktrees", "nothere", "x"), self.home)[0], None)
|
||||
self.assertEqual(groundtruth.resolve_repo(self.proj, self.home)[1], "not-a-git-repo")
|
||||
|
||||
def test_linked_worktree_resolves_to_main_repo(self):
|
||||
d = self.repo()
|
||||
self.commit(d, "a", T0 - 100)
|
||||
wt = os.path.join(self.tmp, "wt")
|
||||
git(d, "worktree", "add", "-q", "-b", "t3/x", wt)
|
||||
self.assertEqual(groundtruth.resolve_repo(wt, self.home)[0], os.path.realpath(d))
|
||||
|
||||
def test_test_command_detection(self):
|
||||
d = self.repo()
|
||||
for name, content, want in (("Cargo.toml", "[package]\n", "cargo test"),):
|
||||
with open(os.path.join(d, name), "w") as f:
|
||||
f.write(content)
|
||||
git(d, "add", "-A")
|
||||
git(d, "commit", "-q", "-m", "i", date=T0)
|
||||
self.assertEqual(groundtruth.test_command(d, git(d, "rev-parse", "HEAD"))[0], "cargo test")
|
||||
e = self.repo("e")
|
||||
with open(os.path.join(e, "package.json"), "w") as f:
|
||||
json.dump({"scripts": {"test": "jest"}}, f)
|
||||
self.assertEqual(groundtruth.test_command(e, None)[0], "npm test")
|
||||
with open(os.path.join(e, "package.json"), "w") as f:
|
||||
json.dump({"scripts": {"test": "echo \"Error: no test specified\" && exit 1"}}, f)
|
||||
self.assertIsNone(groundtruth.test_command(e, None)[0])
|
||||
|
||||
def test_overlap_detection(self):
|
||||
d = self.repo()
|
||||
self.commit(d, "a", T0 - 100)
|
||||
self.session("A", [user(T0, "task one here", cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 1000, "x")], proj="-p")
|
||||
self.session("B", [user(T0 + 500, "task two here", cwd=d), asst(T0 + 600, tool="Read"), asst(T0 + 700, "x")], proj="-p")
|
||||
self.session("C", [user(T0 + 50000, "task three here", cwd=d), asst(T0 + 50010, "x")], proj="-p")
|
||||
con, _ = self.harvest()
|
||||
groundtruth.run(con, home=self.home, workers=1)
|
||||
g = {r["session_id"]: r for r in con.execute("SELECT * FROM groundtruth")}
|
||||
self.assertEqual((g["A"]["overlap_any"], g["A"]["overlap_writers"]), (1, 0)) # B only read
|
||||
self.assertEqual((g["B"]["overlap_any"], g["B"]["overlap_writers"]), (1, 1)) # A wrote
|
||||
self.assertEqual(g["C"]["overlap_any"], 0)
|
||||
|
||||
|
||||
class TestTaskset(Fixture):
|
||||
def test_split_is_stable_and_roughly_70_30(self):
|
||||
ids = ["h-%08x" % random.Random(i).getrandbits(32) for i in range(2000)]
|
||||
first = {i: taskset.split_of(i) for i in ids}
|
||||
dev = sum(1 for v in first.values() if v == "dev") / len(ids)
|
||||
self.assertTrue(0.65 < dev < 0.75, dev)
|
||||
for i in ids:
|
||||
self.assertEqual(taskset.split_of(i), first[i])
|
||||
|
||||
def test_adding_tasks_never_moves_existing(self):
|
||||
con = harvest.connect()
|
||||
now = time.time()
|
||||
existing = {}
|
||||
rng = random.Random(7)
|
||||
for round_ in range(5):
|
||||
for _ in range(40):
|
||||
tid = "t%d" % rng.getrandbits(40)
|
||||
taskset._upsert(con, existing, now, id=tid, kind="human", session_id=tid, grade="B", reasons="[]")
|
||||
existing[tid] = con.execute("SELECT split FROM tasks WHERE id=?", (tid,)).fetchone()[0]
|
||||
snap = {r["id"]: r["split"] for r in con.execute("SELECT id,split FROM tasks")}
|
||||
for tid, sp in snap.items(): # re-upserting with another grade keeps the split
|
||||
taskset._upsert(con, existing, now, id=tid, kind="human", session_id=tid, grade="C", reasons="[]")
|
||||
after = {r["id"]: r["split"] for r in con.execute("SELECT id,split FROM tasks")}
|
||||
self.assertEqual(snap, after)
|
||||
self.assertTrue(all(sp == taskset.split_of(t) for t, sp in after.items()))
|
||||
|
||||
def row(self, **kw):
|
||||
base = dict(start_kind="estimated", test_cmd="just test", overlap_any=0, overlap_writers=0, n_commits=2,
|
||||
first_message="please implement the feature in detail", ran_commit=1, tools="{}")
|
||||
base.update(kw)
|
||||
return base
|
||||
|
||||
def test_grades(self):
|
||||
g = lambda **kw: taskset.grade_human(self.row(**kw), self.row(**kw))[0]
|
||||
self.assertEqual(g(), "A") # no sibling, test command
|
||||
self.assertEqual(g(start_kind="exact", test_cmd=None), "A") # exact start
|
||||
self.assertEqual(g(start_kind="exact", test_cmd=None, overlap_any=1, overlap_writers=1), "C")
|
||||
self.assertEqual(g(overlap_any=1, overlap_writers=1), "B") # estimated, siblings wrote, has tests
|
||||
self.assertEqual(g(test_cmd=None, overlap_any=1, overlap_writers=0), "B")
|
||||
self.assertEqual(g(test_cmd=None), "B") # no sibling but no tests: not A
|
||||
self.assertEqual(g(n_commits=80), "C")
|
||||
self.assertEqual(g(first_message="continue"), "C")
|
||||
self.assertEqual(g(ran_commit=0), "C")
|
||||
self.assertEqual(g(ran_commit=0, tools='{"Edit": 3}'), "A")
|
||||
|
||||
def test_build_end_to_end_with_duplicates(self):
|
||||
d = self.repo()
|
||||
with open(os.path.join(d, "justfile"), "w") as f:
|
||||
f.write("test:\n\ttrue\n")
|
||||
git(d, "add", "-A")
|
||||
git(d, "commit", "-q", "-m", "i", date=T0 - 500)
|
||||
self.commit(d, "n.py", T0 + 400)
|
||||
msg = "please implement the new feature in n.py"
|
||||
self.session("S1", [user(T0, msg, cwd=d), asst(T0 + 10, tool="Edit"), asst(T0 + 500, "ok")], proj="-p")
|
||||
self.session("S2", [user(T0 + 90000, msg, cwd=d), asst(T0 + 90010, tool="Edit"), asst(T0 + 90500, "ok")], proj="-p")
|
||||
self.session("M1", [user(T0 + 300000, "You are a worker. Do the thing.", cwd=d)], proj="-p")
|
||||
con, _ = self.harvest()
|
||||
groundtruth.run(con, home=self.home, workers=1)
|
||||
r = taskset.build(con, home=self.home)
|
||||
self.assertEqual(r["human"], 1) # only S1 has following commits; M1 is machine-written
|
||||
t = taskset.list_tasks(con, kind="human")[0]
|
||||
self.assertEqual((t["id"], t["grade"], t["test_cmd"]), ("h-S1", "A", "just test"))
|
||||
split = t["split"]
|
||||
taskset.build(con, home=self.home)
|
||||
self.assertEqual(taskset.list_tasks(con, kind="human")[0]["split"], split)
|
||||
self.assertEqual(taskset.get_task(con, "h-S")["id"], "h-S1")
|
||||
|
||||
def test_ledger_matching(self):
|
||||
sub = lambda i, t0, t1: {"id": i, "t0": t0, "t1": t1, "names": {"r"}, "classes": {"sonnet"}}
|
||||
led = lambda i, ts, w="sonnet", m=None, p="r": {"id": i, "ts": ts, "worker": w, "project": p, "outcome": "accepted", "minutes": m}
|
||||
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, m=10)])
|
||||
self.assertEqual((out["a"][1], out["a"][0]["id"]), ("high", "L1"))
|
||||
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, m=90)])
|
||||
self.assertEqual(out["a"][1], "medium")
|
||||
out = taskset.match_ledger([sub("a", T0, T0 + 600), sub("b", T0 + 100, T0 + 650)], [led("L1", T0 + 700)])
|
||||
self.assertEqual((out["a"][1], out["a"][0]), ("low", None))
|
||||
self.assertEqual(out["b"][1], "low")
|
||||
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, w="opencode-go/x")])
|
||||
self.assertEqual(out["a"][1], "none")
|
||||
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 700, p="other")])
|
||||
self.assertEqual(out["a"][1], "none")
|
||||
out = taskset.match_ledger([sub("a", T0, T0 + 600)], [led("L1", T0 + 9000)])
|
||||
self.assertEqual(out["a"][1], "none")
|
||||
|
||||
|
||||
class TestEscapesChecksScoreboard(Fixture):
|
||||
def results(self, project, t, ok=True, session=None):
|
||||
return [{"ts": iso(t)[:19] + "Z", "contract": "c", "project": project, "check": "unit", "status": "passed" if ok else "failed",
|
||||
"run": "r%d" % t, "session": session}]
|
||||
|
||||
def test_escapes(self):
|
||||
d = self.repo()
|
||||
self.commit(d, "a", T0 - 100)
|
||||
self.session("S1", [user(T0, "implement the thing in a", cwd=d), asst(T0 + 100, "All tests pass. Done."),
|
||||
user(T0 + 200, "no, that's wrong, it still fails"), asst(T0 + 300, "sorry")], proj="-p")
|
||||
con, _ = self.harvest()
|
||||
groundtruth.run(con, home=self.home, workers=1)
|
||||
res = self.results(d, T0 + 120) # attributed by time and project, no session field
|
||||
out = escapes.find(con, res)
|
||||
kinds = [e["kind"] for e in out]
|
||||
self.assertIn("contract-then-correction", kinds)
|
||||
self.assertIn("premature-done", kinds)
|
||||
# a failed run is not "verified"
|
||||
self.assertEqual([e for e in escapes.find(con, self.results(d, T0 + 120, ok=False)) if e["kind"].startswith("contract")], [])
|
||||
# a correction BEFORE the pass is not an escape
|
||||
self.assertEqual([e for e in escapes.find(con, self.results(d, T0 + 250)) if e["kind"].startswith("contract")], [])
|
||||
|
||||
def test_fix_session_escape(self):
|
||||
d = self.repo()
|
||||
self.commit(d, "a.py", T0 - 100)
|
||||
self.commit(d, "a.py", T0 + 100)
|
||||
self.session("S1", [user(T0, "implement the thing in a.py", cwd=d), asst(T0 + 50, tool="Edit"), asst(T0 + 150, "ok")], proj="-p")
|
||||
c2 = self.commit(d, "a.py", T0 + 86400 * 2, "fix")
|
||||
self.session("S2", [user(T0 + 86400 * 2 - 100, "the thing in a.py is broken, please fix it", cwd=d), asst(T0 + 86400 * 2 - 50, tool="Edit"),
|
||||
asst(T0 + 86400 * 2 + 60, "ok")], proj="-p")
|
||||
con, _ = self.harvest()
|
||||
groundtruth.run(con, home=self.home, workers=1)
|
||||
out = escapes.find(con, self.results(d, T0 + 120, session="S1"))
|
||||
fix = [e for e in out if e["kind"] == "contract-then-fix-session"]
|
||||
self.assertEqual(len(fix), 1)
|
||||
self.assertEqual(fix[0]["evidence"]["later_session"], "S2")
|
||||
|
||||
def test_check_stats(self):
|
||||
rs = [{"check": "a", "status": "passed", "verifier": "v1"} for _ in range(12)]
|
||||
rs += [{"check": "b", "status": "failed"}, {"check": "b", "status": "timeout"}, {"check": "gate", "status": "unverified"}]
|
||||
rs += [{"check": "c", "status": "passed", "verifier": "v2"}, "junk"]
|
||||
st = scoreboard.check_stats(rs)
|
||||
by = {s["id"]: s for s in st["checks"]}
|
||||
self.assertTrue(by["a"]["never_seen_failing"])
|
||||
self.assertEqual((by["b"]["runs"], by["b"]["failures"], by["b"]["timeouts"]), (2, 1, 1))
|
||||
self.assertFalse(by["b"]["never_seen_failing"])
|
||||
self.assertFalse(by["c"]["never_seen_failing"]) # too few runs
|
||||
self.assertNotIn("gate", by)
|
||||
self.assertEqual({s["id"]: s["runs"] for s in st["verifiers"]}, {"v1": 12, "v2": 1})
|
||||
|
||||
def test_scoreboard_weeks(self):
|
||||
w1 = harvest.epoch("2026-11-02T10:00:00.000Z") # Monday of ISO week 45
|
||||
w2 = w1 + 7 * 86400
|
||||
self.session("S1", [user(w1, "do the first task here", cwd="/x"), asst(w1 + 5, "Done. All tests pass."),
|
||||
user(w1 + 60, "no, that's wrong"), asst(w1 + 70, tool="Bash", cmd="sisi contract check")], proj="-p")
|
||||
self.session("S2", [user(w2, "do the second task here", cwd="/x"), asst(w2 + 5, "ok?")], proj="-p")
|
||||
self.session("M", [user(w2, "You are a worker. Do X.", cwd="/x")], proj="-p")
|
||||
con, _ = self.harvest()
|
||||
sb = scoreboard.scoreboard(con)
|
||||
self.assertEqual(list(sb["weeks"]), ["2026-W45", "2026-W46"])
|
||||
a = sb["weeks"]["2026-W45"]
|
||||
self.assertEqual((a["sessions"], a["turns_per_session"], a["corrections_per_100"], a["contract_share"], a["premature_done_share"]),
|
||||
(1, 2.0, 50.0, 1.0, 1.0))
|
||||
self.assertEqual(sb["weeks"]["2026-W46"]["sessions"], 1) # machine-written session excluded
|
||||
self.assertEqual(sb["weeks"]["2026-W46"]["questions_per_100"], 100.0)
|
||||
|
||||
|
||||
class TestCli(Fixture):
|
||||
def run_cli(self, *args):
|
||||
env = dict(os.environ, PYTHONPATH=REPO)
|
||||
return subprocess.run([sys.executable, "-m", "sisi.learn_cli"] + list(args), capture_output=True, text=True, env=env, cwd=self.proj, timeout=120)
|
||||
|
||||
def test_commands_run(self):
|
||||
d = self.repo()
|
||||
self.commit(d, "a", T0 - 100)
|
||||
self.session("S1", [user(T0, "implement the thing here please", cwd=d), asst(T0 + 100, "ok")], proj="-p")
|
||||
p = self.run_cli("harvest", "--json", "--workers", "1")
|
||||
self.assertEqual(p.returncode, 0, p.stderr)
|
||||
self.assertEqual(json.loads(p.stdout)["transcripts"]["parsed"], 1)
|
||||
self.assertEqual(json.loads(self.run_cli("harvest", "--json").stdout)["transcripts"]["parsed"], 0)
|
||||
self.assertEqual(self.run_cli("tasks", "build").returncode, 0)
|
||||
self.assertEqual(self.run_cli("tasks", "list", "--json").returncode, 0)
|
||||
self.assertEqual(self.run_cli("tasks", "show", "nope").returncode, 1)
|
||||
self.assertEqual(self.run_cli("escapes", "--json").returncode, 0)
|
||||
self.assertEqual(self.run_cli("checks").returncode, 0)
|
||||
sb = json.loads(self.run_cli("scoreboard", "--json").stdout)
|
||||
self.assertEqual(sb["weeks"]["2026-W44"]["sessions"], 1)
|
||||
|
||||
def test_register_attaches_commands(self):
|
||||
import argparse
|
||||
ap = argparse.ArgumentParser()
|
||||
learn_cli.register(ap.add_subparsers(dest="cmd"))
|
||||
for argv in (["harvest"], ["tasks", "build"], ["tasks", "list", "--grade", "A"], ["tasks", "show", "x"], ["escapes"], ["checks"], ["scoreboard", "--json"]):
|
||||
self.assertTrue(callable(ap.parse_args(argv).func))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,751 @@
|
||||
"""Product and personal data are separate: the overlay, generated rulebook, migration, update, export/import,
|
||||
install migration, and the property that sisi never writes inside the product."""
|
||||
import hashlib, json, os, signal, time, shutil, sqlite3, stat, subprocess, sys, tarfile, unittest, unittest.mock
|
||||
from support import *
|
||||
from sisi import lifecycle, overlay, paths, pdata, retro, wiring
|
||||
|
||||
RULES = [("alpha", "Alpha rule", "Do alpha things.\n\nWhy: alpha."),
|
||||
("beta", "Beta rule", "Do beta things.\n\nWhy: beta."),
|
||||
("gamma", "Gamma rule", "Do gamma things.\n\nWhy: gamma.")]
|
||||
|
||||
|
||||
def core_text(rules):
|
||||
out = ["# test rulebook", "", "Intro line."]
|
||||
for n, (i, t, b) in enumerate(rules, 1):
|
||||
out += ["", "## %d. %s {#%s}" % (n, t, i), "", b]
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def rule_file(title, body):
|
||||
return "## %s\n\n%s\n" % (title, body)
|
||||
|
||||
|
||||
class PersonalCase(SisiCase):
|
||||
def make_product(self, name, rules=RULES, edit_library=False):
|
||||
root = os.path.join(self.tmp, name)
|
||||
os.makedirs(os.path.join(root, "canon"))
|
||||
for lib in ("verifiers", "done"): # linked (read only) unless the test changes a library file
|
||||
if edit_library:
|
||||
shutil.copytree(os.path.join(REPO, lib), os.path.join(root, lib))
|
||||
else:
|
||||
os.symlink(os.path.join(REPO, lib), os.path.join(root, lib))
|
||||
self.write_product_core(root, rules)
|
||||
return root
|
||||
|
||||
def write_product_core(self, root, rules):
|
||||
with open(os.path.join(root, "canon", "core.md"), "w") as f:
|
||||
f.write(core_text(rules))
|
||||
|
||||
def use_product(self, root):
|
||||
old = (paths.REPO, os.environ.get("SISI_VERIFIERS"), os.environ.get("SISI_DONE"))
|
||||
paths.REPO = root
|
||||
os.environ["SISI_VERIFIERS"] = os.path.join(root, "verifiers")
|
||||
os.environ["SISI_DONE"] = os.path.join(root, "done")
|
||||
|
||||
def undo():
|
||||
paths.REPO = old[0]
|
||||
for k, v in zip(("SISI_VERIFIERS", "SISI_DONE"), old[1:]):
|
||||
os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v)
|
||||
self.addCleanup(undo)
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.p1 = self.make_product("p1")
|
||||
self.use_product(self.p1)
|
||||
|
||||
def ok(self, *a, **kw):
|
||||
r = self.sisi(*a, **kw)
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
return r
|
||||
|
||||
def generated(self):
|
||||
with open(paths.generated()) as f:
|
||||
return f.read()
|
||||
|
||||
def git_log(self):
|
||||
return pdata.git("log", "--format=%s").stdout.splitlines()
|
||||
|
||||
def verifier_text(self, id, title="Mine", src="safety/shellcheck"):
|
||||
with open(os.path.join(REPO, "verifiers", src + ".md")) as f:
|
||||
t = f.read()
|
||||
t = t.replace("id: shellcheck", "id: " + id, 1)
|
||||
return "\n".join("title: " + title if l.startswith("title:") else l for l in t.split("\n"))
|
||||
|
||||
def recipe_text(self, id, title="Mine"):
|
||||
with open(os.path.join(REPO, "done", "bugfix.md")) as f:
|
||||
t = f.read()
|
||||
t = t.replace("id: bugfix", "id: " + id, 1)
|
||||
return "\n".join("title: " + title if l.startswith("title:") else l for l in t.split("\n"))
|
||||
|
||||
|
||||
class OverlayTests(PersonalCase):
|
||||
def test_first_use_creates_personal_repo(self):
|
||||
self.ok("build-canon")
|
||||
self.assertTrue(os.path.isdir(os.path.join(self.data, ".git")))
|
||||
self.assertEqual(open(os.path.join(self.data, "VERSION")).read().strip(), str(pdata.FORMAT_VERSION))
|
||||
self.assertIn("retro.db", open(os.path.join(self.data, ".gitignore")).read())
|
||||
g = self.generated()
|
||||
self.assertTrue(g.startswith("<!-- generated by sisi build-canon"))
|
||||
self.assertEqual(g.split("\n")[0].count("<!--"), 1)
|
||||
self.assertIn("## 1. Alpha rule {#alpha}", g)
|
||||
self.assertEqual(pdata.git("log", "--format=%an <%ae>").stdout.split("\n")[0], "sisi <sisi@localhost>")
|
||||
self.assertFalse(os.path.exists(os.path.join(self.p1, "oracle.md")))
|
||||
|
||||
def test_hooks_and_global_config_are_ignored(self):
|
||||
self.ok("build-canon")
|
||||
hook = os.path.join(self.data, ".git", "hooks", "pre-commit")
|
||||
os.makedirs(os.path.dirname(hook), exist_ok=True)
|
||||
with open(hook, "w") as f:
|
||||
f.write("#!/bin/sh\nexit 1\n")
|
||||
os.chmod(hook, 0o755)
|
||||
gc = os.path.join(self.tmp, "gitconfig")
|
||||
open(gc, "w").write("[commit]\n\tgpgsign = true\n[user]\n\tname = someone\n")
|
||||
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."), env={"GIT_CONFIG_GLOBAL": gc})
|
||||
self.assertEqual(self.git_log()[0], "overlay: add rule delta")
|
||||
|
||||
def test_rules_add_replace_disable_enable(self):
|
||||
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta rule", "Do delta.\n\nWhy: delta."))
|
||||
self.ok("overlay", "replace-rule", "beta", "-", stdin=rule_file("Beta, mine", "My beta."))
|
||||
self.ok("overlay", "disable-rule", "gamma")
|
||||
g = self.generated()
|
||||
self.assertIn("## 1. Alpha rule {#alpha}", g)
|
||||
self.assertIn("## 2. Beta, mine {#beta}\n\nMy beta.", g)
|
||||
self.assertNotIn("Gamma", g)
|
||||
self.assertIn("## 3. Delta rule {#delta}\n\nDo delta.", g)
|
||||
self.assertNotIn("Do beta things", g)
|
||||
out = self.ok("overlay", "list").stdout
|
||||
for w in ("added delta", "replaced beta", "disabled gamma"):
|
||||
self.assertIn(w, out)
|
||||
d = self.ok("overlay", "diff").stdout
|
||||
self.assertIn("-Do beta things.", d)
|
||||
self.assertIn("+My beta.", d)
|
||||
self.ok("overlay", "enable-rule", "gamma")
|
||||
self.assertIn("## 4. Gamma rule {#gamma}", self.generated().replace("## 3. Gamma", "## 4. Gamma")) if False else None
|
||||
self.assertIn("Gamma rule", self.generated())
|
||||
# mistakes are refused, with a reason, and change nothing
|
||||
for args, text in ((("add-rule", "--id", "alpha", "-"), rule_file("A", "b")),
|
||||
(("replace-rule", "nope", "-"), rule_file("A", "b")),
|
||||
(("disable-rule", "nope"), ""), (("add-rule", "-"), "no heading here\n")):
|
||||
before = self.git_log()
|
||||
r = self.sisi("overlay", *args, stdin=text)
|
||||
self.assertEqual(r.returncode, 1, args)
|
||||
self.assertEqual(self.git_log(), before)
|
||||
|
||||
def test_verifiers_and_recipes_overlay(self):
|
||||
self.ok("overlay", "add-verifier", "-", stdin=self.verifier_text("my-new-check", "My new check"))
|
||||
self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Shellcheck, my way"))
|
||||
self.ok("overlay", "disable-verifier", "mutmut")
|
||||
self.ok("overlay", "add-recipe", "-", stdin=self.recipe_text("my-recipe", "My recipe"))
|
||||
self.ok("overlay", "replace-recipe", "bugfix", "-", stdin=self.recipe_text("bugfix", "Bugfix, my way"))
|
||||
self.ok("overlay", "disable-recipe", "release")
|
||||
out = self.ok("verifiers", "--section", "safety").stdout
|
||||
self.assertRegex(out, r"my-new-check .*\[personal addition\]")
|
||||
self.assertRegex(out, r"shellcheck .*Shellcheck, my way.*\[personal, replaces the product's\]")
|
||||
self.assertNotRegex(self.ok("verifiers").stdout, r"\n mutmut ")
|
||||
self.assertIn("personal", self.ok("verifiers", "show", "shellcheck").stdout.split("\n")[0])
|
||||
done = self.ok("done").stdout
|
||||
self.assertRegex(done, r"my-recipe .*\[personal addition\]")
|
||||
self.assertRegex(done, r"bugfix .*Bugfix, my way.*\[personal, replaces")
|
||||
self.assertNotRegex(done, r"\nrelease ")
|
||||
# the product's own files are untouched, and lint accepts the merged library
|
||||
self.assertNotIn("my way", open(os.path.join(self.p1, "verifiers", "safety", "shellcheck.md")).read())
|
||||
self.assertEqual(self.sisi("verifiers", "lint").returncode, 0)
|
||||
# an invalid entry is refused
|
||||
r = self.sisi("overlay", "add-verifier", "-", stdin="---\nid: broken\nsection: safety\n---\nx\n")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "verifiers", "safety", "broken.md")))
|
||||
self.ok("overlay", "enable-verifier", "mutmut")
|
||||
self.assertRegex(self.ok("verifiers").stdout, r"\n mutmut ")
|
||||
|
||||
def test_size_budget_refuses_and_changes_nothing(self):
|
||||
self.ok("build-canon")
|
||||
gen0, log0 = self.generated(), self.git_log()
|
||||
big = rule_file("Big", "\n".join("line %d" % i for i in range(150)))
|
||||
r = self.sisi("overlay", "add-rule", "--id", "big", "-", stdin=big)
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("budget", r.stderr)
|
||||
self.assertEqual((self.generated(), self.git_log()), (gen0, log0))
|
||||
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "rules", "big.md")))
|
||||
# fits after something is made shorter or replaced
|
||||
fill = rule_file("Fill", "\n".join("x%d" % i for i in range(80)))
|
||||
self.ok("overlay", "add-rule", "--id", "fill", "-", stdin=fill)
|
||||
self.assertLessEqual(len(self.generated().splitlines()), overlay.MAX_LINES)
|
||||
r = self.sisi("overlay", "add-rule", "--id", "more", "-", stdin=rule_file("More", "\n".join("y%d" % i for i in range(30))))
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.ok("overlay", "replace-rule", "fill", "-", stdin=rule_file("Fill", "short"))
|
||||
self.ok("overlay", "add-rule", "--id", "more", "-", stdin=rule_file("More", "\n".join("y%d" % i for i in range(30))))
|
||||
|
||||
def test_generated_is_idempotent_and_staleness_is_cheap(self):
|
||||
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."))
|
||||
a = self.generated()
|
||||
for _ in range(2):
|
||||
self.ok("build-canon")
|
||||
self.assertEqual(self.generated(), a)
|
||||
self.assertFalse(overlay.is_stale())
|
||||
t = os.stat(os.path.join(self.p1, "canon", "core.md")).st_mtime_ns - 5_000_000_000
|
||||
os.utime(paths.generated(), ns=(t, t)) # the product's core.md is now newer than the generated file
|
||||
self.assertTrue(overlay.is_stale())
|
||||
self.ok("build-canon")
|
||||
self.assertFalse(overlay.is_stale())
|
||||
|
||||
def test_stale_rulebook_is_reported_by_tick_only_when_wired(self):
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
self.assertEqual(wiring.install()[0], 0)
|
||||
self.assertEqual(wiring.quick_problem(), None)
|
||||
os.remove(paths.generated())
|
||||
self.assertIn("generated rulebook is missing", wiring.quick_problem())
|
||||
self.ok("build-canon")
|
||||
t = os.stat(os.path.join(self.p1, "canon", "core.md")).st_mtime_ns - 5_000_000_000
|
||||
os.utime(paths.generated(), ns=(t, t))
|
||||
self.assertIn("out of date", wiring.quick_problem())
|
||||
|
||||
def test_one_commit_per_change_and_revert_restores_bytes(self):
|
||||
self.ok("build-canon")
|
||||
n0 = len(self.git_log())
|
||||
steps = [(("add-rule", "--id", "delta", "-"), rule_file("Delta", "Body.")),
|
||||
(("replace-rule", "alpha", "-"), rule_file("Alpha, mine", "Mine.")),
|
||||
(("disable-rule", "gamma"), ""),
|
||||
(("add-verifier", "-"), self.verifier_text("my-check")),
|
||||
(("disable-recipe", "release"), "")]
|
||||
gens = [self.generated()]
|
||||
for args, text in steps:
|
||||
self.ok("overlay", *args, stdin=text)
|
||||
gens.append(self.generated())
|
||||
self.assertEqual(len(self.git_log()), n0 + len(gens) - 1)
|
||||
self.assertEqual(self.git_log()[0], "overlay: disable recipe release")
|
||||
# revert the disable-rule commit: the rulebook is exactly what it was after the replace-rule
|
||||
c = pdata.git("log", "--format=%h", "--grep=disable rule gamma").stdout.split()[0]
|
||||
self.ok("overlay", "revert", c)
|
||||
self.assertEqual(self.generated().split("\n")[1:], gens[2].split("\n")[1:])
|
||||
# reverting the add of delta as well gives the state after replace-rule minus delta; reverting all gives the base
|
||||
for subj in ("add rule delta", "replace rule alpha"):
|
||||
self.ok("overlay", "revert", pdata.git("log", "--format=%h", "--grep=overlay: " + subj).stdout.split()[0])
|
||||
base = core_text(RULES)
|
||||
want = overlay.render()
|
||||
self.assertEqual(self.generated(), want)
|
||||
self.assertEqual(self.generated().split("\n", 2)[2].count("## "), 3)
|
||||
# a non-overlay commit cannot be reverted here
|
||||
first = pdata.git("rev-list", "--max-parents=0", "HEAD").stdout.split()[0]
|
||||
self.assertEqual(self.sisi("overlay", "revert", first).returncode, 1)
|
||||
|
||||
def test_revert_gives_back_the_same_generated_file(self):
|
||||
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."))
|
||||
before = open(paths.generated(), "rb").read()
|
||||
self.ok("overlay", "replace-rule", "alpha", "-", stdin=rule_file("Alpha 2", "Other."))
|
||||
self.assertNotEqual(open(paths.generated(), "rb").read(), before)
|
||||
self.ok("overlay", "revert", pdata.git("rev-parse", "--short", "HEAD").stdout.strip())
|
||||
self.assertEqual(open(paths.generated(), "rb").read(), before)
|
||||
|
||||
def test_canon_cost_and_status(self):
|
||||
self.ok("build-canon")
|
||||
out = self.ok("canon", "cost").stdout
|
||||
lines = len(self.generated().splitlines())
|
||||
self.assertIn("rulebook %d lines" % lines, out)
|
||||
self.assertIn("%d characters" % len(self.generated()), out)
|
||||
self.assertIn("lessons block at most %d characters" % retro.LIMIT, out)
|
||||
self.assertIn(out.strip(), self.ok("status").stdout)
|
||||
|
||||
def test_core_md_rules_have_unique_ids_and_the_budget_holds(self):
|
||||
text = open(os.path.join(REPO, "canon", "core.md")).read()
|
||||
heads = [l for l in text.split("\n") if l.startswith("## ")]
|
||||
ids = []
|
||||
import re
|
||||
for h in heads:
|
||||
m = re.match(r"^## \d+\. .+ \{#([a-z0-9-]+)\}$", h)
|
||||
self.assertTrue(m, h)
|
||||
ids.append(m.group(1))
|
||||
self.assertEqual(len(ids), len(set(ids)))
|
||||
self.assertGreaterEqual(len(ids), 7)
|
||||
os.environ.pop("SISI_NOTES", None)
|
||||
paths.REPO = REPO
|
||||
self.assertLessEqual(len(overlay.render().splitlines()), overlay.MAX_LINES)
|
||||
|
||||
|
||||
class UpdateTests(PersonalCase):
|
||||
def test_update_keeps_additions_replacements_and_disables(self):
|
||||
self.ok("overlay", "add-rule", "--id", "mine", "-", stdin=rule_file("My rule", "Mine."))
|
||||
self.ok("overlay", "replace-rule", "beta", "-", stdin=rule_file("Beta, mine", "My beta."))
|
||||
self.ok("overlay", "disable-rule", "gamma")
|
||||
self.ok("overlay", "add-verifier", "-", stdin=self.verifier_text("my-check", "My check"))
|
||||
self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Shellcheck, my way"))
|
||||
self.ok("overlay", "replace-verifier", "semgrep-not-there", "-", stdin=self.verifier_text("semgrep-not-there")) \
|
||||
if False else None
|
||||
self.ok("overlay", "disable-verifier", "mutmut")
|
||||
self.ok("overlay", "replace-recipe", "bugfix", "-", stdin=self.recipe_text("bugfix", "Bugfix, my way"))
|
||||
base_hashes = overlay.bases()
|
||||
self.assertEqual(set(base_hashes), {"rule:beta", "verifier:shellcheck", "recipe:bugfix"})
|
||||
# the product moves on: alpha unchanged, beta changed, gamma removed, delta new; shellcheck changed, bugfix unchanged
|
||||
p2 = self.make_product("p2", [RULES[0], ("beta", "Beta rule", "Do beta things, newly.\n\nWhy: beta."),
|
||||
("delta", "Delta rule", "Do delta things.\n\nWhy: delta.")], edit_library=True)
|
||||
sc = os.path.join(p2, "verifiers", "safety", "shellcheck.md")
|
||||
open(sc, "w").write(open(sc).read().replace("title:", "title: (new) ", 1))
|
||||
self.use_product(p2)
|
||||
out = self.ok("update", "--post").stdout
|
||||
self.assertIn("kept your version of rule beta", out)
|
||||
self.assertIn("kept your version of verifier shellcheck", out)
|
||||
self.assertNotIn("bugfix", out.split("doctor:")[0].replace("backup", ""))
|
||||
g = self.generated()
|
||||
self.assertIn("Beta, mine", g)
|
||||
self.assertNotIn("newly", g)
|
||||
self.assertIn("Alpha rule", g)
|
||||
self.assertIn("Delta rule", g) # the product's new rule arrives
|
||||
self.assertIn("My rule", g) # the addition survives
|
||||
self.assertNotIn("Gamma", g) # removed by the product and disabled by the person
|
||||
libs = self.ok("verifiers", "--section", "safety").stdout
|
||||
self.assertRegex(libs, r"shellcheck .*Shellcheck, my way")
|
||||
self.assertIn("my-check", libs)
|
||||
self.assertNotRegex(self.ok("verifiers").stdout, r"\n mutmut ")
|
||||
queue = [json.loads(l) for l in open(os.path.join(self.data, "retest.jsonl"))]
|
||||
self.assertEqual(sorted((q["kind"], q["id"]) for q in queue), [("rule", "beta"), ("verifier", "shellcheck")])
|
||||
q = {q["id"]: q for q in queue}
|
||||
self.assertEqual(q["beta"]["old_base_hash"], base_hashes["rule:beta"])
|
||||
self.assertEqual(q["beta"]["new_base_hash"], overlay.base_hash("rule", "beta"))
|
||||
self.assertNotEqual(q["beta"]["old_base_hash"], q["beta"]["new_base_hash"])
|
||||
self.assertEqual(q["shellcheck"]["new_base_hash"], overlay.base_hash("verifier", "shellcheck"))
|
||||
# a second update changes nothing and queues nothing new
|
||||
self.ok("update", "--post")
|
||||
self.assertEqual(len(open(os.path.join(self.data, "retest.jsonl")).read().splitlines()), 2)
|
||||
self.assertEqual(self.generated(), g)
|
||||
self.assertTrue(os.listdir(os.path.join(self.data, "backups")))
|
||||
|
||||
def make_origin_and_clone(self):
|
||||
"""A product that is a real git clone of an origin, so `sisi update` can fetch and fast-forward it."""
|
||||
origin = os.path.join(self.tmp, "origin")
|
||||
shutil.copytree(REPO, origin, ignore=shutil.ignore_patterns(".git", "__pycache__", "tests", ".sisi", "docs", "verifiers", "done"))
|
||||
shutil.copytree(os.path.join(REPO, "verifiers"), os.path.join(origin, "verifiers"))
|
||||
shutil.copytree(os.path.join(REPO, "done"), os.path.join(origin, "done"))
|
||||
g = lambda d, *a: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "-C", d] + list(a), check=True, capture_output=True)
|
||||
subprocess.run(["git", "init", "-q", "-b", "main", origin], check=True)
|
||||
g(origin, "add", "-A")
|
||||
g(origin, "commit", "-q", "-m", "one")
|
||||
clone = os.path.join(self.tmp, "clone")
|
||||
subprocess.run(["git", "clone", "-q", origin, clone], check=True, capture_output=True)
|
||||
return origin, clone, g
|
||||
|
||||
def test_update_refusals_and_fast_forward(self):
|
||||
origin, clone, g = self.make_origin_and_clone()
|
||||
self.use_product(clone)
|
||||
# no upstream
|
||||
g(clone, "checkout", "-q", "-b", "local")
|
||||
r = self.sisi("update")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("no upstream", r.stdout)
|
||||
g(clone, "checkout", "-q", "main")
|
||||
# local changes: refused, nothing discarded
|
||||
core = os.path.join(clone, "canon", "core.md")
|
||||
orig = open(core).read()
|
||||
open(core, "a").write("\nlocal edit\n")
|
||||
r = self.sisi("update")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("local changes", r.stdout)
|
||||
self.assertTrue(open(core).read().endswith("local edit\n"))
|
||||
open(core, "w").write(orig)
|
||||
# a person's replacement, then the origin changes that rule
|
||||
rid = "know-done"
|
||||
self.ok("overlay", "replace-rule", rid, "-", stdin=rule_file("Know it, my way", "My text."))
|
||||
text = open(os.path.join(origin, "canon", "core.md")).read()
|
||||
open(os.path.join(origin, "canon", "core.md"), "w").write(text.replace("Skip the contract for small edits", "Skip the contract for tiny edits"))
|
||||
g(origin, "commit", "-q", "-am", "two")
|
||||
r = self.ok("update")
|
||||
self.assertIn("->", r.stdout)
|
||||
self.assertIn("tiny edits", open(core).read())
|
||||
self.assertIn("kept your version of rule know-done", r.stdout)
|
||||
self.assertIn("Know it, my way", self.generated())
|
||||
self.assertIn("rulebook rebuilt", r.stdout)
|
||||
self.assertIn("rulebook", r.stdout.split("doctor:")[1])
|
||||
r = self.ok("update")
|
||||
self.assertIn("already up to date", r.stdout)
|
||||
self.assertEqual(len([l for l in open(os.path.join(self.data, "retest.jsonl"))]), 1)
|
||||
|
||||
def test_update_refuses_outside_a_git_clone(self):
|
||||
r = self.sisi("update")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("not a git clone", r.stdout)
|
||||
|
||||
|
||||
class MigrationTests(PersonalCase):
|
||||
LESSONS = [dict(aim="verified", moment="ran pytest and it passed without the new test", cause="the test never failed",
|
||||
change_kind="rule", change="Always watch a new test fail without the change first", target=None),
|
||||
dict(aim="speed", moment="re-read the same large log three times in a row", cause="no summary kept",
|
||||
change_kind="verifier", change="Note the log tool in the field notes for the verifier", target="fuzz")]
|
||||
|
||||
def legacy_state(self, extra_lesson=False):
|
||||
"""Lay out an old-style installation: personal files in the state dir, oracle and notes in the product."""
|
||||
os.makedirs(os.path.join(self.state, "backups"))
|
||||
db = os.path.join(self.state, "retro.db")
|
||||
with unittest.mock.patch.object(retro, "db_path", return_value=db):
|
||||
con = retro.connect()
|
||||
for f in self.LESSONS + ([dict(aim="intent", moment="built the wrong thing for a day", cause="no check with the human",
|
||||
change_kind="rule", change="Confirm the goal in one line before starting", target=None)] if extra_lesson else []):
|
||||
retro.new_lesson(con, dict(f), self.proj, None)
|
||||
con.commit()
|
||||
con.close()
|
||||
json.dump([self.proj], open(os.path.join(self.state, "trusted.json"), "w"))
|
||||
json.dump({"verify": {"fast_limit_s": 9}}, open(os.path.join(self.state, "config.json"), "w"))
|
||||
for n, t in (("learn-quarantine.jsonl", "quarantined"), ("notes.jsonl", "a note"), ("proposals.jsonl", "a proposal")):
|
||||
open(os.path.join(self.state, n), "w").write(json.dumps({"text": t}) + "\n")
|
||||
open(os.path.join(self.state, "backups", "ab-CLAUDE.md.orig"), "w").write("original\n")
|
||||
json.dump({"dirs": [], "files": {"/x/CLAUDE.md": {"backup": "ab-CLAUDE.md.orig"}}}, open(os.path.join(self.state, "manifest.json"), "w"))
|
||||
for n in ("harvest.db", "results.jsonl"):
|
||||
open(os.path.join(self.state, n), "w").write("scratch\n")
|
||||
os.makedirs(os.path.join(self.p1, "notes"))
|
||||
open(os.path.join(self.p1, "notes", "fuzz.md"), "w").write("# Field notes for fuzz\n\n- 2026-11-01: a field note (aim: speed; seen 2 times; lesson 2)\n")
|
||||
open(os.path.join(self.p1, "canon", "oracle.md"), "w").write("# oracle\n\nThe person wants things asked once.\n")
|
||||
|
||||
def lessons_of(self, path):
|
||||
con = sqlite3.connect(path)
|
||||
con.row_factory = sqlite3.Row
|
||||
try:
|
||||
return [dict(r) for r in con.execute("SELECT * FROM lessons ORDER BY id")], \
|
||||
[dict(r) for r in con.execute("SELECT * FROM occurrences ORDER BY id")]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def test_migrate_moves_everything_once_without_losing_or_duplicating(self):
|
||||
self.legacy_state()
|
||||
before = self.lessons_of(os.path.join(self.state, "retro.db"))
|
||||
self.assertEqual(len(before[0]), 2)
|
||||
out = self.ok("migrate").stdout
|
||||
self.assertIn("backed up", out)
|
||||
for n in ("retro.db", "trusted.json", "config.json", "learn-quarantine.jsonl", "notes.jsonl", "proposals.jsonl", "manifest.json", "backups"):
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, n)), n + " should have moved")
|
||||
for n in ("harvest.db", "results.jsonl"):
|
||||
self.assertTrue(os.path.exists(os.path.join(self.state, n)), n + " is scratch and stays")
|
||||
self.assertEqual(self.lessons_of(os.path.join(self.data, "retro.db")), before)
|
||||
self.assertIn("The person wants things asked once.", open(os.path.join(self.data, "oracle.md")).read())
|
||||
self.assertIn("a field note", open(os.path.join(self.data, "notes", "fuzz.md")).read())
|
||||
self.assertEqual(json.load(open(os.path.join(self.data, "trusted.json"))), [self.proj])
|
||||
self.assertEqual(json.load(open(os.path.join(self.data, "config.json")))["verify"]["fast_limit_s"], 9)
|
||||
self.assertTrue(os.path.exists(os.path.join(self.data, "install", "backups", "ab-CLAUDE.md.orig")))
|
||||
self.assertIn("/x/CLAUDE.md", json.load(open(os.path.join(self.data, "install", "manifest.json")))["files"])
|
||||
# committed: the learned content is in git history, the database is not
|
||||
files = pdata.git("ls-files").stdout.split()
|
||||
for f in ("oracle.md", "lessons.jsonl", "trusted.json", "config.json", "notes/fuzz.md", "VERSION", "learn-quarantine.jsonl"):
|
||||
self.assertIn(f, files)
|
||||
self.assertNotIn("retro.db", files)
|
||||
self.assertEqual(len(open(os.path.join(self.data, "lessons.jsonl")).read().splitlines()), 2 + len(before[1]))
|
||||
self.assertTrue(self.git_log()[0].startswith("migrate:"))
|
||||
# the backup has what moved, before it moved
|
||||
bk = os.path.join(self.data, "backups")
|
||||
b = os.path.join(bk, os.listdir(bk)[0])
|
||||
self.assertEqual(self.lessons_of(os.path.join(b, "state", "retro.db")), before)
|
||||
self.assertTrue(os.path.exists(os.path.join(b, "state", "trusted.json")))
|
||||
self.assertTrue(os.path.exists(os.path.join(b, "product", "canon", "oracle.md")))
|
||||
# the product is only read: its oracle and notes are still there, for the person to delete
|
||||
self.assertTrue(os.path.exists(os.path.join(self.p1, "canon", "oracle.md")))
|
||||
# a second run does nothing
|
||||
n = len(self.git_log())
|
||||
self.assertIn("nothing to migrate", self.ok("migrate").stdout)
|
||||
self.assertEqual(len(self.git_log()), n)
|
||||
self.assertEqual(self.lessons_of(os.path.join(self.data, "retro.db")), before)
|
||||
self.assertEqual(self.ok("lessons", "--json").stdout.count('"change_kind"'), 2)
|
||||
|
||||
def test_old_layout_keeps_working_before_migration(self):
|
||||
self.legacy_state()
|
||||
self.assertEqual(self.ok("lessons").stdout.count("\n"), 2)
|
||||
self.assertEqual(wiring.quick_problem(), None)
|
||||
from sisi import trust
|
||||
self.assertTrue(trust.is_trusted(self.proj))
|
||||
self.assertEqual(self.ok("tick", stdin="{}").returncode, 0)
|
||||
self.assertIn("Always watch", self.sisi("tick", stdin="{}").stdout)
|
||||
|
||||
def test_migrate_merges_when_both_old_and_new_databases_exist(self):
|
||||
self.legacy_state(extra_lesson=True)
|
||||
# the new location already has one of the same lessons and one of its own
|
||||
with unittest.mock.patch.object(retro, "db_path", return_value=os.path.join(self.data, "retro.db")):
|
||||
os.makedirs(self.data)
|
||||
con = retro.connect()
|
||||
retro.new_lesson(con, dict(self.LESSONS[0]), self.proj, None)
|
||||
retro.new_lesson(con, dict(aim="level", moment="asked about a thing the oracle already answered", cause="did not run oracle",
|
||||
change_kind="rule", change="Run sisi oracle before asking anything", target=None), self.proj, None)
|
||||
con.commit()
|
||||
con.close()
|
||||
self.ok("migrate")
|
||||
rows, _ = self.lessons_of(os.path.join(self.data, "retro.db"))
|
||||
changes = sorted(r["change"] for r in rows)
|
||||
self.assertEqual(len(changes), len(set(changes)), "a lesson was duplicated")
|
||||
self.assertEqual(len(changes), 4)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, "retro.db")))
|
||||
|
||||
def test_copy_of_real_state_style_notes_union(self):
|
||||
self.legacy_state()
|
||||
os.makedirs(os.path.join(self.data, "notes"))
|
||||
open(os.path.join(self.data, "notes", "fuzz.md"), "w").write("# Field notes for fuzz\n\n- newer note\n")
|
||||
self.ok("migrate")
|
||||
t = open(os.path.join(self.data, "notes", "fuzz.md")).read()
|
||||
self.assertIn("newer note", t)
|
||||
self.assertIn("a field note", t)
|
||||
|
||||
|
||||
class InstallMigrationTests(PersonalCase):
|
||||
def snap(self, root):
|
||||
from test_wiring import snapshot
|
||||
return snapshot(root)
|
||||
|
||||
def test_old_wiring_is_migrated_and_uninstall_restores_exactly(self):
|
||||
paths.REPO = REPO # the real product: its core.md is where the old wiring pointed
|
||||
os.environ.pop("SISI_VERIFIERS"), os.environ.pop("SISI_DONE")
|
||||
h = lambda *p: os.path.join(self.home, *p)
|
||||
os.makedirs(h(".claude"))
|
||||
os.makedirs(h(".codex"))
|
||||
os.makedirs(h(".config", "opencode"))
|
||||
open(h(".claude", "CLAUDE.md"), "w").write("# mine\n")
|
||||
open(h(".claude", "settings.json"), "w").write('{\n "x": 1\n}\n')
|
||||
before = self.snap(self.home)
|
||||
self.assertEqual(wiring.install()[0], 0)
|
||||
# now make it look the old way: product core.md everywhere, records in the state dir
|
||||
old = os.path.join(REPO, "canon", "core.md")
|
||||
cm = open(h(".claude", "CLAUDE.md")).read().replace(paths.generated(), old)
|
||||
open(h(".claude", "CLAUDE.md"), "w").write(cm)
|
||||
for p in (h(".codex", "AGENTS.md"), h(".config", "opencode", "AGENTS.md")):
|
||||
os.unlink(p)
|
||||
os.symlink(old, p)
|
||||
shutil.copytree(os.path.join(self.data, "install"), self.state)
|
||||
shutil.rmtree(os.path.join(self.data, "install"))
|
||||
shutil.rmtree(paths.data_file("generated"))
|
||||
self.assertEqual({r["tool"]: r["status"] for r in wiring.doctor()}["codex"], "not wired")
|
||||
rc, notes = wiring.install()
|
||||
self.assertEqual(rc, 0, notes)
|
||||
self.assertIn("@" + paths.generated(), open(h(".claude", "CLAUDE.md")).read())
|
||||
self.assertNotIn(old, open(h(".claude", "CLAUDE.md")).read())
|
||||
for p in (h(".codex", "AGENTS.md"), h(".config", "opencode", "AGENTS.md")):
|
||||
self.assertEqual(os.readlink(p), paths.generated())
|
||||
self.assertTrue(os.path.exists(p))
|
||||
self.assertTrue(os.path.exists(os.path.join(self.data, "install", "manifest.json")))
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, "manifest.json")))
|
||||
self.assertTrue(all(r["status"] in ("wired", "current", "ok") for r in wiring.doctor() if r["tool"] not in ("muse", "skills")))
|
||||
again = (self.snap(self.home), self.snap(self.data) if False else None)
|
||||
self.assertEqual(wiring.install()[0], 0)
|
||||
self.assertEqual(self.snap(self.home), again[0])
|
||||
wiring.uninstall()
|
||||
self.assertEqual(self.snap(self.home), before)
|
||||
|
||||
def test_generated_exists_before_anything_points_at_it(self):
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
seen = []
|
||||
orig = wiring._write
|
||||
def spy(p, data):
|
||||
seen.append(os.path.exists(paths.generated()))
|
||||
return orig(p, data)
|
||||
wiring._write = spy
|
||||
self.addCleanup(setattr, wiring, "_write", orig)
|
||||
open(os.path.join(self.home, ".claude", "CLAUDE.md"), "w").write("x\n")
|
||||
wiring.install()
|
||||
self.assertTrue(seen and all(seen))
|
||||
|
||||
def test_doctor_reports_product_personal_and_rulebook(self):
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
out = self.ok("doctor").stdout
|
||||
self.assertIn(self.p1, out)
|
||||
self.assertIn(self.data, out)
|
||||
self.assertRegex(out, r"rulebook\s+missing")
|
||||
wiring.install()
|
||||
out = self.ok("doctor").stdout
|
||||
self.assertRegex(out, r"rulebook\s+current")
|
||||
self.assertRegex(out, r"personal\s+ok")
|
||||
self.assertRegex(out, r"product\s+ok")
|
||||
|
||||
|
||||
class ExportImportTests(PersonalCase):
|
||||
def test_round_trip_is_lossless_for_committed_content(self):
|
||||
self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."))
|
||||
self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Mine"))
|
||||
self.ok("learn", "never", "ask", "twice")
|
||||
self.ok("retro", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
|
||||
"--cause", "the test was written after the code", "--change-kind", "rule",
|
||||
"--change", "write the failing test first and show it fail with `pytest -k new`")
|
||||
os.makedirs(os.path.join(self.state, "sessions"))
|
||||
open(os.path.join(self.state, "sessions", "s1.json"), "w").write('{"a": 1}')
|
||||
open(os.path.join(self.state, "results.jsonl"), "w").write('{"r": 1}\n')
|
||||
files = lambda: sorted(pdata.git("ls-files").stdout.split())
|
||||
content = lambda fs: {f: open(os.path.join(paths.data(), f), "rb").read() for f in fs}
|
||||
f0, c0, log0, gen0 = files(), content(files()), pdata.git("log", "--format=%H").stdout, self.generated()
|
||||
lessons0 = LessonRows()
|
||||
arc = os.path.join(self.tmp, "out.tar.gz")
|
||||
self.ok("export", arc)
|
||||
with tarfile.open(arc) as tf:
|
||||
names = tf.getnames()
|
||||
self.assertIn("personal/overlay/rules/delta.md", names)
|
||||
self.assertIn("personal/retro.db", names)
|
||||
self.assertIn("state/results.jsonl", names)
|
||||
self.assertIn("state/sessions/s1.json", names)
|
||||
self.assertFalse([n for n in names if "/generated" in n or "/backups" in n or "/install" in n])
|
||||
# a fresh machine
|
||||
new = os.path.join(self.tmp, "data2")
|
||||
shutil.rmtree(self.state)
|
||||
os.environ["SISI_DATA"] = new
|
||||
self.ok("import", arc)
|
||||
self.assertEqual(files(), f0)
|
||||
self.assertEqual(content(files()), c0)
|
||||
self.assertEqual(pdata.git("log", "--format=%H").stdout, log0)
|
||||
self.assertEqual(pdata.git("status", "--porcelain").stdout, "")
|
||||
self.assertEqual(self.generated(), gen0.replace("", ""))
|
||||
self.assertEqual(LessonRows(), lessons0)
|
||||
self.assertEqual(open(os.path.join(self.state, "results.jsonl")).read(), '{"r": 1}\n')
|
||||
self.assertTrue(os.path.exists(os.path.join(self.state, "sessions", "s1.json")))
|
||||
self.assertRegex(self.ok("verifiers", "--section", "safety").stdout, r"shellcheck .*Mine")
|
||||
|
||||
def test_import_sets_existing_data_aside_and_rebuilds_db_from_the_dump(self):
|
||||
self.ok("retro", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
|
||||
"--cause", "the test was written after the code", "--change-kind", "rule",
|
||||
"--change", "write the failing test first and show it fail with `pytest -k new`")
|
||||
arc = os.path.join(self.tmp, "out.tar.gz")
|
||||
self.ok("export", arc)
|
||||
# an archive without the database: the dump recreates it
|
||||
slim = os.path.join(self.tmp, "slim.tar.gz")
|
||||
with tarfile.open(arc) as a, tarfile.open(slim, "w:gz") as b:
|
||||
for m in a.getmembers():
|
||||
if m.name != "personal/retro.db":
|
||||
b.addfile(m, a.extractfile(m) if m.isfile() else None)
|
||||
r = self.ok("import", slim)
|
||||
self.assertIn("set aside", r.stdout)
|
||||
self.assertIn("rebuilt from lessons.jsonl", r.stdout)
|
||||
self.assertTrue(glob_aside(self.data))
|
||||
self.assertEqual(self.ok("lessons").stdout.count("\n"), 1)
|
||||
|
||||
def test_import_rejects_bad_archives(self):
|
||||
bad = os.path.join(self.tmp, "bad.tar.gz")
|
||||
with tarfile.open(bad, "w:gz") as tf:
|
||||
data = b"x"
|
||||
ti = tarfile.TarInfo("personal/../../evil")
|
||||
ti.size = 1
|
||||
tf.addfile(ti, __import__("io").BytesIO(data))
|
||||
self.assertEqual(self.sisi("import", bad).returncode, 1)
|
||||
self.assertEqual(self.sisi("import", os.path.join(self.tmp, "nope.tar.gz")).returncode, 1)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.tmp, "evil")))
|
||||
|
||||
|
||||
def glob_aside(data):
|
||||
import glob
|
||||
return glob.glob(data + ".before-import-*")
|
||||
|
||||
|
||||
def LessonRows():
|
||||
con = retro.connect()
|
||||
try:
|
||||
return retro.dump_lines(con)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
class LessonDumpTests(PersonalCase):
|
||||
RETRO = ["--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed",
|
||||
"--cause", "the test was written after the code", "--change-kind", "rule",
|
||||
"--change", "write the failing test first and show it fail with `pytest -k new`"]
|
||||
|
||||
def test_dump_is_committed_sorted_and_the_database_is_not(self):
|
||||
self.ok("retro", *self.RETRO)
|
||||
self.assertEqual(self.git_log()[0], "lessons: retro recorded for lesson #1")
|
||||
self.assertNotIn("retro.db", pdata.git("ls-files").stdout)
|
||||
lines = open(os.path.join(self.data, "lessons.jsonl")).read().splitlines()
|
||||
self.assertEqual(json.loads(lines[0])["t"], "lesson")
|
||||
self.assertEqual(json.loads(lines[1])["t"], "occurrence")
|
||||
n = len(self.git_log())
|
||||
self.ok("lessons", "set", "1", "--status", "rejected")
|
||||
self.assertEqual(len(self.git_log()), n + 1)
|
||||
self.assertIn("lesson #1 set to rejected", self.git_log()[0])
|
||||
self.assertEqual(json.loads(open(os.path.join(self.data, "lessons.jsonl")).readline())["status"], "rejected")
|
||||
# recoverable from history alone
|
||||
old = pdata.git("show", "HEAD~1:lessons.jsonl").stdout
|
||||
self.assertEqual(json.loads(old.splitlines()[0])["status"], "open")
|
||||
# export is stable
|
||||
a = open(os.path.join(self.data, "lessons.jsonl")).read()
|
||||
self.ok("lessons", "export")
|
||||
self.assertEqual(open(os.path.join(self.data, "lessons.jsonl")).read(), a)
|
||||
self.assertEqual(len(self.git_log()), n + 1)
|
||||
|
||||
def test_learn_and_note_are_personal_and_committed(self):
|
||||
self.ok("learn", "Always", "use", "options")
|
||||
self.assertIn("learn: Always use options", self.git_log()[0])
|
||||
self.assertIn("learn-quarantine.jsonl", pdata.git("ls-files").stdout)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.state, "learn-quarantine.jsonl")))
|
||||
self.assertIn("oracle", self.ok("oracle").stdout.lower())
|
||||
|
||||
|
||||
class IsolationTests(PersonalCase):
|
||||
def test_every_resolved_root_is_inside_the_temp_dir(self):
|
||||
real = os.path.realpath(os.path.expanduser("~"))
|
||||
for name in ("home", "state", "data"):
|
||||
r = os.path.realpath(getattr(paths, name)())
|
||||
self.assertTrue(r.startswith(self.tmp + os.sep), (name, r))
|
||||
for f in (paths.generated(), paths.state_file("x"), paths.data_file("y"), paths.notes_dir(), paths.personal("retro.db")):
|
||||
self.assertTrue(os.path.realpath(f).startswith(self.tmp + os.sep), f)
|
||||
# a child process resolves the same roots from the same environment
|
||||
code = "from sisi import paths; print(paths.home(), paths.state(), paths.data(), sep='\\n')"
|
||||
r = subprocess.run([sys.executable, "-c", code], cwd=REPO, capture_output=True, text=True, stdin=subprocess.DEVNULL, env=dict(os.environ))
|
||||
for line in r.stdout.split("\n")[:3]:
|
||||
self.assertTrue(os.path.realpath(line).startswith(self.tmp + os.sep), line)
|
||||
self.assertFalse(os.path.realpath(line).startswith(real + os.sep + ".local"), line)
|
||||
|
||||
def test_the_guard_catches_a_leak(self):
|
||||
for var in ("SISI_STATE", "SISI_DATA", "SISI_HOME"):
|
||||
with unittest.mock.patch.dict(os.environ, {var: os.path.expanduser("~/.local/state/sisi-leak")}):
|
||||
with self.assertRaises(AssertionError):
|
||||
{"SISI_STATE": paths.state, "SISI_DATA": paths.data, "SISI_HOME": paths.home}[var]()
|
||||
|
||||
def test_hooks_do_not_wait_for_stdin_that_never_ends(self):
|
||||
# an inherited, never-closed stdin once hung `tick` (and the whole suite with it)
|
||||
for cmd in ("tick", "gate"):
|
||||
p = subprocess.Popen([sys.executable, BIN, cmd], cwd=self.proj, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, env=dict(os.environ, SISI_STDIN_WAIT="0.3"))
|
||||
try:
|
||||
self.assertEqual(p.wait(timeout=10), 0, cmd) # stdin stays open: it must still return
|
||||
finally:
|
||||
p.kill()
|
||||
p.stdin.close()
|
||||
|
||||
|
||||
class ProductIsReadOnlyTests(PersonalCase):
|
||||
def test_no_command_writes_inside_the_product(self):
|
||||
prod = os.path.join(self.tmp, "product")
|
||||
shutil.copytree(REPO, prod, ignore=shutil.ignore_patterns(".git", "__pycache__", "tests", ".sisi", ".agent-work"))
|
||||
def unlock():
|
||||
for dp, dns, fns in os.walk(prod):
|
||||
os.chmod(dp, 0o755)
|
||||
for n in fns:
|
||||
os.chmod(os.path.join(dp, n), 0o644)
|
||||
self.addCleanup(unlock)
|
||||
from test_wiring import snapshot
|
||||
before = snapshot(prod)
|
||||
for dp, dns, fns in os.walk(prod, topdown=False):
|
||||
for n in fns:
|
||||
os.chmod(os.path.join(dp, n), 0o555 if n == "sisi" else 0o444)
|
||||
os.chmod(dp, 0o555)
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
os.makedirs(os.path.join(self.home, ".codex"))
|
||||
self.git_init()
|
||||
binp = os.path.join(prod, "bin", "sisi")
|
||||
def run(*a, stdin=None):
|
||||
# output goes to files, not pipes: a detached background worker must not hold this test open
|
||||
with open(os.path.join(self.tmp, "o.txt"), "w+") as out, open(os.path.join(self.tmp, "e.txt"), "w+") as err:
|
||||
p = subprocess.Popen([sys.executable, binp] + list(a), cwd=self.proj, stdin=subprocess.PIPE, stdout=out, stderr=err,
|
||||
text=True, env=dict(os.environ, PYTHONFAULTHANDLER="1"))
|
||||
try:
|
||||
p.communicate(stdin, timeout=int(os.environ.get("RO_T", "30")))
|
||||
except subprocess.TimeoutExpired:
|
||||
tree = subprocess.run(["ps", "-eo", "pid,ppid,stat,etime,args", "--forest"], capture_output=True, text=True).stdout
|
||||
p.send_signal(signal.SIGABRT) # faulthandler prints the Python stack
|
||||
time.sleep(1)
|
||||
p.kill()
|
||||
err.seek(0)
|
||||
self.fail("hung: sisi %s\nstderr:\n%s\nprocess tree:\n%s" % (a, err.read(), tree))
|
||||
out.seek(0), err.seek(0)
|
||||
return subprocess.CompletedProcess(a, p.returncode, out.read(), err.read())
|
||||
gate_in = json.dumps({"session_id": "s1", "cwd": self.proj, "stop_hook_active": False})
|
||||
cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("build-canon",), ("status",),
|
||||
("overlay", "add-rule", "--id", "z", "-"), ("overlay", "diff"), ("overlay", "disable-rule", "z"),
|
||||
("learn", "x"), ("lessons", "export"), ("verifiers", "show", "shellcheck"),
|
||||
("contract", "init", "--goal", "g"), ("verify",), ("migrate",), ("update",),
|
||||
("export", os.path.join(self.tmp, "e.tar.gz")), ("gate",), ("uninstall",)]
|
||||
for c in cmds:
|
||||
r = run(*c, stdin=rule_file("Z", "Zed.") if c[:2] == ("overlay", "add-rule") else (gate_in if c == ("gate",) else None))
|
||||
self.assertNotIn("Permission denied", r.stderr + r.stdout, c)
|
||||
self.assertNotIn("Traceback", r.stderr, (c, r.stderr))
|
||||
r = run("retro", *LessonDumpTests.RETRO)
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertEqual(snapshot(prod), before)
|
||||
self.assertTrue(os.path.exists(os.path.join(self.state, "pycache")), "bytecode goes to the scratch dir")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Checks that keep the published repository honest: the README names only real commands, and no file carries
|
||||
a home path or a personal email address."""
|
||||
import os, re, subprocess, sys, unittest
|
||||
|
||||
from support import REPO, SisiCase
|
||||
|
||||
|
||||
def _tracked_or_untracked_files():
|
||||
"""Every file that would be published: tracked files plus untracked ones that .gitignore does not hide.
|
||||
Falls back to a directory walk when git is unavailable."""
|
||||
try:
|
||||
r = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard"], cwd=REPO,
|
||||
capture_output=True, text=True, timeout=30)
|
||||
if r.returncode == 0 and r.stdout.strip():
|
||||
return [f for f in r.stdout.splitlines() if os.path.isfile(os.path.join(REPO, f))]
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
out = []
|
||||
for dp, dns, fns in os.walk(REPO):
|
||||
dns[:] = [d for d in dns if d not in (".git", "__pycache__")]
|
||||
out += [os.path.relpath(os.path.join(dp, n), REPO) for n in fns if not n.endswith(".pyc")]
|
||||
return out
|
||||
|
||||
|
||||
def _text(rel):
|
||||
try:
|
||||
with open(os.path.join(REPO, rel), "rb") as f:
|
||||
data = f.read()
|
||||
except OSError:
|
||||
return None
|
||||
if b"\0" in data:
|
||||
return None
|
||||
return data.decode("utf-8", "replace")
|
||||
|
||||
|
||||
# Paths under /home/ or /Users/ that are placeholders in tests and examples, not real people.
|
||||
_ALLOWED_HOME_USERS = {"alice", "bob", "user", "you", "name", "username", "example", "me"}
|
||||
HOME_RE = re.compile(r"(?<![\w.])/(?:home|Users)/([A-Za-z0-9_.-]+)")
|
||||
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")
|
||||
|
||||
|
||||
class PublishableTree(unittest.TestCase):
|
||||
def test_no_home_paths(self):
|
||||
bad = []
|
||||
for rel in _tracked_or_untracked_files():
|
||||
text = _text(rel)
|
||||
for m in HOME_RE.finditer(text or ""):
|
||||
if m.group(1).rstrip(".-").lower() not in _ALLOWED_HOME_USERS:
|
||||
bad.append("%s: %s" % (rel, m.group(0)))
|
||||
self.assertEqual(bad, [], "home paths in files that would be published")
|
||||
|
||||
def test_no_email_addresses_except_noreply_and_examples(self):
|
||||
bad = []
|
||||
for rel in _tracked_or_untracked_files():
|
||||
for m in EMAIL_RE.finditer(_text(rel) or ""):
|
||||
addr = m.group(0)
|
||||
local, _, domain = addr.rpartition("@")
|
||||
if "noreply" in addr.lower() or domain.lower() in ("example.com", "example.org", "example.net", "b.co"):
|
||||
continue
|
||||
# decorators and npm scopes such as @scope/pkg.js are not addresses: they have no local part
|
||||
bad.append("%s: %s" % (rel, addr))
|
||||
self.assertEqual(bad, [], "email addresses in files that would be published")
|
||||
|
||||
def test_the_scan_can_fail(self):
|
||||
self.assertTrue(HOME_RE.search("see /home/alice/x"))
|
||||
self.assertIsNone(HOME_RE.search("see /homepage/x"))
|
||||
self.assertTrue(EMAIL_RE.search("write to a.person" + "@corp.example"))
|
||||
|
||||
def test_required_project_files_exist(self):
|
||||
for f in ("LICENSE", "README.md", "CONTRIBUTING.md", "SECURITY.md", "CHANGELOG.md", "VERSION", ".editorconfig",
|
||||
".github/workflows/ci.yml", "docs/README.md", "docs/design.md"):
|
||||
self.assertTrue(os.path.isfile(os.path.join(REPO, f)), f)
|
||||
self.assertFalse(os.path.exists(os.path.join(REPO, "docs", "superpowers")))
|
||||
|
||||
|
||||
NOT_BUILT = {"build", "inbox"} # designed in docs/design.md, named in the README as not built
|
||||
|
||||
|
||||
class ReadmeIsHonest(SisiCase):
|
||||
def test_every_subcommand_in_the_readme_exists(self):
|
||||
text = open(os.path.join(REPO, "README.md"), encoding="utf-8").read()
|
||||
help_text = self.sisi("help").stdout
|
||||
from sisi import learn_cli
|
||||
import argparse
|
||||
ap = argparse.ArgumentParser()
|
||||
sub = ap.add_subparsers()
|
||||
learn_cli.register(sub)
|
||||
hidden = set(sub.choices) # data-layer commands that are real but not listed in `sisi help`
|
||||
named = set(re.findall(r"`sisi ([a-z][a-z-]*)", text)) | set(re.findall(r"^ {4}(?:\$ )?sisi ([a-z][a-z-]*)", text, re.M))
|
||||
self.assertTrue(named, "the README names no sisi commands")
|
||||
for cmd in sorted(named - NOT_BUILT):
|
||||
self.assertTrue(re.search(r"\bsisi [^\n]*\b%s\b" % re.escape(cmd), help_text) or cmd in hidden, cmd)
|
||||
# The README may name commands only to say they are not built. If one gets built, the README must change.
|
||||
for cmd in NOT_BUILT:
|
||||
self.assertEqual(self.sisi(cmd).returncode, 64, cmd + " now exists: update the README status section")
|
||||
|
||||
def test_readme_sub_subcommands_are_in_help(self):
|
||||
text = open(os.path.join(REPO, "README.md"), encoding="utf-8").read()
|
||||
help_text = self.sisi("help").stdout
|
||||
for m in set(re.findall(r"`sisi (contract|verifiers|canon|overlay|dev) ([a-z-]+)", text)):
|
||||
self.assertIn(m[1], help_text, " ".join(m))
|
||||
|
||||
def test_python_version_claim_matches_ci_and_code(self):
|
||||
text = open(os.path.join(REPO, "README.md"), encoding="utf-8").read()
|
||||
ci = open(os.path.join(REPO, ".github", "workflows", "ci.yml"), encoding="utf-8").read()
|
||||
m = re.search(r"Python (3\.\d+) or newer", text)
|
||||
self.assertTrue(m, "README must state the minimum Python version as 'Python 3.x or newer'")
|
||||
self.assertIn('"%s"' % m.group(1), ci)
|
||||
|
||||
def test_every_documented_file_link_exists(self):
|
||||
for doc in ("README.md", "CONTRIBUTING.md", "SECURITY.md", os.path.join("docs", "README.md")):
|
||||
base = os.path.dirname(os.path.join(REPO, doc))
|
||||
for target in re.findall(r"\]\(([^)#\s]+)", open(os.path.join(REPO, doc), encoding="utf-8").read()):
|
||||
if re.match(r"^[a-z]+:", target):
|
||||
continue
|
||||
self.assertTrue(os.path.exists(os.path.join(base, target)), "%s -> %s" % (doc, target))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,345 @@
|
||||
import json, os, shutil, unittest
|
||||
from unittest import mock
|
||||
from support import *
|
||||
from sisi import paths, release, wiring
|
||||
|
||||
|
||||
def make_source(root):
|
||||
"""A small stand-in for the source folder: the real code, a tiny library, and things that are not product."""
|
||||
os.makedirs(root)
|
||||
for d in ("bin", "sisi", "canon"):
|
||||
shutil.copytree(os.path.join(REPO, d), os.path.join(root, d), ignore=shutil.ignore_patterns("__pycache__"))
|
||||
shutil.copy(os.path.join(REPO, "config.default.json"), root)
|
||||
shutil.copy(os.path.join(REPO, "VERSION"), root)
|
||||
for d, f in (("verifiers", "x/v.md"), ("done", "r.md"), ("docs", "a.md"), ("tests", "t.py"), ("notes", "n.md"), (".sisi", "contract.json")):
|
||||
os.makedirs(os.path.join(root, d, os.path.dirname(f)), exist_ok=True)
|
||||
open(os.path.join(root, d, f), "w").write("hello\n")
|
||||
return root
|
||||
|
||||
|
||||
class ReleaseCase(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.src = make_source(os.path.join(self.tmp, "source"))
|
||||
self.lib = paths.lib()
|
||||
p = mock.patch.object(release, "run_checks", return_value=(True, "ok"))
|
||||
self.checks = p.start()
|
||||
self.addCleanup(p.stop)
|
||||
self.rebuild = mock.patch.object(release, "_rebuild_rulebook", return_value=("rebuilt", 0))
|
||||
self.rebuild.start() # a subprocess per release is slow; test_regenerates_rulebook runs the real one
|
||||
self.addCleanup(self.rebuild.stop)
|
||||
|
||||
def rel(self, *a):
|
||||
r = self.sisi("release", self.src, *a)
|
||||
return r
|
||||
|
||||
def current(self):
|
||||
return os.path.realpath(os.path.join(self.lib, "current"))
|
||||
|
||||
|
||||
class TestRelease(ReleaseCase):
|
||||
def test_refuses_when_checks_fail(self):
|
||||
self.checks.return_value = (False, "check x failed")
|
||||
r = self.rel()
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("refused", r.stderr)
|
||||
self.assertIn("check x failed", r.stderr)
|
||||
self.assertFalse(os.path.exists(self.lib))
|
||||
|
||||
def test_real_verify_gates_release(self):
|
||||
mock.patch.stopall()
|
||||
os.makedirs(os.path.join(self.src, ".sisi"), exist_ok=True)
|
||||
c = contract([check("bad", "false")])
|
||||
with open(os.path.join(self.src, ".sisi", "contract.json"), "w") as f:
|
||||
json.dump(c, f)
|
||||
from sisi import trust
|
||||
trust.add(self.src)
|
||||
r = self.sisi("release", self.src)
|
||||
self.assertEqual(r.returncode, 1, r.stdout + r.stderr)
|
||||
c = contract([check("ok", "true")])
|
||||
with open(os.path.join(self.src, ".sisi", "contract.json"), "w") as f:
|
||||
json.dump(c, f)
|
||||
r = self.sisi("release", self.src)
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
|
||||
def test_deep_flag_runs_slow_checks(self):
|
||||
self.rel("--deep")
|
||||
self.checks.assert_called_with(self.src, True)
|
||||
self.rel()
|
||||
self.checks.assert_called_with(self.src, False)
|
||||
|
||||
def test_copy_has_product_files_and_nothing_personal(self):
|
||||
open(os.path.join(self.src, "sisi", "junk.pyc"), "w").write("x")
|
||||
os.makedirs(os.path.join(self.src, "sisi", "__pycache__"))
|
||||
r = self.rel()
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
cur = self.current()
|
||||
for p in ("bin/sisi", "sisi/cli.py", "canon/core.md", "verifiers/x/v.md", "done/r.md", "docs/a.md", "config.default.json", "VERSION"):
|
||||
self.assertTrue(os.path.isfile(os.path.join(cur, p)), p)
|
||||
self.assertEqual(sorted(os.listdir(cur)), sorted(["bin", "sisi", "canon", "verifiers", "done", "docs", "config.default.json", "VERSION"]))
|
||||
for dp, dns, fns in os.walk(cur):
|
||||
self.assertNotIn("__pycache__", dns)
|
||||
self.assertFalse([f for f in fns if f.endswith(".pyc")])
|
||||
self.assertTrue(os.access(os.path.join(cur, "bin", "sisi"), os.X_OK))
|
||||
self.assertIn("first release", r.stdout)
|
||||
|
||||
def test_prints_what_changed(self):
|
||||
self.rel()
|
||||
open(os.path.join(self.src, "docs", "new.md"), "w").write("n")
|
||||
open(os.path.join(self.src, "done", "r.md"), "w").write("changed")
|
||||
r = self.rel()
|
||||
self.assertIn("1 added, 1 changed, 0 removed", r.stdout)
|
||||
self.assertIn("+ docs/new.md", r.stdout)
|
||||
self.assertIn("~ done/r.md", r.stdout)
|
||||
|
||||
def test_regenerates_rulebook(self):
|
||||
self.rebuild.stop()
|
||||
self.rel()
|
||||
self.assertTrue(os.path.isfile(paths.generated()))
|
||||
|
||||
def test_switch_is_atomic_rename(self):
|
||||
self.rel()
|
||||
first = release.current_name()
|
||||
calls = []
|
||||
real = os.replace
|
||||
def spy(a, b):
|
||||
calls.append((a, b, os.path.islink(a)))
|
||||
return real(a, b)
|
||||
with mock.patch.object(os, "replace", spy):
|
||||
release.switch(first)
|
||||
link = os.path.join(self.lib, "current")
|
||||
self.assertTrue(any(b == link and islink for a, b, islink in calls))
|
||||
self.assertEqual(os.readlink(link), os.path.join("releases", first))
|
||||
|
||||
def test_current_is_never_missing_twice_running_during_switch(self):
|
||||
self.rel()
|
||||
names = []
|
||||
for i in range(3):
|
||||
names.append(release.make_release(self.src))
|
||||
import threading
|
||||
stop, bad = threading.Event(), []
|
||||
def watch():
|
||||
while not stop.is_set():
|
||||
# On some filesystems (btrfs, measured) a lookup that races the rename can miss for an
|
||||
# instant, about 1 in 40,000. What must hold: a second look straight away finds a
|
||||
# complete release. A hook that hits the instant fails open, like any hook error.
|
||||
target = os.path.join(self.lib, "current", "bin", "sisi")
|
||||
if not os.path.isfile(target) and not os.path.isfile(target):
|
||||
bad.append("missing")
|
||||
t = threading.Thread(target=watch)
|
||||
t.start()
|
||||
for i in range(300):
|
||||
release.switch(names[i % 3])
|
||||
stop.set()
|
||||
t.join()
|
||||
self.assertEqual(bad, [])
|
||||
|
||||
def test_incomplete_release_is_not_visible(self):
|
||||
with mock.patch.object(shutil, "copytree", side_effect=OSError("disk full")):
|
||||
with self.assertRaises(OSError):
|
||||
release.make_release(self.src)
|
||||
self.assertEqual(release.releases(), [])
|
||||
self.assertEqual(os.listdir(paths.releases_dir()), [])
|
||||
|
||||
def test_prunes_to_three(self):
|
||||
names = []
|
||||
for i in range(5):
|
||||
self.assertEqual(self.rel().returncode, 0)
|
||||
names.append(release.current_name())
|
||||
left = release.releases()
|
||||
self.assertEqual(len(left), 3)
|
||||
self.assertEqual(left, sorted(names)[-3:])
|
||||
self.assertEqual(release.current_name(), names[-1])
|
||||
|
||||
def test_same_second_releases_get_distinct_names(self):
|
||||
a, b = release.make_release(self.src), release.make_release(self.src)
|
||||
self.assertNotEqual(a, b)
|
||||
self.assertEqual(release.releases(), [a, b])
|
||||
|
||||
def test_rollback(self):
|
||||
self.rel()
|
||||
a = release.current_name()
|
||||
self.rel()
|
||||
b = release.current_name()
|
||||
self.assertNotEqual(a, b)
|
||||
r = self.sisi("rollback")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertEqual(release.current_name(), a)
|
||||
r = self.sisi("rollback")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("no earlier release", r.stderr)
|
||||
self.assertEqual(release.current_name(), a)
|
||||
|
||||
def test_lib_override(self):
|
||||
other = os.path.join(self.tmp, "elsewhere")
|
||||
with mock.patch.dict(os.environ, {"SISI_LIB": other}):
|
||||
self.assertEqual(paths.releases_dir(), os.path.join(other, "releases"))
|
||||
self.assertEqual(paths.current_link(), os.path.join(other, "current"))
|
||||
|
||||
def test_stable_copy_runs(self):
|
||||
self.rel()
|
||||
launcher = paths.stable_launcher()
|
||||
import subprocess
|
||||
r = subprocess.run([sys.executable, launcher, "help"], capture_output=True, text=True, env=dict(os.environ))
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertIn("sisi verify", r.stdout)
|
||||
|
||||
|
||||
class TestInstallUsesStable(ReleaseCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
|
||||
def hook_cmd(self):
|
||||
with open(os.path.join(self.home, ".claude", "settings.json")) as f:
|
||||
return json.load(f)["hooks"]["Stop"][0]["hooks"][0]["command"]
|
||||
|
||||
def test_install_without_release_uses_clone(self):
|
||||
self.assertEqual(self.sisi("install").returncode, 0)
|
||||
self.assertEqual(os.readlink(wiring.loc()["bin"]), os.path.join(paths.REPO, "bin", "sisi"))
|
||||
self.assertIn(os.path.join(paths.REPO, "bin", "sisi"), self.hook_cmd())
|
||||
r = self.sisi("doctor")
|
||||
self.assertIn("the clone", r.stdout)
|
||||
self.assertNotIn("not wired", "\n".join(l for l in r.stdout.splitlines() if l.startswith(("cli", "claude"))))
|
||||
|
||||
def test_install_with_release_uses_stable_copy(self):
|
||||
self.rel()
|
||||
stable = os.path.join(self.lib, "current", "bin", "sisi")
|
||||
self.assertEqual(self.sisi("install").returncode, 0)
|
||||
self.assertEqual(os.readlink(wiring.loc()["bin"]), stable)
|
||||
self.assertIn(stable, self.hook_cmd())
|
||||
self.assertNotIn(paths.REPO, self.hook_cmd())
|
||||
r = self.sisi("doctor")
|
||||
self.assertNotIn("not wired", "\n".join(l for l in r.stdout.splitlines() if l.startswith(("cli", "claude"))))
|
||||
self.assertEqual(self.sisi("uninstall").returncode, 0)
|
||||
self.assertFalse(os.path.lexists(wiring.loc()["bin"]))
|
||||
|
||||
def test_release_after_clone_install_asks_for_reinstall_then_rewires(self):
|
||||
self.assertEqual(self.sisi("install").returncode, 0)
|
||||
r = self.rel()
|
||||
self.assertIn("run `sisi install`", r.stdout)
|
||||
self.assertEqual(self.sisi("install").returncode, 0)
|
||||
self.assertEqual(os.readlink(wiring.loc()["bin"]), os.path.join(self.lib, "current", "bin", "sisi"))
|
||||
self.assertEqual(self.hook_cmd().count("sisi"), self.hook_cmd().count("sisi"))
|
||||
r = self.rel()
|
||||
self.assertNotIn("run `sisi install`", r.stdout)
|
||||
|
||||
def test_doctor_reports_live_copy_and_source_ahead(self):
|
||||
self.sisi("dev", "on", self.src)
|
||||
self.rel()
|
||||
r = self.sisi("doctor")
|
||||
self.assertIn("release " + release.current_name(), r.stdout)
|
||||
self.assertIn("in step", r.stdout)
|
||||
open(os.path.join(self.src, "docs", "more.md"), "w").write("x")
|
||||
r = self.sisi("doctor")
|
||||
self.assertIn("ahead (1 file differ)", r.stdout)
|
||||
|
||||
|
||||
class TestDev(ReleaseCase):
|
||||
def test_on_off_status(self):
|
||||
self.assertIn("off", self.sisi("dev", "status").stdout)
|
||||
r = self.sisi("dev", "on", self.src)
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(paths.personal_config()["developer"]["source"], self.src)
|
||||
self.assertEqual(store_cfg()["developer"]["source"], self.src)
|
||||
self.assertIn(self.src, self.sisi("dev", "status").stdout)
|
||||
self.assertEqual(self.sisi("dev", "off").returncode, 0)
|
||||
self.assertNotIn("developer", paths.personal_config())
|
||||
self.assertIn("off", self.sisi("dev", "status").stdout)
|
||||
|
||||
def test_on_rejects_non_source_and_keeps_other_config(self):
|
||||
r = self.sisi("dev", "on", self.proj)
|
||||
self.assertEqual(r.returncode, 1)
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
json.dump({"gate": {"budget_s": 5}, "developer": {"personal_terms": ["zed"]}}, open(os.path.join(self.data, "config.json"), "w"))
|
||||
self.sisi("dev", "on", self.src)
|
||||
self.sisi("dev", "off")
|
||||
cfg = paths.personal_config()
|
||||
self.assertEqual(cfg["gate"], {"budget_s": 5})
|
||||
self.assertEqual(cfg["developer"], {"personal_terms": ["zed"]})
|
||||
|
||||
def test_release_finds_source_from_release_copy(self):
|
||||
self.sisi("dev", "on", self.src)
|
||||
self.assertEqual(self.sisi("release").returncode, 0)
|
||||
with mock.patch.object(paths, "REPO", self.current()): # now running as the stable copy
|
||||
self.assertEqual(release.source(), self.src)
|
||||
self.assertEqual(self.sisi("release").returncode, 0)
|
||||
self.sisi("dev", "off")
|
||||
with self.assertRaises(release.ReleaseError):
|
||||
release.source()
|
||||
|
||||
|
||||
def store_cfg():
|
||||
from sisi import store
|
||||
return store.config()
|
||||
|
||||
|
||||
class TestPromote(ReleaseCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.sisi("dev", "on", self.src)
|
||||
self.assertEqual(self.rel().returncode, 0)
|
||||
# run as the stable copy, so the source is found through developer mode and never the real repository
|
||||
p = mock.patch.object(paths, "REPO", self.current())
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
self.assertEqual(release.source(), self.src)
|
||||
|
||||
def promote(self, *a):
|
||||
with mock.patch.dict(os.environ, {"USER": "alice"}), \
|
||||
mock.patch("os.path.expanduser", lambda p: "/home/alice" if p == "~" else p):
|
||||
return self.sisi("promote", *a)
|
||||
|
||||
def put(self, rel, text):
|
||||
p = os.path.join(self.data, "overlay", rel)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
open(p, "w").write(text)
|
||||
|
||||
def test_dry_run_lists_scrubbed_and_writes_nothing(self):
|
||||
self.put("done/my-recipe.md", "see /home/alice/Code/x and bob@example.com, alice said Acme rules\n")
|
||||
json.dump({"developer": {"source": self.src, "personal_terms": ["Acme"]}}, open(os.path.join(self.data, "config.json"), "w"))
|
||||
r = self.promote("my-recipe")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
for t in ("/home/alice", "bob@example.com", "alice", "Acme", "dry run"):
|
||||
self.assertIn(t, r.stdout)
|
||||
self.assertIn("~/Code/x and <email>, <user> said <personal> rules", r.stdout)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.src, "done", "my-recipe.md")))
|
||||
|
||||
def test_apply_writes_scrubbed_recipe_and_verifier(self):
|
||||
self.put("done/my-recipe.md", "path /home/alice/x\n")
|
||||
self.put("verifiers/sec/my-v.md", "mail a@b.co\n")
|
||||
self.assertEqual(self.promote("my-recipe", "--apply").returncode, 0)
|
||||
self.assertEqual(open(os.path.join(self.src, "done", "my-recipe.md")).read(), "path ~/x\n")
|
||||
self.assertEqual(self.promote("my-v", "--apply").returncode, 0)
|
||||
self.assertEqual(open(os.path.join(self.src, "verifiers", "sec", "my-v.md")).read(), "mail <email>\n")
|
||||
|
||||
def test_refuses_naming_lines_when_terms_remain(self):
|
||||
self.put("done/leaky.md", "fine\nAlice was here\nALICE too\n")
|
||||
r = self.promote("leaky", "--apply")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("refused", r.stderr)
|
||||
self.assertIn("3: ALICE too", r.stderr)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.src, "done", "leaky.md")))
|
||||
|
||||
def test_rule_appended_and_replaced(self):
|
||||
self.put("rules/new-rule.md", "## Be kind\n\nSay thanks at /home/alice.\n")
|
||||
self.assertEqual(self.promote("new-rule", "--apply").returncode, 0)
|
||||
core = open(os.path.join(self.src, "canon", "core.md")).read()
|
||||
self.assertIn("{#new-rule}", core)
|
||||
self.assertIn("Say thanks at ~.", core)
|
||||
self.assertNotIn("alice", core)
|
||||
self.put("rules/new-rule.md", "## Be kinder\n\nAlways.\n")
|
||||
self.assertEqual(self.promote("new-rule", "--apply").returncode, 0)
|
||||
core = open(os.path.join(self.src, "canon", "core.md")).read()
|
||||
self.assertEqual(core.count("{#new-rule}"), 1)
|
||||
self.assertIn("Be kinder", core)
|
||||
self.assertNotIn("Be kind\n", core)
|
||||
|
||||
def test_unknown_id_and_no_commit(self):
|
||||
r = self.promote("nope")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("no overlay", r.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,540 @@
|
||||
import io, json, os, random, shutil, sqlite3, sys, time, unittest
|
||||
from unittest import mock
|
||||
from support import *
|
||||
from sisi import cli, gate, retro, store
|
||||
from test_verifiers import LibCase, vfile, dfile
|
||||
|
||||
GOOD = dict(aim="verified",
|
||||
moment="I ran `cargo test` for 4 minutes before noticing that the fuzz verifier for parser work was never chosen",
|
||||
cause="the parser-or-codec recipe does not list the fuzz verifier under Checks",
|
||||
change_kind="recipe",
|
||||
change="Add the fuzz verifier to the Checks of the parser-or-codec recipe so parser work picks it by default",
|
||||
target="parser-or-codec")
|
||||
|
||||
|
||||
def argv(f):
|
||||
out = []
|
||||
for k, v in f.items():
|
||||
if k == "new":
|
||||
out.append("--new")
|
||||
else:
|
||||
out += ["--" + k.replace("_", "-"), v]
|
||||
return out
|
||||
|
||||
|
||||
class RetroCase(LibCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
os.environ["SISI_RETRO_REQUIRED"] = "1"
|
||||
self.put("prove/fuzz.md", vfile("fuzz"))
|
||||
self.put("parser-or-codec.md", dfile("parser-or-codec"), self.ddir)
|
||||
self.notes = os.path.join(self.data, "notes")
|
||||
|
||||
def retro(self, f=None, env=None, **kw):
|
||||
return self.sisi("retro", *argv(dict(GOOD, **(f or {}), **kw)), env=env)
|
||||
|
||||
def lessons(self):
|
||||
con = retro.connect()
|
||||
try:
|
||||
return [dict(r) for r in con.execute("SELECT * FROM lessons ORDER BY id")]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def occurrences(self):
|
||||
con = retro.connect()
|
||||
try:
|
||||
return con.execute("SELECT count(*) FROM occurrences").fetchone()[0]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
class RefusalTests(RetroCase):
|
||||
def test_good_answer_accepted(self):
|
||||
r = self.retro()
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
l = self.lessons()
|
||||
self.assertEqual((len(l), l[0]["count"], l[0]["status"], l[0]["aim"]), (1, 1, "open", "verified"))
|
||||
self.assertEqual(self.occurrences(), 1)
|
||||
|
||||
def test_each_refusal(self):
|
||||
bad = {
|
||||
"missing aim": {"aim": ""}, "missing moment": {"moment": ""}, "missing cause": {"cause": " "},
|
||||
"missing change": {"change": ""}, "bad aim": {"aim": "vibes"}, "bad kind": {"change_kind": "magic"},
|
||||
"nothing moment": {"moment": "Nothing, it went well and nothing could be better"},
|
||||
"nothing change": {"change": "None"}, "na cause": {"cause": "n/a"},
|
||||
"nothing could be better": {"cause": "honestly nothing could be better here at all"},
|
||||
"short moment": {"moment": "it was slow"}, "short change": {"change": "fix the rule"},
|
||||
"short cause": {"cause": "bad"},
|
||||
"generic change": {"change": "be more careful and double-check everything next time around"},
|
||||
"no concrete moment": {"moment": "it took longer than it needed to because things were slower than I expected"},
|
||||
"same text": {"moment": GOOD["change"], "change": GOOD["change"]},
|
||||
}
|
||||
for name, over in bad.items():
|
||||
with self.subTest(name):
|
||||
r = self.retro(over)
|
||||
self.assertEqual(r.returncode, 2, r.stdout)
|
||||
self.assertIn("refused", r.stdout)
|
||||
self.assertEqual(self.lessons(), [])
|
||||
self.assertEqual(self.occurrences(), 0)
|
||||
|
||||
def test_missing_message_names_the_field(self):
|
||||
r = self.sisi("retro", "--aim", "speed")
|
||||
self.assertEqual(r.returncode, 2)
|
||||
for w in ("moment", "cause", "change-kind", "change"):
|
||||
self.assertIn(w, r.stdout)
|
||||
|
||||
def test_json_on_stdin(self):
|
||||
r = self.sisi("retro", "--json", "-", stdin=json.dumps({k.replace("_", "-"): v for k, v in GOOD.items()}))
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertEqual(len(self.lessons()), 1)
|
||||
self.assertEqual(self.sisi("retro", "--json", "-", stdin="not json").returncode, 2)
|
||||
self.assertEqual(self.sisi("retro", "--json", "-", stdin=json.dumps({"aim": "speed"})).returncode, 2)
|
||||
|
||||
def test_property_refused_answers_are_never_stored(self):
|
||||
generic = ["nothing", "n/a", "none", "it went well", "be more careful", "short", "", " ", "test more next time",
|
||||
"nothing could have been better", "I will try harder"]
|
||||
for seed in [0, 1, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]:
|
||||
rng = random.Random(seed)
|
||||
for _ in range(8 * ITERS):
|
||||
f = dict(GOOD)
|
||||
for k in rng.sample(["aim", "moment", "cause", "change_kind", "change"], rng.randint(1, 3)):
|
||||
f[k] = rng.choice(generic)
|
||||
with self.subTest(seed=seed, f=f):
|
||||
argv_ = []
|
||||
for k, v in f.items():
|
||||
argv_ += ["--" + k.replace("_", "-"), v]
|
||||
self.assertEqual(retro.validate({k: v for k, v in f.items()}) != [], True)
|
||||
r = self.sisi("retro", *argv_)
|
||||
self.assertEqual(r.returncode, 2, r.stdout)
|
||||
self.assertEqual(self.lessons(), [])
|
||||
self.assertEqual(self.occurrences(), 0)
|
||||
|
||||
|
||||
class SimilarityAndSameAsTests(RetroCase):
|
||||
def test_similar_lessons_listed_exit_4_then_new_or_same_as(self):
|
||||
self.retro()
|
||||
near = dict(moment="I again ran `cargo test` for 6 minutes before noticing that the fuzz verifier for parser work was never chosen",
|
||||
change="Add the fuzz verifier to the parser-or-codec recipe Checks so parser work picks it")
|
||||
r = self.retro(near)
|
||||
self.assertEqual(r.returncode, 4)
|
||||
self.assertIn("#1", r.stdout)
|
||||
self.assertIn("seen 1", r.stdout)
|
||||
self.assertIn("--same-as", r.stdout)
|
||||
self.assertEqual(len(self.lessons()), 1) # nothing stored
|
||||
self.assertEqual(self.retro(near, new=True).returncode, 0)
|
||||
self.assertEqual(len(self.lessons()), 2)
|
||||
|
||||
def test_dissimilar_lesson_accepted_directly(self):
|
||||
self.retro()
|
||||
other = dict(aim="speed", change_kind="tool", target="",
|
||||
moment="the screenshot comparison in `web-ui` waited 90 seconds on a dev server that never started",
|
||||
cause="no readiness probe before the browser step",
|
||||
change="Make sisi verify wait for the declared port instead of sleeping a fixed time")
|
||||
other.pop("target")
|
||||
self.assertEqual(self.sisi("retro", *argv(other)).returncode, 0)
|
||||
self.assertEqual(len(self.lessons()), 2)
|
||||
|
||||
def test_same_as_adds_one_occurrence_to_exactly_one_lesson(self):
|
||||
self.retro()
|
||||
for i in range(3):
|
||||
self.retro(aim="speed", change_kind="tool", moment="distinct %d: `make build` took 9 minutes in lib%d/src" % (i, i),
|
||||
cause="a cold cache every time on this machine", change="Cache the build artefacts between %d runs in the gate config" % (1000 + i * 7919),
|
||||
target="", new=True) if False else None
|
||||
self.assertEqual(len(self.lessons()), 1)
|
||||
r = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` ran for 5 minutes with no fuzz verifier chosen")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertIn("seen 2", r.stdout)
|
||||
l = self.lessons()
|
||||
self.assertEqual((len(l), l[0]["count"]), (1, 2))
|
||||
self.assertEqual(self.occurrences(), 2)
|
||||
|
||||
def test_same_as_needs_a_real_moment_and_an_existing_id(self):
|
||||
self.retro()
|
||||
self.assertEqual(self.sisi("retro", "--same-as", "1", "--moment", "nothing").returncode, 2)
|
||||
self.assertEqual(self.sisi("retro", "--same-as", "1").returncode, 2)
|
||||
self.assertEqual(self.sisi("retro", "--same-as", "99", "--moment", "again `cargo test` ran for 5 minutes, no fuzz").returncode, 2)
|
||||
self.assertEqual(self.lessons()[0]["count"], 1)
|
||||
|
||||
def test_property_same_as_increments_exactly_one(self):
|
||||
ids = []
|
||||
for i in range(4):
|
||||
r = self.retro(aim=["speed", "level", "intent", "hands-off"][i], change_kind="tool", target=None,
|
||||
moment="unique%dx: `cmd%d --flag` hung for %d minutes at step number %d" % (i, i, 7 + i, i),
|
||||
cause="reason %d: widget%d misconfigured" % (i, i),
|
||||
change="Teach tool%d to %s%d automatically" % (i, ["zip", "yank", "frob", "quux"][i], i)) if False else None
|
||||
con = retro.connect()
|
||||
lid = retro.new_lesson(con, dict(GOOD, aim="speed", change_kind="tool", target=None,
|
||||
moment="m%d: command%d failed %d times" % (i, i, i),
|
||||
cause="cause%d" % i, change="change%d" % i), self.proj, None)
|
||||
con.commit()
|
||||
con.close()
|
||||
ids.append(lid)
|
||||
counts = {i: 1 for i in ids}
|
||||
for seed in [0, 1, random.randrange(2 ** 32)]:
|
||||
rng = random.Random(seed)
|
||||
for _ in range(5 * ITERS):
|
||||
lid = rng.choice(ids)
|
||||
r = self.sisi("retro", "--same-as", str(lid), "--moment", "again `cmd%d` failed in run number %d of the gate suite" % (lid, rng.randrange(1000)))
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
counts[lid] += 1
|
||||
self.assertEqual({l["id"]: l["count"] for l in self.lessons()}, counts)
|
||||
con = retro.connect()
|
||||
self.assertEqual(con.execute("SELECT count(*) FROM occurrences").fetchone()[0], sum(counts.values()))
|
||||
con.close()
|
||||
|
||||
|
||||
class AutoApplyAndLessonsTests(RetroCase):
|
||||
def occ(self, sid, lid=None):
|
||||
env = {"SISI_SESSION_ID": sid}
|
||||
if lid is None:
|
||||
return self.retro(env=env)
|
||||
return self.sisi("retro", "--same-as", str(lid), "--moment", "again `cargo test` ran 5 min, no fuzz verifier chosen (%s)" % sid, env=env)
|
||||
|
||||
def test_second_occurrence_from_second_session_applies_to_notes(self):
|
||||
self.assertEqual(self.occ("s1").returncode, 0)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.notes, "parser-or-codec.md")))
|
||||
r = self.occ("s1", 1) # same session again: not enough
|
||||
self.assertNotIn("applied", r.stdout)
|
||||
self.assertEqual(self.lessons()[0]["status"], "open")
|
||||
r = self.occ("s2", 1)
|
||||
self.assertIn("applied", r.stdout)
|
||||
text = open(os.path.join(self.notes, "parser-or-codec.md")).read()
|
||||
self.assertIn("Add the fuzz verifier", text)
|
||||
self.assertEqual(self.lessons()[0]["status"], "applied")
|
||||
# the entry itself is untouched, and show/done print the notes under a heading
|
||||
self.assertNotIn("Field notes", open(os.path.join(self.ddir, "parser-or-codec.md")).read())
|
||||
out = self.sisi("done", "parser-or-codec").stdout
|
||||
self.assertIn("Field notes from earlier agents", out)
|
||||
self.assertIn("Add the fuzz verifier", out)
|
||||
|
||||
def test_verifier_notes_in_show_and_other_kinds_never_auto_apply(self):
|
||||
f = dict(GOOD, change_kind="verifier", target="fuzz")
|
||||
self.sisi("retro", *argv(f), env={"SISI_SESSION_ID": "a"})
|
||||
self.sisi("retro", "--same-as", "1", "--moment", "again `fuzz` was skipped in run 2", env={"SISI_SESSION_ID": "b"})
|
||||
self.assertIn("Field notes from earlier agents", self.sisi("verifiers", "show", "fuzz").stdout)
|
||||
for kind in ("rule", "oracle", "tool", "brief"):
|
||||
with self.subTest(kind):
|
||||
con = retro.connect()
|
||||
lid = retro.new_lesson(con, dict(GOOD, change_kind=kind, target="fuzz", moment="m %s" % kind, cause="c", change="x %s" % kind), self.proj, None)
|
||||
for s in ("p", "q", "r"):
|
||||
os.environ["SISI_SESSION_ID"] = s
|
||||
retro.add_occurrence(con, lid, "again", self.proj, None)
|
||||
self.assertFalse(retro.maybe_auto_apply(con, lid))
|
||||
os.environ.pop("SISI_SESSION_ID")
|
||||
con.commit()
|
||||
self.assertEqual(con.execute("SELECT status FROM lessons WHERE id=?", (lid,)).fetchone()[0], "open")
|
||||
con.close()
|
||||
self.assertFalse(os.path.exists(os.path.join(self.notes, "x rule.md")))
|
||||
|
||||
def test_invalid_target_is_never_applied_and_manual_apply_rules(self):
|
||||
con = retro.connect()
|
||||
a = retro.new_lesson(con, dict(GOOD, target="no-such-recipe"), self.proj, None)
|
||||
b = retro.new_lesson(con, dict(GOOD, change_kind="rule", target=None, moment="m rule", change="rule change text"), self.proj, None)
|
||||
c = retro.new_lesson(con, dict(GOOD, moment="m ok `x` 1", change="ok change for the recipe notes"), self.proj, None)
|
||||
con.commit(); con.close()
|
||||
self.assertEqual(self.sisi("lessons", "apply", str(a)).returncode, 1)
|
||||
self.assertEqual(self.sisi("lessons", "apply", str(b)).returncode, 1)
|
||||
self.assertEqual(self.sisi("lessons", "apply", str(c)).returncode, 0)
|
||||
self.assertEqual(self.sisi("lessons", "apply", str(c)).stdout.strip(), "already applied")
|
||||
self.assertEqual(open(os.path.join(self.notes, "parser-or-codec.md")).read().count("ok change"), 1)
|
||||
|
||||
def test_lessons_listing_filters_order_show_set(self):
|
||||
con = retro.connect()
|
||||
mk = lambda n, **k: retro.new_lesson(con, dict(GOOD, moment="m%d `x`" % n, cause="c", change="change number %d" % n, **k), self.proj, None)
|
||||
l1 = mk(1, target=None, aim="speed", change_kind="tool") if False else None
|
||||
ids = []
|
||||
for n, (aim, kind) in enumerate([("speed", "tool"), ("intent", "rule"), ("speed", "rule")]):
|
||||
g = dict(GOOD, aim=aim, change_kind=kind, target=None, moment="m%d `x`" % n, cause="c", change="change number %d" % n)
|
||||
ids.append(retro.new_lesson(con, g, self.proj, None))
|
||||
retro.add_occurrence(con, ids[1], "again", self.proj, None)
|
||||
retro.add_occurrence(con, ids[1], "again", self.proj, None)
|
||||
con.commit(); con.close()
|
||||
out = self.sisi("lessons").stdout.splitlines()
|
||||
self.assertTrue(out[0].startswith("#%-4d" % ids[1])) # highest count first
|
||||
self.assertEqual(len(self.sisi("lessons", "--aim", "speed").stdout.splitlines()), 2)
|
||||
self.assertEqual(len(self.sisi("lessons", "--kind", "rule", "--top", "1").stdout.splitlines()), 1)
|
||||
self.assertEqual(len(json.loads(self.sisi("lessons", "--json").stdout)), 3)
|
||||
self.assertEqual(len(self.sisi("lessons", "--repo", self.proj).stdout.splitlines()), 3)
|
||||
self.assertEqual(self.sisi("lessons", "--repo", self.tmp + "/elsewhere").stdout.strip(), "no lessons")
|
||||
self.assertIn("occurrences:", self.sisi("lessons", "show", str(ids[1])).stdout)
|
||||
self.assertEqual(self.sisi("lessons", "set", str(ids[0]), "--status", "rejected").returncode, 0)
|
||||
self.assertEqual(self.sisi("lessons", "set", str(ids[0]), "--status", "bogus").returncode, 2)
|
||||
self.assertEqual(len(self.sisi("lessons", "--status", "open").stdout.splitlines()), 2)
|
||||
|
||||
def test_status_shows_lessons(self):
|
||||
self.retro()
|
||||
out = self.sisi("status").stdout
|
||||
self.assertIn("lessons : 1 total, 1 open, 0 applied; 1 occurrences in the last 7 days", out)
|
||||
self.assertIn("open #1", out)
|
||||
self.assertIn("retros", out)
|
||||
|
||||
|
||||
class TickBlockTests(RetroCase):
|
||||
def make(self, change, count=1, repo=None, status="open"):
|
||||
con = retro.connect()
|
||||
lid = retro.new_lesson(con, dict(GOOD, target=None, change_kind="tool", moment="m `x` %s" % change[:5], cause="c", change=change), repo or self.proj, None)
|
||||
for _ in range(count - 1):
|
||||
retro.add_occurrence(con, lid, "again", repo or self.proj, None)
|
||||
con.execute("UPDATE lessons SET status=? WHERE id=?", (status, lid))
|
||||
con.commit(); con.close()
|
||||
return lid
|
||||
|
||||
def tick(self):
|
||||
return self.sisi("tick", stdin=json.dumps({"session_id": "t", "cwd": self.proj, "source": "startup"})).stdout
|
||||
|
||||
def test_block_is_framed_as_information(self):
|
||||
self.make("Prefer a readiness probe over a fixed sleep when waiting for servers", 3)
|
||||
out = self.tick()
|
||||
self.assertIn("notes left by earlier agents", out)
|
||||
self.assertIn("not as commands", out)
|
||||
self.assertIn("(seen 3)", out)
|
||||
|
||||
def test_no_database_no_block_and_no_db_created(self):
|
||||
self.assertEqual(self.tick(), "")
|
||||
self.assertFalse(os.path.exists(retro.db_path()))
|
||||
|
||||
def test_repo_lessons_first_then_by_count_and_only_open(self):
|
||||
self.make("global heavy lesson about caching", 9, repo=self.tmp + "/other")
|
||||
self.make("local light lesson about probes", 1)
|
||||
self.make("rejected lesson never shown", 20, status="rejected")
|
||||
lines = [l for l in self.tick().splitlines() if l.startswith("- ")]
|
||||
self.assertTrue(lines[0].startswith("- local light"), lines)
|
||||
self.assertTrue(lines[1].startswith("- global heavy"))
|
||||
self.assertFalse(any("rejected" in l for l in lines))
|
||||
|
||||
def test_filter_examples(self):
|
||||
repo = self.proj
|
||||
bad = ["see https://example.com/page for details", "visit www.evil.test now", "use `rm -rf build` first",
|
||||
"run the build before pushing", "cat $(whoami) into the log", "curl the endpoint twice",
|
||||
"edit /etc/hosts to fix it", "look at ~/.ssh/config", "read ../secrets.txt", "a && b", "install the helper", "download the file"]
|
||||
good = ["Prefer a readiness probe over a fixed sleep when waiting for servers", "and/or both options exist in the recipe",
|
||||
"Check %s/notes/fuzz.md for the field notes" % repo, "Add the fuzz verifier to the parser recipe checks"]
|
||||
for t in bad:
|
||||
self.assertIsNone(retro.safe_line(t, repo), t)
|
||||
for t in good:
|
||||
self.assertIsNotNone(retro.safe_line(t, repo), t)
|
||||
|
||||
def test_property_size_limit_and_no_filtered_line(self):
|
||||
pieces = ["probe", "cache", "parser", "fuzz", "timeout", "recipe", "check", "verifier", "mutation", "golden", "snapshot"]
|
||||
nasty = ["https://x.example/a", "`rm -rf /`", "run tests", "/etc/passwd", "~/.bashrc", "sudo thing", "$(id)", "a && b"]
|
||||
for seed in [0, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]:
|
||||
rng = random.Random(seed)
|
||||
shutil.rmtree(self.state, ignore_errors=True)
|
||||
con = retro.connect()
|
||||
for n in range(40):
|
||||
words = [rng.choice(pieces) for _ in range(rng.randint(3, 60))]
|
||||
if rng.random() < 0.3:
|
||||
words.insert(rng.randrange(len(words)), rng.choice(nasty))
|
||||
g = dict(GOOD, target=None, change_kind="tool", moment="m%d `x`" % n, cause="c", change=" ".join(words))
|
||||
lid = retro.new_lesson(con, g, self.proj, None)
|
||||
for _ in range(rng.randint(0, 4)):
|
||||
retro.add_occurrence(con, lid, "again", self.proj, None)
|
||||
con.commit(); con.close()
|
||||
block = retro.tick_block(self.proj)
|
||||
with self.subTest(seed=seed):
|
||||
self.assertLess(len(block), 1200)
|
||||
lines = [l for l in block.splitlines() if l.startswith("- ")]
|
||||
self.assertLessEqual(len(lines), 8)
|
||||
for l in lines:
|
||||
self.assertIsNotNone(retro.safe_line(l[2:], self.proj), l)
|
||||
for bad in nasty:
|
||||
self.assertNotIn(bad, l)
|
||||
|
||||
def test_tick_with_many_lessons_stays_fast(self):
|
||||
con = retro.connect()
|
||||
for i in range(150):
|
||||
lid = retro.new_lesson(con, dict(GOOD, target=None, change_kind="tool", moment="m `x` %d" % i, cause="c",
|
||||
change="lesson number %d about caching and probes" % i), self.proj, None)
|
||||
for _ in range(i % 3):
|
||||
retro.add_occurrence(con, lid, "again", self.proj, None)
|
||||
con.commit(); con.close()
|
||||
self.tick()
|
||||
best = 9
|
||||
for _ in range(5):
|
||||
t = time.perf_counter()
|
||||
self.tick()
|
||||
best = min(best, time.perf_counter() - t)
|
||||
__import__('support').skip_timing_if_busy(self)
|
||||
self.assertLess(best, 0.2)
|
||||
|
||||
def test_env_file_export_when_claude_provides_one(self):
|
||||
envf = os.path.join(self.tmp, "envfile")
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": "abc 1", "cwd": self.proj, "source": "startup"}), env={"CLAUDE_ENV_FILE": envf})
|
||||
self.assertIn("export SISI_SESSION_ID='abc 1'", open(envf).read())
|
||||
|
||||
|
||||
class GateRetroTests(RetroCase):
|
||||
sid = "gr"
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.git_init()
|
||||
self.write_contract(contract([check("ok", "true")]))
|
||||
self.tick()
|
||||
|
||||
def tick(self):
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "source": "startup"}))
|
||||
|
||||
def gate(self, sid=None):
|
||||
return gate.decide({"session_id": sid or self.sid, "cwd": self.proj})
|
||||
|
||||
def work(self, text="x"):
|
||||
with open(os.path.join(self.proj, "work.txt"), "a") as f:
|
||||
f.write(text + "\n")
|
||||
|
||||
def do_retro(self, n=0):
|
||||
r = self.sisi("retro", *argv(dict(GOOD, moment="`cargo test` run %d took 4 minutes before the fuzz verifier showed up" % n,
|
||||
change="Add the fuzz verifier to the parser-or-codec recipe Checks, variant %d" % n, new=True)))
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
|
||||
def test_question_only_turn_is_never_asked(self):
|
||||
self.assertEqual(self.gate(), ("allow", None))
|
||||
self.assertEqual(self.gate(), ("allow", None))
|
||||
|
||||
def test_real_work_needs_a_retro_for_this_tree_state(self):
|
||||
self.work()
|
||||
a, msg = self.gate()
|
||||
self.assertEqual(a, "block")
|
||||
self.assertIn("sisi retro --aim", msg)
|
||||
self.assertIn("--change-kind", msg)
|
||||
self.assertIn("how, not whether", msg)
|
||||
self.do_retro()
|
||||
self.assertEqual(self.gate()[0], "allow")
|
||||
self.assertEqual(self.gate()[0], "allow") # unchanged since: not asked again
|
||||
self.work("more") # the tree changed after the retro
|
||||
self.assertEqual(self.gate()[0], "block")
|
||||
|
||||
def test_same_as_also_satisfies(self):
|
||||
self.do_retro()
|
||||
self.work()
|
||||
self.assertEqual(self.gate()[0], "block")
|
||||
self.assertEqual(self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` ran 5 min with no fuzz verifier").returncode, 0)
|
||||
self.assertEqual(self.gate()[0], "allow")
|
||||
|
||||
def test_three_strike_release_and_switch(self):
|
||||
self.work()
|
||||
self.assertEqual([self.gate()[0] for _ in range(3)], ["block"] * 3)
|
||||
a, msg = self.gate()
|
||||
self.assertEqual(a, "allow")
|
||||
self.assertIn("retrospective", msg)
|
||||
self.assertNotIn("unverified", [r["status"] for r in self.results()]) # a missing retro is not an unverified result
|
||||
os.environ["SISI_RETRO_REQUIRED"] = "0"
|
||||
self.work("again")
|
||||
self.assertEqual(self.gate("other")[0], "allow")
|
||||
|
||||
def test_waiver_counts_as_real_work(self):
|
||||
shutil.rmtree(os.path.join(self.proj, ".sisi"))
|
||||
self.tick()
|
||||
self.work()
|
||||
self.assertEqual(self.gate()[0], "allow") # small change, no waiver: not real work
|
||||
self.sisi("contract", "waive", "typo")
|
||||
self.work("typo fix")
|
||||
self.assertEqual(self.gate()[0], "block")
|
||||
self.do_retro()
|
||||
self.assertEqual(self.gate()[0], "allow")
|
||||
|
||||
def test_hook_output_is_a_block_for_claude(self):
|
||||
self.work()
|
||||
r = self.sisi("gate", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj}))
|
||||
d = json.loads(r.stdout)
|
||||
self.assertEqual(d["decision"], "block")
|
||||
self.assertIn("sisi retro", d["reason"])
|
||||
|
||||
def test_property_no_pass_after_real_work_without_a_retro(self):
|
||||
for seed in [0, 1, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]:
|
||||
rng = random.Random(seed)
|
||||
for n in range(4 * ITERS):
|
||||
sid = "pr-%d-%d" % (seed, n)
|
||||
self.tick_for(sid)
|
||||
did_work = rng.random() < 0.7
|
||||
recorded = rng.random() < 0.5
|
||||
if did_work:
|
||||
self.work("%d-%d" % (seed, n))
|
||||
if did_work and recorded:
|
||||
self.do_retro(seed % 1000 * 100 + n)
|
||||
with self.subTest(seed=seed, n=n, work=did_work, retro=recorded):
|
||||
if not did_work:
|
||||
self.assertEqual(self.gate(sid)[0], "allow") # nothing changed: never asked
|
||||
elif recorded:
|
||||
self.assertEqual(self.gate(sid)[0], "allow")
|
||||
else:
|
||||
self.assertEqual([self.gate(sid)[0] for _ in range(3)], ["block"] * 3) # never passes early
|
||||
self.assertEqual(self.gate(sid)[0], "allow") # only the 3-strike release
|
||||
|
||||
def tick_for(self, sid):
|
||||
self.sisi("tick", stdin=json.dumps({"session_id": sid, "cwd": self.proj, "source": "startup"}))
|
||||
|
||||
|
||||
class SubagentTests(RetroCase):
|
||||
def transcript(self, edits=True, start="2020-01-01T00:00:00.000Z", name="agent-a1.jsonl"):
|
||||
p = os.path.join(self.tmp, name)
|
||||
rows = [{"timestamp": start, "message": {"role": "user", "content": "do it"}}]
|
||||
content = [{"type": "tool_use", "name": "Edit" if edits else "Read", "input": {}}]
|
||||
rows.append({"timestamp": start, "message": {"role": "assistant", "content": content}})
|
||||
with open(p, "w") as f:
|
||||
f.write("\n".join(json.dumps(r) for r in rows) + "\n")
|
||||
return p
|
||||
|
||||
def hook(self, **kw):
|
||||
payload = dict({"session_id": "s", "cwd": self.proj, "hook_event_name": "SubagentStop", "agent_id": "a1",
|
||||
"agent_type": "general-purpose", "stop_hook_active": False}, **kw)
|
||||
return self.sisi("gate", "--subagent", stdin=json.dumps(payload))
|
||||
|
||||
def test_subagent_that_edited_files_must_retro(self):
|
||||
r = self.hook(agent_transcript_path=self.transcript())
|
||||
d = json.loads(r.stdout)
|
||||
self.assertEqual(d["decision"], "block")
|
||||
self.assertIn("sisi retro", d["reason"])
|
||||
self.assertEqual(self.retro().returncode, 0)
|
||||
self.assertEqual(self.hook(agent_transcript_path=self.transcript()).stdout, "")
|
||||
|
||||
def test_retro_older_than_the_subagent_does_not_count(self):
|
||||
self.retro()
|
||||
r = self.hook(agent_transcript_path=self.transcript(start="2999-01-01T00:00:00.000Z"))
|
||||
self.assertEqual(json.loads(r.stdout)["decision"], "block")
|
||||
|
||||
def test_read_only_or_undeterminable_subagents_are_never_blocked(self):
|
||||
self.assertEqual(self.hook(agent_transcript_path=self.transcript(edits=False)).stdout, "")
|
||||
self.assertEqual(self.hook().stdout, "") # no transcript path in the input
|
||||
self.assertEqual(self.hook(agent_transcript_path=self.tmp + "/missing.jsonl").stdout, "") # fail open
|
||||
p = os.path.join(self.tmp, "garbage.jsonl")
|
||||
open(p, "w").write("not json\n{{{")
|
||||
self.assertEqual(self.hook(agent_transcript_path=p).stdout, "")
|
||||
|
||||
def test_three_strikes_per_agent_and_switch_and_no_contract_checks(self):
|
||||
self.write_contract(contract([check("bad", "false")])) # the contract is irrelevant for subagents
|
||||
t = self.transcript()
|
||||
acts = [self.hook(agent_transcript_path=t).stdout != "" for _ in range(4)]
|
||||
self.assertEqual(acts, [True, True, True, False])
|
||||
self.assertTrue(self.hook(agent_transcript_path=t, agent_id="other").stdout != "") # separate counter
|
||||
os.environ["SISI_RETRO_REQUIRED"] = "0"
|
||||
self.assertEqual(self.hook(agent_transcript_path=t, agent_id="third").stdout, "")
|
||||
|
||||
|
||||
class CliHookTests(SisiCase):
|
||||
def test_learn_cli_commands_are_reachable(self):
|
||||
r = self.sisi("scoreboard", "--json")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertIn("harvest", self.sisi("harvest", "--help").stdout)
|
||||
self.assertEqual(self.sisi("nonsense").returncode, 64)
|
||||
|
||||
def test_broken_or_absent_learn_cli_does_not_break_the_cli(self):
|
||||
broken = mock.MagicMock()
|
||||
broken.register.side_effect = TypeError("boom")
|
||||
import sisi
|
||||
with mock.patch.dict(sys.modules, {"sisi.learn_cli": broken}), mock.patch.object(sisi, "learn_cli", broken, create=True):
|
||||
self.assertEqual(cli._learn_cli("harvest", []), 70)
|
||||
with mock.patch.dict(sys.modules, {"sisi.learn_cli": None}), mock.patch.object(sisi, "learn_cli", None, create=True):
|
||||
self.assertEqual(cli._learn_cli("harvest", []), 70) # import of the module fails
|
||||
self.assertEqual(self.sisi("help").returncode, 0)
|
||||
|
||||
def test_help_points_to_retro_and_note_propose_still_work(self):
|
||||
out = self.sisi("help").stdout
|
||||
self.assertIn("sisi retro", out)
|
||||
self.assertIn("prefer retro", out)
|
||||
self.assertEqual(self.sisi("note", "still works").returncode, 0)
|
||||
self.assertEqual(self.sisi("propose", "still works").returncode, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,157 @@
|
||||
import json, os, shutil, time, unittest
|
||||
from support import *
|
||||
from sisi import store
|
||||
|
||||
|
||||
class TickTests(SisiCase):
|
||||
def payload(self, **kw):
|
||||
return json.dumps(dict({"session_id": "s1", "cwd": self.proj, "hook_event_name": "SessionStart",
|
||||
"source": "startup"}, **kw))
|
||||
|
||||
def test_records_session_baseline(self):
|
||||
self.git_init()
|
||||
with open(os.path.join(self.proj, "pre.txt"), "w") as f:
|
||||
f.write("a\nb\n")
|
||||
r = self.sisi("tick", stdin=self.payload())
|
||||
self.assertEqual(r.returncode, 0)
|
||||
with open(os.path.join(self.state, "sessions", "s1.json")) as f:
|
||||
s = json.load(f)
|
||||
self.assertEqual(s["cwd"], self.proj)
|
||||
self.assertEqual(len(s["head"]), 40)
|
||||
self.assertEqual(s["baseline"]["files"], ["pre.txt"])
|
||||
self.assertGreaterEqual(s["baseline"]["lines"], 2)
|
||||
|
||||
def test_prints_at_most_one_short_line(self):
|
||||
os.makedirs(os.path.join(self.home, ".claude")) # claude present but not wired
|
||||
r = self.sisi("tick", stdin=self.payload())
|
||||
self.assertLessEqual(len(r.stdout.strip().splitlines()), 1)
|
||||
self.assertIn("sisi doctor", r.stdout)
|
||||
self.sisi("install")
|
||||
self.assertEqual(self.sisi("tick", stdin=self.payload()).stdout, "")
|
||||
|
||||
def test_garbage_and_broken_state_fail_open(self):
|
||||
self.assertEqual(self.sisi("tick", stdin="garbage").returncode, 0)
|
||||
shutil.rmtree(self.state, ignore_errors=True)
|
||||
open(self.state, "w").close()
|
||||
r = self.sisi("tick", stdin=self.payload())
|
||||
self.assertEqual(r.returncode, 0)
|
||||
|
||||
def test_resume_keeps_baseline(self):
|
||||
self.git_init()
|
||||
self.sisi("tick", stdin=self.payload())
|
||||
p = os.path.join(self.state, "sessions", "s1.json")
|
||||
d = json.load(open(p)); d["marker"] = 1
|
||||
json.dump(d, open(p, "w"))
|
||||
self.sisi("tick", stdin=self.payload(source="resume"))
|
||||
self.assertEqual(json.load(open(p)).get("marker"), 1)
|
||||
|
||||
def test_prunes_old_session_files_only(self):
|
||||
sd = os.path.join(self.state, "sessions")
|
||||
os.makedirs(sd)
|
||||
old, new, other = (os.path.join(sd, n) for n in ("old.json", "new.json", "keep.txt"))
|
||||
for p in (old, new, other):
|
||||
open(p, "w").write("{}")
|
||||
t = time.time() - 31 * 86400
|
||||
os.utime(old, (t, t))
|
||||
os.utime(other, (t, t))
|
||||
self.sisi("tick", stdin=self.payload())
|
||||
self.assertFalse(os.path.exists(old))
|
||||
self.assertTrue(os.path.exists(new))
|
||||
self.assertTrue(os.path.exists(other)) # only *.json session records are pruned
|
||||
self.assertTrue(os.path.exists(os.path.join(sd, "s1.json")))
|
||||
|
||||
def test_warm_run_under_200ms(self):
|
||||
self.git_init()
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
self.sisi("install")
|
||||
self.sisi("tick", stdin=self.payload()) # warm
|
||||
best = 9
|
||||
for i in range(60): # many session files: pruning must stay cheap
|
||||
open(os.path.join(self.state, "sessions", "x%d.json" % i), "w").write("{}")
|
||||
for _ in range(5):
|
||||
t = time.perf_counter()
|
||||
self.sisi("tick", stdin=self.payload())
|
||||
best = min(best, time.perf_counter() - t)
|
||||
__import__('support').skip_timing_if_busy(self)
|
||||
self.assertLess(best, 0.2, "tick took %.0f ms" % (best * 1000))
|
||||
|
||||
|
||||
class StoreTests(SisiCase):
|
||||
def read(self, name):
|
||||
with open(os.path.join(self.data, name)) as f: # what the person taught sisi is personal data
|
||||
return [json.loads(l) for l in f]
|
||||
|
||||
def test_note_propose_learn_append_with_context(self):
|
||||
for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl"), ("learn", "learn-quarantine.jsonl")):
|
||||
self.assertEqual(self.sisi(cmd, "first", "entry", env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
|
||||
self.sisi(cmd, "second")
|
||||
recs = self.read(fn)
|
||||
self.assertEqual([r["text"] for r in recs], ["first entry", "second"])
|
||||
self.assertEqual(recs[0]["cwd"], self.proj)
|
||||
self.assertEqual((recs[0]["tool"], recs[0]["session"]), ("codex", "s9"))
|
||||
self.assertIn("ts", recs[0])
|
||||
# learn never reaches the other files
|
||||
self.assertEqual(len(self.read("notes.jsonl")), 2)
|
||||
self.assertEqual(len(self.read("proposals.jsonl")), 2)
|
||||
|
||||
def test_empty_text_rejected(self):
|
||||
self.assertEqual(self.sisi("note").returncode, 1)
|
||||
self.assertFalse(os.path.exists(os.path.join(self.data, "notes.jsonl")))
|
||||
|
||||
def test_oracle_prints_file(self):
|
||||
r = self.sisi("oracle")
|
||||
self.assertIn("oracle", r.stdout.lower())
|
||||
|
||||
def test_concurrent_appends_stay_whole_lines(self):
|
||||
import threading
|
||||
def w(i):
|
||||
for j in range(50):
|
||||
store.append("notes", {"i": i, "j": j, "pad": "x" * 200})
|
||||
ts = [threading.Thread(target=w, args=(i,)) for i in range(6)]
|
||||
[t.start() for t in ts]; [t.join() for t in ts]
|
||||
self.assertEqual(len(self.read("notes.jsonl")), 300)
|
||||
|
||||
def test_status(self):
|
||||
self.write_contract(contract([check("a", "true", rung=2), check("b", "true", rung=3), human("h")]))
|
||||
self.sisi("verify")
|
||||
self.write_contract(contract([check("a", "false", rung=2)]))
|
||||
self.sisi("verify")
|
||||
self.sisi("contract", "waive", "tiny")
|
||||
out = self.sisi("status").stdout
|
||||
self.assertIn("contracts verified : 1", out)
|
||||
self.assertIn("pass rate 50%", out)
|
||||
self.assertIn("waivers : 1", out)
|
||||
self.assertIn("unverified passes : 0", out)
|
||||
|
||||
|
||||
class HelpTests(SisiCase):
|
||||
def test_help_and_unknown(self):
|
||||
out = self.sisi("help").stdout
|
||||
for w in ("verify", "gate", "tick", "install", "audit", "learn", "verifiers"):
|
||||
self.assertIn(w, out)
|
||||
self.assertNotEqual(self.sisi("bogus").returncode, 0)
|
||||
|
||||
def test_every_command_in_core_md_exists(self):
|
||||
import re
|
||||
text = open(os.path.join(REPO, "canon", "core.md")).read()
|
||||
for m in set(re.findall(r"`sisi ([a-z]+)", text)):
|
||||
self.assertIn("sisi " + m, self.sisi("help").stdout, m)
|
||||
|
||||
def test_version_matches_the_version_file(self):
|
||||
want = open(os.path.join(REPO, "VERSION")).read().strip()
|
||||
self.assertRegex(want, r"^\d+\.\d+\.\d+$")
|
||||
for a in ("--version", "version"):
|
||||
r = self.sisi(a)
|
||||
self.assertEqual((r.returncode, r.stdout.strip()), (0, want), a)
|
||||
|
||||
def test_audit_runs_on_fake_home(self):
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
with open(os.path.join(self.home, ".claude", "CLAUDE.md"), "w") as f:
|
||||
f.write("a\nb\n")
|
||||
out = self.sisi("audit").stdout
|
||||
self.assertIn("claude-code", out)
|
||||
self.assertIn("global instructions", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,371 @@
|
||||
import json, os, random, shutil, time, unittest
|
||||
from support import *
|
||||
from sisi import contract as C, deep as D, gate, gitutil, verify as V
|
||||
from test_verifiers import LibCase, vfile, BODY_V
|
||||
|
||||
|
||||
def deepc(id, cmd="true", timeout_s=3600, **kw):
|
||||
return dict(check(id, cmd, rung=2, timeout_s=timeout_s, **kw), tier="deep")
|
||||
|
||||
|
||||
class TierContractTests(SisiCase):
|
||||
def errs(self, c):
|
||||
return C.validate(c)
|
||||
|
||||
def test_fast_default_and_limit(self):
|
||||
self.assertEqual(self.errs(contract([check("a", "true", timeout_s=60)])), [])
|
||||
e = self.errs(contract([check("a", "true", timeout_s=61)]))
|
||||
self.assertTrue(any("deep" in x and "61" in x for x in e), e)
|
||||
self.assertTrue(self.errs(contract([check("a", "true")], [check("i", "true", timeout_s=900)]))) # invariants too
|
||||
self.assertEqual(self.errs(contract([check("a", "true"), deepc("d")])), []) # deep may be long
|
||||
|
||||
def test_bad_tier_value(self):
|
||||
self.assertTrue(self.errs(contract([dict(check("a", "true"), tier="slow")])))
|
||||
|
||||
def test_fast_limit_is_configurable(self):
|
||||
os.makedirs(self.state)
|
||||
json.dump({"verify": {"fast_limit_s": 10}}, open(os.path.join(self.state, "config.json"), "w"))
|
||||
self.assertTrue(self.errs(contract([check("a", "true", timeout_s=30)])))
|
||||
|
||||
def test_sum_over_gate_budget_is_a_warning_only(self):
|
||||
c = contract([check("a%d" % i, "true", timeout_s=50) for i in range(3)])
|
||||
self.assertEqual(self.errs(c), [])
|
||||
self.assertTrue(C.warnings(c))
|
||||
self.assertFalse(C.warnings(contract([check("a", "true"), deepc("d"), deepc("e")]))) # deep not counted
|
||||
|
||||
def test_check_command_prints_warning_and_ok(self):
|
||||
self.write_contract(contract([check("a%d" % i, "true", timeout_s=50) for i in range(3)]))
|
||||
r = self.sisi("contract", "check")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertIn("warning", r.stdout)
|
||||
self.write_contract(contract([check("a", "true", timeout_s=999)]))
|
||||
r = self.sisi("contract", "check")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("deep", r.stdout)
|
||||
|
||||
def test_skeleton_shows_fast_and_deep_placeholders(self):
|
||||
self.sisi("contract", "init")
|
||||
c = json.load(open(os.path.join(self.proj, ".sisi", "contract.json")))
|
||||
self.assertEqual([x.get("tier", "fast") for x in c["checks"]], ["fast", "deep"])
|
||||
self.assertTrue(all("PLACEHOLDER" in x["claim"] for x in c["checks"]))
|
||||
self.assertEqual(C.validate(c), [])
|
||||
self.assertTrue(C.is_unedited_skeleton(c))
|
||||
|
||||
|
||||
class VerifyTierTests(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.git_init()
|
||||
self.fast, self.dp = os.path.join(self.tmp, "fast"), os.path.join(self.tmp, "deep")
|
||||
self.write_contract(contract([check("f", "echo x >> %s" % self.fast), deepc("d", "echo x >> %s" % self.dp)]))
|
||||
|
||||
def ran(self, p):
|
||||
return os.path.exists(p)
|
||||
|
||||
def test_default_fast_only_deep_only_all(self):
|
||||
self.assertEqual(self.sisi("verify").returncode, 0)
|
||||
self.assertTrue(self.ran(self.fast) and not self.ran(self.dp))
|
||||
os.remove(self.fast)
|
||||
self.assertEqual(self.sisi("verify", "--deep").returncode, 0)
|
||||
self.assertTrue(self.ran(self.dp) and not self.ran(self.fast))
|
||||
os.remove(self.dp)
|
||||
self.assertEqual(self.sisi("verify", "--all").returncode, 0)
|
||||
self.assertTrue(self.ran(self.dp) and self.ran(self.fast))
|
||||
|
||||
def test_records_carry_tier_and_fingerprint(self):
|
||||
self.sisi("verify", "--all")
|
||||
fp = gitutil.fingerprint(self.proj, [os.path.join(self.proj, ".sisi", "contract.json")])
|
||||
self.assertTrue(fp)
|
||||
recs = self.results()
|
||||
self.assertEqual({r["tier"] for r in recs}, {"fast", "deep"})
|
||||
self.assertEqual({r["fp"] for r in recs}, {fp})
|
||||
|
||||
def test_state_lifecycle_and_line(self):
|
||||
st = lambda: self.sisi("verify", "--state").stdout.strip()
|
||||
self.assertTrue(st().startswith("deep checks: never-run (1 item)"), st())
|
||||
self.sisi("verify", "--deep")
|
||||
self.assertTrue(st().startswith("deep checks: fresh-pass (1 item, last run"), st())
|
||||
self.assertIn("on the current tree", st())
|
||||
with open(os.path.join(self.proj, "new.txt"), "w") as f:
|
||||
f.write("change\n")
|
||||
self.assertTrue(st().startswith("deep checks: stale-pass"), st())
|
||||
self.assertIn("older tree", st())
|
||||
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
|
||||
self.sisi("verify", "--deep")
|
||||
self.assertTrue(st().startswith("deep checks: failed"), st())
|
||||
self.assertIn("failing: d", st())
|
||||
|
||||
def test_every_mode_ends_with_state_line(self):
|
||||
for mode in ([], ["--deep"], ["--all"]):
|
||||
out = self.sisi("verify", *mode).stdout
|
||||
self.assertIn("deep checks:", out.strip().splitlines()[-1], mode)
|
||||
|
||||
def test_state_json_and_no_deep_items(self):
|
||||
d = json.loads(self.sisi("verify", "--state", "--json").stdout)
|
||||
self.assertEqual((d["state"], d["items"]), ("never-run", 1))
|
||||
self.write_contract(contract([check("f", "true")]))
|
||||
self.assertIn("none", self.sisi("verify", "--state").stdout)
|
||||
self.assertNotIn("deep checks: ", self.sisi("verify").stdout.replace("deep checks: none", ""))
|
||||
|
||||
def test_failed_deep_exit_code_and_modes_conflict(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
|
||||
self.assertEqual(self.sisi("verify", "--deep").returncode, 1)
|
||||
self.assertEqual(self.sisi("verify").returncode, 0) # fast mode ignores deep
|
||||
self.assertEqual(self.sisi("verify", "--deep", "--all").returncode, 1)
|
||||
self.assertEqual(self.sisi("verify", "--background").returncode, 1) # needs --deep
|
||||
|
||||
|
||||
class BackgroundTests(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.git_init()
|
||||
self.counter = os.path.join(self.tmp, "count")
|
||||
self.go = os.path.join(self.tmp, "go") # the deep check waits for this file, so "running" is deterministic
|
||||
self.write_contract(contract([check("f", "true"), deepc(
|
||||
"d", "echo x >> %s; i=0; while [ ! -f %s ] && [ $i -lt 400 ]; do sleep 0.05; i=$((i+1)); done" % (self.counter, self.go))]))
|
||||
|
||||
def release(self):
|
||||
open(self.go, "w").close()
|
||||
|
||||
def wait_state(self, want, timeout=15):
|
||||
t = time.time()
|
||||
while time.time() - t < timeout:
|
||||
s = self.sisi("verify", "--state").stdout
|
||||
if s.startswith("deep checks: " + want):
|
||||
return s
|
||||
time.sleep(0.2)
|
||||
self.fail("never reached %s; last: %s" % (want, s))
|
||||
|
||||
def test_detached_run_records_after_parent_exits(self):
|
||||
r = self.sisi("verify", "--deep", "--background")
|
||||
self.assertEqual(r.returncode, 0) # returned although the check is still waiting for `go`
|
||||
log = r.stdout.split("log: ")[1].split()[0]
|
||||
self.assertTrue(log.startswith(self.state))
|
||||
self.assertTrue(self.sisi("verify", "--state").stdout.startswith("deep checks: running"))
|
||||
lock = json.load(open(os.path.join(self.state, "locks", os.listdir(os.path.join(self.state, "locks"))[0])))
|
||||
self.assertEqual(os.getpgid(lock["pid"]), lock["pid"]) # own process group
|
||||
self.release()
|
||||
self.wait_state("fresh-pass") # the parent is long gone by now
|
||||
deeprecs = [x for x in self.results() if x["tier"] == "deep"]
|
||||
self.assertEqual([(x["check"], x["status"]) for x in deeprecs], [("d", "passed")])
|
||||
self.assertTrue(deeprecs[0]["fp"])
|
||||
self.assertTrue(os.path.exists(log))
|
||||
self.assertFalse(os.listdir(os.path.join(self.state, "locks"))) # lock released
|
||||
|
||||
def test_second_request_while_running_says_so_and_exits_0(self):
|
||||
self.sisi("verify", "--deep", "--background")
|
||||
t = time.time()
|
||||
while not os.path.exists(self.counter) and time.time() - t < 15: # the worker has started its check
|
||||
time.sleep(0.05)
|
||||
r = self.sisi("verify", "--deep", "--background")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertIn("already running", r.stdout)
|
||||
with open(os.path.join(self.proj, "edit.txt"), "w") as f:
|
||||
f.write("x")
|
||||
r = self.sisi("verify", "--deep", "--background") # tree changed: reported, not killed or restarted
|
||||
self.assertIn("older tree", r.stdout)
|
||||
self.assertIn("running", self.sisi("verify", "--state").stdout)
|
||||
self.release()
|
||||
self.wait_state("stale-pass") # finished run was against the older tree
|
||||
self.assertEqual(len(open(self.counter).read().split()), 1)
|
||||
|
||||
def test_foreground_deep_respects_the_lock(self):
|
||||
self.sisi("verify", "--deep", "--background")
|
||||
r = self.sisi("verify", "--deep")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertIn("already running", r.stdout)
|
||||
self.release()
|
||||
self.wait_state("fresh-pass")
|
||||
|
||||
def test_stale_lock_from_dead_process_is_ignored(self):
|
||||
p = D._lock_path(self.proj)
|
||||
os.makedirs(os.path.dirname(p))
|
||||
json.dump({"pid": 2 ** 22 + 12345, "start": "1", "fp": None, "ts": time.time()}, open(p, "w"))
|
||||
self.assertNotIn("running", self.sisi("verify", "--state").stdout)
|
||||
self.release()
|
||||
self.assertEqual(self.sisi("verify", "--deep").returncode, 0)
|
||||
|
||||
|
||||
class GateDeepTests(SisiCase):
|
||||
sid = "gd"
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.git_init()
|
||||
self.path = os.path.join(self.proj, ".sisi", "contract.json")
|
||||
|
||||
def gate(self, sid=None):
|
||||
return gate.decide({"session_id": sid or self.sid, "cwd": self.proj})
|
||||
|
||||
def hook(self):
|
||||
return self.sisi("gate", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj}))
|
||||
|
||||
def fp(self):
|
||||
return V.tree_fp(self.proj, self.path)
|
||||
|
||||
def set_deep(self, ok, fp="current"):
|
||||
c = json.load(open(self.path))
|
||||
res = [{"tier": "deep", "id": x["id"], "status": "passed" if ok else "failed", "tail": "" if ok else "kaboom-deep"}
|
||||
for x in D.deep_items(c)]
|
||||
D.save_state(self.proj, c["id"], self.fp() if fp == "current" else "older", res, [x["id"] for x in D.deep_items(c)])
|
||||
|
||||
def edit(self, t="x"):
|
||||
with open(os.path.join(self.proj, "w.txt"), "a") as f:
|
||||
f.write(t + "\n")
|
||||
|
||||
def test_pending_deep_allows_and_tells_the_model_once(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d", "sleep 100")]))
|
||||
t = time.time()
|
||||
r = self.hook()
|
||||
self.assertLess(time.time() - t, 5) # never waits for deep items
|
||||
out = json.loads(r.stdout)
|
||||
ctx = out["hookSpecificOutput"]
|
||||
self.assertEqual(ctx["hookEventName"], "Stop")
|
||||
self.assertIn("not yet", ctx["additionalContext"])
|
||||
self.assertIn("never-run", ctx["additionalContext"])
|
||||
self.assertIn("deep", out["systemMessage"])
|
||||
self.assertNotIn("decision", out)
|
||||
self.assertEqual(self.hook().stdout, "") # same tree: said once, no loop
|
||||
|
||||
def test_stale_pass_notifies_fresh_pass_is_silent(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
self.set_deep(True)
|
||||
self.assertEqual(self.hook().stdout, "")
|
||||
self.edit()
|
||||
self.assertIn("stale-pass", json.loads(self.hook().stdout)["hookSpecificOutput"]["additionalContext"])
|
||||
|
||||
def test_deep_failure_on_current_tree_blocks_with_tail_and_strikes(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
self.set_deep(False)
|
||||
a, msg = self.gate()
|
||||
self.assertEqual(a, "block")
|
||||
self.assertIn("kaboom-deep", msg)
|
||||
self.assertEqual([self.gate()[0] for _ in range(2)], ["block", "block"]) # unchanged tree keeps blocking
|
||||
a, msg = self.gate()
|
||||
self.assertEqual(a, "allow")
|
||||
self.assertIn("UNVERIFIED", msg)
|
||||
|
||||
def test_deep_failure_on_older_tree_does_not_block(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
self.set_deep(False, fp="older")
|
||||
self.assertEqual(self.gate()[0], "allow")
|
||||
|
||||
def test_deep_failure_arriving_after_an_allow_is_noticed_on_unchanged_tree(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
self.assertEqual(self.gate()[0], "allow")
|
||||
self.assertEqual(self.gate()[0], "allow") # short-circuit
|
||||
self.set_deep(False) # a background run finished and failed
|
||||
self.assertEqual(self.gate()[0], "block")
|
||||
|
||||
def test_deep_rerun_that_passes_unblocks_unchanged_tree(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
self.set_deep(False)
|
||||
self.assertEqual(self.gate()[0], "block")
|
||||
self.set_deep(True)
|
||||
self.assertEqual(self.gate()[0], "allow")
|
||||
|
||||
def test_fast_failure_still_blocks_regardless_of_deep(self):
|
||||
self.write_contract(contract([check("f", "false"), deepc("d")]))
|
||||
self.set_deep(True)
|
||||
self.assertEqual(self.gate()[0], "block")
|
||||
|
||||
def test_running_deep_is_not_a_block(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
ok, _ = D.acquire(self.proj, self.fp())
|
||||
self.assertTrue(ok)
|
||||
self.addCleanup(D.release, self.proj)
|
||||
self.set_deep(False) # an old failure while a new run is in progress
|
||||
self.assertEqual(self.gate()[0], "allow")
|
||||
|
||||
def test_property_deep_never_blocks_by_itself_and_current_failure_always_does(self):
|
||||
seeds = [0, 1, random.randrange(2 ** 32)] + [random.randrange(2 ** 32) for _ in range(ITERS - 1)]
|
||||
for seed in seeds:
|
||||
rng = random.Random(seed)
|
||||
for n in range(6 * ITERS):
|
||||
deeps = [deepc("d%d" % i, rng.choice(["true", "false", "sleep 100"]), timeout_s=rng.choice([60, 3600, 86400]))
|
||||
for i in range(rng.randint(1, 3))]
|
||||
c = contract([check("f", "true")] + ([human("h")] if rng.random() < 0.3 else []), [])
|
||||
c["checks"] += deeps
|
||||
self.write_contract(c)
|
||||
self.edit("%d-%d" % (seed, n)) # new tree for each case
|
||||
mode = rng.choice(["unrun", "running", "pass-fresh", "pass-stale", "fail-fresh", "fail-stale"])
|
||||
shutil.rmtree(os.path.join(self.state, "deep"), ignore_errors=True)
|
||||
shutil.rmtree(os.path.join(self.state, "locks"), ignore_errors=True)
|
||||
if mode == "running":
|
||||
D.acquire(self.proj, self.fp())
|
||||
elif mode != "unrun":
|
||||
self.set_deep(mode.startswith("pass"), "current" if mode.endswith("fresh") else "older")
|
||||
sid = "prop-%d-%d" % (seed, n)
|
||||
with self.subTest(seed=seed, n=n, mode=mode):
|
||||
a, msg = self.gate(sid)
|
||||
if mode == "fail-fresh":
|
||||
self.assertEqual(a, "block")
|
||||
self.assertEqual([self.gate(sid)[0] for _ in range(2)], ["block", "block"])
|
||||
self.assertEqual(self.gate(sid)[0], "allow") # 3-strike release
|
||||
else:
|
||||
self.assertEqual(a, "allow")
|
||||
D.release(self.proj)
|
||||
|
||||
|
||||
class TickDeepTests(SisiCase):
|
||||
def tick(self):
|
||||
return self.sisi("tick", stdin=json.dumps({"session_id": "t", "cwd": self.proj, "source": "startup"})).stdout
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.git_init()
|
||||
|
||||
def test_line_for_not_fresh_states_silent_when_fresh_or_untrusted(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
self.assertIn("never-run", self.tick())
|
||||
self.assertEqual(len(self.tick().strip().splitlines()), 1)
|
||||
self.sisi("verify", "--deep")
|
||||
self.assertEqual(self.tick(), "")
|
||||
with open(os.path.join(self.proj, "n.txt"), "w") as f:
|
||||
f.write("x")
|
||||
self.assertIn("stale-pass", self.tick())
|
||||
self.write_contract(contract([check("f", "true"), deepc("d", "false")]))
|
||||
self.sisi("verify", "--deep")
|
||||
self.assertIn("failed", self.tick())
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]), trusted=False)
|
||||
os.remove(os.path.join(self.data, "trusted.json"))
|
||||
self.assertEqual(self.tick(), "")
|
||||
|
||||
def test_still_fast(self):
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
self.tick()
|
||||
best = 9
|
||||
for _ in range(5):
|
||||
t = time.perf_counter()
|
||||
self.tick()
|
||||
best = min(best, time.perf_counter() - t)
|
||||
__import__('support').skip_timing_if_busy(self)
|
||||
self.assertLess(best, 0.2)
|
||||
|
||||
|
||||
class StatusLintTests(LibCase):
|
||||
def test_status_lists_recent_contracts(self):
|
||||
self.git_init()
|
||||
self.write_contract(contract([check("f", "true"), deepc("d")]))
|
||||
self.sisi("verify")
|
||||
out = self.sisi("status").stdout
|
||||
self.assertIn("recent contracts:", out)
|
||||
self.assertRegex(out, r"t\s+fast: pass\s+deep: never-run")
|
||||
self.sisi("verify", "--deep")
|
||||
self.assertRegex(self.sisi("status").stdout, r"deep: fresh-pass")
|
||||
|
||||
def test_lint_warns_on_long_untiered_example(self):
|
||||
def body(extra):
|
||||
return BODY_V.replace("## As a contract check\ntext", '## As a contract check\n```json\n{"id": "x", "timeout_s": %s%s}\n```' % extra)
|
||||
self.put("prove/slow.md", vfile("slow", body=body(("3600", ""))))
|
||||
self.put("prove/ok.md", vfile("ok", body=body(("3600", ', "tier": "deep"'))))
|
||||
self.put("prove/quick.md", vfile("quick", body=body(("60", ""))))
|
||||
r = self.sisi("verifiers", "lint")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
warn = [l for l in r.stdout.splitlines() if "no \"tier\": \"deep\"" in l]
|
||||
self.assertEqual(len(warn), 1)
|
||||
self.assertIn("slow.md", warn[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,332 @@
|
||||
import json, os, unittest
|
||||
from support import *
|
||||
from sisi import verifiers as V
|
||||
|
||||
BODY_V = "\n".join("## " + h + "\ntext" for h in V.V_HEADINGS) + "\n"
|
||||
BODY_D = "\n".join("## " + h + "\ntext" for h in V.D_HEADINGS) + "\n"
|
||||
|
||||
|
||||
def vfile(id, section="prove", rung=1, cost="low", languages="any", kinds="general", detect="true", ran="no",
|
||||
title=None, answers="Is it true?", body=BODY_V, extra=""):
|
||||
return ("---\nid: %s\ntitle: %s\nanswers: %s\nrung: %s\nsection: %s\nlanguages: %s\nkinds: %s\ncost: %s\n"
|
||||
"detect: %s\nran_here: %s\n%s---\n%s" % (id, title or id.title(), answers, rung, section, languages, kinds,
|
||||
cost, detect, ran, extra, body))
|
||||
|
||||
|
||||
def dfile(id, title="T", applies="work", body=BODY_D):
|
||||
return "---\nid: %s\ntitle: %s\napplies_to: %s\n---\n%s" % (id, title, applies, body)
|
||||
|
||||
|
||||
class LibCase(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.vdir, self.ddir = os.path.join(self.tmp, "verifiers"), os.path.join(self.tmp, "done")
|
||||
os.makedirs(self.vdir)
|
||||
os.makedirs(self.ddir)
|
||||
os.environ["SISI_VERIFIERS"], os.environ["SISI_DONE"] = self.vdir, self.ddir
|
||||
self.addCleanup(os.environ.pop, "SISI_VERIFIERS", None)
|
||||
self.addCleanup(os.environ.pop, "SISI_DONE", None)
|
||||
|
||||
def put(self, rel, text, root=None):
|
||||
p = os.path.join(root or self.vdir, rel)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with open(p, "w") as f:
|
||||
f.write(text)
|
||||
|
||||
def seed(self):
|
||||
self.put("prove/lean4.md", vfile("lean4", "prove", 1, "high", "lean, rust", "general, parsing", "false",
|
||||
title="Lean 4 proofs", answers="Is this property true for every input, not just the ones I tried?"))
|
||||
self.put("many-inputs/proptest.md", vfile("proptest", "many-inputs", 2, "low", "rust", "parsing, money", "true",
|
||||
title="Rust property testing", answers="Does parsing round trip for random inputs?"))
|
||||
self.put("many-inputs/hypothesis.md", vfile("hypothesis", "many-inputs", 2, "low", "python", "parsing", "exit 3",
|
||||
title="Python hypothesis", answers="Do random inputs break this function?"))
|
||||
self.put("regression/snapshot.md", vfile("snapshot", "regression", 4, "low", "any", "ui", "",
|
||||
title="Screenshot comparison", answers="Did the page stop looking the same?"))
|
||||
self.put("flat-one.md", vfile("flat-one", "design", 3, "medium", "any", "general", "true", title="Flat file at root",
|
||||
answers="Is the design sound?")) # tolerated at root depth
|
||||
|
||||
def ids(self, out):
|
||||
return [l.split()[0] for l in out.splitlines() if l.startswith(" ")]
|
||||
|
||||
|
||||
class ParseTests(LibCase):
|
||||
def test_header_parsing_and_lists(self):
|
||||
self.put("prove/x.md", vfile("x", languages="Lean, Rust", kinds="parsing,money"))
|
||||
e = V.load_verifiers()[0]
|
||||
self.assertEqual((e["id"], e["rung"], e["section"]), ("x", 1, "prove"))
|
||||
self.assertEqual(e["languages"], ["lean", "rust"])
|
||||
self.assertEqual(e["kinds"], ["parsing", "money"])
|
||||
self.assertIn("Use when", e["body"])
|
||||
self.assertEqual(e["problems"], [])
|
||||
|
||||
def test_value_may_contain_colon(self):
|
||||
self.put("prove/x.md", vfile("x", answers="Is it true: for all inputs?"))
|
||||
self.assertEqual(V.load_verifiers()[0]["answers"], "Is it true: for all inputs?")
|
||||
|
||||
def test_missing_header(self):
|
||||
self.put("old.md", "# old file\nno header\n")
|
||||
self.assertTrue(V.load_verifiers()[0]["problems"])
|
||||
self.assertEqual(V.usable(V.load_verifiers()), [])
|
||||
|
||||
|
||||
class ListTests(LibCase):
|
||||
def test_grouped_by_section_with_columns(self):
|
||||
self.seed()
|
||||
out = self.sisi("verifiers").stdout
|
||||
self.assertLess(out.index("design"), out.index("prove"))
|
||||
self.assertLess(out.index("prove"), out.index("many-inputs"))
|
||||
line = next(l for l in out.splitlines() if "lean4" in l)
|
||||
for w in ("r1", "high", "lean, rust", "Lean 4 proofs"):
|
||||
self.assertIn(w, line)
|
||||
self.assertIn("flat-one", out) # root-depth file tolerated
|
||||
|
||||
def test_filters(self):
|
||||
self.seed()
|
||||
f = lambda *a: self.ids(self.sisi("verifiers", *a).stdout)
|
||||
self.assertEqual(sorted(f("--lang", "rust")), ["flat-one", "lean4", "proptest", "snapshot"])
|
||||
self.assertEqual(sorted(f("--lang", "python")), ["flat-one", "hypothesis", "snapshot"])
|
||||
self.assertEqual(sorted(f("--kind", "money")), ["proptest"])
|
||||
self.assertEqual(sorted(f("--rung", "2")), ["hypothesis", "lean4", "proptest"]) # 2 or stronger
|
||||
self.assertEqual(f("--section", "regression"), ["snapshot"])
|
||||
self.assertEqual(sorted(f("--installed")), ["flat-one", "proptest", "snapshot"]) # lean4/hypothesis detect fails; empty detect = n/a
|
||||
|
||||
def test_free_text_all_words_case_insensitive(self):
|
||||
self.seed()
|
||||
self.put("prove/body.md", vfile("body", body=BODY_V + "\nmentions Zebra crossing\n"))
|
||||
f = lambda *a: self.ids(self.sisi("verifiers", *a).stdout)
|
||||
self.assertEqual(f("ZEBRA"), ["body"])
|
||||
self.assertEqual(f("property", "lean"), ["lean4"])
|
||||
self.assertEqual(f("property", "python"), [])
|
||||
self.assertEqual(f("round", "trip"), ["proptest"]) # matches answers
|
||||
|
||||
def test_json(self):
|
||||
self.seed()
|
||||
d = json.loads(self.sisi("verifiers", "--json", "--section", "prove").stdout)
|
||||
self.assertEqual([x["id"] for x in d], ["lean4"])
|
||||
self.assertEqual(d[0]["installed"], "no")
|
||||
self.assertEqual(d[0]["rung"], 1)
|
||||
|
||||
def test_bad_flag_value(self):
|
||||
self.assertEqual(self.sisi("verifiers", "--rung", "x").returncode, 1)
|
||||
|
||||
|
||||
class ShowAndChooseTests(LibCase):
|
||||
def test_show_with_installed_line(self):
|
||||
self.seed()
|
||||
out = self.sisi("verifiers", "show", "proptest").stdout
|
||||
self.assertIn("installed here: yes", out)
|
||||
self.assertIn("Use when", out)
|
||||
self.assertIn("installed here: no", self.sisi("verifiers", "show", "lean4").stdout)
|
||||
self.assertIn("n/a", self.sisi("verifiers", "show", "snapshot").stdout)
|
||||
self.assertEqual(self.sisi("verifiers", "show", "nope").returncode, 1)
|
||||
|
||||
def test_show_never_fails_on_broken_or_slow_detect(self):
|
||||
self.put("prove/weird.md", vfile("weird", detect="definitely-not-a-command-xyz"))
|
||||
self.put("prove/slow.md", vfile("slow", detect="sleep 30"))
|
||||
import time
|
||||
os.environ["SISI_DETECT_TIMEOUT"] = "0.5"
|
||||
self.addCleanup(os.environ.pop, "SISI_DETECT_TIMEOUT", None)
|
||||
t = time.time()
|
||||
r = self.sisi("verifiers", "show", "weird")
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertIn("installed here: no", r.stdout)
|
||||
self.assertEqual(self.sisi("verifiers", "show", "slow").returncode, 0)
|
||||
self.assertLess(time.time() - t, 5)
|
||||
|
||||
def test_for_ranks_by_overlap_rung_and_installed(self):
|
||||
self.seed()
|
||||
out = self.sisi("verifiers", "for", "random inputs for a parsing function in python").stdout
|
||||
ids = [l.split()[1] for l in out.splitlines() if l[:2].strip().rstrip(".").isdigit()]
|
||||
self.assertEqual(ids[0], "hypothesis")
|
||||
self.assertIn("proptest", ids)
|
||||
self.assertNotIn("snapshot", ids)
|
||||
self.assertIn("installed:", out)
|
||||
self.assertIn("Do random inputs break this function?", out)
|
||||
|
||||
def test_for_stronger_rung_wins_when_relevance_ties(self):
|
||||
self.put("prove/strong.md", vfile("strong", rung=1, answers="Does the cache evict correctly?", detect=""))
|
||||
self.put("prove/weak.md", vfile("weak", rung=4, answers="Does the cache evict correctly?", detect=""))
|
||||
out = self.sisi("verifiers", "for", "cache evict").stdout
|
||||
self.assertLess(out.index("strong"), out.index("weak"))
|
||||
|
||||
def test_for_installed_boost(self):
|
||||
self.put("prove/here.md", vfile("here", rung=2, answers="Does the queue drain?", detect="true"))
|
||||
self.put("prove/gone.md", vfile("gone", rung=2, answers="Does the queue drain?", detect="false"))
|
||||
out = self.sisi("verifiers", "for", "queue drain").stdout
|
||||
self.assertLess(out.index("here"), out.index("gone"))
|
||||
|
||||
def test_for_top_8_only(self):
|
||||
for i in range(12):
|
||||
self.put("prove/e%02d.md" % i, vfile("e%02d" % i, answers="Does the widget work?"))
|
||||
out = self.sisi("verifiers", "for", "widget").stdout
|
||||
self.assertEqual(len([l for l in out.splitlines() if l[:1].isdigit()]), 8)
|
||||
|
||||
def test_for_kind_floor_marking(self):
|
||||
self.seed()
|
||||
out = self.sisi("verifiers", "for", "parsing round trip", "--kind", "parsing").stdout
|
||||
self.assertIn("Floor: parsing claims need rung 2", out)
|
||||
self.assertIn("[floor ok]", out)
|
||||
self.put("prove/weakparse.md", vfile("weakparse", rung=4, kinds="parsing", answers="Does parsing look fine?"))
|
||||
out = self.sisi("verifiers", "for", "parsing looks fine", "--kind", "parsing").stdout
|
||||
self.assertIn("[below floor]", out)
|
||||
out = self.sisi("verifiers", "for", "page looks", "--kind", "ui").stdout
|
||||
self.assertNotIn("Floor:", out)
|
||||
|
||||
def test_for_lang_and_kind_filters(self):
|
||||
self.seed()
|
||||
out = self.sisi("verifiers", "for", "random inputs parsing", "--lang", "rust").stdout
|
||||
self.assertIn("proptest", out)
|
||||
self.assertNotIn("hypothesis", out)
|
||||
|
||||
def test_for_no_match_and_empty(self):
|
||||
self.seed()
|
||||
self.assertIn("no verifier matches", self.sisi("verifiers", "for", "zzzqqq").stdout)
|
||||
self.assertEqual(self.sisi("verifiers", "for").returncode, 1)
|
||||
|
||||
|
||||
class DoctorTests(LibCase):
|
||||
def test_doctor_summarises_per_section(self):
|
||||
self.seed()
|
||||
out = self.sisi("verifiers", "doctor").stdout
|
||||
self.assertIn("many-inputs: 1 of 2 installed", out)
|
||||
self.assertIn("prove: 0 of 1 installed", out)
|
||||
self.assertNotIn("snapshot", out) # no detect command
|
||||
self.assertIn("total: 2 of 4", out)
|
||||
|
||||
def test_doctor_runs_concurrently_under_cap(self):
|
||||
import time
|
||||
for i in range(8):
|
||||
self.put("prove/s%d.md" % i, vfile("s%d" % i, detect="sleep 0.7"))
|
||||
t = time.time()
|
||||
out = self.sisi("verifiers", "doctor").stdout
|
||||
self.assertLess(time.time() - t, 3.5) # 8 x 0.7 s would be 5.6 s if serial
|
||||
self.assertIn("8 of 8", out)
|
||||
|
||||
|
||||
class DoneTests(LibCase):
|
||||
def seed_done(self):
|
||||
self.put("bugfix.md", dfile("bugfix", "Fixing a bug", "a defect in existing behaviour, fix, regression"), self.ddir)
|
||||
self.put("new-library.md", dfile("new-library", "Writing a new library", "a reusable package with a public API"), self.ddir)
|
||||
self.put("web-ui.md", dfile("web-ui", "Changing a web UI", "pages, layout, screenshots"), self.ddir)
|
||||
|
||||
def test_list_show_for(self):
|
||||
self.seed_done()
|
||||
out = self.sisi("done").stdout
|
||||
for i in ("bugfix", "new-library", "web-ui"):
|
||||
self.assertIn(i, out)
|
||||
self.assertIn("Done means", self.sisi("done", "bugfix").stdout)
|
||||
self.assertEqual(self.sisi("done", "nope").returncode, 1)
|
||||
out = self.sisi("done", "for", "fix a regression bug in the parser").stdout
|
||||
self.assertTrue(out.startswith("Best match: bugfix"))
|
||||
out = self.sisi("done", "for", "change the page layout").stdout
|
||||
self.assertTrue(out.startswith("Best match: web-ui"))
|
||||
self.assertIn("no recipe matches", self.sisi("done", "for", "zzzqqq").stdout)
|
||||
|
||||
|
||||
class LintTests(LibCase):
|
||||
def lint(self):
|
||||
r = self.sisi("verifiers", "lint")
|
||||
return r.returncode, r.stdout
|
||||
|
||||
def test_clean(self):
|
||||
self.seed()
|
||||
self.put("bugfix.md", dfile("bugfix"), self.ddir)
|
||||
rc, out = self.lint()
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("lint ok", out)
|
||||
|
||||
def test_each_problem_is_reported(self):
|
||||
cases = {
|
||||
"missing key": ("prove/a.md", vfile("a").replace("answers: Is it true?\n", ""), "missing or empty 'answers'"),
|
||||
"bad rung": ("prove/a.md", vfile("a", rung=7), "rung must be"),
|
||||
"rung word": ("prove/a.md", vfile("a", rung="strong"), "rung must be"),
|
||||
"unknown section": ("zzz/a.md", vfile("a", section="zzz"), "unknown section"),
|
||||
"bad cost": ("prove/a.md", vfile("a", cost="huge"), "cost must be"),
|
||||
"id != stem": ("prove/a.md", vfile("b"), "must equal the file name"),
|
||||
"no header": ("prove/a.md", "# nothing\n", "no header block"),
|
||||
"bad kind": ("prove/a.md", vfile("a", kinds="vibes"), "unknown kind"),
|
||||
"bad ran_here": ("prove/a.md", vfile("a", ran="maybe"), "ran_here"),
|
||||
"wrong dir": ("design/a.md", vfile("a", section="prove"), "does not match its directory"),
|
||||
"heading": ("prove/a.md", vfile("a", body=BODY_V.replace("## Run\ntext\n", "")), "'Run'"),
|
||||
"heading needs to be a heading": ("prove/a.md", vfile("a", body=BODY_V.replace("## Set up", "Set up")), "'Set up'"),
|
||||
}
|
||||
for name, (rel, text, expect) in cases.items():
|
||||
with self.subTest(name):
|
||||
for d in (self.vdir, self.ddir):
|
||||
for f in os.listdir(d):
|
||||
import shutil
|
||||
p = os.path.join(d, f)
|
||||
shutil.rmtree(p) if os.path.isdir(p) else os.remove(p)
|
||||
self.put(rel, text)
|
||||
rc, out = self.lint()
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn(expect, out)
|
||||
|
||||
def test_duplicate_ids_and_recipes(self):
|
||||
self.put("prove/a.md", vfile("a"))
|
||||
self.put("design/a.md", vfile("a", section="design"))
|
||||
rc, out = self.lint()
|
||||
self.assertIn("duplicate id", out)
|
||||
self.put("bad.md", dfile("bad").replace("## Checks\ntext\n", ""), self.ddir)
|
||||
self.put("other.md", dfile("else"), self.ddir)
|
||||
rc, out = self.lint()
|
||||
self.assertIn("'Checks'", out)
|
||||
self.assertIn("must equal the file name", out)
|
||||
|
||||
def test_empty_detect_allowed_missing_detect_key_not(self):
|
||||
self.put("prove/a.md", vfile("a", detect=""))
|
||||
self.assertEqual(self.lint()[0], 0)
|
||||
self.put("prove/b.md", vfile("b").replace("detect: true\n", ""))
|
||||
self.assertIn("'detect'", self.lint()[1])
|
||||
|
||||
|
||||
class LintCrossCheckTests(LibCase):
|
||||
def recipe(self, checks_text):
|
||||
body = "## Done means\nx\n\n## Checks\n%s\n## Common false finishes\nx\n" % checks_text
|
||||
self.put("r.md", dfile("r", body=body), self.ddir)
|
||||
|
||||
def test_unknown_cited_id_fails_with_file_and_id(self):
|
||||
self.seed()
|
||||
self.recipe("- Fast: `proptest`, `lean4` (prove), rung 2; run `cargo test --release` or `pytest -q`.\n- `no-such-check`\n")
|
||||
r = self.sisi("verifiers", "lint")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("r.md", r.stdout)
|
||||
self.assertIn("'no-such-check'", r.stdout)
|
||||
self.assertNotIn("'proptest'", r.stdout)
|
||||
self.assertNotIn("cargo", r.stdout) # commands are not citations
|
||||
self.assertNotIn("pytest", r.stdout)
|
||||
|
||||
def test_valid_citations_and_other_sections_ignored(self):
|
||||
self.seed()
|
||||
body = "## Done means\nsee `not-checked-here`\n\n## Checks\n- `lean4`\n\n## Common false finishes\n`also-ignored`\n"
|
||||
self.put("r.md", dfile("r", body=body), self.ddir)
|
||||
self.assertEqual(self.sisi("verifiers", "lint").returncode, 0)
|
||||
|
||||
def test_warnings_do_not_fail(self):
|
||||
self.put("prove/short.md", vfile("short", extra="verified: memory\n"))
|
||||
self.put("prove/long.md", vfile("long", body=BODY_V + "line\n" * 90))
|
||||
r = self.sisi("verifiers", "lint")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertIn("lines (aim for 30-80)", r.stdout)
|
||||
self.assertIn("short.md: 30" if False else "verified: memory", r.stdout)
|
||||
self.assertIn("warning(s)", r.stdout)
|
||||
|
||||
def test_status_shows_library_size(self):
|
||||
self.put("prove/a.md", vfile("a", extra="verified: ran\n"))
|
||||
self.put("prove/b.md", vfile("b", extra="verified: memory\n"))
|
||||
self.put("prove/c.md", vfile("c", extra="verified: docs\n"))
|
||||
self.put("prove/d.md", vfile("d", extra="verified: docs\n"))
|
||||
self.put("r.md", dfile("r"), self.ddir)
|
||||
out = self.sisi("status").stdout
|
||||
self.assertIn("4 verifiers (verified ran 1, docs 2, memory 1), 1 recipes", out)
|
||||
|
||||
|
||||
class CoreMdTests(SisiCase):
|
||||
def test_help_lists_new_commands(self):
|
||||
out = self.sisi("help").stdout
|
||||
for w in ("verifiers show", "verifiers for", "verifiers doctor | lint", "sisi done", "done for"):
|
||||
self.assertIn(w, out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,72 @@
|
||||
import json, unittest
|
||||
from support import *
|
||||
|
||||
|
||||
class VerifyTests(SisiCase):
|
||||
def run_verify(self, c, *extra):
|
||||
self.write_contract(c)
|
||||
return self.sisi("verify", *extra)
|
||||
|
||||
def statuses(self):
|
||||
return {r["check"]: r["status"] for r in self.results()}
|
||||
|
||||
def test_statuses(self):
|
||||
c = contract([check("ok", "true"), check("bad", "exit 3"), check("slow", "sleep 5", timeout_s=0.3),
|
||||
check("out", "echo hello", stdout_contains="hello"), check("out2", "echo hi", stdout_contains="zzz"),
|
||||
check("code", "exit 3", exit=3), human("h5", 5), human("h6", 6)],
|
||||
[check("inv", "true")])
|
||||
r = self.run_verify(c)
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertEqual(self.statuses(), {"ok": "passed", "bad": "failed", "slow": "timeout", "out": "passed",
|
||||
"out2": "failed", "code": "passed", "h5": "awaiting-human",
|
||||
"h6": "awaiting-human", "inv": "passed"})
|
||||
self.assertIn("awaiting-human", r.stdout)
|
||||
|
||||
def test_all_good_exit_zero_and_record_fields(self):
|
||||
r = self.run_verify(contract([check("ok", "true"), human("h")]))
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
rec = self.results()[0]
|
||||
for k in ("contract", "project", "check", "kind", "rung", "status", "duration_s", "ts", "tool"):
|
||||
self.assertIn(k, rec)
|
||||
r = self.sisi("verify", env={"SISI_TOOL": "codex"})
|
||||
self.assertEqual(self.results()[-1]["tool"], "codex")
|
||||
|
||||
def test_invariant_failure_fails(self):
|
||||
r = self.run_verify(contract([check("ok", "true")], [check("inv", "false")]))
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertEqual(self.statuses()["inv"], "failed")
|
||||
|
||||
def test_runs_in_project_dir(self):
|
||||
r = self.run_verify(contract([check("pwd", "pwd", stdout_contains=self.proj)]))
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
|
||||
def test_floor_fails(self):
|
||||
r = self.run_verify(contract([check("m", "true", rung=3, kind="money")]))
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("floor", r.stdout)
|
||||
r = self.run_verify(contract([check("m", "true", rung=2, kind="money")]))
|
||||
self.assertEqual(r.returncode, 0)
|
||||
|
||||
def test_no_contract_exit_2(self):
|
||||
self.assertEqual(self.sisi("verify").returncode, 2)
|
||||
|
||||
def test_invalid_contract_exit_1(self):
|
||||
self.assertEqual(self.run_verify({"id": "x"}).returncode, 1)
|
||||
|
||||
def test_json_output(self):
|
||||
r = self.run_verify(contract([check("ok", "true")]), "--json")
|
||||
d = json.loads(r.stdout)
|
||||
self.assertTrue(d["ok"])
|
||||
self.assertEqual(d["results"][0]["status"], "passed")
|
||||
|
||||
def test_timeout_kills_process_group(self):
|
||||
marker = self.tmp + "/survivor"
|
||||
c = contract([check("slow", "(sleep 0.35; touch %s) & sleep 30" % marker, timeout_s=0.3)])
|
||||
self.assertEqual(self.run_verify(c).returncode, 1)
|
||||
import time; time.sleep(0.7)
|
||||
import os
|
||||
self.assertFalse(os.path.exists(marker))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,330 @@
|
||||
import json, os, random, shutil, unittest
|
||||
from support import *
|
||||
from sisi import paths, wiring
|
||||
|
||||
|
||||
def snapshot(root):
|
||||
snap = {}
|
||||
for dp, dns, fns in os.walk(root):
|
||||
for n in dns + fns:
|
||||
p = os.path.join(dp, n)
|
||||
rel = os.path.relpath(p, root)
|
||||
if os.path.islink(p):
|
||||
snap[rel] = ("l", os.readlink(p))
|
||||
elif os.path.isdir(p):
|
||||
snap[rel] = ("d",)
|
||||
else:
|
||||
with open(p, "rb") as f:
|
||||
snap[rel] = ("f", f.read())
|
||||
return snap
|
||||
|
||||
|
||||
class WiringBase(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
# A fake repo so skills linking can be tested without touching the real canon.
|
||||
self.repo = os.path.join(self.tmp, "repo")
|
||||
os.makedirs(os.path.join(self.repo, "canon", "skills", "alpha"))
|
||||
os.makedirs(os.path.join(self.repo, "bin"))
|
||||
for f in ("canon/core.md", "bin/sisi", "canon/skills/alpha/SKILL.md"):
|
||||
open(os.path.join(self.repo, f), "w").write("x\n")
|
||||
old = paths.REPO
|
||||
paths.REPO = self.repo
|
||||
self.addCleanup(setattr, paths, "REPO", old)
|
||||
os.makedirs(os.path.join(self.home, ".claude"))
|
||||
|
||||
def path(self, *p):
|
||||
return os.path.join(self.home, *p)
|
||||
|
||||
def put(self, rel, data):
|
||||
p = self.path(rel)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
return p
|
||||
|
||||
def state_snapshot(self):
|
||||
return snapshot(self.state)
|
||||
|
||||
|
||||
def rand_json(rng, depth=0):
|
||||
r = rng.random()
|
||||
if depth > 2 or r < 0.4:
|
||||
return rng.choice([None, True, 1, 2.5, 1.0, -7, "s", "unïcode ✓", "", 10**20])
|
||||
if r < 0.7:
|
||||
return [rand_json(rng, depth + 1) for _ in range(rng.randint(0, 3))]
|
||||
return {rng.choice("abcdef") + str(i): rand_json(rng, depth + 1) for i in range(rng.randint(0, 3))}
|
||||
|
||||
|
||||
def rand_hook_group(rng):
|
||||
return {"matcher": rng.choice(["*", "Bash", "startup"]), "hooks": [
|
||||
{"type": "command", "command": "echo %d" % rng.randint(0, 9), "timeout": rng.randint(1, 30)}
|
||||
for _ in range(rng.randint(0, 2))]}
|
||||
|
||||
|
||||
def rand_settings(rng):
|
||||
obj = {rng.choice("pqrs") + str(i): rand_json(rng) for i in range(rng.randint(0, 4))}
|
||||
r = rng.random()
|
||||
if r < 0.7:
|
||||
h = {}
|
||||
for ev in ("SessionStart", "Stop", "PreToolUse"):
|
||||
if rng.random() < 0.5:
|
||||
h[ev] = [rand_hook_group(rng) for _ in range(rng.randint(0, 2))]
|
||||
obj["hooks"] = h
|
||||
elif r < 0.8:
|
||||
obj["hooks"] = None if rng.random() < 0.5 else {}
|
||||
keys = list(obj.items())
|
||||
rng.shuffle(keys)
|
||||
obj = dict(keys)
|
||||
ind = rng.choice([None, 1, 2, 4, "\t"])
|
||||
text = json.dumps(obj, indent=ind, ensure_ascii=rng.random() < 0.5)
|
||||
if rng.random() < 0.5:
|
||||
text += "\n"
|
||||
if rng.random() < 0.2:
|
||||
text = "\n " + text + " \n\n"
|
||||
return text.encode("utf-8")
|
||||
|
||||
|
||||
def rand_md(rng):
|
||||
parts = []
|
||||
for _ in range(rng.randint(0, 6)):
|
||||
parts.append(rng.choice(["# Title", "", "some text ünï", "@~/other.md", " indented", "<!-- c -->", "x\r"]))
|
||||
sep = rng.choice(["\n", "\r\n"])
|
||||
text = sep.join(parts)
|
||||
if parts and rng.random() < 0.6:
|
||||
text += sep
|
||||
return text.encode("utf-8")
|
||||
|
||||
|
||||
class WiringPropertyTests(WiringBase):
|
||||
def run_case(self, rng):
|
||||
md = None if rng.random() < 0.2 else rand_md(rng)
|
||||
st = None if rng.random() < 0.2 else rand_settings(rng)
|
||||
if md is not None:
|
||||
self.put(".claude/CLAUDE.md", md)
|
||||
if st is not None:
|
||||
self.put(".claude/settings.json", st)
|
||||
r = rng.random()
|
||||
if r < 0.3:
|
||||
os.makedirs(self.path(".codex"))
|
||||
elif r < 0.5:
|
||||
self.put(".codex/AGENTS.md", b"mine\n")
|
||||
if rng.random() < 0.5:
|
||||
os.makedirs(self.path(".local", "bin"))
|
||||
if rng.random() < 0.3:
|
||||
os.makedirs(self.path(".agents", "skills"))
|
||||
if rng.random() < 0.3:
|
||||
os.makedirs(self.path(".config", "opencode"))
|
||||
before, state0 = snapshot(self.home), self.state_snapshot()
|
||||
|
||||
rc, _ = wiring.install()
|
||||
self.assertEqual(rc, 0)
|
||||
after1, st1 = snapshot(self.home), self.state_snapshot()
|
||||
wiring.install()
|
||||
self.assertEqual(snapshot(self.home), after1, "install not idempotent (home)")
|
||||
self.assertEqual(self.state_snapshot(), st1, "install not idempotent (state)")
|
||||
# everything else survives install
|
||||
if st is not None and st.strip():
|
||||
orig = json.loads(st)
|
||||
now = json.loads(self.path(".claude/settings.json") and open(self.path(".claude/settings.json"), "rb").read())
|
||||
wiring.remove_hooks(now)
|
||||
|
||||
def norm(d): # empty hook lists/objects may legitimately disappear in the structural path
|
||||
h = d.get("hooks")
|
||||
if isinstance(h, dict):
|
||||
d["hooks"] = {k: v for k, v in h.items() if v != []}
|
||||
if d.get("hooks") in (None, {}):
|
||||
d.pop("hooks", None)
|
||||
return d
|
||||
self.assertEqual(norm(now), norm(orig))
|
||||
if md is not None:
|
||||
self.assertTrue(open(self.path(".claude/CLAUDE.md"), "rb").read().startswith(md))
|
||||
self.assertEqual(wiring.doctor()[0]["status"], "wired")
|
||||
wiring.uninstall()
|
||||
self.assertEqual(snapshot(self.home), before, "uninstall did not restore the original")
|
||||
|
||||
def test_install_idempotent_and_uninstall_exact(self):
|
||||
for seed in [0, 1] + [random.randrange(2**32) for _ in range(ITERS + 1)]:
|
||||
rng = random.Random(seed)
|
||||
for n in range(10 * ITERS):
|
||||
with self.subTest(seed=seed, n=n):
|
||||
shutil.rmtree(self.home, ignore_errors=True)
|
||||
shutil.rmtree(self.state, ignore_errors=True)
|
||||
shutil.rmtree(self.data, ignore_errors=True)
|
||||
os.makedirs(self.path(".claude"))
|
||||
self.run_case(rng)
|
||||
|
||||
|
||||
class WiringTests(WiringBase):
|
||||
def test_existing_hooks_preserved_in_place(self):
|
||||
orig = {"hooks": {"SessionStart": [{"matcher": "*", "hooks": [{"type": "command", "command": "keep-me"}]}]}, "x": 1}
|
||||
self.put(".claude/settings.json", json.dumps(orig, indent=2).encode())
|
||||
wiring.install()
|
||||
d = json.load(open(self.path(".claude/settings.json")))
|
||||
self.assertEqual(d["hooks"]["SessionStart"][0], orig["hooks"]["SessionStart"][0])
|
||||
cmds = [h["command"] for g in d["hooks"]["SessionStart"] for h in g["hooks"]]
|
||||
self.assertTrue(any(c.endswith("sisi tick --tool claude-code") for c in cmds))
|
||||
self.assertTrue(any(h["command"].endswith("gate --tool claude-code") for g in d["hooks"]["Stop"] for h in g["hooks"]))
|
||||
self.assertEqual(d["x"], 1)
|
||||
|
||||
def test_import_line_and_marker(self):
|
||||
wiring.install()
|
||||
text = open(self.path(".claude/CLAUDE.md")).read()
|
||||
self.assertIn("<!-- sisi:begin -->", text)
|
||||
self.assertIn("@" + paths.generated(), text) # the generated rulebook, not the product's file
|
||||
self.assertNotIn("x\n", text.replace("@", "")) # canon text is not copied
|
||||
|
||||
def test_symlinks_and_conflicts(self):
|
||||
os.makedirs(self.path(".codex"))
|
||||
os.makedirs(self.path(".config", "opencode"))
|
||||
self.put(".config/opencode/AGENTS.md", b"mine\n")
|
||||
rc, notes = wiring.install()
|
||||
self.assertTrue(os.path.islink(self.path(".codex/AGENTS.md")))
|
||||
self.assertEqual(open(self.path(".config/opencode/AGENTS.md"), "rb").read(), b"mine\n")
|
||||
self.assertTrue(any("not touched" in n for n in notes))
|
||||
self.assertTrue(os.path.islink(self.path(".agents/skills/alpha")))
|
||||
self.assertTrue(os.path.islink(self.path(".local/bin/sisi")))
|
||||
st = {r["tool"]: r["status"] for r in wiring.doctor()}
|
||||
self.assertEqual((st["codex"], st["opencode"], st["muse"]), ("wired", "not wired", "not wired"))
|
||||
wiring.uninstall()
|
||||
self.assertEqual(open(self.path(".config/opencode/AGENTS.md"), "rb").read(), b"mine\n")
|
||||
self.assertFalse(os.path.lexists(self.path(".codex/AGENTS.md")))
|
||||
|
||||
def test_invalid_settings_left_alone(self):
|
||||
self.put(".claude/settings.json", b"{ not json")
|
||||
rc, notes = wiring.install()
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertEqual(open(self.path(".claude/settings.json"), "rb").read(), b"{ not json")
|
||||
|
||||
def test_backups_made_in_personal_data(self):
|
||||
self.put(".claude/CLAUDE.md", b"orig")
|
||||
self.put(".claude/settings.json", b"{}")
|
||||
wiring.install()
|
||||
names = os.listdir(os.path.join(self.data, "install", "backups"))
|
||||
self.assertEqual(len(names), 2)
|
||||
|
||||
def test_doctor_not_wired_then_wired(self):
|
||||
self.assertEqual(wiring.doctor()[0]["status"], "not wired")
|
||||
wiring.install()
|
||||
r = wiring.doctor()[0]
|
||||
self.assertEqual((r["status"], r["blocking_hook"]), ("wired", "yes (Stop)"))
|
||||
|
||||
def test_uninstall_after_user_edit_keeps_edit(self):
|
||||
self.put(".claude/settings.json", b'{"a": 1}\n')
|
||||
wiring.install()
|
||||
p = self.path(".claude/settings.json")
|
||||
d = json.load(open(p)); d["b"] = 2
|
||||
json.dump(d, open(p, "w"), indent=2)
|
||||
wiring.uninstall()
|
||||
self.assertEqual(json.load(open(p)), {"a": 1, "b": 2})
|
||||
|
||||
def test_cli_install_uses_overridden_home_only(self):
|
||||
r = self.sisi("install")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertTrue(os.path.islink(self.path(".local/bin/sisi")))
|
||||
r = self.sisi("doctor")
|
||||
self.assertIn("claude-code", r.stdout)
|
||||
self.assertEqual(self.sisi("uninstall").returncode, 0)
|
||||
|
||||
|
||||
class SubagentHookTests(WiringBase):
|
||||
def test_subagent_stop_registered_idempotent_and_removed(self):
|
||||
before = snapshot(self.home)
|
||||
wiring.install()
|
||||
d = json.load(open(self.path(".claude/settings.json")))
|
||||
cmds = [h["command"] for g in d["hooks"]["SubagentStop"] for h in g["hooks"]]
|
||||
self.assertEqual(len(cmds), 1)
|
||||
self.assertIn("gate --subagent --tool claude-code", cmds[0])
|
||||
self.assertEqual(len(d["hooks"]["Stop"]), 1) # the Stop hook is not duplicated by the subagent one
|
||||
snap = snapshot(self.home)
|
||||
wiring.install()
|
||||
self.assertEqual(snapshot(self.home), snap)
|
||||
wiring.uninstall()
|
||||
self.assertEqual(snapshot(self.home), before)
|
||||
|
||||
def test_doctor_notices_a_missing_subagent_hook(self):
|
||||
wiring.install()
|
||||
p = self.path(".claude/settings.json")
|
||||
d = json.load(open(p))
|
||||
del d["hooks"]["SubagentStop"]
|
||||
json.dump(d, open(p, "w"))
|
||||
r = wiring.doctor()[0]
|
||||
self.assertEqual(r["status"], "not wired")
|
||||
self.assertIn("subagent hook", r["detail"])
|
||||
self.assertIn("subagent hook", wiring.quick_problem())
|
||||
wiring.install() # repairs it
|
||||
self.assertEqual(wiring.doctor()[0]["status"], "wired")
|
||||
|
||||
|
||||
class WiringSafetyTests(WiringBase):
|
||||
def test_symlinked_settings_and_claude_md_written_through(self):
|
||||
real = os.path.join(self.tmp, "dotfiles")
|
||||
os.makedirs(real)
|
||||
for name, data in (("settings.json", b'{\n "a": 1\n}\n'), ("CLAUDE.md", b"mine")):
|
||||
with open(os.path.join(real, name), "wb") as f:
|
||||
f.write(data)
|
||||
os.symlink(os.path.join(real, name), self.path(".claude", name))
|
||||
wiring.install()
|
||||
for name in ("settings.json", "CLAUDE.md"):
|
||||
self.assertTrue(os.path.islink(self.path(".claude", name)), name + " link was replaced")
|
||||
self.assertIn(b"sisi:begin", open(os.path.join(real, "CLAUDE.md"), "rb").read())
|
||||
self.assertIn(b"sisi", open(os.path.join(real, "settings.json"), "rb").read())
|
||||
wiring.uninstall()
|
||||
for name in ("settings.json", "CLAUDE.md"):
|
||||
self.assertTrue(os.path.islink(self.path(".claude", name)))
|
||||
self.assertEqual(open(os.path.join(real, "CLAUDE.md"), "rb").read(), b"mine")
|
||||
self.assertEqual(open(os.path.join(real, "settings.json"), "rb").read(), b'{\n "a": 1\n}\n')
|
||||
|
||||
def test_dangling_symlink_refused_and_nothing_changed(self):
|
||||
os.symlink(os.path.join(self.tmp, "nowhere"), self.path(".claude", "settings.json"))
|
||||
before = snapshot(self.home)
|
||||
rc, notes = wiring.install()
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertEqual(snapshot(self.home), before)
|
||||
|
||||
def test_invalid_settings_changes_nothing_at_all(self):
|
||||
os.makedirs(self.path(".codex"))
|
||||
self.put(".claude/settings.json", b"{ not json")
|
||||
self.put(".claude/CLAUDE.md", b"keep\n")
|
||||
before, st = snapshot(self.home), self.state_snapshot()
|
||||
r = self.sisi("install")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("nothing was changed", r.stdout)
|
||||
self.assertEqual(snapshot(self.home), before) # no CLAUDE.md edit, no codex link, no ~/.local/bin
|
||||
self.assertEqual(self.state_snapshot(), st) # no manifest or backups
|
||||
|
||||
def test_unwritable_target_changes_nothing(self):
|
||||
self.put(".claude/settings.json", b"{}\n")
|
||||
os.chmod(self.path(".claude/settings.json"), 0o444)
|
||||
os.chmod(self.path(".claude"), 0o555)
|
||||
self.addCleanup(os.chmod, self.path(".claude"), 0o755)
|
||||
if os.access(self.path(".claude/settings.json"), os.W_OK):
|
||||
self.skipTest("running as a user that ignores permissions")
|
||||
before = snapshot(self.home)
|
||||
rc, _ = wiring.install()
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertEqual(snapshot(self.home), before)
|
||||
|
||||
def test_hook_command_path_with_spaces(self):
|
||||
repo = os.path.join(self.tmp, "my repo", "sisi")
|
||||
shutil.copytree(REPO, repo, ignore=shutil.ignore_patterns(".git", "__pycache__", "tests"))
|
||||
paths.REPO = repo
|
||||
wiring.install()
|
||||
d = json.load(open(self.path(".claude/settings.json")))
|
||||
cmd = d["hooks"]["Stop"][0]["hooks"][0]["command"]
|
||||
self.assertIn("'", cmd) # quoted
|
||||
snap = snapshot(self.home)
|
||||
wiring.install() # still recognised as ours: no duplicate entries
|
||||
self.assertEqual(snapshot(self.home), snap)
|
||||
self.assertEqual(wiring.doctor()[0]["status"], "wired")
|
||||
# the command string really runs under a shell
|
||||
import subprocess
|
||||
r = subprocess.run(cmd, shell=True, input=json.dumps({"session_id": "s", "cwd": self.proj}),
|
||||
capture_output=True, text=True, env=dict(os.environ))
|
||||
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
||||
wiring.uninstall()
|
||||
self.assertFalse(os.path.exists(self.path(".claude/settings.json"))) # it did not exist before install
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user