Learning loop tests; remove tests of deleted behaviour

This commit is contained in:
swaits committed 2026-11-23 11:04:32 -07:00
1 parent 553b397ad0
commit ee6fc292d8
12 files changed
+341 -4159

No files matched your search

+10 -4
View File
@@ -256,8 +256,14 @@ def validate_doc(doc, rows):
if rec.get("proposed", {}).get("mechanism") == "tool":
raise CycleError("learning %s is a tool change to sisi itself; it goes to the backlog "
"and the contribution export, not a cycle mechanism" % rec["id"])
if kind == "command-check" and not (a.get("cmd") or "").strip():
raise CycleError("command-check for %s needs a cmd" % rec["id"])
if kind == "command-check":
if not (a.get("cmd") or "").strip():
raise CycleError("command-check for %s needs a cmd" % rec["id"])
if not _consequential(a, rec): # replay now, so a failed replay refuses before anything applies
a["_replay"] = replay_validate(rec, a)
if a["_replay"][0] == "failed":
raise CycleError("replay validation failed for %s: %s; nothing is applied"
% (rec["id"], a["_replay"][1]))
if kind == "contract-requirement" and not (a.get("require_kind") and a.get("when")):
raise CycleError("contract-requirement for %s needs when and require_kind" % rec["id"])
if kind == "rule-text":
@@ -298,9 +304,9 @@ def _apply_one(a, rec, rows):
kind = a.get("mechanism_kind")
ref, result, detail = None, "unvalidated", "no replay for this mechanism kind"
if kind == "command-check":
result, detail = replay_validate(rec, a)
result, detail = a.get("_replay") or replay_validate(rec, a)
if result == "failed":
raise CycleError("replay validation failed for %s: %s; nothing further is applied" % (lid, detail))
raise CycleError("replay validation failed for %s: %s" % (lid, detail))
d = _overlay_json("enforced.json", "checks")
d.setdefault("checks", []).append(
{"type": "command", "lesson": lid, "cmd": a["cmd"],
+4 -4
View File
@@ -33,8 +33,8 @@ def trace_lines(kind, entry_id):
def check_budgets(rendered=None):
"""(ok, message) for the rendered rulebook against the overlay budgets."""
rendered = overlay.render() if rendered is None else rendered
s = overlay.size(rendered)
if s["lines"] > overlay.MAX_LINES or s["chars"] > overlay.MAX_CHARS:
lines, chars = overlay.size(rendered)
if lines > overlay.MAX_LINES or chars > overlay.MAX_CHARS:
return False, ("rulebook over budget: %d lines (max %d), %d chars (max %d)"
% (s["lines"], overlay.MAX_LINES, s["chars"], overlay.MAX_CHARS))
return True, "%d lines, %d chars, inside budget" % (s["lines"], s["chars"])
% (lines, overlay.MAX_LINES, chars, overlay.MAX_CHARS))
return True, "%d lines, %d chars, inside budget" % (lines, chars)
-373
View File
@@ -1,373 +0,0 @@
"""Short lines, topics, the human digest, and the cycle writing them."""
import json, os, sqlite3, unittest
from support import *
from sisi import cycle, paths, retro, store
from test_verifiers import LibCase, vfile, dfile
WHEN = "parser, fuzzing, codec, hostile input, generated input, parsing"
def fields(**kw):
f = dict(aim="verified", change_kind="rule", target=None,
moment="the parser server waited 90 seconds in step 4 of the nightly job",
cause="no readiness probe existed before the browser step",
change="Prefer a readiness probe over a fixed sleep when waiting for parser servers to answer",
when=WHEN)
f.update(kw)
return f
class ShortCase(LibCase):
def setUp(self):
super().setUp()
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 mk(self, **kw):
con = retro.connect()
try:
lid = retro.new_lesson(con, fields(**kw), self.proj, None)
con.commit()
return lid
finally:
con.close()
def lesson(self, lid):
con = retro.connect()
try:
return dict(con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone())
finally:
con.close()
def set_lesson(self, lid, **kw):
con = retro.connect()
try:
for k, v in kw.items():
con.execute("UPDATE lessons SET %s=? WHERE id=?" % k, (v, lid))
con.commit()
finally:
con.close()
def cycle_doc(self, notes=None, **parts):
doc = {"version": 1, "base": cycle.base_version(), "summary": "test cycle"}
if notes is not None:
notes = list(notes)
have = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-scope"}
for e in list(notes):
if isinstance(e, dict) and isinstance(e.get("lesson"), int) and e["lesson"] not in have:
notes.append({"lesson": e["lesson"], "action": "set-scope", "scope": "core"})
have.add(e["lesson"])
# every active lesson lacking a pattern needs a set-pattern too
try:
_con = retro.connect()
try:
_prows = [dict(r) for r in _con.execute(
"SELECT id, pattern_id, scope FROM lessons WHERE status IN ('open','applied')")]
finally:
_con.close()
_have_p = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-pattern"}
_exempt = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") in ("retire", "withdraw", "merge")}
for r in _prows:
if not r.get("pattern_id") and r["id"] not in _have_p and r["id"] not in _exempt and r.get("scope") != "project":
notes.append({"lesson": r["id"], "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"})
except Exception:
pass
doc["notes"] = notes
doc.update(parts)
# A cycle file must also answer for every document the brief lists for whole-document
# review: mark them reviewed here (tests of rewriting itself live in test_documents).
try:
from sisi import documents as _docs
_con = retro.connect()
try:
_have = {e.get("doc") for e in doc.get("documents") or [] if isinstance(e, dict)}
_rev = [{"doc": d["doc"], "action": "reviewed", "reason": "test helper: structure left as it is"}
for d in _docs.required_documents(_con) if d["doc"] not in _have]
finally:
_con.close()
if _rev:
doc["documents"] = list(doc.get("documents") or []) + _rev
except Exception:
pass
p = os.path.join(self.tmp, "cycle.json")
with open(p, "w") as f:
json.dump(doc, f)
return p
def cycle_path(self, doc):
p = os.path.join(self.tmp, "cycle-%s.json" % id(doc))
with open(p, "w") as f:
json.dump(doc, f)
return p
class RetroShortTests(ShortCase):
def retro_cli(self, **over):
from test_retro import argv as retro_argv, GOOD
f = dict(GOOD)
f.update(over)
return self.sisi("retro", "--new", *retro_argv(f))
def test_retro_stores_short_and_topic(self):
r = self.retro_cli(short="Add fuzzing to the parser recipe checks.", topic="testing")
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
rows = [tuple(r) for r in con.execute("SELECT short, topic FROM lessons")]
con.close()
self.assertEqual(rows[0], ("Add fuzzing to the parser recipe checks.", "testing"))
def test_retro_without_short_says_next_round_will_write_it(self):
r = self.retro_cli()
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("next learning round will write", r.stdout)
def test_retro_limits_are_enforced(self):
long_short = "word " * 40 + "end."
self.assertEqual(self.retro_cli(short=long_short.strip()).returncode, 2)
self.assertEqual(self.retro_cli(short="Do the thing...").returncode, 2)
self.assertEqual(self.retro_cli(short="Do the thing\u2026").returncode, 2)
self.assertEqual(self.retro_cli(topic="Testing Stuff").returncode, 2)
self.assertEqual(self.retro_cli(topic="one two three four").returncode, 2)
self.assertEqual(self.retro_cli(topic="a" * 31).returncode, 2)
self.assertEqual(self.retro_cli(short="line one\nline two is long enough here.").returncode, 2)
con = retro.connect()
try:
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0)
finally:
con.close()
class HeadingTests(ShortCase):
def test_word_boundary_cut_never_mid_word(self):
text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda"
cut = retro.word_cut(text, 30)
self.assertTrue(cut.endswith("\u2026"), cut)
self.assertTrue(text.startswith(cut[:-1]), cut)
self.assertEqual(text[len(cut[:-1])], " ")
self.assertLessEqual(len(cut), 30)
def test_loose_heading_uses_short_when_present(self):
lid = self.mk(short="Use a readiness probe, not a sleep.", topic="testing")
row = self.lesson(lid)
self.assertIn("Use a readiness probe, not a sleep.", retro.loose_heading(row))
def test_loose_heading_without_short_is_word_cut(self):
lid = self.mk(change="Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma")
h = retro.loose_heading(self.lesson(lid))
self.assertTrue(h.endswith("\u2026"), h)
body = h.split(": ", 1)[1][:-1]
self.assertTrue(self.lesson(lid)["change"].startswith(body))
def test_lessons_list_and_backlog_use_short(self):
lid = self.mk(short="Use a readiness probe, not a sleep.", topic="testing")
out = self.sisi("lessons").stdout
self.assertIn("Use a readiness probe, not a sleep.", out)
tool = self.mk(change_kind="tool", change="Make sisi cycle print much faster for very large lesson stores",
short="Make sisi cycle faster.", topic="sisi itself")
bout = self.sisi("backlog").stdout
self.assertIn("Make sisi cycle faster.", bout)
class DigestTests(ShortCase):
def seed_digest(self):
a = self.mk(short="Use a readiness probe, not a sleep.", topic="testing")
self.set_lesson(a, folded_into="rule:know-done", effect="learned-note", status="applied")
b = self.mk(change_kind="verifier", target="fuzz",
change="Seed the fuzz corpus from golden parser files before fuzzing anything",
moment="fuzz seeds were missing at step 5 of the job",
short="Seed the fuzz corpus from golden files.", topic="testing")
self.set_lesson(b, count=3)
c = self.mk(change="Ask the person before guessing when the request is unclear about success",
moment="a guess about success at step 2 was wrong",
short="Ask before guessing what success means.", topic="asking questions")
d = self.mk(change_kind="tool", change="Make sisi lessons digest group lessons by topic for the owner",
moment="the owner asked for a digest at step 1",
short="Group the digest by topic.", topic="releases")
e = self.mk(change="Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega extra words here",
moment="a long lesson moment at step 9")
f = self.mk(short="Retired short line should hide.", topic="testing")
self.set_lesson(f, status="retired", folded_into="rule:know-done")
return a, b, c, d, e, f
def test_digest_grouping_plain_states_and_order(self):
a, b, c, d, e, f = self.seed_digest()
out = self.sisi("lessons", "digest").stdout
lines = out.splitlines()
self.assertTrue(lines[0].count(".") >= 1 and "lesson" in lines[0], lines[0])
self.assertIn("5 lessons", lines[0])
# topics by size: testing (2) before singletons, Not yet summarized last topical heading
self.assertLess(out.index("## testing"), out.index("## asking questions"))
self.assertLess(out.index("## asking questions"), out.index("## Not yet summarized"))
self.assertIn("Use a readiness probe, not a sleep.", out)
self.assertIn("in the rulebook", out)
self.assertIn("attached to Fuzz work", out)
self.assertIn("loose note", out)
self.assertIn("change to sisi itself, not built yet", out)
self.assertIn("seen 3 times", out)
# seen only when > 1: lesson a has count 1, its line must not say seen
a_line = [l for l in lines if "lesson %d" % a in l][0]
self.assertNotIn("seen", a_line)
self.assertNotIn("#%d" % f, out) # retired left out by default
self.assertNotIn("Retired short line", out)
self.assertIn("lesson %d" % e, out) # every line shows its ID
last = [l for l in lines if l.strip()][-1]
self.assertIn("sisi lessons show", last)
low = out.lower()
for bad in ("strength", "field-note", "aim:"):
self.assertNotIn(bad, low)
def test_digest_all_includes_retired_and_not_yet_is_word_cut(self):
a, b, c, d, e, f = self.seed_digest()
out = self.sisi("lessons", "digest", "--all").stdout
self.assertIn("Retired short line should hide.", out)
e_line = [l for l in out.splitlines() if "lesson %d" % e in l][0]
self.assertTrue(e_line.rstrip().endswith(("\u2026", ")")) or "\u2026" in e_line, e_line)
def test_digest_shows_what_you_said_first(self):
self.seed_digest()
self.assertEqual(self.sisi("learn", "--scope", "everywhere", "Always", "show", "the", "options.").returncode, 0)
out = self.sisi("lessons", "digest").stdout
self.assertIn("## What you said", out)
self.assertIn("Always show the options.", out)
self.assertLess(out.index("## What you said"), out.index("## testing"))
class CycleShortTests(ShortCase):
def test_brief_lists_lacking_topics_and_limits(self):
have = self.mk(short="Use a readiness probe, not a sleep.", topic="testing")
need = self.mk(change="Widget caching lesson about parser readiness probes for servers",
moment="widget wait at step 2")
out = cycle.brief_text()
self.assertIn("short line", out)
self.assertIn("#%d" % need, out)
self.assertIn("testing", out) # topics already in use
self.assertIn("140", out)
self.assertIn("30", out)
self.assertIn("set-short", out)
def test_check_refuses_file_omitting_set_short_naming_lesson(self):
need = self.mk()
doc = self.cycle_doc(notes=[{"lesson": need, "action": "keep"}])
r = self.sisi("cycle", "check", doc)
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("set-short", r.stdout)
self.assertIn(str(need), r.stdout)
good = self.cycle_doc(notes=[{"lesson": need, "action": "keep"},
{"lesson": need, "action": "set-short",
"short": "Use a readiness probe, not a sleep.", "topic": "testing"}])
r2 = self.sisi("cycle", "check", good)
self.assertEqual(r2.returncode, 0, r2.stdout + r2.stderr)
def test_set_short_combined_and_limits_in_cycle(self):
lid = self.mk()
bad = self.cycle_doc(notes=[{"lesson": lid, "action": "set-short",
"short": "word " * 40, "topic": "testing"}])
r = self.sisi("cycle", "check", bad)
self.assertEqual(r.returncode, 1, r.stdout)
good = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"},
{"lesson": lid, "action": "set-short",
"short": "Use a readiness probe, not a sleep.", "topic": "testing"}])
self.assertEqual(self.sisi("cycle", "apply", good).returncode, 0)
l = self.lesson(lid)
self.assertEqual((l["short"], l["topic"]), ("Use a readiness probe, not a sleep.", "testing"))
def test_cycle_now_prints_brief_when_not_due(self):
self.assertEqual(self.sisi("cycle", "due").returncode, 1)
r = self.sisi("cycle", "--now")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("Base version", r.stdout)
class BulletTests(ShortCase):
def test_field_note_bullet_uses_short_at_creation(self):
lid = self.mk(change_kind="verifier", target="fuzz",
change="Seed the fuzz corpus from golden parser files before fuzzing anything",
moment="fuzz seeds were missing at step 5",
short="Seed the fuzz corpus from golden files.", topic="testing")
text = open(os.path.join(self.notes, "fuzz.md")).read()
self.assertIn("Seed the fuzz corpus from golden files.", text)
self.assertIn("seen 1 times; lesson %d; full text: sisi lessons show %d" % (lid, lid), text)
def test_bullet_rewrite_and_exact_revert(self):
lid = self.mk(change_kind="verifier", target="fuzz",
change="Seed the fuzz corpus from golden parser files before fuzzing anything",
moment="fuzz seeds were missing at step 5")
p = os.path.join(self.notes, "fuzz.md")
before = open(p, "rb").read()
self.assertIn(b"Seed the fuzz corpus from golden parser files", before)
doc = self.cycle_doc(notes=[{"lesson": lid, "action": "set-short",
"short": "Seed the fuzz corpus from golden files.", "topic": "testing"}])
r = self.sisi("cycle", "apply", doc)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
after = open(p, "rb").read()
self.assertNotEqual(after, before)
self.assertIn(b"Seed the fuzz corpus from golden files.", after)
self.assertIn(("full text: sisi lessons show %d" % lid).encode(), after)
self.assertNotIn(b"Seed the fuzz corpus from golden parser files before fuzzing", after)
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertEqual(open(p, "rb").read(), before) # exact bytes restored
l = self.lesson(lid)
self.assertIsNone(l["short"])
self.assertIsNone(l["topic"])
def test_explicit_note_bullet_is_not_rewritten(self):
lid = self.mk(change="Parser recipes need a readiness probe before any server work begins",
moment="server wait at step 3")
doc = self.cycle_doc(notes=[
{"lesson": lid, "action": "fold-into-entry", "into": "parser-or-codec",
"note": "Explicit split note about readiness probes"},
{"lesson": lid, "action": "set-short",
"short": "Use a readiness probe, not a sleep.", "topic": "testing"}])
self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0)
text = open(os.path.join(self.notes, "parser-or-codec.md")).read()
self.assertIn("Explicit split note about readiness probes", text)
# a later set-short in a new cycle also leaves the explicit bullet alone
self.set_lesson(lid, short=None, topic=None)
# restore base: the previous cycle changed the lesson, so clear via a fresh cycle file
doc2 = {"version": 1, "base": cycle.base_version(), "summary": "second",
"notes": [{"lesson": lid, "action": "set-short",
"short": "Prefer probes over sleeps.", "topic": "testing"}],
"documents": [{"doc": "recipe:parser-or-codec", "action": "reviewed",
"reason": "this round only rewrites the short line"}]}
p2 = self.cycle_path(doc2)
r = self.sisi("cycle", "apply", p2)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
text2 = open(os.path.join(self.notes, "parser-or-codec.md")).read()
self.assertIn("Explicit split note about readiness probes", text2)
self.assertNotIn("Prefer probes over sleeps.", text2)
class MigrationTests(ShortCase):
def test_old_store_without_fields_still_loads(self):
old = os.path.join(self.tmp, "old.db")
con = sqlite3.connect(old)
con.executescript("""
CREATE TABLE lessons(id INTEGER PRIMARY KEY, created TEXT, aim TEXT, change_kind TEXT, target TEXT,
moment TEXT, cause TEXT, change TEXT, status TEXT DEFAULT 'open', count INTEGER DEFAULT 1, last_seen TEXT);
CREATE TABLE occurrences(id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT, tool TEXT,
cwd TEXT, repo TEXT, moment TEXT, fp TEXT);
""")
con.execute("INSERT INTO lessons VALUES (1,'2020-01-01T00:00:00Z','speed','verifier','fuzz','m','c',"
"'Seed the fuzz corpus from golden parser files','open',2,'2020-01-02T00:00:00Z')")
con.commit(); con.close()
import shutil
os.makedirs(os.path.dirname(retro.db_path()), exist_ok=True)
shutil.copy(old, retro.db_path())
con = retro.connect()
try:
row = dict(con.execute("SELECT * FROM lessons WHERE id=1").fetchone())
cols = [r[1] for r in con.execute("PRAGMA table_info(lessons)")]
finally:
con.close()
self.assertIn("short", cols)
self.assertIn("topic", cols)
self.assertEqual(row["change"], "Seed the fuzz corpus from golden parser files")
self.assertIsNone(row["short"])
out = self.sisi("lessons", "digest").stdout
self.assertIn("Seed the fuzz corpus", out)
if __name__ == "__main__":
unittest.main()
-289
View File
@@ -1,289 +0,0 @@
"""Whole-document edits in a learning round: folded lessons become part of the document's own
text, every lesson stays traceable to the exact fragment that carries it, structure is checked
mechanically, and a stale personal copy is listed for re-merge instead of silently kept."""
import json, os, unittest
from support import *
from sisi import cycle, documents, overlay, paths, retro
from test_verifiers import LibCase, vfile, dfile
WHEN = "parser, codec, parse, decode, round trip, fuzzing, tabular data"
RECIPE_BODY = """## Done means
- The parser accepts every valid input in the corpus.
- Invalid input is refused with a clear error.
## Checks
- Round trip: `proptest` (many-inputs), rung 2.
## Common false finishes
- Only the examples in the report were tried.
"""
REWRITE = """---
id: parser-or-codec
title: Parser or codec work
applies_to: parsing work
---
## Done means
- The parser accepts every valid input in the corpus.
- Invalid input is refused with a clear error.
- Seed the corpus from the golden files before fuzzing.
- Try truncated input at every length.
## Checks
- Round trip: `proptest` (many-inputs), rung 2.
## Common false finishes
- Only the examples in the report were tried.
"""
class DocCase(LibCase):
def setUp(self):
super().setUp()
self.put("prove/fuzz.md", vfile("fuzz"))
self.put("many-inputs/proptest.md", vfile("proptest", "many-inputs", 2))
self.put("parser-or-codec.md",
dfile("parser-or-codec", title="Parser or codec work", applies="parsing work",
body="\n" + RECIPE_BODY), self.ddir)
self.notes = os.path.join(self.data, "notes")
def mk(self, change, **kw):
f = dict(aim="verified", change_kind="recipe", target="parser-or-codec",
moment="the parser accepted a truncated file in the nightly job",
cause="no truncated-input case existed", change=change, when=WHEN,
scope="core", short="Seed the corpus from golden files.", topic="parsing", pattern="Reach for the familiar tool instead of the check that fits the claim")
f.update(kw)
con = retro.connect()
try:
lid = retro.new_lesson(con, f, self.proj, None)
con.commit()
return lid
finally:
con.close()
def cycle_file(self, **parts):
doc = {"version": 1, "base": cycle.base_version(), "summary": "document round"}
doc.update(parts)
p = os.path.join(self.tmp, "cycle.json")
with open(p, "w") as fh:
json.dump(doc, fh)
return p
def tree_bytes(self):
out = {}
for root in (paths.overlay_dir(), paths.notes_dir()):
for dp, dns, fns in os.walk(root):
for n in fns:
p = os.path.join(dp, n)
with open(p, "rb") as fh:
out[p] = fh.read()
return out
class BriefAndCheckTests(DocCase):
def test_brief_lists_recipe_with_field_notes_in_full(self):
a = self.mk("Seed the corpus from the golden files before fuzzing parsers")
b = self.mk("Try truncated input at every length when testing a parser",
short="Try truncated input at every length.")
brief = cycle.brief_text()
self.assertIn("recipe:parser-or-codec", brief)
self.assertIn("whole-document", brief.lower())
self.assertIn("Seed the corpus from the golden files", brief) # the folded lesson, universal part
self.assertIn("one instruction per bullet", brief.lower()) # the editorial standard
self.assertIn(RECIPE_BODY.splitlines()[1], brief) # the document's current text
def test_check_refuses_a_file_that_skips_a_listed_document(self):
self.mk("Seed the corpus from the golden files before fuzzing parsers")
r = self.sisi("cycle", "check", self.cycle_file())
self.assertEqual(r.returncode, 1)
self.assertIn("recipe:parser-or-codec", r.stdout)
self.assertIn("documents", r.stdout)
def test_reviewed_entry_satisfies_the_round(self):
self.mk("Seed the corpus from the golden files before fuzzing parsers")
p = self.cycle_file(documents=[{"doc": "recipe:parser-or-codec", "action": "reviewed",
"reason": "two short sections, one instruction per bullet, nothing duplicated"}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 0, r.stdout)
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
# still shown as a field note until a rewrite integrates it
self.assertIn("Seed the corpus", retro.notes_for("parser-or-codec"))
class RewriteTests(DocCase):
def _two_lessons(self):
a = self.mk("Seed the corpus from the golden files before fuzzing parsers")
b = self.mk("Try truncated input at every length when testing a parser",
short="Try truncated input at every length.")
return a, b
def test_rewrite_integrates_lessons_and_traces_them(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("done", "parser-or-codec").stdout
self.assertIn("Seed the corpus from the golden files before fuzzing.", out)
self.assertNotIn("Field notes from earlier agents", out) # integrated, not appended
self.assertEqual(retro.notes_for("parser-or-codec"), "")
show = self.sisi("lessons", "show", str(a)).stdout
self.assertIn("recipe:parser-or-codec", show)
self.assertIn("Seed the corpus from the golden files before fuzzing.", show)
traced = self.sisi("done", "parser-or-codec", "--trace").stdout
self.assertIn("#%d" % a, traced)
self.assertIn("Seed the corpus", traced)
def test_rewrite_missing_one_fragment_is_refused(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("lesson #%d" % b, r.stdout)
def test_fragment_must_occur_in_the_new_text(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "This sentence is nowhere in the document."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("fragment", r.stdout)
def test_dated_journal_bullet_is_refused(self):
a, b = self._two_lessons()
bad = REWRITE + "- 2024-01-02: an old note (aim: verified; seen 1 times; lesson %d)\n" % a
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": bad,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("dated", r.stdout.lower())
def test_lint_failing_recipe_is_refused(self):
a, b = self._two_lessons()
bad = REWRITE.replace("## Checks", "## Things")
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": bad,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
def test_revert_restores_documents_and_notes_byte_for_byte(self):
a, b = self._two_lessons()
before = self.tree_bytes()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertNotEqual(self.tree_bytes(), before)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
self.assertEqual(self.tree_bytes(), before)
def test_product_change_lists_the_document_for_remerge(self):
a, b = self._two_lessons()
p = self.cycle_file(documents=[{
"doc": "recipe:parser-or-codec", "action": "rewrite", "text": REWRITE,
"trace": [{"lesson": a, "fragment": "Seed the corpus from the golden files before fuzzing."},
{"lesson": b, "fragment": "Try truncated input at every length."}]}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertNotIn("needs a re-merge", cycle.brief_text())
prod = os.path.join(self.ddir, "parser-or-codec.md")
with open(prod) as fh:
text = fh.read()
with open(prod, "w") as fh:
fh.write(text.replace("Invalid input is refused", "Bad input is refused"))
brief = cycle.brief_text()
self.assertIn("Document recipe:parser-or-codec", brief)
self.assertIn("needs a re-merge", brief)
class RulebookTests(DocCase):
def test_rule_order_applies_and_numbers_follow_it(self):
_pre, rules = overlay.effective()
ids = [r["id"] for r in rules]
new_order = [ids[1], ids[0]] + ids[2:]
p = self.cycle_file(rule_order=new_order)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout)
_pre2, rules2 = overlay.effective()
self.assertEqual([x["id"] for x in rules2], new_order)
out = self.sisi("rule", "1").stdout
self.assertIn("{#%s}" % new_order[0], out)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
_pre3, rules3 = overlay.effective()
self.assertEqual([x["id"] for x in rules3], ids)
def _rulebook_text(self, drop=None, extra=None):
pre, rules = overlay.effective()
parts = [pre] if pre.strip() else []
for r in rules:
if r["id"] == drop:
continue
body = r["body"] + (("\n\n" + extra) if extra and r["id"] == "know-done" else "")
parts.append("## %s {#%s}\n\n%s" % (r["title"], r["id"], body))
return "\n\n".join(parts) + "\n"
def test_rulebook_rewrite_traces_a_rule_lesson(self):
lid = self.mk("Name the check that decides done before starting the work",
change_kind="rule", target=None, short="Name the deciding check first.")
p = self.cycle_file(notes=[{"lesson": lid, "action": "fold-into-rule", "into": "know-done"}])
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
frag = "Name the check that decides done before starting."
bad = self.cycle_file(documents=[{"doc": "rulebook", "action": "rewrite",
"text": self._rulebook_text(drop="deliver-quickly", extra=frag),
"shortens": "know-done: tightened while integrating",
"trace": [{"lesson": lid, "fragment": frag}]}])
r = self.sisi("cycle", "check", bad)
self.assertEqual(r.returncode, 1)
self.assertIn("deliver-quickly", r.stdout)
good = self.cycle_file(documents=[{"doc": "rulebook", "action": "rewrite",
"text": self._rulebook_text(extra=frag),
"shortens": "know-done: tightened while integrating",
"trace": [{"lesson": lid, "fragment": frag}]}])
r = self.sisi("cycle", "apply", good)
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("rule", "know-done").stdout
self.assertIn(frag, out)
self.assertIn("carried in rulebook", out)
self.assertIn("lives : in rulebook", self.sisi("lessons", "show", str(lid)).stdout)
self.assertEqual(self.sisi("cycle", "revert").returncode, 0)
self.assertNotIn(frag, self.sisi("rule", "know-done").stdout)
def test_rule_order_must_name_every_rule_once(self):
_pre, rules = overlay.effective()
p = self.cycle_file(rule_order=[rules[0]["id"]])
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1)
self.assertIn("rule_order", r.stdout)
class StructureTests(unittest.TestCase):
def test_existing_library_passes_the_structure_checks(self):
bad = []
for kind, root in (("recipe", os.path.join(REPO, "done")),
("verifier", os.path.join(REPO, "verifiers"))):
for dp, dns, fns in os.walk(root):
for n in sorted(fns):
if not n.endswith(".md"):
continue
p = os.path.join(dp, n)
with open(p, encoding="utf-8") as fh:
text = fh.read()
for prob in documents.structure_problems(kind, text, n[:-3]):
bad.append("%s: %s" % (p, prob))
self.assertEqual(bad, [])
if __name__ == "__main__":
unittest.main()
-492
View File
@@ -1,492 +0,0 @@
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()
File diff suppressed because it is too large. Load diff
+327
View File
@@ -0,0 +1,327 @@
"""The learning loop, rebuilt. Docstrings cite docs/spec/requirements.json ids."""
import json, os, subprocess
from support import SisiCase
def _contract(case, uid="u1", proj=None):
d = proj or case.proj
os.makedirs(os.path.join(d, ".sisi"), exist_ok=True)
with open(os.path.join(d, ".sisi", "contract.json"), "w") as f:
json.dump({"id": uid, "goal": "g", "checks": []}, f)
PROMOTE = ("retro", "--finding", "f.txt held the word bug and shipped without a content check",
"--cause", "no check asserted file contents before delivery",
"--impact", "correctness", "--disposition", "promote",
"--change", "grep for fixed in f.txt must pass", "--mechanism", "verification",
"--expect", "bug text is caught", "--validate", "replay the grep before and after")
class LearningLoop(SisiCase):
def retro(self, *a, **kw):
return self.sisi("retro", *a, **kw)
def rows(self):
from sisi import learning as L
return L.load_learnings()
def test_generic_finding_refused(self):
"""R-11.1-9, R-11.1-13: generic findings are refused, not invented."""
_contract(self)
r = self.retro("--finding", "be more careful", "--cause", "x" * 20,
"--impact", "time", "--disposition", "drop", "--why-not", "no value here")
self.assertNotEqual(r.returncode, 0)
self.assertEqual(self.rows(), [])
def test_dispositions_record_only_what_they_need(self):
"""R-11.1-14, R-11.1-16, R-11.4-1: promote/record/drop persist concrete findings."""
_contract(self)
self.assertEqual(self.retro(*PROMOTE[1:]).returncode, 0)
self.assertEqual(self.retro(
"--finding", "the fixture had one file so nothing general was learned here at all",
"--cause", "single file fixture scope", "--impact", "time",
"--disposition", "record", "--limits", "single-file fixtures only").returncode, 0)
self.assertEqual(self.retro(
"--finding", "commit messages in the fixture were terse single letters today",
"--cause", "fixture brevity by design", "--impact", "attention",
"--disposition", "drop", "--why-not", "fixture only, no change worth making").returncode, 0)
from sisi import learning as L
rows = self.rows()
self.assertEqual(len(rows), 2)
self.assertEqual(rows[0]["status"], "proposed")
self.assertEqual(rows[1]["status"], "observed")
self.assertEqual(len(L.findings_for_unit(self.proj, "u1")), 3)
self.assertIn(rows[0]["status"], L.STATUSES)
self.assertTrue(rows[0]["terms"]) # derived by the tool, not demanded
def test_promote_missing_fields_refused(self):
"""R-11.1-11: a promoted opportunity needs action, expected effect, validation."""
_contract(self)
r = self.retro("--finding", "a real thing happened with evidence attached here now",
"--cause", "a concrete root cause here", "--impact", "cost",
"--disposition", "promote", "--change", "do the thing")
self.assertNotEqual(r.returncode, 0)
self.assertEqual(self.rows(), [])
def test_one_unit_learning_not_delivered_in_other_project(self):
"""R-11.6-1, R-11.6-2, R-12-2: scope is earned; one incident is origin-only."""
_contract(self)
self.git_init()
self.assertEqual(self.retro(*PROMOTE[1:]).returncode, 0)
from sisi import learning as L
self.assertIn("L-0001", L.delivery_text(self.proj, "f.txt bug content check"))
other = os.path.join(self.tmp, "other")
os.makedirs(other)
self.git_init(other)
self.assertNotIn("L-0001", L.delivery_text(other, "f.txt bug content check"))
# earn it: a second unit in a second project
_contract(self, "u9", other)
r = self.sisi("retro", "--finding", "f.txt held the word bug and shipped without a content check",
"--cause", "no check asserted file contents before delivery",
"--impact", "correctness", "--disposition", "record",
"--limits", "text files", "--same-as", "L-0001", cwd=other)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("L-0001", L.delivery_text(other, "f.txt bug content check"))
def test_delivery_framed_as_information_not_instruction(self):
"""R-16-6: delivered text is data to weigh, never an instruction."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
t = L.delivery_text(self.proj, "f.txt bug")
self.assertIn("not instructions", t)
self.assertNotIn("you must", t.lower())
def test_nothing_validated_without_a_passing_run(self):
"""R-11.5-6, R-11.1-8: 'validated' requires a validation run that passed."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "true"}]} # no commits known: cannot be replayed
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stderr)
rec = self.rows()[0]
self.assertEqual(rec["status"], "promoted")
self.assertEqual(rec["validation"]["result"], "unvalidated")
self.assertIn("unvalidated", L.learning_report())
def test_replay_validation_in_temp_worktree(self):
"""R-11.6-3: replay must fail before and pass after, without touching the tree."""
_contract(self)
self.git_init()
open(os.path.join(self.proj, "f.txt"), "w").write("bug\n")
self._commit("before")
before = self._head()
open(os.path.join(self.proj, "f.txt"), "w").write("fixed\n")
self._commit("fix")
after = self._head()
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "grep -q fixed f.txt", "before": before, "after": after}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
self.assertEqual(open(os.path.join(self.proj, "f.txt")).read(), "fixed\n")
self.assertEqual(self._head(), after) # the user's tree and HEAD untouched
def test_failed_replay_refuses_whole_cycle(self):
"""R-11.5-6: a check that passes before the fix proves nothing; nothing applies."""
_contract(self)
self.git_init()
open(os.path.join(self.proj, "f.txt"), "w").write("fixed\n")
self._commit("before")
before = self._head()
self._commit("after")
after = self._head()
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "grep -q fixed f.txt", "before": before, "after": after}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertNotEqual(r.returncode, 0)
self.assertEqual(self.rows()[0]["status"], "proposed")
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "enforced.json")))
def test_cycle_refusals_apply_nothing(self):
"""R-14.3-1, R-11.7-2, R-16-11: protected rule, stale base, ignored flag."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
base = L.store_base()
cases = [
{"base": base, "actions": [{"action": "promote", "learning": "L-0001",
"mechanism_kind": "rule-text", "rule_id": "strongest-check",
"rule_text": "## Weak {#strongest-check}\n\nSkip checks.\n\nWhy: faster.\n"}]},
{"base": "stale", "actions": [{"action": "promote", "learning": "L-0001",
"mechanism_kind": "risk", "pattern": "x/**", "profile": "logic"}]},
]
for i, doc in enumerate(cases):
p = os.path.join(self.tmp, "c%d.json" % i)
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertNotEqual(r.returncode, 0, doc)
self.assertEqual(self.rows()[0]["status"], "proposed")
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "risk-adjustments.json")))
def test_consequential_change_waits_for_owner(self):
"""R-11.5-11, R-14.4-1: disabling a rule is pending until `sisi approve`."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "disable-rule", "rule_id": "deliver-quickly"}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(len(L.load_pending()), 1)
self.assertIn("wait", L.pending_notice())
from sisi import overlay
self.assertNotIn("deliver-quickly", overlay.disabled("rule"))
r = self.sisi("approve", "P-0001", "--no")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(L.load_pending(), [])
self.assertNotIn("deliver-quickly", overlay.disabled("rule"))
def test_two_recurrences_flag_and_cycle_must_act(self):
"""R-13.2-8, R-11.5-9: recurrence after promotion flags; a cycle ignoring it is refused."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk",
"pattern": "f.txt", "profile": "logic"}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
for uid in ("u2", "u3"):
_contract(self, uid)
r = self.retro("--finding", "f.txt held the word bug and shipped without a content check",
"--cause", "no check asserted file contents before delivery",
"--impact", "correctness", "--disposition", "record",
"--limits", "here", "--same-as", "L-0001")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertTrue(self.rows()[0]["flagged_not_working"])
doc = {"base": L.store_base(), "actions": [
{"action": "reject", "learning": "L-0001", "why": "wrong idea"}]}
# a cycle that does act on it passes; first prove an ignoring cycle is refused
self.retro("--finding", "another unrelated slowness appeared in the test run today",
"--cause", "the suite runs everything serially", "--impact", "time",
"--disposition", "promote", "--change", "run independent checks in parallel",
"--mechanism", "infrastructure", "--expect", "faster runs",
"--validate", "time the suite")
bad = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0002", "mechanism_kind": "risk",
"pattern": "y/**", "profile": "logic"}]}
json.dump(bad, open(p, "w"))
self.assertNotEqual(self.sisi("cycle", "apply", p).returncode, 0)
doc["base"] = L.store_base()
json.dump(doc, open(p, "w"))
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertEqual(self.rows()[0]["status"], "rejected")
def test_revert_is_exact(self):
"""R-11.6-6, R-16-9: reverting a cycle restores the user store."""
_contract(self)
self.retro(*PROMOTE[1:])
from sisi import learning as L
doc = {"base": L.store_base(), "actions": [
{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "true"}]}
p = os.path.join(self.tmp, "c.json")
json.dump(doc, open(p, "w"))
self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0)
self.assertTrue(os.path.exists(os.path.join(self.data, "overlay", "enforced.json")))
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "enforced.json")))
self.assertEqual(self.rows()[0]["status"], "proposed")
def test_subagent_learning_held_until_parent_adopts(self):
"""R-16-10: a subagent's learning is a candidate until the parent retro adopts it."""
_contract(self)
r = self.sisi("retro", *PROMOTE[1:], env={"SISI_SUBAGENT": "1"})
self.assertEqual(r.returncode, 0, r.stderr)
from sisi import learning as L
self.assertTrue(self.rows()[0]["candidate"])
self.assertEqual(L.delivery_text(self.proj, "f.txt bug"), "")
_contract(self, "u2")
r = self.retro("--finding", "adopting the subagent finding about f.txt content checks now",
"--cause", "the parent reviewed the subagent report", "--impact", "correctness",
"--disposition", "record", "--limits", "here", "--same-as", "L-0001")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertFalse(self.rows()[0]["candidate"])
def test_learn_and_oracle_one_path(self):
"""R-12-1, R-12-5: `sisi learn` writes, `sisi oracle` prints, one store."""
r = self.sisi("learn", "prefer short plain reports over long ones")
self.assertEqual(r.returncode, 0, r.stderr)
r = self.sisi("oracle")
self.assertIn("prefer short plain reports", r.stdout)
from sisi import learning as L
self.assertEqual(len(L.owner_statements()), 1)
def test_dead_commands_gone(self):
"""Target section 13: improve, backlog and lessons digest are retired."""
self.assertNotEqual(self.sisi("improve").returncode, 0)
self.assertNotEqual(self.sisi("backlog").returncode, 0)
self.assertNotEqual(self.sisi("lessons", "digest").returncode, 0)
def test_report_claims_no_rate_when_too_few(self):
"""R-13.2-7: the realization rate says 'too few' instead of inventing a number."""
from sisi import learning as L
self.assertIn("too few", L.learning_report())
def test_migration_is_lossless_and_idempotent(self):
"""R-12-10: every old lesson and owner statement survives; counts asserted."""
os.makedirs(self.data, exist_ok=True)
rows = [
{"t": "lesson", "id": 1, "moment": "m one happened here", "cause": "c one",
"change": "change one", "change_kind": "rule", "status": "applied",
"project": self.proj, "created": "2026-01-01T00:00:00Z"},
{"t": "lesson", "id": 2, "moment": "m two happened here", "cause": "c two",
"change": "change two", "change_kind": "tool", "status": "open",
"project": self.proj, "created": "2026-01-01T00:00:00Z"},
{"t": "occurrence", "id": 1, "lesson_id": 1, "repo": self.proj,
"session": "s1", "ts": "2026-01-01T00:00:00Z"},
{"t": "impression", "id": 1, "lesson_id": 1, "place": "tick",
"ts": "2026-01-01T00:00:00Z"},
]
with open(os.path.join(self.data, "lessons.jsonl"), "w") as f:
for r in rows:
f.write(json.dumps(r) + "\n")
with open(os.path.join(self.data, "learn.jsonl"), "w") as f:
f.write(json.dumps({"text": "always ask before spending", "ts": "2026-01-01T00:00:00Z"}) + "\n")
from sisi import lifecycle, learning as L
notes = lifecycle.migrate_learnings()
self.assertTrue(notes)
got = self.rows()
self.assertEqual(len(got), 3) # 2 lessons + 1 statement; impression dropped
self.assertEqual(got[0]["status"], "implemented")
self.assertTrue(all(r["validation"]["result"] != "validated" for r in got))
self.assertEqual(len(got[0]["provenance"]), 1)
self.assertEqual(len(L.owner_statements()), 1)
self.assertEqual(lifecycle.migrate_learnings(), []) # idempotent
self.assertEqual(len(self.rows()), 3)
def _commit(self, msg):
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "add", "."],
cwd=self.proj, check=True, capture_output=True)
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q",
"--allow-empty", "-m", msg], cwd=self.proj, check=True, capture_output=True)
def _head(self):
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=self.proj,
capture_output=True, text=True).stdout.strip()
-167
View File
@@ -1,167 +0,0 @@
"""Patterns: `sisi retro --pattern`, `sisi retro patterns`, the cycle's set-pattern action,
and patterns-first digest/improve."""
import json, os, unittest
from support import *
from sisi import retro
WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
PATTERN = "Build the obvious thing instead of using what the environment already provides"
def retro_args(**kw):
f = dict(aim="verified", moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with the writer the project already had",
change_kind="rule", change="Write delimited files with a quoting writer so fields survive",
when=WHEN, scope="core", pattern=PATTERN,
short="Use a quoting writer for delimited exports.", topic="data files")
f.update(kw)
out = []
for k in ("aim", "moment", "cause", "change_kind", "change", "when", "scope", "short", "topic", "pattern"):
if f.get(k) is not None:
out += ["--" + k.replace("_", "-"), str(f[k])]
if f.get("pattern_id") is not None:
out += ["--pattern-id", str(f["pattern_id"])]
return out
class RetroPatternTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def test_pattern_is_required_for_a_new_lesson(self):
r = self.sisi("retro", *retro_args(pattern=None))
self.assertNotEqual(r.returncode, 0, r.stdout)
self.assertIn("pattern", (r.stdout + r.stderr).lower())
def test_pattern_is_stored_and_reused_not_duplicated(self):
r = self.sisi("retro", *retro_args())
self.assertEqual(r.returncode, 0, r.stdout)
r = self.sisi("retro", "--new", *retro_args(
moment="another export broke on an embedded newline at step 4 of the run",
change="Write delimited files with a quoting writer so newlines survive"))
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
try:
pats = retro.patterns(con)
self.assertEqual(len(pats), 1, pats)
self.assertEqual(pats[0]["statement"], PATTERN)
ids = [row[0] for row in con.execute("SELECT pattern_id FROM lessons ORDER BY id")]
self.assertEqual(ids, [pats[0]["id"], pats[0]["id"]])
finally:
con.close()
def test_retro_patterns_lists_them_and_pattern_id_selects(self):
self.assertEqual(self.sisi("retro", *retro_args()).returncode, 0)
out = self.sisi("retro", "patterns").stdout
self.assertIn(PATTERN, out)
r = self.sisi("retro", "--new", *retro_args(
pattern=None, pattern_id=1,
moment="a third export broke on a delimiter in a name at step 1 of the run",
change="Write delimited files with a quoting writer so delimiters survive"))
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
try:
self.assertEqual(len(retro.patterns(con)), 1)
finally:
con.close()
def test_pattern_naming_the_project_or_restating_the_change_is_refused(self):
r = self.sisi("retro", *retro_args(pattern="proj export rows are joined by hand in this repo"))
self.assertNotEqual(r.returncode, 0, r.stdout)
r = self.sisi("retro", *retro_args(pattern="Write delimited files with a quoting writer so fields survive"))
self.assertNotEqual(r.returncode, 0, r.stdout)
class CyclePatternTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def lesson_without_pattern(self):
con = retro.connect()
try:
lid = retro.new_lesson(con, dict(
aim="verified", change_kind="rule", target=None,
moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with a quoting writer",
change="Write delimited files with a quoting writer so fields survive",
when=WHEN, short="Use a quoting writer for delimited exports.", topic="data files",
scope="core"), self.proj, None)
con.commit()
return lid
finally:
con.close()
def test_cycle_brief_lists_patterns_and_check_requires_set_pattern(self):
lid = self.lesson_without_pattern()
brief = self.sisi("cycle", "--now").stdout
self.assertIn("pattern", brief.lower())
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "x",
"notes": [{"lesson": lid, "action": "keep"}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("set-pattern", r.stdout)
doc["notes"].append({"lesson": lid, "action": "set-pattern", "pattern": PATTERN})
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
try:
self.assertEqual(retro.patterns(con)[0]["statement"], PATTERN)
finally:
con.close()
def test_pattern_merge_keeps_one(self):
con = retro.connect()
try:
a = retro.get_or_create_pattern(con, PATTERN)
b = retro.get_or_create_pattern(con, "Rebuild what already exists instead of calling it")
con.commit()
finally:
con.close()
lid = self.lesson_without_pattern()
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "merge patterns",
"notes": [{"lesson": lid, "action": "set-pattern", "pattern_id": b}],
"patterns": [{"pattern": b, "action": "merge", "into": a}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
try:
pats = retro.patterns(con)
self.assertEqual([x["id"] for x in pats], [a])
self.assertEqual(con.execute("SELECT pattern_id FROM lessons WHERE id=?", (lid,)).fetchone()[0], a)
finally:
con.close()
class PatternsFirstTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
self.assertEqual(self.sisi("retro", *retro_args()).returncode, 0)
def test_digest_shows_patterns_first(self):
out = self.sisi("lessons", "digest").stdout
self.assertIn("## Patterns", out)
self.assertLess(out.index("## Patterns"), out.index("## In sisi itself"))
self.assertIn(PATTERN, out)
def test_improve_shows_patterns(self):
out = self.sisi("improve").stdout
self.assertIn(PATTERN, out)
if __name__ == "__main__":
unittest.main()
-685
View File
@@ -1,685 +0,0 @@
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",
when="parser, fuzzing, codec, hostile input, generated input, parsing",
scope="everywhere", target="parser-or-codec", pattern="Reach for the familiar tool instead of the check that fits the claim")
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()
# a recipe lesson with a valid target takes effect at once, on its first occurrence
self.assertEqual((len(l), l[0]["count"], l[0]["status"], l[0]["aim"]), (1, 1, "applied", "verified"))
self.assertEqual(self.occurrences(), 1)
def test_each_refusal(self):
# Structural checks only: presence, length, enums, moment-is-not-change, exact empty answers.
bad = {
"missing aim": {"aim": ""}, "missing moment": {"moment": ""}, "missing cause": {"cause": " "},
"missing change": {"change": ""}, "bad aim": {"aim": "vibes"}, "bad kind": {"change_kind": "magic"},
"nothing change": {"change": "None"}, "na cause": {"cause": "n/a"},
"nothing moment exact": {"moment": "nothing"},
"be more careful exact": {"change": "be more careful"},
"short moment": {"moment": "it was slow"}, "short change": {"change": "fix the rule"},
"short cause": {"cause": "bad"},
"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.assertIn("(check:", r.stdout) # every refusal names the check that failed
self.assertEqual(self.lessons(), [])
self.assertEqual(self.occurrences(), 0)
VALID = [
("Dates in the report were one day early for users in Sydney",
"the code formatted UTC timestamps without the user's time zone",
"For anything that shows or compares dates, test with a time zone ahead of and behind UTC and across a daylight saving change"),
("Everything looked fine on my machine and then failed for everyone in the beta",
"my local data was a week old and far too small",
"Anything that reads user data should always be checked against a large recent copy before shipping"),
("Nothing could be imported after the upgrade and nobody noticed for a day",
"the importer swallowed every error and reported success",
"An import should never report success when everything was skipped; zero imported is a failure"),
("The button did nothing at all when pressed quickly twice in a row",
"the handler always waited for the first request to finish",
"Buttons that start work should disable themselves until the work settles, always"),
("It was never clear which of the three copies was the newest one",
"each tool kept its own copy and none said which was live",
"Anything installed in two places should print which copy is running and how old it is"),
("Everything was rebuilt from scratch even for a one-word edit",
"the build never reused anything between runs at all",
"A build should always say what it reused and what it redid, so waste is visible"),
("The search found nothing for a perfectly ordinary plural word",
"matching compared whole words only, with no stemming at all",
"Search over user text should stem words so plurals and verb forms meet"),
("Users in Auckland saw tomorrow's date on everything after midnight",
"dates were formatted in the server zone, never the viewer's",
"For anything dated, format in the viewer's zone and test both sides of UTC"),
("The whole page went blank whenever one record had no title",
"rendering assumed every field is always present on every record",
"Rendering should survive any single record missing any optional field"),
("Nobody could tell whether the job had finished or was still running",
"long work reported nothing between starting and ending",
"Anything that takes more than a few seconds should say what stage it is at"),
("The same invoice was sent twice to the same customer in one morning",
"a retry after a timeout could not tell the first send had landed",
"Anything sent to a customer should carry an id that makes a retry harmless"),
("Accented names vanished from the list after the upgrade finished",
"the new code compared names byte for byte across normalisation forms",
"Names should be normalised the same way on write and on every later read"),
("The report said twenty thousand users when nothing had been measured",
"a file count was presented as a session count without checking",
"Any number a decision depends on should come from measuring the thing it names"),
("Saving appeared to work while nothing was actually written anywhere",
"the write error was logged once and the indicator stayed green",
"A failed save should be visible where the save was asked for, never only in a log"),
("The oldest message in the inbox was never shown to anyone at all",
"paging always sorted newest first and the tail fell off the page",
"Any list that pages should be checked for items that can never be reached"),
("Everything slowed down only when the office came online at nine",
"every client retried at the same second after any failure",
"Retries should always spread out with jitter so clients never stampede together"),
("A file that should never change was quietly rewritten by the installer",
"the install step wrote everywhere instead of only where asked",
"Installers should write nothing outside the places the user was told about"),
("The totals never matched the spreadsheet by exactly one cent",
"money travelled as floats and rounded differently in two places",
"Money should be integer minor units from end to end, always, no exceptions"),
("Nobody could open the attachment because its name had spaces in it",
"the download path was built by joining text with no escaping anywhere",
"Anything that turns a name into a path should be tested with spaces and accents"),
("The night run silently did nothing because the clock had moved",
"a fixed local time never occurred on the spring-forward night",
"Scheduled work should say what happens when its local time never occurs"),
("Search results showed records the signed-in person should never see",
"the filter ran after results were already assembled for display",
"Visibility should be decided before anything user-shaped is assembled for output"),
("The copy on the laptop and the copy at work disagreed about everything",
"sync copied files both ways with nothing recording which won",
"Sync should record, for every conflict, which side won and why it won"),
("It always picked the first answer even when the first was clearly stale",
"ranking never considered how old a result was at selection time",
"Anything cached should carry its age and prefer a fresh answer over a stale one"),
("Nothing was logged when the payment provider answered with an error",
"the error path returned early without touching the log at all",
"Every early return on an error path should leave exactly one log line behind"),
("The whole import stopped on one row that nobody could identify later",
"rows were counted from one in the file and from zero in the message",
"Errors about a row should name it the way the person holding the file counts it"),
("Settings changed on one machine never appeared on the other machine",
"settings were read once at startup and never watched afterwards",
"Anything read at startup that users can edit should say when a restart is needed"),
("The preview and the printed page never agreed about the typeface",
"the preview used a font the printer substituted without telling anyone",
"Anything printable should be checked in the form it is finally printed in"),
("Undo brought back a version nobody recognised from any point in time",
"undo restored whole files while other work had landed in between",
"Undo should reverse one change exactly and refuse when later work touches it"),
("The helper kept asking questions that the request had already answered",
"it never read the answers already recorded earlier in the session",
"Before asking anything, an agent should check what was already settled and say so"),
("Everything passed locally and the first real user hit a crash at once",
"tests only ever used the small tidy examples written by hand",
"Anything parsing outside files should be tested on generated hostile examples"),
]
def test_valid_lessons_in_varied_wording_are_all_accepted(self):
self.assertGreaterEqual(len(self.VALID), 30)
for moment, cause, change in self.VALID:
f = dict(GOOD, moment=moment, cause=cause, change=change)
self.assertEqual(retro.validate(f), [], moment)
# and through the real command, Sydney included (no digit, no path, no ALLCAPS in the moment)
m, c, ch = self.VALID[0]
r = self.retro({"moment": m, "cause": c, "change": ch})
self.assertEqual(r.returncode, 0, r.stdout)
EMPTY = [
{"moment": "nothing"}, {"moment": "None."}, {"cause": "n/a"}, {"cause": "nothing"},
{"change": "be more careful"}, {"change": "test more"}, {"change": "none"},
{"moment": "ok"}, {"cause": "all good"}, {"change": "short"}, {"moment": "it went well"},
{"cause": "fine"}, {"change": "no"},
]
def test_empty_answers_are_refused_with_the_check_named(self):
self.assertGreaterEqual(len(self.EMPTY), 12)
for over in self.EMPTY:
with self.subTest(over):
errs = retro.validate(dict(GOOD, **over))
self.assertTrue(errs)
self.assertTrue(any("(check:" in e for e in errs), errs)
r = self.retro({"change": "be more careful"})
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn('change is an empty answer: "be more careful"', r.stdout)
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", "--when"):
self.assertIn(w, r.stdout)
self.assertIn("at least 5 terms", r.stdout)
def test_when_is_required_with_five_terms_for_new_lessons(self):
no_when = dict(GOOD); no_when.pop("when")
r = self.sisi("retro", *argv(no_when))
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("--when needs at least 5 terms", r.stdout)
self.assertIn("delimited file", r.stdout) # the worked example in the refusal
few = self.retro({"when": "parser, fuzzing"})
self.assertEqual(few.returncode, 2, few.stdout)
self.assertIn("--when has 2 term(s)", few.stdout)
self.assertEqual(self.lessons(), [])
self.assertEqual(self.retro().returncode, 0) # five-plus terms: accepted and stored
self.assertIn("fuzzing", self.lessons()[0]["when_terms"])
same = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` ran for 5 minutes with no fuzz verifier chosen")
self.assertEqual(same.returncode, 0, same.stdout) # --same-as needs no --when
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):
# Only structural failures belong here now: exact empty answers, too-short text, bad enums.
generic = ["nothing", "n/a", "none", "it went well", "be more careful", "test more", "short", "", " ", "ok"]
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="", scope="everywhere",
pattern="Reach for the familiar tool instead of the check that fits the claim",
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",
when="browser, screenshot, dev server, port waiting, ui checks, startup",
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):
# The learning loop changed this: the field note is written on the FIRST occurrence,
# and later occurrences never duplicate the bullet.
r = self.occ("s1")
self.assertEqual(r.returncode, 0)
self.assertIn("applied", r.stdout)
self.assertTrue(os.path.exists(os.path.join(self.notes, "parser-or-codec.md")))
self.assertEqual(self.lessons()[0]["status"], "applied")
r = self.occ("s2", 1)
self.assertEqual(r.returncode, 0, r.stdout)
text = open(os.path.join(self.notes, "parser-or-codec.md")).read()
self.assertIn("Add the fuzz verifier", text)
self.assertEqual(text.count("Add the fuzz verifier"), 1)
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, 0 open, 1 applied; 1 occurrences in the last 7 days", out)
self.assertIn("active #1", out)
self.assertIn("retros", out)
self.assertIn("learning : 1 lessons taking effect", 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 --scope", 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()
-279
View File
@@ -1,279 +0,0 @@
import json, os, subprocess, unittest
from support import *
from sisi import retro, scope, store
WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
def retro_args(**kw):
f = dict(aim="verified", moment="the export broke in the acme-widgets repo when a field held a newline",
cause="rows were joined by hand in acme-widgets instead of with a quoting writer",
change_kind="rule",
change="Write delimited files with a quoting writer so embedded newlines survive",
when=WHEN, short="Use a quoting writer for delimited exports.", topic="data files",
pattern="Build the obvious thing instead of using what the environment already provides")
f.update(kw)
out = []
for k, v in f.items():
out += ["--" + k.replace("_", "-"), v]
return out
# (text, kind, expected) expected True = universal passes, False = refused as naming this project
LABELLED = [
("Write delimited files with a quoting writer so embedded newlines survive", "rule", True),
("Check the README and CHANGELOG agree with the version before publishing", "rule", True),
("Update the changelog when behaviour changes and keep the readme example runnable", "rule", True),
("Run the whole test suite before saying work is done", "rule", True),
("Prefer a readiness probe over a fixed sleep when waiting for servers", "rule", True),
("Write the failing test first and watch it fail before fixing code", "rule", True),
("Keep functions small enough to test without a display or network", "rule", True),
("Never report success when every input record was skipped silently", "rule", True),
("Compare totals before and after any data migration with an independent count", "rule", True),
("Make error messages name the field that failed and what would be valid", "rule", True),
("In the acme-widgets project always quote fields by hand in the exporter", "rule", False),
("The acme-widgets exporter must join rows with its own quoting code", "rule", False),
("Fix export in widget_export.py by using a quoting writer there", "rule", False),
("Change src/widget_export.py to use a quoting writer for every row", "rule", False),
("See https://github.com/acme/acme-widgets for how exports should work here", "rule", False),
("In acme-widgets, release notes live in the changelog of that repository only", "rule", False),
("sisi should refuse lessons that name the project they came from", "tool", True),
("sisi must show the backlog separately from loose lesson headings", "tool", True),
("Agents should record a retro at the end of every piece of work", "rule", True),
("A parser should reject overlong input instead of allocating without bound", "rule", True),
("Use the acme-widgets keyboard layout with control on the left in every project", "rule", False),
("Keep the widget test fixture frozen at the acme-widgets sample rows", "rule", False),
("Always run tests with the licence and security notes updated for releases", "rule", True),
("Document every public function with its errors and limits in the readme", "rule", True),
]
class ScopeCase(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
subprocess.run(["git", "remote", "add", "origin", "https://github.com/acme/acme-widgets.git"], cwd=self.proj, check=True)
with open(os.path.join(self.proj, "widget_export.py"), "w") as f:
f.write("x=1\n")
os.makedirs(os.path.join(self.proj, "src"))
with open(os.path.join(self.proj, "src", "widget_export.py"), "w") as f:
f.write("x=1\n")
class ProjectIdTests(ScopeCase):
def test_remote_id_stable_across_clone_and_rename(self):
self.assertEqual(scope.project_id(self.proj), scope.normalized_remote("git" + chr(64) + "github.com:acme/acme-widgets.git"))
other = os.path.join(self.tmp, "renamed")
subprocess.run(["git", "clone", "-q", self.proj, other], check=True)
# clone from local path has local remote; set same remote
subprocess.run(["git", "remote", "set-url", "origin", "git" + chr(64) + "github.com:acme/acme-widgets"], cwd=other, check=True)
self.assertEqual(scope.project_id(other), scope.project_id(self.proj))
def test_path_fallback_without_remote(self):
d = os.path.join(self.tmp, "plainproj"); os.makedirs(d)
subprocess.run(["git", "init", "-q"], cwd=d, check=True)
self.assertEqual(scope.project_id(d), os.path.realpath(d))
class LabelledUniversalTests(ScopeCase):
def test_labelled_set(self):
hits = false_refusals = 0
for text, kind, want_pass in LABELLED:
reason = scope.universal_refusal([text], self.proj, kind=kind)
got_pass = reason is None
if got_pass and want_pass:
hits += 1
if not got_pass and want_pass:
false_refusals += 1
self.assertEqual(got_pass, want_pass, "%r kind=%s reason=%s" % (text, kind, reason))
self.assertGreaterEqual(len(LABELLED), 20)
def test_universal_change_with_project_moment_passes(self):
# amendment: moment/cause may name the project; only delivered parts are checked
for text in LABELLED[:4]:
self.assertIsNone(scope.universal_refusal([text], self.proj, kind="rule"))
r = self.sisi("retro", *retro_args(scope="everywhere"))
self.assertEqual(r.returncode, 0, r.stdout)
class RetroScopeTests(ScopeCase):
def test_missing_scope_refused_with_explanation(self):
r = self.sisi("retro", *retro_args())
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("core", r.stdout); self.assertIn("user", r.stdout); self.assertIn("project", r.stdout)
self.assertIn("general terms", r.stdout)
def test_everywhere_naming_project_refused(self):
r = self.sisi("retro", *retro_args(scope="everywhere",
change="In acme-widgets always use a quoting writer in the exporter for rows"))
self.assertEqual(r.returncode, 2, r.stdout)
self.assertIn("rewrite", r.stdout.lower())
def test_project_scope_goes_to_handover_not_global(self):
r = self.sisi("retro", *retro_args(scope="project",
change="Use a quoting writer for delimited exports in this project",
short="Use a quoting writer here."))
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0); con.close()
from sisi import handover
items = handover.for_project(scope.project_id(self.proj))
self.assertEqual(len(items), 1)
self.assertIn("acme-widgets", items[0]["moment"])
part1, part2 = retro.delivery("csv spreadsheet export delimited file")
self.assertFalse(part1 or part2)
self.assertIn("belong to this project", retro.tick_block(self.proj))
other = os.path.join(self.tmp, "otherproj"); os.makedirs(other)
self.assertNotIn("belong to this project", retro.tick_block(other))
out = self.sisi("handover").stdout
self.assertIn("Use a quoting writer for delimited exports in this project", out)
hid = items[0]["hid"]
bad = self.sisi("handover", "done", hid, "--where", "NOTES.md")
self.assertEqual(bad.returncode, 1, bad.stdout)
with open(os.path.join(self.proj, "NOTES.md"), "w") as f:
f.write("# design notes\n\nUse a quoting writer for delimited exports in this project.\n")
ok = self.sisi("handover", "done", hid, "--where", "NOTES.md")
self.assertEqual(ok.returncode, 0, ok.stdout)
self.assertEqual(handover.load_pile(), [])
self.assertIn("NOTES.md", open(handover.filed_path()).read())
def test_learn_missing_scope_and_project_learn(self):
r = self.sisi("learn", "always show options")
self.assertEqual(r.returncode, 2, (r.stdout, r.stderr))
r = self.sisi("learn", "--scope", "project", "use the left control key here")
self.assertEqual(r.returncode, 0, (r.stdout, r.stderr))
self.assertEqual(store.read("quarantine"), [])
from sisi import handover
items = handover.for_project(scope.project_id(self.proj))
self.assertEqual(items[-1]["text"], "use the left control key here")
r = self.sisi("learn", "--scope", "everywhere", "in acme-widgets always show options")
self.assertEqual(r.returncode, 2, (r.stdout, r.stderr))
def test_lessons_show_split(self):
r = self.sisi("retro", *retro_args(scope="everywhere"))
self.assertEqual(r.returncode, 0, r.stdout)
out = self.sisi("lessons", "show", "1").stdout
self.assertIn("Where this came from (historical example)", out)
self.assertLess(out.index("Write delimited files"), out.index("Where this came from"))
self.assertIn("acme-widgets", out.split("Where this came from (historical example)", 1)[1])
def test_digest_universal_first_then_project(self):
self.sisi("retro", *retro_args(scope="everywhere"))
self.sisi("retro", "--new", *retro_args(scope="project",
change="Use a quoting writer for delimited exports in this project",
short="Use a quoting writer here.", moment="another export broke at step 2 in this repo today"))
out = self.sisi("lessons", "digest").stdout
self.assertIn("Use a quoting writer for delimited exports.", out)
self.assertNotIn("Use a quoting writer here.", out)
self.assertIn("waiting to be filed", out)
self.assertIn("acme-widgets", out)
class StaleReadingTests(ScopeCase):
def test_reading_lessons_does_not_stale_cycle(self):
# folded lesson shown 20x via lessons show retires; cycle check must still pass
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="verifier", target=None,
moment="fuzz seeds missing at step 5 of the nightly run",
cause="the corpus was not seeded from golden files",
change="Seed the fuzz corpus from golden parser files before fuzzing",
when=WHEN, short="Seed fuzz corpus from golden files.", topic="testing"), self.proj, None)
con.execute("UPDATE lessons SET folded_into='fuzz', status='applied', effect='field-note' WHERE id=?", (lid,))
con.commit(); con.close()
from sisi import cycle
base = cycle.base_version()
for _ in range(20):
out = self.sisi("lessons", "show", str(lid))
self.assertEqual(out.returncode, 0, out.stdout)
con = retro.connect()
st = dict(con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone()); con.close()
self.assertEqual(st["status"], "applied") # retirement deferred while the round is open
doc = {"version": 1, "base": base, "summary": "keep",
"notes": [{"lesson": lid, "action": "set-short", "short": "Seed fuzz corpus from golden files.", "topic": "testing"},
{"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"},
{"lesson": lid, "action": "set-scope", "scope": "core"}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
class DueAndBacklogTests(ScopeCase):
def test_tool_lessons_do_not_make_cycle_due_by_headings(self):
con = retro.connect()
for i in range(10):
retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None,
moment="tool wait %d at step 2 of the run" % i, cause="no cache existed for that step",
change="Make sisi cache transcript scans between gate decisions number %d and reuse them always" % i,
when=WHEN, short="Cache transcript scans.", topic="sisi itself"), self.proj, None)
con.commit(); con.close()
from sisi import cycle
st = cycle.due_state()
self.assertFalse(any("loose lesson headings" in r for r in st["reasons"]), st["reasons"])
out = self.sisi("backlog").stdout
self.assertIn("cap", out.lower())
def test_applied_tool_lesson_not_not_built_in_digest(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None,
moment="tool wait at step 2 of the run today", cause="no cache existed for that step",
change="Make sisi cache transcript scans between gate decisions and reuse them",
when=WHEN, short="Cache transcript scans.", topic="sisi itself"), self.proj, None)
con.commit(); con.close()
self.assertEqual(self.sisi("lessons", "set", str(lid), "--status", "applied").returncode, 0)
out = self.sisi("lessons", "digest").stdout
self.assertNotIn("not built yet", out)
self.assertIn("built", out)
self.assertNotIn("#%d" % lid, self.sisi("backlog").stdout)
class CycleScopeTests(ScopeCase):
def test_cycle_refuses_folding_project_lesson_into_entry(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="rule", target=None,
moment="export broke at step 2 in this repo", cause="rows joined by hand here",
change="Use a quoting writer for delimited exports in this project",
when=WHEN, short="Use a quoting writer here.", topic="data files"), self.proj, None)
con.execute("UPDATE lessons SET scope='project', project=? WHERE id=?", (scope.project_id(self.proj), lid))
con.commit(); con.close()
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "x",
"notes": [{"lesson": lid, "action": "fold-into-rule", "into": "know-done"},
{"lesson": lid, "action": "set-short", "short": "Use a quoting writer here.", "topic": "data files"}]}
p = os.path.join(self.tmp, "cyc2.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "check", p)
self.assertEqual(r.returncode, 1, r.stdout)
self.assertIn("project", r.stdout)
class CleanupRevertTests(ScopeCase):
def test_set_scope_project_moves_and_revert_restores(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(aim="verified", change_kind="rule", target=None,
moment="export broke at step 2 in acme-widgets today", cause="rows joined by hand here",
change="Use a quoting writer for delimited exports in this project",
when=WHEN, short="Use a quoting writer here.", topic="data files"), self.proj, None)
con.commit(); con.close()
store.append("quarantine", store.stamp({"text": "use the left control key here"}))
from sisi import cycle
base = cycle.base_version()
brief = self.sisi("cycle", "--now").stdout
self.assertIn("Scope cleanup", brief)
self.assertIn(self.proj, brief)
doc = {"version": 1, "base": base, "summary": "cleanup",
"notes": [{"lesson": lid, "action": "set-scope", "scope": "project",
"project": scope.project_id(self.proj)}],
"learn": [{"text": "use the left control key here", "action": "set-scope",
"scope": "project", "project": scope.project_id(self.proj)}]}
p = os.path.join(self.tmp, "cleanup.json")
with open(p, "w") as f: json.dump(doc, f)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertIn("characters ->", r.stdout)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 0); con.close()
self.assertEqual(store.read("quarantine"), [])
from sisi import handover
self.assertEqual(len(handover.load_pile()), 2)
self.assertNotIn("Use a quoting writer here", self.sisi("lessons", "digest").stdout)
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
self.assertEqual(con.execute("SELECT count(*) FROM lessons").fetchone()[0], 1); con.close()
self.assertEqual(len(store.read("quarantine")), 1)
self.assertEqual(handover.load_pile(), [])
if __name__ == "__main__":
unittest.main()
-371
View File
@@ -1,371 +0,0 @@
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()
-207
View File
@@ -1,207 +0,0 @@
"""Three tiers (core, user, project): round-trips, migration of `everywhere`, the sisi-name
exemption, promote on a developer install, export, and exact cycle revert with tiers."""
import json, os, shutil, subprocess, unittest
from support import *
from sisi import retro, scope, store
WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file"
PATTERN = "Build the obvious thing instead of using what the environment already provides"
def retro_cli(case, tier, **kw):
f = dict(aim="verified", moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with a quoting writer",
change_kind="rule", change="Write delimited files with a quoting writer so fields survive",
when=WHEN, pattern=PATTERN, short="Use a quoting writer for delimited exports.",
topic="data files")
f.update(kw)
args = ["retro", "--scope", tier]
for k in ("aim", "moment", "cause", "change_kind", "change", "when", "pattern", "short", "topic"):
args += ["--" + k.replace("_", "-"), f[k]]
return case.sisi(*args)
class TierTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
def test_tier_decisions_round_trip(self):
for tier in ("core", "user"):
r = retro_cli(self, tier, moment="export %s broke on a quoted field at step 3" % tier,
change="Write delimited files with a quoting writer so %s fields survive" % tier)
if tier == "user":
self.assertIn(r.returncode, (0, 4), r.stdout) # 4 = similar lesson kept as sighting
if r.returncode == 4:
r = self.sisi("retro", "--new", "--scope", "user", "--aim", "verified",
"--moment", "export user broke on a quoted field at step 3",
"--cause", "rows were joined by hand instead of with a quoting writer",
"--change-kind", "rule",
"--change", "Write delimited files with a quoting writer so user fields survive",
"--when", WHEN, "--pattern", PATTERN,
"--short", "Use a quoting writer for delimited exports.",
"--topic", "data files")
self.assertEqual(r.returncode, 0, r.stdout)
con = retro.connect()
try:
tiers = [scope.tier_of(r[0]) for r in con.execute("SELECT scope FROM lessons ORDER BY id")]
finally:
con.close()
self.assertEqual(tiers, ["core", "user"])
for tier, text in (("core", "sisi should anticipate what is needed from what was already said"),
("user", "always ask questions as options with a recommendation")):
r = self.sisi("learn", "--scope", tier, text)
self.assertEqual(r.returncode, 0, r.stdout)
recs = store.read("learn")
self.assertEqual([r["scope"] for r in recs], ["core", "user"])
out = self.sisi("oracle").stdout
self.assertIn("always ask questions as options", out)
self.assertIn("sisi should anticipate", out) # core, until the product carries it
def test_missing_scope_text_asks_the_two_questions(self):
r = self.sisi("learn", "always show options")
self.assertEqual(r.returncode, 2)
self.assertIn("all projects where sisi may be used", r.stdout)
self.assertIn("every user who installs sisi", r.stdout)
def test_statement_naming_sisi_is_accepted_as_core_inside_sisi_repo(self):
d = os.path.join(self.tmp, "sisi")
os.makedirs(d)
subprocess.run(["git", "init", "-q"], cwd=d, check=True)
r = self.sisi("learn", "--scope", "core",
"sisi should anticipate what I need from what I already said", cwd=d)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual(store.read("learn")[0]["scope"], "core")
def test_everywhere_migrates_to_unscoped_tier_and_still_delivers(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(
aim="verified", change_kind="rule", target=None,
moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with a quoting writer",
change="Write delimited files with a quoting writer so fields survive",
when=WHEN, short="Use a quoting writer.", topic="data files",
scope="user", pattern=PATTERN), self.proj, None)
con.execute("UPDATE lessons SET scope='everywhere' WHERE id=?", (lid,))
con.commit(); con.close()
con = retro.connect() # migration on open
try:
v = con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0]
finally:
con.close()
self.assertEqual(v, "unscoped-tier")
self.assertIn("Use a quoting writer", retro.tick_block(self.proj))
brief = self.sisi("cycle", "--now").stdout
self.assertIn("tier", brief.lower())
def test_digest_groups_core_user_and_project_counts(self):
r = retro_cli(self, "core")
self.assertEqual(r.returncode, 0, r.stdout)
self.sisi("learn", "--scope", "user", "always ask questions as options with a recommendation")
out = self.sisi("lessons", "digest").stdout
self.assertIn("## In sisi itself, for every user", out)
self.assertIn("## How you want work done", out)
self.assertIn("waiting to be promoted", out)
class PromoteTierTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
self.src = os.path.join(self.tmp, "src")
for d in ("bin", "sisi", "canon"):
os.makedirs(os.path.join(self.src, d))
open(os.path.join(self.src, "bin", "sisi"), "w").write("#!/bin/sh\n")
open(os.path.join(self.src, "sisi", "cli.py"), "w").write("# cli\n")
shutil.copy(os.path.join(REPO, "canon", "core.md"), os.path.join(self.src, "canon", "core.md"))
os.makedirs(os.path.join(self.data), exist_ok=True)
json.dump({"developer": {"source": self.src}}, open(os.path.join(self.data, "config.json"), "w"))
def core_lesson_folded_to_rule(self):
r = retro_cli(self, "core")
self.assertEqual(r.returncode, 0, r.stdout)
d = os.path.join(self.data, "overlay", "rules")
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "quoting-writer.md"), "w") as f:
f.write("## Write delimited files with a quoting writer\n\n"
"Write delimited files with a quoting writer so embedded delimiters and "
"newlines survive.\n\nWhy: hand-joined rows break on real data.\n")
con = retro.connect()
try:
con.execute("UPDATE lessons SET folded_into='rule:quoting-writer' WHERE id=1")
con.commit()
finally:
con.close()
def test_promote_lists_core_items(self):
self.assertEqual(retro_cli(self, "core").returncode, 0)
out = self.sisi("promote").stdout
self.assertIn("lesson:1", out)
def test_promote_on_dev_install_edits_product_and_drops_personal_copy(self):
self.core_lesson_folded_to_rule()
overlay_file = os.path.join(self.data, "overlay", "rules", "quoting-writer.md")
self.assertTrue(os.path.exists(overlay_file))
r = self.sisi("promote", "lesson:1") # dry run: product untouched
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertNotIn("quoting-writer", open(os.path.join(self.src, "canon", "core.md")).read())
r = self.sisi("promote", "lesson:1", "--apply")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
core = open(os.path.join(self.src, "canon", "core.md")).read()
self.assertIn("quoting writer so embedded delimiters", core)
self.assertFalse(os.path.exists(overlay_file)) # dropped only after the product has it
con = retro.connect()
try:
self.assertTrue(con.execute("SELECT promoted FROM lessons WHERE id=1").fetchone()[0])
finally:
con.close()
self.assertNotIn("lesson:1", self.sisi("promote").stdout)
def test_export_contains_no_history_or_names(self):
self.assertEqual(retro_cli(self, "core").returncode, 0)
self.sisi("learn", "--scope", "core", "sisi should use what the host already provides")
p = os.path.join(self.tmp, "contrib.md")
r = self.sisi("promote", "--export", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
text = open(p).read()
self.assertIn("Write delimited files with a quoting writer", text)
self.assertIn("sisi should use what the host already provides", text)
self.assertNotIn("the export broke on a quoted field", text) # the moment (history)
self.assertNotIn("rows were joined by hand", text) # the cause (history)
self.assertNotIn(self.tmp, text)
def test_cycle_set_scope_to_core_and_exact_revert(self):
con = retro.connect()
lid = retro.new_lesson(con, dict(
aim="verified", change_kind="rule", target=None,
moment="the export broke on a quoted field at step 2 of the run",
cause="rows were joined by hand instead of with a quoting writer",
change="Write delimited files with a quoting writer so fields survive",
when=WHEN, short="Use a quoting writer.", topic="data files",
pattern=PATTERN), self.proj, None)
con.commit(); con.close()
from sisi import cycle
doc = {"version": 1, "base": cycle.base_version(), "summary": "tier it",
"notes": [{"lesson": lid, "action": "set-scope", "scope": "core"}]}
p = os.path.join(self.tmp, "cyc.json")
with open(p, "w") as f:
json.dump(doc, f)
r = self.sisi("cycle", "apply", p)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
try:
self.assertEqual(con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0], "core")
finally:
con.close()
r = self.sisi("cycle", "revert")
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
con = retro.connect()
try:
self.assertEqual(con.execute("SELECT scope FROM lessons WHERE id=?", (lid,)).fetchone()[0],
"unscoped-tier")
finally:
con.close()
if __name__ == "__main__":
unittest.main()