diff --git a/sisi/cycle.py b/sisi/cycle.py index 7aea31a..4a1d804 100644 --- a/sisi/cycle.py +++ b/sisi/cycle.py @@ -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"], diff --git a/sisi/documents.py b/sisi/documents.py index cc56d74..19ae699 100644 --- a/sisi/documents.py +++ b/sisi/documents.py @@ -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) diff --git a/tests/test_digest_short.py b/tests/test_digest_short.py deleted file mode 100644 index 55c1531..0000000 --- a/tests/test_digest_short.py +++ /dev/null @@ -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() diff --git a/tests/test_documents.py b/tests/test_documents.py deleted file mode 100644 index 72a63f4..0000000 --- a/tests/test_documents.py +++ /dev/null @@ -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() diff --git a/tests/test_learn.py b/tests/test_learn.py deleted file mode 100644 index c7701a0..0000000 --- a/tests/test_learn.py +++ /dev/null @@ -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 ("x", "x", - "x", "This session is being continued from a previous conversation", - "Caveat: x"): - 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": "/clear"}})[0]) - self.assertEqual(tt({"type": "user", "message": {"content": "/xdo it"}})[0], "do it") - txt, pasted, _ = tt({"type": "user", "message": {"content": "look " + "z" * 50 + " 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": "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() diff --git a/tests/test_learning.py b/tests/test_learning.py deleted file mode 100644 index fca1014..0000000 --- a/tests/test_learning.py +++ /dev/null @@ -1,1288 +0,0 @@ -"""The learning loop: lessons take effect at once, are delivered at the moment they match, are measured, -climb the strength ladder, and are consolidated by `sisi cycle`. Nothing here uses a scheduler: due-ness -is a counter checked in tick, the gate, retro, verify and done-for, announced at most once per session -until 20 further checks pass or the counter grows.""" -import json, os, random, sqlite3, time, unittest -from support import * -from sisi import cycle, gate, overlay, paths, pdata, retro, store -from test_verifiers import LibCase, vfile, dfile - -PARSER_CHANGE = "Prefer a readiness probe over a fixed sleep when waiting for parser servers to answer" -CSV_WHEN = "csv, tsv, spreadsheet, tabular data, import, export, parse, delimited file" -PARSER_WHEN = "parser, server readiness, startup wait, readiness probe, dev server, waiting" - - -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=PARSER_CHANGE) - f.update(kw) - return f - - -class LearningCase(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 again(self, lid): - con = retro.connect() - try: - retro.add_occurrence(con, lid, "again the parser server waited in step 7", self.proj, None) - con.commit() - finally: - con.close() - - def cycle_doc(self, **parts): - doc = {"version": 1, "base": cycle.base_version(), "summary": "test cycle"} - doc.update(parts) - # A cycle file must now summarise every active lesson lacking a short line: - # add a set-short for any not already covered or leaving the active notes. - try: - con = retro.connect() - try: - rows = [dict(r) for r in con.execute( - "SELECT id, short, topic, pattern_id, scope FROM lessons WHERE status IN ('open','applied')")] - finally: - con.close() - notes = list(doc.get("notes") or []) - covered = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-short"} - scoped = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-scope"} - exempt = {e.get("lesson") for e in notes if isinstance(e, dict) - and e.get("action") in ("retire", "withdraw", "merge")} - extra = [] - patterned = {e.get("lesson") for e in notes if isinstance(e, dict) and e.get("action") == "set-pattern"} - for r in rows: - if r["id"] not in scoped and r["id"] not in exempt: - extra.append({"lesson": r["id"], "action": "set-scope", "scope": "core"}) - if not r.get("pattern_id") and r["id"] not in patterned and r["id"] not in exempt and r.get("scope") != "project": - extra.append({"lesson": r["id"], "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"}) - if r["id"] in covered or r["id"] in exempt: - continue - if (r.get("short") or "").strip() and (r.get("topic") or "").strip(): - continue - e = {"lesson": r["id"], "action": "set-short"} - if not (r.get("short") or "").strip(): - e["short"] = "Use a readiness probe, not a sleep." - if not (r.get("topic") or "").strip(): - e["topic"] = "testing" - extra.append(e) - if extra: - doc["notes"] = notes + extra - except Exception: - pass - # 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 overlay_bytes(self): - out = {} - base = paths.overlay_dir() - for dp, dns, fns in os.walk(base): - for n in fns: - p = os.path.join(dp, n) - with open(p, "rb") as f: - out[os.path.relpath(p, base)] = f.read() - return out - - -class ImmediateEffectTests(LearningCase): - def test_field_note_on_first_occurrence_verifier_and_recipe(self): - a = self.mk(change_kind="verifier", target="fuzz", - change="Say in the fuzz notes: seed the corpus from the golden files before fuzzing parsers") - b = self.mk(change_kind="recipe", target="parser-or-codec", - change="Add the readiness probe to the parser-or-codec recipe Checks for server work") - for lid, target in ((a, "fuzz"), (b, "parser-or-codec")): - l = self.lesson(lid) - self.assertEqual((l["status"], l["effect"], l["folded_into"]), ("applied", "field-note", target)) - self.assertIn("lesson %d" % lid, open(os.path.join(self.notes, target + ".md")).read()) - self.again(a) # a later occurrence never duplicates the bullet - self.assertEqual(open(os.path.join(self.notes, "fuzz.md")).read().count("seed the corpus"), 1) - - def test_draft_recipe_note_for_a_recipe_that_does_not_exist(self): - lid = self.mk(change_kind="recipe", target="curated-record-change", - change="Add a recipe 'curated-record-change' for editing a sourced record in a curated dataset") - l = self.lesson(lid) - self.assertEqual((l["effect"], l["folded_into"]), ("draft-recipe", "draft:curated-record-change")) - self.assertTrue(os.path.exists(os.path.join(self.notes, "draft-curated-record-change.md"))) - out = self.sisi("done", "for", "editing a sourced record in a curated dataset").stdout - self.assertIn("Draft recipe curated-record-change", out) - miss = self.sisi("done", "for", "quantum chromodynamics lattice gauge").stdout - self.assertNotIn("Draft recipe", miss) - - def test_rule_oracle_brief_become_learned_notes_with_triggers(self): - for kind in ("rule", "oracle", "brief"): - lid = self.mk(change_kind=kind, change=PARSER_CHANGE + " (%s)" % kind, - moment="moment for %s at step 2 of the upload" % kind) - l = self.lesson(lid) - self.assertEqual(l["effect"], "learned-note") - self.assertIn("pars", l["triggers"]) # stems: parser/parsing/parse all meet at 'pars' - self.assertTrue(l["applied_at"]) - - def test_tool_lessons_backlog_order_and_dev_mode_tick_line(self): - a = self.mk(change_kind="tool", change="Make the gate count session edits separately per session") - b = self.mk(change_kind="tool", change="Make sisi verify name the slowest check first") - c = self.mk(change_kind="tool", change="Cache transcript scans between gate decisions") - self.again(b); self.again(b); self.again(c); self.again(c) - out = self.sisi("backlog").stdout.splitlines() - ids = [int(l.split()[0][1:]) for l in out if l.startswith("#")] - self.assertEqual(ids, [b, c, a]) # most seen first; the tie goes to the older lesson - self.assertEqual(self.lesson(b)["effect"], "backlog") - paths.set_personal_config(("developer", "source"), self.proj, "test") - tick = self.sisi("tick", stdin=json.dumps({"session_id": "dev1", "cwd": self.proj, "source": "startup"})).stdout - self.assertIn("top sisi backlog #%d" % b, tick) - other = os.path.join(self.tmp, "elsewhere"); os.makedirs(other) - tick2 = self.sisi("tick", stdin=json.dumps({"session_id": "dev2", "cwd": other, "source": "startup"})).stdout - self.assertNotIn("backlog", tick2) - - -class DeliveryTests(LearningCase): - def setUp(self): - super().setUp() - self.lid = self.mk() - - def test_each_moment_appends_matching_lessons_and_records_it(self): - checks = [ - ("done-for", lambda: self.sisi("done", "for", "parser-or-codec server readiness").stdout), - ("verifiers-for", lambda: self.sisi("verifiers", "for", "parser server readiness probe").stdout), - ("verifiers-show", lambda: self.sisi("verifiers", "show", "fuzz").stdout - if False else self._show()), - ] - block = retro.lessons_block("parser server readiness probe", "done-for", session="s-x") - self.assertIn("#%d" % self.lid, block) - self.assertLessEqual(len(block), 600) - out = checks[0][1]() - self.assertIn("lessons from earlier agents", out) - con = retro.connect() - places = [r[0] for r in con.execute("SELECT place FROM impressions WHERE lesson_id=?", (self.lid,))] - con.close() - self.assertIn("done-for", places) - out2 = checks[1][1]() - self.assertIn("lessons from earlier agents", out2) - - def _show(self): - lid = self.mk(change_kind="verifier", target="fuzz", - change="Seed the fuzz corpus from golden parser files before fuzzing") - return self.sisi("verifiers", "show", "fuzz").stdout - - def test_verifiers_show_and_contract_init(self): - out = self._show() - self.assertIn("lessons from earlier agents", out) - proj2 = os.path.join(self.tmp, "proj2"); os.makedirs(proj2) - r = self.sisi("contract", "init", "--goal", "parser server readiness for uploads", cwd=proj2) - self.assertEqual(r.returncode, 0, r.stdout) - self.assertIn("lessons from earlier agents", r.stdout) - - def test_irrelevant_query_surfaces_nothing(self): - self.assertEqual(retro.lessons_block("quantum chromodynamics lattice gauge theory", "done-for"), "") - self.assertEqual(retro.match_lessons("zebra xylophone quasar"), []) - - def test_block_is_capped_at_three_and_600_characters(self): - for i in range(8): - self.mk(change="Parser server readiness variant %d prefers probes over fixed sleeps always" % i, - moment="parser wait number %d at step 3" % i) - block = retro.lessons_block("parser server readiness probe fixed sleep", "done-for") - self.assertLessEqual(len(block), 600) - self.assertLessEqual(len([l for l in block.splitlines() if l.startswith("- #")]), 3) - - def test_tick_shows_highest_strength_first_and_records(self): - strong = self.mk(change="Zebra marker lesson about caching widgets quietly", moment="widget cache step 1") - con = retro.connect() - con.execute("UPDATE lessons SET strength=3 WHERE id=?", (strong,)) - con.commit(); con.close() - block = retro.tick_block(self.proj, session="tick-s") - lines = [l for l in block.splitlines() if l.startswith("- ")] - self.assertTrue(lines[0].startswith("- Zebra marker"), lines) - con = retro.connect() - self.assertTrue(con.execute("SELECT 1 FROM impressions WHERE lesson_id=? AND place='tick' AND session='tick-s'", - (strong,)).fetchone()) - con.close() - - def test_gate_send_back_carries_matching_lessons(self): - self.git_init() - c = check("parser-readiness", "false") - c["claim"] = "the parser server answers the readiness probe" - self.write_contract(contract([c])) - self.sisi("tick", stdin=json.dumps({"session_id": "g1", "cwd": self.proj, "source": "startup"})) - with open(os.path.join(self.proj, "work.txt"), "w") as f: - f.write("x\n") - a, msg = gate.decide({"session_id": "g1", "cwd": self.proj}) - self.assertEqual(a, "block") - self.assertIn("lessons from earlier agents", msg) - self.assertIn("#%d" % self.lid, msg) - - -class LadderTests(LearningCase): - def test_promotion_needs_two_showings_then_recurrence(self): - lid = self.mk() - self.again(lid) - self.assertEqual(self.lesson(lid)["strength"], 1) # never shown: no promotion - retro.record_shown([lid], "tick", "s") - self.again(lid) - self.assertEqual(self.lesson(lid)["strength"], 1) # shown once: still no - retro.record_shown([lid], "tick", "s") - self.again(lid) - l = self.lesson(lid) - self.assertEqual((l["strength"], l["needs_cycle"]), (2, 1)) - self.again(lid) # no fresh showings since the promotion: no second step on stale evidence - self.assertEqual(self.lesson(lid)["strength"], 2) - retro.record_shown([lid], "tick", "s") - self.again(lid) # only one fresh showing: still no - self.assertEqual(self.lesson(lid)["strength"], 2) - retro.record_shown([lid], "tick", "s") - self.again(lid) # two fresh showings, another recurrence: strength 3 - self.assertEqual(self.lesson(lid)["strength"], 3) - self.again(lid) - self.assertEqual(self.lesson(lid)["status"], "open") # withdrawal also needs fresh showings - retro.record_shown([lid], "tick", "s"); retro.record_shown([lid], "tick", "s") - self.again(lid) # enforced, shown afresh, still recurring: withdrawn - self.assertEqual(self.lesson(lid)["status"], "withdrawn") - self.assertEqual(retro.match_lessons("parser server readiness probe"), []) - - def test_property_ladder_matches_a_simple_reference(self): - def reference(events): - s, shown, promoted_at, status = 1, 0, 0, "open" - for ev in events: - if status != "open": - continue - if ev == "show": - shown += 1 - elif shown - promoted_at >= 2: - if s < 3: - s += 1 - promoted_at = shown - else: - status = "withdrawn" - return s, status - for seed in [0, 1, 7] + [random.randrange(2 ** 32) for _ in range(ITERS)]: - rng = random.Random(seed) - events = [rng.choice(("show", "recur")) for _ in range(30)] - lid = self.mk(change="Reference lesson %d about parser readiness probes" % seed, - moment="reference wait %d at step 2" % seed) - for ev in events: - if ev == "show": - retro.record_shown([lid], "tick", "ref") - else: - self.again(lid) - l = self.lesson(lid) - got = (l["strength"], "withdrawn" if l["status"] == "withdrawn" else "open") - self.assertEqual(got, reference(events), "seed %d" % seed) - - def test_folded_lesson_shown_twenty_times_without_recurrence_retires(self): - lid = self.mk(change_kind="verifier", target="fuzz", - change="Seed the fuzz corpus from golden parser files before fuzzing") - for _ in range(19): - retro.record_shown([lid], "tick", "s") - self.assertEqual(self.lesson(lid)["status"], "applied") - retro.record_shown([lid], "tick", "s") - self.assertEqual(self.lesson(lid)["status"], "retired") - lid2 = self.mk(change_kind="verifier", target="fuzz", - change="Keep fuzz seeds beside the parser golden files always", - moment="fuzz seeds missing at step 5") - retro.record_shown([lid2], "tick", "s") - self.again(lid2) # a recurrence after being shown: retirement must not fire - for _ in range(20): - retro.record_shown([lid2], "tick", "s") - self.assertNotEqual(self.lesson(lid2)["status"], "retired") - - def test_withdrawn_lesson_is_not_relearned_in_the_same_form(self): - lid = self.mk() - con = retro.connect() - con.execute("UPDATE lessons SET status='withdrawn' WHERE id=?", (lid,)) - con.commit(); con.close() - from test_retro import argv as retro_argv, GOOD - r = self.sisi("retro", *retro_argv(dict(GOOD, change=PARSER_CHANGE, new=True))) - self.assertEqual(r.returncode, 2, r.stdout) - self.assertIn("withdrawn", r.stdout) - - def test_measurement_counts_shows_and_recurrences(self): - lid = self.mk() - retro.record_shown([lid], "done-for", "sess-9") - retro.record_shown([lid], "gate", "sess-9") - self.again(lid) - con = retro.connect() - row = con.execute("SELECT * FROM lessons WHERE id=?", (lid,)).fetchone() - self.assertEqual(retro.shown_count(con, lid), 2) - self.assertEqual(retro.recurrences_after_shown(con, row), 1) - sess = con.execute("SELECT DISTINCT session FROM impressions WHERE lesson_id=?", (lid,)).fetchone()[0] - self.assertEqual(sess, "sess-9") - con.close() - out = self.sisi("lessons", "show", str(lid)).stdout - self.assertIn("listed 2 time(s), read 0, 1 recurrence(s)", out) - - -class CycleDueTests(LearningCase): - def make_due(self, n=5): - return [self.mk(change="Due lesson %d about parser readiness probes" % i, - moment="due wait %d at step 2" % i) for i in range(n)] - - def test_due_by_count_pending_and_notes_size(self): - self.assertEqual(self.sisi("cycle", "due").returncode, 1) - self.make_due(2) - con = retro.connect() - con.execute("UPDATE lessons SET needs_cycle=1 WHERE id=(SELECT min(id) FROM lessons)") - con.commit(); con.close() - r = self.sisi("cycle", "due") - self.assertEqual(r.returncode, 0, r.stdout) - self.assertIn("waiting for consolidation", r.stdout) - - def test_due_by_five_lessons_and_by_notes_size(self): - self.make_due(5) - r = self.sisi("cycle", "due") - self.assertEqual(r.returncode, 0) - self.assertIn("5 lessons recorded since the last cycle", r.stdout) - con = retro.connect() - con.execute("UPDATE lessons SET created='2000-01-01T00:00:00Z'") - retro.set_meta(con, "last_cycle_ts", "2999-01-01T00:00:00Z") - con.execute("UPDATE lessons SET change=change || ? ", (" padding" * 300,)) - con.commit(); con.close() - st = cycle.due_state() - self.assertTrue(any("note" in x for x in st["reasons"]), st) - - def test_no_nag_for_twenty_checks_then_again_and_counter_growth(self): - self.make_due() - first = cycle.due_notice(session="nag") - self.assertIn("learning cycle is due", first) - for _ in range(20): - self.assertEqual(cycle.due_notice(session="nag"), "") - self.assertIn("learning cycle is due", cycle.due_notice(session="nag")) - self.assertEqual(cycle.due_notice(session="nag"), "") - self.mk(change="One more parser readiness lesson arrives", moment="one more wait at step 9") - self.assertIn("learning cycle is due", cycle.due_notice(session="nag")) # the counter grew - - def test_due_line_in_retro_verify_done_for_gate_and_tick(self): - self.make_due(4) - from test_retro import argv as retro_argv, GOOD - r = self.sisi("retro", *retro_argv(dict(GOOD, change="Add the readiness probe to every server recipe Checks list", - moment="`sisi done` run 12 showed no readiness probe for servers", new=True)), - env={"SISI_SESSION_ID": "due-retro"}) - self.assertEqual(r.returncode, 0, r.stdout) - self.assertIn("learning cycle is due", r.stdout) - tick = self.sisi("tick", stdin=json.dumps({"session_id": "due-tick", "cwd": self.proj, "source": "startup"})).stdout - self.assertIn("learning cycle is due", tick) - self.assertIn("learning cycle is due", - self.sisi("done", "for", "parser-or-codec", env={"SISI_SESSION_ID": "due-done"}).stdout) - self.git_init() - self.write_contract(contract([check("ok", "true")])) - v = self.sisi("verify", env={"SISI_SESSION_ID": "due-verify"}) - self.assertEqual(v.returncode, 0, v.stdout) - self.assertIn("learning cycle is due", v.stdout) - v2 = self.sisi("verify", env={"SISI_SESSION_ID": "due-verify"}) - self.assertNotIn("learning cycle is due", v2.stdout) # same session: no nagging - with open(os.path.join(self.proj, "work.txt"), "w") as f: - f.write("x\n") - a, msg = gate.decide({"session_id": "due-gate", "cwd": self.proj}) - self.assertEqual(a, "allow") - self.assertIn("learning cycle is due", msg or "") - - -RULE_BODY = ("Before non-trivial work, write a contract at `.sisi/contract.json` in the project " - "(`sisi contract init` creates the skeleton) listing the checks that decide success.\n\n" - "Why: a request says what is wanted, rarely how success is measured.") - - -class CycleApplyTests(LearningCase): - def test_brief_has_base_lessons_rulebook_and_format(self): - lid = self.mk() - con = retro.connect() - con.execute("UPDATE lessons SET strength=3 WHERE id=?", (lid,)) - con.commit(); con.close() - out = self.sisi("cycle").stdout - self.assertIn("Base version (copy into your file): " + cycle.base_version(), out) - self.assertIn("#%-4d" % lid, out) - self.assertIn("NEEDS A CHECK", out) - self.assertIn("budget %d" % overlay.MAX_LINES, out) - self.assertIn("Current rulebook", out) - self.assertIn("sisi cycle apply FILE", out) - self.assertIn("contract-requirement", out) - - def test_apply_merges_folds_replaces_and_enforces(self): - a = self.mk(change="Parser readiness probes beat fixed sleeps for servers", moment="wait a at step 1") - b = self.mk(change="Fixed sleeps waste minutes when parser servers start slowly", moment="wait b at step 2") - c = self.mk(change_kind="recipe", target="parser-or-codec", - change="Parser recipes need a fuzz check for hostile inputs", moment="hostile input at step 3") - pre, base = overlay.base_rules() - title = next(r["title"] for r in base if r["id"] == "know-done") - doc = self.cycle_doc( - rules=[{"id": "know-done", "title": title, "body": RULE_BODY, "action": "replace"}], - notes=[{"lesson": a, "action": "fold-into-rule", "into": "know-done"}, - {"lesson": b, "action": "merge", "merged_into": a}], - enforced=[{"lesson": c, "type": "contract-requirement", "when": "parser", - "require_kind": "parsing", "max_rung": 2}]) - r = self.sisi("cycle", "apply", doc) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertTrue(os.path.exists(paths.overlay_dir("rules", "know-done.md"))) - self.assertIn("success is measured", open(paths.generated()).read()) - la, lb, lc = self.lesson(a), self.lesson(b), self.lesson(c) - self.assertEqual((la["folded_into"], la["strength"]), ("rule:know-done", 2)) - self.assertEqual(lb["status"], "superseded") - self.assertEqual((lc["strength"], bool(lc["check_json"])), (3, True)) - self.assertEqual(len(cycle.load_enforced()), 1) - self.assertIn("cycle-0001", self.sisi("cycle", "status").stdout) - log = pdata.git("log", "--format=%s", "-1").stdout - self.assertIn("cycle cycle-0001", log) - - def test_apply_refuses_saying_exactly_why(self): - lid = self.mk() - cases = [ - ({"notes": [{"lesson": 9999, "action": "keep"}]}, "no lesson with id 9999"), - ({"rules": [{"id": "know-done", "title": "X", "body": "no reason here", "action": "replace"}]}, "must keep its Why"), - ({"enforced": [{"lesson": lid, "type": "command", "cmd": "definitely-not-here-xyz --fast", - "expect": {"exit": 0}}]}, "does not exist on this machine"), - ({"rules": [{"id": "know-done", "title": "X", "body": "Use `sisi frobnicate` first.\n\nWhy: testing", - "action": "replace"}]}, "not a command"), - ] - for parts, why in cases: - with self.subTest(why): - before = self.overlay_bytes() - r = self.sisi("cycle", "apply", self.cycle_doc(**parts)) - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn(why, r.stdout) - self.assertEqual(self.overlay_bytes(), before) - doc = {"version": 1, "base": "stale", "summary": "x", "notes": [{"lesson": lid, "action": "keep"}]} - p = os.path.join(self.tmp, "stale.json") - with open(p, "w") as f: - json.dump(doc, f) - r = self.sisi("cycle", "apply", p) - self.assertEqual(r.returncode, 1) - self.assertIn("stale base", r.stdout) - - def test_rulebook_may_grow_only_by_replacement(self): - r = self.sisi("cycle", "apply", self.cycle_doc(disable_rules=["know-done"])) - self.assertEqual(r.returncode, 0, r.stdout) - doc = self.cycle_doc(rules=[{"id": "brand-new-rule", "title": "Brand new", - "body": "Do the brand new thing carefully.\n\nWhy: it helps.", "action": "add"}]) - r = self.sisi("cycle", "apply", doc) - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("would grow", r.stdout) - - def test_two_sessions_second_apply_refuses_cleanly(self): - a = self.mk(change="Session one lesson about parser readiness", moment="s1 wait at step 1") - b = self.mk(change="Session two lesson about widget caching", moment="s2 wait at step 2") - base = cycle.base_version() # both sessions read the same brief - _ss = lambda lid: {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"} - _sc = lambda lid: {"lesson": lid, "action": "set-scope", "scope": "core"} - _sp = lambda lid: {"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"} - doc1 = {"version": 1, "base": base, "summary": "one", "notes": [{"lesson": a, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b), _sp(a), _sp(b)]} - doc2 = {"version": 1, "base": base, "summary": "two", "notes": [{"lesson": b, "action": "keep"}, _ss(a), _ss(b), _sc(a), _sc(b), _sp(a), _sp(b)]} - paths_ = [] - for i, d in enumerate((doc1, doc2)): - p = os.path.join(self.tmp, "two-%d.json" % i) - with open(p, "w") as f: - json.dump(d, f) - paths_.append(p) - self.assertEqual(self.sisi("cycle", "apply", str(paths_[0])).returncode, 0) - r = self.sisi("cycle", "apply", str(paths_[1])) - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("stale base", r.stdout) - self.assertEqual(len(cycle.cycle_records()), 1) - - def test_revert_undoes_exactly_and_only_the_newest(self): - a = self.mk() - before = self.overlay_bytes() - doc = self.cycle_doc(notes=[{"lesson": a, "action": "retire"}], - enforced=[{"lesson": a, "type": "command", "cmd": "true", "expect": {"exit": 0}}]) - self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) - self.assertNotEqual(self.overlay_bytes(), before) - self.assertEqual(self.lesson(a)["strength"], 3) - r = self.sisi("cycle", "revert", "cycle-9999") - self.assertEqual(r.returncode, 1) - self.assertIn("not the newest", r.stdout) - r = self.sisi("cycle", "revert") - self.assertEqual(r.returncode, 0, r.stdout) - self.assertEqual(self.overlay_bytes(), before) - l = self.lesson(a) - self.assertEqual((l["status"], l["strength"], l["check_json"]), ("open", 1, None)) - self.assertEqual(cycle.load_enforced(), []) - - def test_property_apply_then_revert_leaves_overlay_byte_identical(self): - pre, base = overlay.base_rules() - title = next(r["title"] for r in base if r["id"] == "know-done") - ids = [self.mk(change="Property lesson %d about parser readiness" % i, - moment="property wait %d at step 2" % i) for i in range(4)] - for seed in [0, 3] + [random.randrange(2 ** 32) for _ in range(ITERS)]: - rng = random.Random(seed) - before = self.overlay_bytes() - notes = [{"lesson": i, "action": rng.choice(("keep", "retire"))} for i in rng.sample(ids, rng.randint(1, 3))] - body = RULE_BODY + " (variant %d)" % seed - doc = self.cycle_doc( - rules=[{"id": "know-done", "title": title, "body": body, "action": "replace"}], - notes=notes, - enforced=[{"lesson": rng.choice(ids), "type": "contract-requirement", "when": "parser", - "require_kind": "parsing", "max_rung": 2}]) - r = self.sisi("cycle", "apply", doc) - self.assertEqual(r.returncode, 0, "seed %d: %s" % (seed, r.stdout + r.stderr)) - r = self.sisi("cycle", "revert") - self.assertEqual(r.returncode, 0, "seed %d: %s" % (seed, r.stdout)) - self.assertEqual(self.overlay_bytes(), before, "seed %d" % seed) - - def test_status_flags_a_cycle_that_made_deliveries_worse(self): - lid = self.mk() - rows = [{"end": "2020-01-01T00:00:00Z", "seconds": 60, "send_backs": 0} for _ in range(3)] - for r in rows: - store.append("deliveries", r) - doc = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}]) - self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) - rec = cycle.cycle_records()[-1] - self.assertFalse(cycle.flagged(rec)) # nothing measured since yet - for _ in range(10): - store.append("deliveries", {"end": "2999-01-01T00:00:00Z", "seconds": 900, "send_backs": 4}) - self.assertTrue(cycle.flagged(rec)) - self.assertIn("WORSE", self.sisi("cycle", "status").stdout) - self.assertIn("FIRST:", cycle.brief_text()) - - def test_cycle_can_set_when_terms_on_an_old_lesson(self): - lid = self.mk() - self.assertIsNone(self.lesson(lid)["when_terms"]) - brief = cycle.brief_text() - self.assertIn("Lessons with no when-terms yet", brief) - self.assertIn("#%d" % lid, brief) - bad = self.sisi("cycle", "apply", self.cycle_doc( - notes=[{"lesson": lid, "action": "keep", "when": "parser, servers"}])) - self.assertEqual(bad.returncode, 1, bad.stdout) - self.assertIn("when needs at least 5 terms", bad.stdout) - good = self.sisi("cycle", "apply", self.cycle_doc( - notes=[{"lesson": lid, "action": "keep", "when": PARSER_WHEN}])) - self.assertEqual(good.returncode, 0, good.stdout) - self.assertIn("readiness probe", self.lesson(lid)["when_terms"]) - self.assertNotIn("MISSING", cycle.brief_text().split("#%-4d" % lid)[1].splitlines()[2]) - - -class EnforcedTests(LearningCase): - def apply_enforced(self, entry): - lid = entry["lesson"] - doc = self.cycle_doc(enforced=[entry]) - r = self.sisi("cycle", "apply", doc) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - return lid - - def test_contract_requirement_is_checked_like_a_floor(self): - lid = self.mk() - self.apply_enforced({"lesson": lid, "type": "contract-requirement", "when": "parser", - "require_kind": "parsing", "max_rung": 2}) - weak = contract([check("p1", "true", rung=3, kind="general")]) - weak["checks"][0]["claim"] = "the parser accepts the sample files" - self.write_contract(weak) - r = self.sisi("verify") - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("enforced lesson #%d" % lid, r.stdout) - strong = contract([check("p1", "true", rung=2, kind="parsing")]) - strong["checks"][0]["claim"] = "the parser accepts the sample files" - self.write_contract(strong) - self.assertEqual(self.sisi("verify").returncode, 0) - - def test_command_check_runs_only_for_trusted_projects(self): - lid = self.mk() - self.apply_enforced({"lesson": lid, "type": "command", "cmd": "false", "expect": {"exit": 0}}) - c = contract([check("ok", "true")]) - self.write_contract(c, trusted=True) - res = cycle.enforced_results(c, self.proj) - self.assertEqual([x["status"] for x in res], ["failed"]) - from sisi import trust - trust.remove(self.proj) - self.assertEqual(cycle.enforced_results(c, self.proj), []) # never run untrusted - trust.add(self.proj) - self.assertEqual(self.sisi("verify").returncode, 1) - - -class ImproveAndMigrationTests(LearningCase): - def test_improve_says_too_little_data_then_answers(self): - out = self.sisi("improve").stdout - self.assertIn("Is it getting better?", out) - self.assertIn("Too little data", out) - lid = self.mk() - self.again(lid) - for _ in range(6): - store.append("deliveries", {"end": store.now(), "seconds": 120, "send_backs": 1}) - out = self.sisi("improve").stdout - self.assertIn("1 taking effect", out) - self.assertIn("0 folded into a recipe, entry or rule, 1 still loose notes", out) - self.assertIn("showings:", out) - self.assertIn("rulebook:", out) - self.assertIn("Not measured:", out) - self.assertIn("learning :", self.sisi("status").stdout) - - def test_old_database_migrates_without_loss(self): - # a second, old-shaped database on the side, opened through retro.connect by swapping files - 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.execute("INSERT INTO occurrences VALUES (1,1,'2020-01-01T00:00:00Z','s','t','/tmp','/tmp','m','f')") - 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() # migration happens on open - row = dict(con.execute("SELECT * FROM lessons WHERE id=1").fetchone()) - occ = con.execute("SELECT count(*) FROM occurrences").fetchone()[0] - retro.ensure_effects(con) - con.close() - self.assertEqual((row["change"], occ), ("Seed the fuzz corpus from golden parser files", 1)) - self.assertEqual(row["strength"], 1) - self.assertIn("fuzz", row["triggers"]) - self.assertTrue(os.path.exists(os.path.join(self.notes, "fuzz.md"))) # effect folds in too - self.assertEqual(self.lesson(1)["status"], "applied") - - def test_old_lessons_jsonl_imports(self): - p = os.path.join(self.tmp, "old.jsonl") - with open(p, "w") as f: - f.write(json.dumps({"t": "lesson", "id": 7, "created": "2020-01-01T00:00:00Z", "aim": "speed", - "change_kind": "rule", "target": None, "moment": "m", "cause": "c", - "change": PARSER_CHANGE, "status": "open", "count": 1, - "last_seen": "2020-01-01T00:00:00Z"}) + "\n") - r = self.sisi("lessons", "import", p) - self.assertEqual(r.returncode, 0, r.stdout) - l = self.lesson(7) - self.assertEqual(l["change"], PARSER_CHANGE) - con = retro.connect() - retro._backfill(con) - con.close() - self.assertIn("pars", self.lesson(7)["triggers"]) - - -# ---- measured matching: a labelled corpus ----------------------------------- -# (lesson change, a later request as a different agent would phrase the same work) -SHOULD_MATCH = [ - ("For any CSV importer, run a property test that round-trips generated rows containing quotes, commas and newlines before saying it works", - "write a CSV importer for customer records"), - ("On btrfs, os.replace of a symlink is not atomic for readers: a lookup can see ENOENT mid-switch, so retry a missing current link briefly", - "atomically switch a symlink to the new release folder"), - ("Any test that runs a command which reads stdin must pass stdin explicitly (input or DEVNULL), because an inherited open pipe makes it hang", - "my test hangs when the subprocess reads from a pipe"), - ("Verify webhook HMAC signatures over the raw request body before parsing JSON, because reserialized JSON never matches", - "add a webhook endpoint that checks the signature"), - ("A daily 02:30 local job must decide what happens in the DST spring-forward gap, when that wall-clock time never occurs", - "schedule a daily job at 2:30 local time"), - ("Cursor pagination needs a stable tie-breaker on id after the timestamp, or rows sharing a timestamp are skipped between pages", - "paginate a feed without skipping items that share a timestamp"), - ("JWT tokens need a small clock-skew leeway on expiry, because client and server clocks differ by seconds", - "auth tokens rejected as expired due to clock differences"), - ("Money must be integer cents end to end; float prices round differently per platform and totals drift by a cent", - "price totals are off by a cent sometimes"), - ("Websocket reconnects need exponential backoff with jitter, or a dropped server gets a thundering herd of retries", - "live socket connection drops and reconnects in a loop"), - ("Phone photos carry EXIF orientation; decode must apply it or portrait uploads render sideways", - "uploaded photos appear sideways"), - ("Normalize filenames to NFC on read and write; macOS returns NFD, so accented names miss lookups byte-wise", - "file with an accented name is not found on disk"), - ("Reject tar entries whose names escape the destination with .. or absolute paths before extracting anything", - "extract a tar archive from an upload"), - ("Respect DNS TTL values and never cache address records in the process beyond them", - "DNS cache keeps serving old records after a change"), - ("Add a required column with expand-contract: nullable first, backfill in batches, then set NOT NULL in a later deploy", - "add a required column to a huge table without downtime"), - ("Copy dependency manifests and install before copying source, so the Docker layer cache survives code edits", - "docker build is slow because the dependency layer rebuilds after source edits"), - ("OAuth redirect URIs match exactly, including a trailing slash; register the byte-exact callback", - "OAuth callback fails with redirect mismatch"), - ("Resample microphone input from 48 kHz to the model's 16 kHz explicitly; playing it raw pitches a voice recording down", - "recorded voice plays back pitched down"), - ("Store GPS coordinates at full double precision; rounding to 4 decimal places moves a pin by metres", - "map pins drift by a few metres"), - ("Encode non-ASCII mail subjects as MIME encoded-words, or accented subjects arrive garbled", - "email subject lines with accents arrive garbled"), - ("Escape ampersands in sitemap URLs; a raw ampersand makes the XML unparsable", - "sitemap XML rejected for invalid characters in URLs"), - ("Plural choice must use CLDR plural categories per locale; one/other breaks Russian and Polish", - "Russian translations show the wrong plural form"), - ("Embed and subset fonts in generated PDFs, or printing on a machine without the font substitutes another typeface", - "PDF prints in the wrong typeface on another machine"), - ("A Redis lock must carry a random token and release by compare-and-delete, or an expired lock lets a second worker run the job", - "a second worker entered while the lock was still held"), - ("Parallel branches belong in git worktrees; two agents in one checkout share an index and stomp each other's staging", - "work on two branches at once in separate folders of one repo"), - ("A failed charge may be retried safely only with an idempotency key per checkout attempt, stored with the first response", - "retry a failed charge without billing the customer twice"), -] -# Later requests that must surface nothing: common words only, or a single distinctive word with no support. -SHOULD_NOT_MATCH = [ - "run the test file and check the output", "add a check for empty input", - "the tests take a long time to run", "read the input file line by line", - "run all the checks before finishing", "test it with a small example first", - "check the output matches the example", "write the results to a file", - "add a test for this change", "run it again and check the output", - "check the first line of the output file", "write a small test for the change", - "run the whole test suite again", "the output file is empty after the run", - "add the missing import and run it", "check the return value is not empty", - "write the output to a new file each time", "test the change with the example input", - "the first run is slower than the second", "add a line to the output for each input", - "write tests first, then the code", "open the CSV in a spreadsheet to look at it", - "restart the websocket service", "the tar file is huge", "renew the OAuth secret", - "rename a variable in the logger", -] - - -def _reached(block, lid): - import re - return bool(re.search(r"#%d \(" % lid, block)) - - -class MatchingCorpusTests(LearningCase): - def test_measured_part_one_precision_and_overall_reach(self): - # New behaviour: part one ("likely to apply", in full) must never fire on a should-not - # request; overall reach counts the right lesson in part one OR listed in part two within - # its budget, where the asking agent reads the headings and decides. - ids = [] - for i, (change, _) in enumerate(SHOULD_MATCH): - ids.append(self.mk(change=change, moment="incident %d at step 3" % i, - cause="overlooked at step 2")) - hits, misses = 0, [] - for lid, (_, query) in zip(ids, SHOULD_MATCH): - if _reached(retro.delivery_block(query, "corpus"), lid): - hits += 1 - else: - misses.append((lid, query)) - wrong = [q for q in SHOULD_NOT_MATCH if retro.delivery(q)[0]] - print("matching corpus: reach (part one or listed) %d/%d, part-one wrong %d/%d" - % (hits, len(SHOULD_MATCH), len(wrong), len(SHOULD_NOT_MATCH))) - self.assertGreaterEqual(hits / len(SHOULD_MATCH), 0.90, "misses: %r" % (misses,)) - self.assertEqual(wrong, [], "part one must stay empty for should-not requests") - - def test_csv_lesson_reaches_the_next_agent_three_ways(self): - r = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified", - "--moment", "The CSV importer test passed but 'python3 import.py big.csv' crashed on a quoted comma in row 4011", - "--cause", "the importer was only tested with three hand-written rows", - "--change-kind", "rule", "--when", CSV_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", - "--change", "For any CSV importer, run a property test that round-trips generated rows containing quotes, commas and newlines before saying it works") - self.assertEqual(r.returncode, 0, r.stdout) - self.assertIn("lesson #", r.stdout) - lid = int(r.stdout.split("lesson #")[1].split(",")[0]) - for q in ("write a CSV importer for customer records", "CSV importer with quotes and commas", - "import customer rows from a csv file"): - with self.subTest(q): - out = self.sisi("done", "for", q).stdout - self.assertIn("#%d" % lid, out) - self.assertIn("CSV importer", out) - - def test_recipe_title_words_alone_never_create_a_match(self): - # Regression: 'rename a variable in the logger' matched a gate lesson only through the words - # 'docs-change Changing' that `done for` added from the chosen recipe (chang escaped COMMON). - lid = self.mk(change="Make the gate attribute tree changes to sessions and stop counting a " - "send-back when another live session is changing the same files", - moment="gate send-backs in step 4 while files changed underneath") - self.assertEqual(retro.match_lessons("rename a variable in the logger"), []) - self.assertEqual(retro.match_lessons("rename a variable in the logger", - extra="docs-change Changing documentation"), []) - self.assertIn(retro._stem("changing"), retro.COMMON) - self.assertTrue(retro.match_lessons("gate send-backs when sessions change files", - extra="docs-change Changing documentation")) - - def test_part_two_headings_are_listed_not_read(self): - lid = self.mk(change="Seed the fuzz corpus from golden parser files before fuzzing", - moment="fuzz seeds missing at step 5", - when="fuzzing, parser, hostile input, generated input, corpus seeds, property testing") - out = self.sisi("done", "for", "fuzzing").stdout # one shared when word: a heading, not part one - self.assertIn("other lessons from earlier agents; open any that apply", out) - self.assertNotIn("likely to apply", out) - self.assertIn("#%d" % lid, out) - con = retro.connect() - self.assertEqual((retro.listed_count(con, lid), retro.read_count(con, lid)), (1, 0)) - self.assertEqual(con.execute("SELECT place FROM impressions WHERE lesson_id=?", (lid,)).fetchone()[0], - "done-for-listed") - con.close() - self.sisi("lessons", "show", str(lid)) # opening one in full is the reading - con = retro.connect() - self.assertEqual((retro.listed_count(con, lid), retro.read_count(con, lid)), (1, 1)) - con.close() - - def test_semicolon_prose_is_not_hidden_and_generic_fix_is_no_bridge(self): - # Two real-corpus failures: '; fixed-position...' read as a shell separator and silently hid - # the lesson; and the generic verb 'fix' offered an unrelated lesson as possibly related. - self.assertIsNotNone(retro.display_line("check it before shipping; fixed-position footers hide buttons", self.proj)) - self.assertIsNone(retro.display_line("do the thing; rm -rf build", self.proj)) - lid = self.mk(change="Check every page at a 375px phone width before shipping; fixed-position footers hide primary buttons", - moment="the button was below the fold in step 2 on a phone", - when="responsive, mobile, phone screen, small screen, layout, signup form") - out = self.sisi("done", "for", "make the signup form responsive on mobile").stdout - self.assertIn("#%d" % lid, out) - part1, _ = retro.delivery("fix the flaky thing") - self.assertEqual(part1, []) # a generic verb in the anecdote never makes a part-one match - - def test_done_id_also_shows_matched_lessons(self): - lid = self.mk(change_kind="recipe", target="parser-or-codec", - change="Parser recipes need a fuzz check over hostile generated inputs", - moment="hostile parser input at step 3", - when="parser, fuzzing, codec, hostile input, generated input") - out = self.sisi("done", "parser-or-codec").stdout - self.assertIn("likely to apply", out) # one when hit + target is the entry being printed - self.assertIn("#%d" % lid, out) - - def test_unconfirmed_duplicate_sighting_is_recorded(self): - first = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified", - "--moment", "the parser server waited 90 seconds in step 4 of the nightly job", - "--cause", "no readiness probe existed before the browser step", - "--change-kind", "rule", "--when", PARSER_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--change", PARSER_CHANGE) - self.assertEqual(first.returncode, 0, first.stdout) - lid = int(first.stdout.split("lesson #")[1].split(",")[0]) - dup = self.sisi("retro", "--scope", "everywhere", "--aim", "verified", - "--moment", "again the parser server waited 90 seconds in step 9 of the nightly job", - "--cause", "still no readiness probe before the browser step at all", - "--change-kind", "rule", "--when", PARSER_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", - "--change", "Prefer a readiness probe over a fixed sleep when waiting for parser servers") - self.assertEqual(dup.returncode, 4, dup.stdout) - self.assertIn("sighting was kept", dup.stdout) - con = retro.connect() - self.assertEqual(retro.sightings_count(con, lid), 1) - con.close() - self.assertIn("1 unconfirmed sighting(s)", self.sisi("lessons", "show", str(lid)).stdout) - as_new = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified", - "--moment", "again the parser server waited 90 seconds in step 9 of the nightly job", - "--cause", "still no readiness probe before the browser step at all", - "--change-kind", "rule", "--when", PARSER_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", - "--change", "Prefer a readiness probe over a fixed sleep when waiting for parser servers") - self.assertEqual(as_new.returncode, 0, as_new.stdout) # kept apart, but the sighting is not lost - con = retro.connect() - self.assertEqual(retro.sightings_count(con, lid), 1) - con.close() - - -# A harder set: each request shares NO content word with its lesson's moment, cause or change text. -# Only the recording agent's when-terms bridge the two wordings, as another agent would write them. -# (change, when, later request) -HARD_MATCH = [ - ("For any CSV importer, run a property test that round-trips generated rows containing quotes, commas and newlines before saying it works", - CSV_WHEN, "parse a spreadsheet export of orders into the database"), - ("Check every page at a 375px phone width with a screenshot before shipping; fixed-position footers hide primary buttons", - "responsive, mobile, phone screen, small screen, layout, viewport, signup form, login page", - "make the signup form responsive on mobile"), - ("Expand-contract only: nullable first, backfill in batches, switch reads, only then drop the old shape", - "migration, schema change, add column, users table, backfill, move data, alter table", - "add a column to the users table and move the data over"), - ("Photographs carry orientation metadata; decode must apply it or portraits render rotated", - "sideways photos, image rotation, uploaded pictures, EXIF, photo orientation", - "uploaded pictures appear sideways"), - ("Verify HMAC signatures over the raw request body before parsing JSON, because reserialized JSON never matches", - "webhook, payment callback, provider notifications, signed callbacks, callback authentication", - "payment provider callbacks must be authenticated"), - ("On btrfs, os.replace of a link is not atomic for readers: a lookup can see ENOENT midway, so retry a missing one briefly", - "symlink, release switch, atomic deploy, current pointer, live version", - "point the live release symlink at the new build"), - ("Pass standard input explicitly or use DEVNULL; inherited descriptors can block", - "stdin, pipe, subprocess hang, blocked process, standard input, inherited pipe", - "subprocess hangs reading from a pipe"), - ("A 02:30 daily trigger must define behaviour for the spring-forward gap, when that local time never occurs", - "DST, daylight saving, schedule, nightly job, clock change, timezone", - "schedule a nightly job that survives clock changes"), - ("Cursor order needs a stable tie-breaker on id after the timestamp, or rows sharing a timestamp are skipped between responses", - "pagination, feed scrolling, cursor pages, endless list, missing items", - "scrolling the feed misses items"), - ("Amounts must be integer cents end to end; floats round differently per platform", - "money, prices, totals, penny, rounding, billing amounts, checkout total", - "checkout total differs by a penny"), - ("Expiry checks need a small leeway in seconds, because two machines' clocks differ", - "JWT, tokens, logged out, session expiry, auth, token expired", - "users randomly logged out with token expired errors"), - ("Reject entries whose names escape the destination with dot-dot or absolute paths before extracting anything", - "archive extraction, zip slip, unpack upload, tar, path traversal, extracting archives", - "safely unpack a zip from a customer"), - ("Respect TTL values; a process-level resolver cache must expire entries on time", - "DNS, old server, address change, resolver, hostname lookup, stale address", - "app keeps calling the old server address after the move"), - ("Copy dependency manifests and install before copying source, so the layer cache survives code edits", - "docker, container build, image layers, slow builds, caching, dockerfile", - "container image builds take ten minutes after every tweak"), - ("Redirect URIs match exactly, including a trailing slash; register the byte-exact callback", - "OAuth, login, Google sign-in, callback mismatch, redirect, sign in", - "login with Google fails after consent"), - ("Resample microphone input from 48 kHz to the model's 16 kHz explicitly; playing it raw pitches speech lower", - "audio, voice notes, pitch, sample rate, microphone, resampling", - "voice notes sound like a slowed-down robot"), - ("Store coordinates at full double precision; rounding to 4 decimal places moves a pin by metres", - "GPS, map markers, coordinates, location accuracy, pins", - "map markers land on the wrong street"), - ("Encode non-ASCII mail subjects as encoded-words, or accented subjects arrive garbled", - "MIME, email subject, umlauts, garbled headers, header encoding, non-ASCII mail", - "German umlauts in email headers break"), - ("Plural choice must use CLDR categories per locale; one/other is not enough for many languages", - "i18n, plural forms, Polish, Russian, translations, word forms, localization", - "Polish users see incorrect word forms for counts"), - ("A Redis lock must carry a random token and release by compare-and-delete, or expiry lets another holder in", - "distributed lock, cron overlap, duplicate runs, Redis lock, mutex, scheduled job", - "the same scheduled job executed on two machines at once"), - ("A missing config file must print one plain line naming the path it wanted and exit 2, never a traceback", - "cli, command line, terminal tool, script, arguments, flags, config file, error message, exit code, usage", - "add a --verbose option to the backup script"), -] -HARD_NOT_MATCH = [ - "write a haiku about autumn", "fix flaky websocket reconnect", "rename a variable in the logger", - "translate the README into French", "tidy up CSS variable names", - "show each task's deadline on the weekly planner", "optimise the image thumbnail resizer", - "run the test file and check the output", "add a check for empty input", - "read the input file line by line", "run all the checks before finishing", - "export the quarterly report", "mobile app crashes on startup", - "schedule a team lunch next week", "polish the landing page design", - "check the return value is not empty", "write the output to a new file each time", - "test the change with the example input", "add a line to the output for each input", - "write tests first, then the code", "restart the websocket service", - "check the first line of the output file", "run it again and check the output", - "add the missing import and run it", -] -HARD_MOMENT, HARD_CAUSE = "spotted at step 3", "overlooked at step 2" - - -class HarderMatchingTests(LearningCase): - def test_measured_recall_when_only_when_terms_bridge_the_words(self): - ids = [] - for change, when, query in HARD_MATCH: - content = (retro._stems(change) | retro._stems(HARD_MOMENT) | retro._stems(HARD_CAUSE)) - retro.COMMON - asked = retro._stems(query) - retro.COMMON - self.assertFalse(content & asked, "pair shares content words %r: %r" % (content & asked, query)) - self.assertTrue(retro._stems(when) & asked, "pair shares no when word either: %r" % query) - ids.append(self.mk(change=change, moment=HARD_MOMENT, cause=HARD_CAUSE, when=when)) - hits, part1_hits, misses = 0, 0, [] - for lid, (_, _, query) in zip(ids, HARD_MATCH): - p1, _ = retro.delivery(query) - if lid in [d["row"]["id"] for d in p1]: - part1_hits += 1 - if _reached(retro.delivery_block(query, "corpus"), lid): - hits += 1 - else: - misses.append((lid, query)) - wrong = [q for q in HARD_NOT_MATCH if retro.delivery(q)[0]] - print("harder matching (when-terms only): reach %d/%d (part one %d), part-one wrong %d/%d" - % (hits, len(HARD_MATCH), part1_hits, len(wrong), len(HARD_NOT_MATCH))) - self.assertEqual(hits, len(HARD_MATCH), "misses: %r" % (misses,)) - self.assertEqual(wrong, [], "part one must stay empty for should-not requests") - - -class ImproveFromUseTests(LearningCase): - def test_sisi_improves_from_use_end_to_end(self): - """The purpose itself: a lesson from session A reaches session B doing the same kind of work, - its showing is recorded, and recurrence after fresh showings strengthens it until a cycle is due.""" - a = self.sisi("retro", "--new", "--scope", "everywhere", "--aim", "verified", - "--moment", "The CSV importer test passed but 'python3 import.py big.csv' crashed on a quoted comma in row 4011", - "--cause", "the importer was only tested with three hand-written rows", - "--change-kind", "rule", "--when", CSV_WHEN, "--pattern", "Reach for the familiar tool instead of the check that fits the claim", - "--change", "For any CSV importer, run a property test that round-trips generated rows containing quotes, commas and newlines before saying it works", - env={"SISI_SESSION_ID": "session-A"}) - self.assertEqual(a.returncode, 0, a.stdout) - lid = int(a.stdout.split("lesson #")[1].split(",")[0]) - b_env = {"SISI_SESSION_ID": "session-B"} - for out in (self.sisi("done", "for", "write a CSV importer for customer records", env=b_env).stdout, - self.sisi("verifiers", "for", "csv parsing must survive quotes and commas", env=b_env).stdout): - self.assertIn("#%d" % lid, out) - proj2 = os.path.join(self.tmp, "csvproj"); os.makedirs(proj2) - init = self.sisi("contract", "init", "--goal", "import customer rows from a csv file", cwd=proj2, env=b_env) - self.assertIn("#%d" % lid, init.stdout) - unrelated = self.sisi("done", "for", "style a settings page with a sidebar", env=b_env).stdout - self.assertEqual(retro.delivery("style a settings page with a sidebar")[0], []) # never in part one - self.assertNotIn("likely to apply", unrelated) # at most an unconfirmed heading in part two - con = retro.connect() - places = sorted(r[0] for r in con.execute( - "SELECT DISTINCT place FROM impressions WHERE lesson_id=? AND session='session-B'", (lid,))) - con.close() - # verifiers-for matched in part one (csv + parse in the when-terms); the other two listed it - self.assertEqual(places, ["contract-init-listed", "done-for-listed", "verifiers-for"]) - same = self.sisi("retro", "--same-as", str(lid), - "--moment", "again a quoted comma in row 88 broke 'python3 import.py small.csv'", - env=b_env) - self.assertEqual(same.returncode, 0, same.stdout) - self.assertEqual(self.lesson(lid)["strength"], 2) # three showings, then the same mistake - due = self.sisi("cycle", "due") - self.assertEqual(due.returncode, 0, due.stdout) - self.assertIn("waiting for consolidation", due.stdout) - # a second round of showings, then another recurrence: up another step on fresh evidence - self.sisi("done", "for", "CSV importer with quotes and commas", env=b_env) - self.sisi("verifiers", "for", "csv parsing must survive quotes and commas", env=b_env) - same2 = self.sisi("retro", "--same-as", str(lid), - "--moment", "a newline inside a quoted field broke 'python3 import.py rows.csv' at row 12", - env=b_env) - self.assertEqual(same2.returncode, 0, same2.stdout) - self.assertEqual(self.lesson(lid)["strength"], 3) - - -RECIPE_TEXT = """--- -id: curated-record-change -title: Editing a curated record -applies_to: Editing a sourced record in a curated dataset. ---- - -## Done means -- The record is edited and its source is cited. - -## Checks -- Show the edited record matches its source. - -## Common false finishes -- Editing without checking the source. -""" - - -class CycleGapTests(LearningCase): - def test_gap01_brief_full_text_and_show_hint(self): - lid = self.mk(change="Parser readiness probes beat fixed sleeps for servers always", - moment="the parser server waited at step 4") - out = cycle.brief_text() - self.assertIn("Parser readiness probes beat fixed sleeps", out) - self.assertIn("sisi lessons show ID", out) # reading instruction present - old = cycle.BRIEF_TEXT_BUDGET - cycle.BRIEF_TEXT_BUDGET = 10 - try: - out2 = cycle.brief_text() - finally: - cycle.BRIEF_TEXT_BUDGET = old - self.assertIn("`sisi lessons show %d`" % lid, out2) - self.assertIn("text budget", out2) - - def test_gap02_reading_does_not_stale_base_and_stale_is_precise(self): - lid = self.mk() - base = cycle.base_version() - self.sisi("lessons", "show", str(lid)) # a read: counters only - retro.record_shown([lid], "done-for", "s") - doc = self.cycle_doc(notes=[{"lesson": lid, "action": "keep"}]) - # cycle_doc recomputes base; rebuild with the original base - d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}, - {"lesson": lid, "action": "set-scope", "scope": "core"}, - {"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"}, - {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]} - p = os.path.join(self.tmp, "g2.json") - with open(p, "w") as f: - json.dump(d, f) - self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0) - # now a real change stales a fresh brief, precisely - lid2 = self.mk(change="Second parser readiness lesson for stale check", moment="second wait at step 2") - base2 = cycle.base_version() - con = retro.connect() - con.execute("UPDATE lessons SET status='retired' WHERE id=?", (lid2,)) - con.commit(); con.close() - d2 = {"version": 1, "base": base2, "summary": "x", "notes": [{"lesson": lid2, "action": "keep"}]} - p2 = os.path.join(self.tmp, "g2b.json") - with open(p2, "w") as f: - json.dump(d2, f) - r = self.sisi("cycle", "apply", p2) - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("lesson #%d changed" % lid2, r.stdout) - self.assertNotIn("likely another cycle", r.stdout) - - def test_gap03_new_lesson_does_not_block_apply(self): - lid = self.mk() - base = cycle.base_version() - self.mk(change="Brand new parser lesson arriving mid cycle", moment="new wait at step 5") - d = {"version": 1, "base": base, "summary": "x", "notes": [{"lesson": lid, "action": "keep"}, - {"lesson": lid, "action": "set-scope", "scope": "core"}, - {"lesson": lid, "action": "set-pattern", "pattern": "Reach for the familiar tool instead of the check that fits the claim"}, - {"lesson": lid, "action": "set-short", "short": "Use a readiness probe, not a sleep.", "topic": "testing"}]} - p = os.path.join(self.tmp, "g3.json") - with open(p, "w") as f: - json.dump(d, f) - self.assertEqual(self.sisi("cycle", "apply", p).returncode, 0) - - def test_gap04_create_entry_and_keep_as_draft(self): - lid = self.mk(change_kind="recipe", target="curated-record-change", - change="Add a recipe 'curated-record-change' for editing a sourced record in a curated dataset") - doc = self.cycle_doc(notes=[{"lesson": lid, "action": "create-entry", "into": "curated-record-change", - "entry_kind": "recipe", "entry_text": RECIPE_TEXT}]) - r = self.sisi("cycle", "apply", doc) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertTrue(os.path.exists(paths.overlay_dir("done", "curated-record-change.md"))) - from sisi import verifiers as V - self.assertIn("curated-record-change", [e["id"] for e in V.load_recipes()]) - lid2 = self.mk(change="A draft-only parser readiness lesson", moment="draft wait at step 2") - bad = self.sisi("cycle", "apply", self.cycle_doc( - notes=[{"lesson": lid2, "action": "keep-as-draft"}])) - self.assertEqual(bad.returncode, 1) - self.assertIn("needs a reason", bad.stdout) - self.assertIn("create-entry", cycle.brief_text()) - self.assertIn("keep-as-draft", cycle.HELP_TEXT) - - def test_gap05_fold_into_entry_appends_field_note(self): - lid = self.mk(change="Parser recipes need a readiness probe before server work", - moment="server wait at step 3") - doc = self.cycle_doc(notes=[{"lesson": lid, "action": "fold-into-entry", "into": "parser-or-codec"}]) - self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) - text = open(os.path.join(self.notes, "parser-or-codec.md")).read() - self.assertIn("readiness probe", text) - self.assertIn("lesson %d" % lid, text) - self.assertIn("field-note bullet", cycle.HELP_TEXT) - - def test_gap06_into_list_and_split(self): - self.put("prove/other.md", vfile("other")) - lid = self.mk(change="Compound parser lesson about probes and fuzz corpus seeding", - moment="compound wait at step 3") - doc = self.cycle_doc(notes=[ - {"lesson": lid, "action": "fold-into-entry", "into": "parser-or-codec", "note": "Use a readiness probe before parser server work"}, - {"lesson": lid, "action": "fold-into-entry", "into": "fuzz", "note": "Seed the fuzz corpus from golden files"}]) - r = self.sisi("cycle", "apply", doc) - self.assertEqual(r.returncode, 0, r.stdout) - self.assertIn("readiness probe", open(os.path.join(self.notes, "parser-or-codec.md")).read()) - self.assertIn("Seed the fuzz corpus", open(os.path.join(self.notes, "fuzz.md")).read()) - lid2 = self.mk(change="Multi target parser readiness lesson", moment="multi wait at step 2") - doc2 = self.cycle_doc(notes=[{"lesson": lid2, "action": "fold-into-entry", "into": ["parser-or-codec", "fuzz"]}]) - self.assertEqual(self.sisi("cycle", "apply", doc2).returncode, 0) - - def test_gap07_unknown_id_suggests_closest_and_brief_lists_ids(self): - lid = self.mk() - r = self.sisi("cycle", "apply", self.cycle_doc( - notes=[{"lesson": lid, "action": "fold-into-entry", "into": "parser-or-code"}])) - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("Closest valid", r.stdout) - self.assertIn("parser-or-codec", r.stdout) - out = cycle.brief_text() - self.assertIn("parser-or-codec", out) - self.assertIn("fuzz", out) - - def test_gap08_brief_gives_recipe_applies_to(self): - out = cycle.brief_text() - self.assertIn("applies-to", out) - # a real recipe's applies_to line from the library - from sisi import verifiers as V - rec = [e for e in V.load_recipes() if e["id"] == "parser-or-codec"][0] - self.assertIn(rec["applies_to"][:40], out) - - def test_gap09_tool_lesson_refused_in_cycle(self): - lid = self.mk(change_kind="tool", change="Make sisi cycle print faster for large stores") - r = self.sisi("cycle", "apply", self.cycle_doc( - notes=[{"lesson": lid, "action": "fold-into-entry", "into": "fuzz"}])) - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("tool lessons cannot be done in a cycle", r.stdout) - self.assertIn("sisi backlog", cycle.brief_text()) - - def test_gap10_merge_keeps_survivor_text_and_count(self): - a = self.mk(change="Parser readiness probes beat fixed sleeps for servers", moment="merge a at step 1") - b = self.mk(change="Fixed sleeps waste time for parser servers", moment="merge b at step 2") - before = self.lesson(a) - doc = self.cycle_doc(notes=[{"lesson": b, "action": "merge", "merged_into": a}]) - self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) - after = self.lesson(a) - self.assertEqual((after["change"], after["count"]), (before["change"], before["count"])) - self.assertEqual(self.lesson(b)["status"], "superseded") - self.assertIn("SAME change", cycle.HELP_TEXT) - self.assertIn("Superseded", cycle.HELP_TEXT) - - def test_gap11_retire_definition_in_brief_and_help(self): - self.assertIn("fully folded and quiet", cycle.brief_text()) - self.assertIn("20", cycle.HELP_TEXT) - self.assertIn("does not make it quiet", cycle.HELP_TEXT) - - def test_gap12_set_when_only(self): - lid = self.mk() - doc = self.cycle_doc(notes=[{"lesson": lid, "action": "set-when", "when": PARSER_WHEN}]) - self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) - l = self.lesson(lid) - self.assertIn("readiness probe", l["when_terms"]) - self.assertEqual(l["status"], "open") - - def test_gap14_shortens_required_when_book_grows(self): - pre, base = overlay.base_rules() - title = next(r["title"] for r in base if r["id"] == "know-done") - long_body = ("Before work, write a contract. " * 40) + "\n\nWhy: a request says what is wanted." - doc = self.cycle_doc(rules=[{"id": "know-done", "title": title, "body": long_body, "action": "replace"}]) - r = self.sisi("cycle", "apply", doc) - self.assertEqual(r.returncode, 1, r.stdout) - self.assertIn("shortens", r.stdout) - doc2 = self.cycle_doc(rules=[{"id": "know-done", "title": title, "body": long_body, "action": "replace", - "shortens": "know-done: the old preamble is removed"}]) - # with shortens it may still fail the hard char budget, but not for missing shortens - r2 = self.sisi("cycle", "check", doc2) - if r2.returncode != 0: - self.assertNotIn("add `shortens`", r2.stdout) - - def test_gap15_char_budget_rewrap_and_canon_cost(self): - self.sisi("build-canon") - self.assertIn("characters (budget %d)" % overlay.MAX_CHARS, self.sisi("canon", "cost").stdout) - pre, base = overlay.base_rules() - title = next(r["title"] for r in base if r["id"] == "know-done") - body = ("Before non-trivial work write a contract listing the checks that decide success " - "and draft it yourself from the request and the project in front of you today.\n\n" - "Why: a request says what is wanted, rarely how success is measured.") - doc = self.cycle_doc(rules=[{"id": "know-done", "title": title, "body": body, "action": "replace"}]) - self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) - gen = open(paths.generated()).read() - section = gen.split("Know how you will know you are done")[1].split("## 2.")[0] - self.assertTrue(all(len(l) <= 101 for l in section.splitlines()), [l for l in section.splitlines() if len(l) > 101][:3]) - self.assertTrue(all(len(l) <= 101 for l in open(paths.overlay_dir("rules", "know-done.md")).read().splitlines())) - - def test_gap16_rule_numbers_map_to_ids(self): - out = cycle.brief_text() - self.assertIn("1. choose-the-approach", out) - self.assertIn("2. know-done", out) - self.assertIn("rule 5", out) - - def test_gap17_enforced_help_fields_and_examples(self): - out = self.sisi("cycle", "help").stdout - self.assertIn("contract-requirement", out) - self.assertIn("require_kind", out) - self.assertIn("max_rung", out) - self.assertIn("below strength 3", out) - self.assertIn("timeout_s", out) - - def test_gap18_notes_chars_exclude_folded(self): - ids = [self.mk(change="Loose parser readiness lesson number %d with enough text to count here" % i, - moment="loose wait %d at step 2" % i) for i in range(3)] - before = cycle.due_state()["notes_chars"] - self.assertGreater(before, 0) - doc = self.cycle_doc(notes=[{"lesson": ids[0], "action": "fold-into-entry", "into": "parser-or-codec"}]) - self.assertEqual(self.sisi("cycle", "apply", doc).returncode, 0) - after = cycle.due_state()["notes_chars"] - self.assertLess(after, before) - self.assertIn("do not count", cycle.brief_text()) - - def test_gap19_brief_names_cycle_file_path(self): - out = cycle.brief_text() - self.assertIn(cycle.cycle_file_path(), out) - self.assertIn("sisi cycle check FILE", out) - - def test_gap20_help_is_detailed_and_brief_points_to_it(self): - self.assertIn("sisi cycle help", cycle.brief_text()) - out = self.sisi("cycle", "help").stdout - self.assertIn("create-entry", out) - self.assertIn("fold-into-entry", out) - - def test_also_cycle_check_dry_run_changes_nothing(self): - lid = self.mk() - before = self.overlay_bytes() - doc = self.cycle_doc(notes=[{"lesson": lid, "action": "retire"}]) - for args in (("cycle", "check", doc), ("cycle", "--dry-run", doc)): - r = self.sisi(*args) - self.assertEqual(r.returncode, 0, r.stdout) - self.assertIn("nothing was changed", r.stdout) - self.assertIn("retire", r.stdout) - self.assertEqual(self.overlay_bytes(), before) - self.assertEqual(self.lesson(lid)["status"], "open") - self.assertEqual(cycle.cycle_records(), []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_learning_loop.py b/tests/test_learning_loop.py new file mode 100644 index 0000000..66c826e --- /dev/null +++ b/tests/test_learning_loop.py @@ -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() diff --git a/tests/test_patterns.py b/tests/test_patterns.py deleted file mode 100644 index bd90a7f..0000000 --- a/tests/test_patterns.py +++ /dev/null @@ -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() diff --git a/tests/test_retro.py b/tests/test_retro.py deleted file mode 100644 index 612020d..0000000 --- a/tests/test_retro.py +++ /dev/null @@ -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() diff --git a/tests/test_scope.py b/tests/test_scope.py deleted file mode 100644 index 8bd3bc9..0000000 --- a/tests/test_scope.py +++ /dev/null @@ -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() diff --git a/tests/test_tiers.py b/tests/test_tiers.py deleted file mode 100644 index 26168cf..0000000 --- a/tests/test_tiers.py +++ /dev/null @@ -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() diff --git a/tests/test_tiers_amendment.py b/tests/test_tiers_amendment.py deleted file mode 100644 index b86510b..0000000 --- a/tests/test_tiers_amendment.py +++ /dev/null @@ -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()