"""The learning loop, rebuilt and hardened. Docstrings cite docs/spec/requirements.json ids. Each gate is tested twice: the caller who trips it, and the caller who walks around it (omits the field that triggers approval, forges the field that marks trust or origin, supplies a `before` that is unrelated to `after`, makes the fail-before step fail for an unrelated reason, repeats a retro in one unit, approves from a non-terminal, adds a row to the store by hand). """ import json, os, stat, subprocess, sys, unittest.mock from support import SisiCase, terminal from sisi import learning as L 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) FINDING = "f.txt held the word bug and shipped without a content check" CAUSE = "no check asserted file contents before delivery" PROMOTE = ("retro", "--finding", FINDING, "--cause", CAUSE, "--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 Base(SisiCase): def retro(self, *a, **kw): return self.sisi("retro", *a, **kw) def rows(self): return L.load_learnings() def _commit(self, msg, d=None): d = d or self.proj subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "add", "."], cwd=d, check=True, capture_output=True) subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", msg], cwd=d, check=True, capture_output=True) def _head(self, d=None): return subprocess.run(["git", "rev-parse", "HEAD"], cwd=d or self.proj, capture_output=True, text=True).stdout.strip() def write(self, name, text, d=None, mode=None): p = os.path.join(d or self.proj, name) with open(p, "w") as f: f.write(text) if mode: os.chmod(p, mode) def fixed_repo(self): """A trusted project whose history has a bug at `before` and the fix at `after`.""" from sisi import trust _contract(self) self.git_init() trust.add(self.proj) self.write("f.txt", "bug\n") self._commit("before") before = self._head() self.write("f.txt", "fixed\n") self._commit("fix") return before, self._head() def archive_unit(self, before, after, uid=None, d=None): """The unit record, as `sisi unit close` writes it: the unit's start and closing commits.""" uid = uid or self.rows()[0]["source_unit"] d = os.path.join(d or self.proj, ".sisi", "units") os.makedirs(d, exist_ok=True) from sisi import store with open(os.path.join(d, store.safe_id(uid) + ".json"), "w") as f: json.dump({"id": uid, "start_commit": before, "closing_commit": after}, f) def cycle_file(self, actions, name="c.json", base=None): p = os.path.join(self.tmp, name) with open(p, "w") as f: json.dump({"base": base or L.store_base(), "actions": actions}, f) return p def apply(self, actions, **kw): return self.sisi("cycle", "apply", self.cycle_file(actions, **kw)) def tty(self): return terminal() def other_project(self, name="other"): d = os.path.join(self.tmp, name) os.makedirs(d) self.git_init(d) return d def pending(self): return L.load_pending() def read_json(self, rel): with open(os.path.join(self.data, rel)) as f: return json.load(f) def exists(self, rel): return os.path.exists(os.path.join(self.data, rel)) def earn(self, lid="L-0001", other=None, finding=FINDING, cause=CAUSE): """A second unit in a second project records the same finding against `lid`: scope earned.""" other = other or self.other_project() _contract(self, "u9", other) r = self.retro("--finding", finding, "--cause", cause, "--impact", "correctness", "--disposition", "record", "--limits", "here", "--same-as", lid, cwd=other) self.assertEqual(r.returncode, 0, r.stderr) return other def another(self, n): """A further proposed learning (L-000n), recorded as its own (--new) with words of its own.""" word = ("alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike november oscar papa " "quebec romeo sierra tango").split()[n] r = self.retro("--new", "--finding", "the %s importer dropped %s rows in the nightly run" % (word, 10 + n), "--cause", "no fixture covered the %s case" % word, "--impact", "correctness", "--disposition", "promote", "--change", "add a %s fixture to the importer tests" % word, "--mechanism", "verification", "--expect", "the %s case is caught" % word, "--validate", "run the %s fixture" % word) self.assertEqual(r.returncode, 0, r.stderr) return self.rows()[-1]["id"] def set_config(self, cfg): os.makedirs(self.data, exist_ok=True) with open(os.path.join(self.data, "config.json"), "w") as f: json.dump(cfg, f) class Retro(Base): 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_generic_advice_refused_wherever_the_filler_appears(self): """R-11.1-9 (item 12): a finding that is only generic advice is refused, however it is phrased; an honest short specific one is accepted.""" _contract(self) for text in ("be more careful when writing tests in future", "Always write better tests going forward", "We should use cheaper models next time", "pay more attention and double check everything"): with self.subTest(text=text): r = self.retro("--finding", text, "--cause", "the root cause was carelessness", "--impact", "time", "--disposition", "drop", "--why-not", "nothing to promote") self.assertNotEqual(r.returncode, 0, text) self.assertEqual(self.rows(), []) self.assertEqual(L.load_findings(), []) r = self.retro("--finding", "Tests flaked on CI: 3 of 10 runs", "--cause", "shared tmp dir between workers", "--impact", "time", "--disposition", "drop", "--why-not", "one-off, fixed by hand") self.assertEqual(r.returncode, 0, r.stderr) self.assertEqual(len(L.load_findings()), 1) 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) 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_secrets_are_scrubbed_before_anything_is_stored(self): """R-12-2 (item 13): keys, tokens and passwords never reach the store.""" _contract(self) secret_tokens = ["sk-abcdef0123456789abcdef0123456789", "hunter2supersecret", "ghp_abcdefghijklmnopqrstuvwxyz0123456789", "AKIAABCDEFGHIJKLMNOP"] r = self.retro("--finding", "the deploy failed with api_key=%s and password: %s in the log" % (secret_tokens[0], secret_tokens[1]), "--cause", "the token %s and key %s were echoed by the script" % (secret_tokens[2], secret_tokens[3]), "--impact", "correctness", "--disposition", "record", "--limits", "deploy script only") self.assertEqual(r.returncode, 0, r.stderr) for name in ("learnings.jsonl", "findings.jsonl"): with open(os.path.join(self.data, name)) as f: text = f.read() for s in secret_tokens: self.assertNotIn(s, text, name) self.assertIn("", "test"))) self.assertEqual(r.returncode, 0, r.stderr) self.assertEqual(L.owner_statements(), []) def test_learn_records_whether_the_owner_typed_it(self): """A statement quoted from a human-typed message of the session transcript is `typed by the owner`; a relayed one, or none to check, is `relayed by an agent`. Never blocked.""" from sisi import store tp = os.path.join(self.tmp, "t.jsonl") with open(tp, "w") as f: f.write(json.dumps({"type": "user", "message": {"content": "please remember: prefer short plain reports"}}) + "\n") f.write(json.dumps({"type": "user", "toolUseResult": {}, "message": {"content": [ {"type": "tool_result", "content": "use spaces never tabs in everything"}]}}) + "\n") store.save_session("s1", {"session_id": "s1", "transcript_path": tp}) env = {"SISI_SESSION_ID": "s1"} self.assertEqual(self.sisi("learn", "prefer short plain reports", env=env).returncode, 0) self.assertEqual(self.sisi("learn", "use spaces never tabs in everything", env=env).returncode, 0) self.assertEqual(self.sisi("learn", "something nobody typed at all here").returncode, 0) # no transcript origins = [r["statement_origin"] for r in self.rows()] self.assertEqual(origins, ["typed by the owner", "relayed by an agent", "relayed by an agent"]) out = self.sisi("oracle").stdout self.assertIn("relayed by an agent", out) def test_withdraw_keeps_history_and_never_delivers_again(self): """A statement recorded by mistake can be withdrawn, with a reason.""" self.sisi("learn", "prefer short plain reports over long ones") self.assertNotEqual(self.sisi("learn", "--withdraw", "L-0001").returncode, 0) # a reason is required r = self.sisi("learn", "--withdraw", "L-0001", "--reason", "the agent paraphrased me wrongly") self.assertEqual(r.returncode, 0, r.stderr) self.assertNotIn("prefer short", self.sisi("oracle").stdout) rec = self.rows()[0] self.assertEqual(rec["status"], "rejected") self.assertEqual(rec["history"][-1]["action"], "withdraw") self.assertIn("paraphrased", rec["history"][-1]["why"]) self.assertEqual(L.delivery_text(self.proj, "prefer short plain reports over long ones"), "") self.assertNotEqual(self.sisi("learn", "--withdraw", "L-0001", "--reason", "again").returncode, 0) _contract(self) self.retro(*PROMOTE[1:]) self.assertNotEqual(self.sisi("learn", "--withdraw", "L-0002", "--reason", "not a statement").returncode, 0) 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_nothing_reads_the_retired_store(self): """Item 8: no caller of the removed sqlite lesson store is left, guarded or not.""" root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) bad = [] for n in sorted(os.listdir(os.path.join(root, "sisi"))): if not n.endswith(".py"): continue with open(os.path.join(root, "sisi", n)) as f: for i, line in enumerate(f, 1): if any(w in line for w in ("retro.db_path", "retro.cycle_records", "retro.lesson", "retro.connect", "_folded_lessons(rule_id):\n try")): bad.append("%s:%d" % (n, i)) self.assertEqual(bad, []) def test_no_guarded_seams_between_modules_that_always_exist(self): """Item 4: no `except ImportError` or `hasattr(module, ...)` probe stands in for a module of this package, and nothing names a removed seam. The one platform probe (fcntl, absent on Windows, in pdata) stays.""" import re root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) bad = [] for n in sorted(os.listdir(os.path.join(root, "sisi"))): if not n.endswith(".py"): continue with open(os.path.join(root, "sisi", n)) as f: for i, line in enumerate(f, 1): if n != "pdata.py" and re.search(r"except \(?ImportError|hasattr\((delivery|unit|gate|retro|learning|cycle)\b", line): bad.append("%s:%d" % (n, i)) if re.search(r"retro\.(TEMPLATE|satisfied|lessons_block)|ensure_imported", line): bad.append("%s:%d" % (n, i)) self.assertEqual(bad, []) def test_no_resource_warnings_from_the_learning_commands(self): """Item 13: file handles are closed; every learning command runs clean under -W always.""" _contract(self) env = {"PYTHONWARNINGS": "always::ResourceWarning"} runs = [PROMOTE, ("lessons",), ("learn", "prefer short plain reports over long ones"), ("oracle",), ("cycle",), ("approve",), ("rule", "deliver-fast"), ("promote", "--export"), ("overlay", "add-rule", "--id", "tmp-rule", "-"), ("status", "--learning")] for args in runs: r = self.sisi_proc(*args, env=env, stdin="## Tmp rule\n\nBody.\n\nWhy: test.\n") self.assertNotIn("ResourceWarning", r.stderr, (args[:2], r.stderr)) self.assertNotIn("Traceback", r.stderr, (args[:2], r.stderr)) class Monitoring(Base): """R-13.2-7, R-13.2-8 (item 9): units in the learning's own scope decide "holding".""" def promoted(self): _contract(self) self.git_init() self.retro(*PROMOTE[1:]) self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", "pattern": "f.txt", "profile": "logic"}]) def units(self, rows): with open(os.path.join(self.data, "units.jsonl"), "w") as f: for i, (proj, closed) in enumerate(rows): f.write(json.dumps({"id": "x%d" % i, "project": proj, "closed_at": closed, "risk": "logic"}) + "\n") 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.""" self.assertIn("too few", L.learning_report()) def test_no_units_file_means_zero_units(self): """The unit worker's file may not exist yet.""" self.promoted() rep = L.learning_report() self.assertIn("0 unit(s) in scope since promotion", rep) self.assertIn("too few units to judge", rep) def test_units_of_other_projects_do_not_count(self): """Five units in another project do not make a project-scoped learning 'holding'.""" self.promoted() other = self.other_project() self.units([(other, "2099-01-0%dT00:00:00Z" % (i + 1)) for i in range(5)]) rep = L.learning_report() self.assertIn("0 unit(s) in scope since promotion", rep) self.assertNotIn("holding", rep) self.units([(self.proj, "2099-01-0%dT00:00:00Z" % (i + 1)) for i in range(5)]) rep = L.learning_report() self.assertIn("5 unit(s) in scope since promotion", rep) self.assertIn("holding", rep) def test_units_before_promotion_do_not_count(self): """Only units closed after promotion count.""" self.promoted() self.units([(self.proj, "2000-01-0%dT00:00:00Z" % (i + 1)) for i in range(5)]) self.assertIn("0 unit(s) in scope since promotion", L.learning_report()) class Cycle(Base): def test_no_partial_apply_when_a_later_action_breaks_the_budget(self): """R-11.6-6 (item 11): the budget check runs before anything is written.""" _contract(self) self.retro(*PROMOTE[1:]) 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") big = "## Huge {#huge-rule}\n\n" + "\n".join("line %d of the rule" % i for i in range(400)) + "\n\nWhy: no.\n" with open(L.learnings_path()) as f: before = f.read() r = self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", "pattern": "f.txt", "profile": "logic"}, {"action": "promote", "learning": "L-0002", "mechanism_kind": "rule-replace", "rule_id": "huge-rule", "shortens": "nothing: no rule can be shortened here", "rule_text": big}]) self.assertNotEqual(r.returncode, 0) self.assertIn("budget", r.stderr) self.assertFalse(self.exists("overlay/risk-adjustments.json")) self.assertEqual(self.rows()[0]["status"], "proposed") with open(L.learnings_path()) as f: self.assertEqual(f.read(), before) def test_a_failure_while_applying_restores_the_store(self): """R-11.6-6 (item 11): if applying fails part-way, every file the cycle wrote is restored.""" from sisi import cycle _contract(self) self.retro(*PROMOTE[1:]) 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") real = cycle._apply_mechanism calls = [] def flaky(a, rec, granted, approval=None): calls.append(rec["id"]) if len(calls) == 2: raise RuntimeError("disk full") return real(a, rec, granted, approval) p = self.cycle_file([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", "pattern": "f.txt", "profile": "logic"}, {"action": "promote", "learning": "L-0002", "mechanism_kind": "risk", "pattern": "g.txt", "profile": "logic"}]) with open(L.learnings_path()) as f: before = f.read() with unittest.mock.patch.object(cycle, "_apply_mechanism", flaky): with self.assertRaises(RuntimeError): cycle.apply_file(p) self.assertFalse(self.exists("overlay/risk-adjustments.json")) with open(L.learnings_path()) as f: self.assertEqual(f.read(), before) def test_revert_undoes_only_that_cycle(self): """R-11.6-6, R-16-9 (item 11): revert restores what the cycle touched; statements and findings recorded after it survive.""" _contract(self) self.retro(*PROMOTE[1:]) self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", "pattern": "f.txt", "profile": "logic"}]) self.assertTrue(self.exists("overlay/risk-adjustments.json")) self.sisi("learn", "prefer short plain reports over long ones") # after the cycle _contract(self, "u2") self.retro("--finding", "an unrelated build slowness showed up in the nightly run", "--cause", "the cache key changed every night", "--impact", "time", "--disposition", "record", "--limits", "nightly only") n_findings = len(L.load_findings()) r = self.sisi("cycle", "revert") self.assertEqual(r.returncode, 0, r.stderr) self.assertFalse(self.exists("overlay/risk-adjustments.json")) rows = self.rows() self.assertEqual(rows[0]["status"], "proposed") self.assertEqual(rows[0]["validation"]["result"], "unvalidated") self.assertEqual(len(rows), 3) # the statement and the later learning survive self.assertIn("prefer short plain reports", self.sisi("oracle").stdout) self.assertEqual(len(L.load_findings()), n_findings) self.assertIn("L-0002", [x["id"] for x in L.learnings_in_scope(self.proj)]) # still delivered self.assertNotEqual(self.sisi("cycle", "revert").returncode, 0) # nothing left to revert def test_revert_refuses_when_a_later_change_touched_the_same_file(self): """A revert never silently drops a later cycle's work in the same mechanism file.""" _contract(self) self.retro(*PROMOTE[1:]) 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") self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "risk", "pattern": "f.txt", "profile": "logic"}]) self.apply([{"action": "promote", "learning": "L-0002", "mechanism_kind": "risk", "pattern": "g.txt", "profile": "logic"}]) r = self.sisi("cycle", "revert", "cycle-0001") self.assertNotEqual(r.returncode, 0) self.assertEqual(len(self.read_json("overlay/risk-adjustments.json")["adjustments"]), 2) self.assertEqual(self.sisi("cycle", "revert").returncode, 0) # the later one first self.assertEqual(self.sisi("cycle", "revert").returncode, 0) def test_approving_a_change_makes_a_revertible_cycle(self): """What the owner approves is recorded like any cycle and can be reverted.""" _contract(self) self.git_init() self.retro(*PROMOTE[1:]) self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check", "cmd": "make check"}]) with self.tty(): self.assertEqual(self.sisi("approve", "P-0001", "--yes").returncode, 0) self.assertTrue(self.exists("overlay/enforced.json")) self.assertEqual(self.rows()[0]["status"], "promoted") self.assertEqual(self.sisi("cycle", "revert").returncode, 0) self.assertFalse(self.exists("overlay/enforced.json")) self.assertEqual(self.rows()[0]["status"], "proposed") # no decision waits for it any more class Migration(Base): def seed(self, extra_lessons=(), learn_lines=None): os.makedirs(self.data, exist_ok=True) link = os.path.join(self.tmp, "alias") if not os.path.exists(link): os.symlink(self.proj, link) rows = [ {"t": "lesson", "id": 1, "moment": "m one happened here", "cause": "c one", "change": "change one", "change_kind": "rule", "status": "applied", "target": "rule:define-done", "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": "lesson", "id": 3, "moment": "m three happened here", "cause": "c three", "change": "change three", "change_kind": "check", "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": "occurrence", "id": 2, "lesson_id": 1, "repo": link, "session": "s2", "ts": "2026-01-02T00:00:00Z"}, {"t": "occurrence", "id": 3, "lesson_id": 3, "repo": self.proj, "session": "s3", "ts": "2026-01-02T00:00:00Z"}, {"t": "occurrence", "id": 4, "lesson_id": 3, "repo": self.tmp, "session": "s4", "ts": "2026-01-03T00:00:00Z"}, {"t": "occurrence", "id": 5, "lesson_id": 77, "repo": self.proj, "session": "s5", "ts": "2026-01-03T00:00:00Z"}, {"t": "impression", "id": 1, "lesson_id": 1, "place": "tick", "ts": "2026-01-01T00:00:00Z"}, {"t": "pattern", "id": 1, "statement": "p"}, ] + list(extra_lessons) with open(os.path.join(self.data, "lessons.jsonl"), "w") as f: for r in rows: f.write(json.dumps(r) + "\n") f.write("{this line is not json\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", "cwd": self.proj}) + "\n") f.write(json.dumps({"text": "use tabs in this project", "scope": "project", "ts": "2026-01-02T00:00:00Z", "cwd": self.proj}) + "\n") f.write("also not json\n") f.write(json.dumps({"text": "always ask before spending", "ts": "2026-01-03T00:00:00Z"}) + "\n") def test_migration_is_lossless_idempotent_and_reports(self): """R-12-10: every old lesson and owner statement survives; counts and skipped lines reported.""" from sisi import lifecycle self.seed() notes = lifecycle.migrate_learnings() self.assertTrue(notes) self.assertIn("2 malformed line(s) skipped", notes[0]) self.assertIn("1 without a lesson", notes[0]) got = self.rows() self.assertEqual(len(got), 5) # 3 lessons + 2 distinct statements (one duplicate dropped) self.assertEqual(got[0]["status"], "implemented") self.assertEqual(got[0]["proposed"]["target"], "define-done") self.assertTrue(all(r["validation"]["result"] != "validated" for r in got)) self.assertEqual(len(got[0]["provenance"]), 2) self.assertEqual({p["project"] for p in got[0]["provenance"]}, {L.project_key(self.proj)}) # normalised self.assertEqual(len(L.owner_statements()), 2) counts = self.read_json("learnings-migrated.json") self.assertEqual((counts["lessons_migrated"], counts["occurrences_attached"], counts["occurrences_without_a_lesson"], counts["owner_statements_duplicate"]), (3, 4, 1, 1)) self.assertEqual(counts["malformed_lines_skipped"], {"lessons.jsonl": 1, "learn.jsonl": 1}) self.assertEqual(lifecycle.migrate_learnings(), []) # idempotent self.assertEqual(len(self.rows()), 5) # ...and delivered: the migrated rows are in the ledger self.assertEqual(len(L.learnings_in_scope(self.proj)), 5) # 3 lessons + both statements, here def test_a_record_written_before_the_first_migration_does_not_hide_the_old_store(self): """Item 7: writing a record first used to skip the migration for good.""" from sisi import lifecycle self.seed() _contract(self) L.new_record("a finding made before anything was migrated here", "a cause long enough", "time", "record", self.proj, "u1", limits="here") notes = lifecycle.migrate_learnings() self.assertTrue(notes) self.assertEqual(len(self.rows()), 6) self.assertEqual(self.rows()[0]["id"], "L-0001") # the earlier record kept its id def test_learn_before_the_first_migration_loses_nothing(self): """`sisi learn` migrates first, so old lessons are not left behind.""" self.seed() self.assertEqual(self.sisi("learn", "prefer short plain reports over long ones").returncode, 0) self.assertEqual(len(self.rows()), 6) def test_merge_by_legacy_id(self): """A lesson already carried over (same legacy id) is not carried over twice.""" from sisi import lifecycle self.seed() lifecycle.migrate_learnings() os.remove(os.path.join(self.data, "learnings-migrated.json")) self.seed(extra_lessons=[{"t": "lesson", "id": 4, "moment": "m four happened later", "cause": "c four", "change": "change four", "change_kind": "rule", "status": "open", "project": self.proj, "created": "2026-02-01T00:00:00Z"}]) lifecycle.migrate_learnings() got = self.rows() self.assertEqual(len([r for r in got if r.get("legacy_id") is not None]), 4) self.assertEqual(len(got), 6) def test_earned_only_under_the_same_rule_as_new_learnings(self): """A lesson seen in two sessions of the same project (however the path is spelled) is not earned; two sessions in two projects is.""" from sisi import lifecycle self.seed() lifecycle.migrate_learnings() by = {r["legacy_id"]: r for r in self.rows() if r.get("legacy_id")} self.assertEqual(L.earned_scope(by[1]), "project") # s1, s2: both this project self.assertEqual(L.earned_scope(by[3]), "organization") # s3 here, s4 elsewhere self.assertEqual(L.earned_scope(by[2]), "project") def test_old_sqlite_store_is_read_too(self): """An install whose committed dump never existed is read from the database.""" import sqlite3 from sisi import lifecycle os.makedirs(self.data, exist_ok=True) con = sqlite3.connect(os.path.join(self.data, "retro.db")) con.execute("CREATE TABLE lessons (id INTEGER PRIMARY KEY, aim TEXT, change_kind TEXT, target TEXT," " moment TEXT, cause TEXT, change TEXT, status TEXT, project TEXT, created TEXT)") con.execute("CREATE TABLE occurrences (id INTEGER PRIMARY KEY, lesson_id INTEGER, ts TEXT, session TEXT," " moment TEXT, repo TEXT)") con.execute("INSERT INTO lessons(id,aim,change_kind,moment,cause,change,status,project,created) VALUES " "(1,'v','rule','m','c','ch','open',?, '2026-01-01T00:00:00Z')", (self.proj,)) con.execute("INSERT INTO occurrences(lesson_id,ts,session,moment,repo) VALUES (1,'2026-01-01T00:00:00Z','s1','m',?)", (self.proj,)) con.commit() con.close() lifecycle.migrate_learnings() self.assertEqual(len(self.rows()), 1) class Product(Base): """Item 8: the routes by which learnings reach the product, and the readers of the new store.""" def earned_tool_learning(self): _contract(self) self.git_init() self.retro("--finding", "the gate keyed its decision on the working tree alone and misread a worker's edits", "--cause", "attribution is by tree state not by session", "--impact", "correctness", "--disposition", "promote", "--change", "attribute edits to the session that made them", "--mechanism", "tool", "--expect", "no false blocks", "--validate", "replay the case") self.retro("--finding", FINDING, "--cause", CAUSE, "--impact", "correctness", "--disposition", "promote", "--change", "grep for fixed in f.txt must pass", "--mechanism", "verification", "--expect", "bug text is caught", "--validate", "replay the grep", "--target", "my-recipe") def test_export_writes_tool_and_organization_scope_learnings(self): """R-12-4 (item 8): `sisi promote --export` writes the contribution file, scrubbed.""" self.earned_tool_learning() out = os.path.join(self.tmp, "contrib.md") r = self.sisi("promote", "--export", out) self.assertEqual(r.returncode, 0, r.stdout + r.stderr) with open(out) as f: text = f.read() self.assertIn("attribute edits to the session", text) # the tool learning self.assertNotIn("grep for fixed", text) # a one-incident learning is not universal self.earn("L-0002") self.assertEqual(self.sisi("promote", "--export", out).returncode, 0) with open(out) as f: text = f.read() self.assertIn("grep for fixed", text) self.assertNotIn(os.path.basename(self.proj) if len(os.path.basename(self.proj)) > 4 else "\0", text) self.assertIn("L-0001", self.sisi("promote").stdout) def test_promote_lesson_does_not_crash_and_says_why(self): """`sisi promote lesson:N --apply` used to raise AttributeError (retro.db_path).""" self.earned_tool_learning() r = self.sisi("promote", "lesson:2", "--apply") # one incident: not queued for the product self.assertEqual(r.returncode, 1) self.assertNotIn("Traceback", r.stderr) self.assertIn("not queued", r.stderr) r = self.sisi("promote", "lesson:1", "--apply") # a tool learning, but not folded into a rule yet self.assertEqual(r.returncode, 1) self.assertIn("not folded", r.stderr) self.assertEqual(self.sisi("promote", "lesson:99").returncode, 1) def test_promote_lesson_writes_the_product_file_and_marks_it(self): """The folded rule of an earned learning goes into the product, scrubbed, and the learning is marked.""" from sisi import overlay, release self.earned_tool_learning() self.earn("L-0002") overlay.add_rule("## My rule {#my-recipe}\n\nAssert contents.\n\nWhy: a bug shipped.\n", "my-recipe") src = os.path.join(self.tmp, "src") os.makedirs(os.path.join(src, "canon")) with open(os.path.join(src, "canon", "core.md"), "w") as f: f.write("# book\n\n## 1. First {#first}\n\nBody.\n\nWhy: x.\n") with unittest.mock.patch.object(release, "source", return_value=src): rc = release._promote_lesson("L-0002", True) self.assertEqual(rc, 0) with open(os.path.join(src, "canon", "core.md")) as f: self.assertIn("Assert contents.", f.read()) self.assertTrue(self.rows()[1].get("in_product")) self.assertNotIn("L-0002", [r["id"] for r in release._waiting_for_product()]) def test_rule_shows_the_learnings_behind_it_by_target(self): """R-12-10 (item 8): `sisi rule` lists the learnings whose target is the rule, and its cycles.""" _contract(self) self.git_init() self.retro(*PROMOTE[1:], "--target", "deliver-fast") out = self.sisi("rule", "deliver-fast").stdout self.assertIn("Learnings behind this rule", out) self.assertIn("L-0001", out) self.assertNotIn("L-0001", self.sisi("rule", "deliver-fast", cwd=self.other_project("o2")).stdout) self.earn("L-0001") rule = "## Deliver {#deliver-fast}\n\nShip it at once.\n\nWhy: speed.\n" self.assertEqual(self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "rule-replace", "rule_id": "deliver-fast", "shortens": "nothing: no rule can be shortened here", "rule_text": rule}]).returncode, 0) with self.tty(): self.sisi("approve", "P-0001", "--yes") hist = self.sisi("rule", "deliver-fast").stdout self.assertIn("cycle-", hist) def test_done_and_verifiers_show_learnings_that_target_the_entry(self): """R-12-12 (item 8): `sisi done ID` shows the learnings in scope that target that recipe.""" _contract(self) self.git_init() self.retro(*PROMOTE[1:], "--target", "release") out = self.sisi("done", "release").stdout self.assertIn("L-0001", out) self.assertIn("not instructions", out) self.assertNotIn("L-0001", self.sisi("done", "release", cwd=self.other_project("o2")).stdout) def test_handover_reads_project_scope_records_from_the_new_store(self): """Item 8: project-scope records are listed for their project and filed with `done`.""" _contract(self) self.git_init() self.retro(*PROMOTE[1:], "--scope", "project") self.assertEqual(self.sisi("learn", "--scope", "project", "use tabs in this project please").returncode, 0) out = self.sisi("handover").stdout self.assertIn("L-0001", out) self.assertIn("use tabs in this project", out) self.assertNotIn("L-0001", self.sisi("handover", cwd=self.other_project("o2")).stdout) self.write("DESIGN.md", "Notes: grep for fixed in f.txt must pass. Rule: use tabs in this project please\n") r = self.sisi("handover", "done", "L-0001", "--where", "DESIGN.md") self.assertEqual(r.returncode, 0, r.stdout + r.stderr) self.assertNotIn("L-0001", self.sisi("handover").stdout) self.assertIn("L-0002", self.sisi("handover").stdout)