"""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 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 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 unittest.mock.patch("sisi.cycle._stdin_is_tty", return_value=True) 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 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(" 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-text", "rule_id": "deliver-fast", "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)