Files
sisi/tests/test_personal.py
T
swaitsandClaude Fable 5.2 7a097f94c7
ci / tests (macos-latest, python 3.10) (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.10) (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
sisi 0.2.0: the self-improvement loop, and every major harness
Lessons take effect when recorded, are offered to later agents starting the
same kind of work, are counted as listed and read, and are strengthened when
the mistake recurs: note, rule, enforced check. `sisi cycle` consolidates
them from normal use with no scheduler; `sisi improve` reports the effect.

Wiring for Codex, Gemini CLI, Copilot CLI, Qwen Code, Pi, Cursor, OpenCode
and rulebook loading for nine more tools, with a dry run, preflight checks
and a tested uninstall guarantee. Time to delivery is measured per turn.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 00:06:34 -07:00

755 lines
43 KiB
Python

"""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",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--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",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--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",
"--when", "tests, pytest, failing first, regression, test quality, red green",
"--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()