diff --git a/README.md b/README.md index d7253ba..7fea0ea 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ it learns about you is kept outside the clone, so updating never loses it. The name is recursive: its first word is the name itself. It is also a plain statement of where things stand: each turn leaves your tools a little better, and that work is never finished. What is -not yet shown is that this makes agents measurably better over weeks of real use. `sisi improve` +not yet shown is that this makes agents measurably better over weeks of real use. `sisi status --learning` reports the counted evidence for that question, and it needs real use to have data. ## How it works diff --git a/sisi/learning.py b/sisi/learning.py index 425635c..4fefaf9 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -147,17 +147,36 @@ def get(rows, lid): # ---- derived text (the tool derives search terms, topics, short lines) --------- -def stems(text): - out = set() - for w in re.findall(r"[a-z0-9]{3,}", (text or "").lower()): - if w in STOP: - continue - for suf in ("ing", "edly", "ed", "es", "s"): - if w.endswith(suf) and len(w) - len(suf) >= 3: - w = w[: -len(suf)] +def _stem(w): + """A crude stem so 'parsing', 'parser' and 'parse' meet, as do plurals.""" + s = w + if len(s) > 4 and s.endswith("ies"): + s = s[:-3] + "y" + else: + done = False + for suf in ("ingly", "ing", "edly", "ed"): + if s.endswith(suf) and len(s) - len(suf) >= 3: + base = s[:-len(suf)] + if len(base) >= 2 and base[-1] == base[-2] and base[-1] not in "aeious": + base = base[:-1] + s, done = base, True break - out.add(w) - return out + if not done: + if s.endswith(("ses", "xes", "zes", "ches", "shes")) and len(s) - 2 >= 3: + s = s[:-2] + else: + for suf in ("ers", "er", "s"): + if s.endswith(suf) and len(s) - len(suf) >= 3: + s = s[:-len(suf)] + break + if len(s) >= 4 and s.endswith("e"): + s = s[:-1] + return s + + +def stems(text): + return {_stem(w) for w in re.findall(r"[a-z0-9_]+", (text or "").lower()) + if len(w) > 2 and w not in STOP} def derive_terms(*texts): @@ -179,10 +198,11 @@ def similar_learnings(rows, text, limit=3): hay = set(r.get("terms") or []) | stems(r.get("observation", {}).get("evidence", "")) \ | stems(r.get("proposed", {}).get("description", "")) inter = len(q & hay) - if inter >= 3: - scored.append((inter / max(1, len(q | hay)), r)) + if inter >= 1: + scored.append((inter / max(1, len(q)), inter, r)) scored.sort(key=lambda x: -x[0]) - return [r for s, r in scored if s >= 0.25][:limit] + return [r for s, inter, r in scored + if s >= 0.3 or (inter >= 1 and s >= 0.25 and len(q) <= 4)][:limit] # ---- scope (earned, never claimed) --------------------------------------------- @@ -219,8 +239,7 @@ def delivery_text(project, query=""): """Learnings in scope, framed as information, never as instructions. No showing is recorded.""" rows = learnings_in_scope(project) if query: - match = similar_learnings(rows, query, limit=5) - rows = match if match else rows + rows = similar_learnings(rows, query, limit=5) # silence is the default rows = [r for r in rows if r.get("status") in ("promoted", "monitored", "proposed", "observed", "implemented", "validated")] if not rows: diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index 7fb87aa..ea46d55 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -264,6 +264,20 @@ def migrate_learnings(): return [] bdir = snapshot("learning-migration") lessons, occs, impressions = {}, {}, 0 + db = paths.data_file("retro.db") + if not os.path.exists(src) and os.path.exists(db): + # an install whose committed dump was never written: read the sqlite store directly + con = sqlite3.connect(db, timeout=30) + con.row_factory = sqlite3.Row + try: + for r in con.execute("SELECT * FROM lessons ORDER BY id"): + lessons[r["id"]] = dict(r) + for r in con.execute("SELECT * FROM occurrences ORDER BY id"): + occs.setdefault(r["lesson_id"], []).append(dict(r)) + except sqlite3.Error: + lessons, occs = {}, {} + finally: + con.close() if os.path.exists(src): with open(src, encoding="utf-8") as f: for line in f: diff --git a/sisi/overlay.py b/sisi/overlay.py index 48ca03f..f47c424 100644 --- a/sisi/overlay.py +++ b/sisi/overlay.py @@ -280,23 +280,22 @@ def is_stale(): def cost(): - """Always-loaded size: the generated rulebook and the largest session-start lessons block.""" - from . import retro + """Always-loaded size: the generated rulebook. No lesson list is loaded at session start.""" try: lines, chars = size(_read(paths.generated())) except OSError: lines = chars = None return {"rulebook_lines": lines, "rulebook_chars": chars, "rulebook_budget_lines": MAX_LINES, - "rulebook_budget_chars": MAX_CHARS, - "lessons_block_max_chars": retro.LIMIT, "lessons_block_max_lines": 1 + 8} + "rulebook_budget_chars": MAX_CHARS} def cost_line(c=None): c = c or cost() if c["rulebook_lines"] is None: - return "rulebook not generated yet (run `sisi build-canon`); lessons block at most %d characters" % c["lessons_block_max_chars"] - return "rulebook %d lines (budget %d), %d characters (budget %d); session-start lessons block at most %d characters, %d lines" % ( - c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"], c.get("rulebook_budget_chars", MAX_CHARS), c["lessons_block_max_chars"], c["lessons_block_max_lines"]) + return "rulebook not generated yet (run `sisi build-canon`)" + return "rulebook %d lines (budget %d), %d characters (budget %d)" % ( + c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"], + c.get("rulebook_budget_chars", MAX_CHARS)) # ---- library overlay (verifiers, recipes) --------------------------------------- diff --git a/sisi/principles.py b/sisi/principles.py index a94f17f..b0f355a 100644 --- a/sisi/principles.py +++ b/sisi/principles.py @@ -1,16 +1,38 @@ """Owner statements, printed by `sisi oracle`. One store: learning records with owner_statement. `sisi learn` writes them and `sisi oracle` prints them. The old parallel stores -(learn.jsonl, oracle.md) are merged by the migration in lifecycle.py. +(learn.jsonl, oracle.md) are merged by the migration in lifecycle.py; until an install +has migrated, statements are still read from learn.jsonl so nothing goes silent. """ -from . import learning as L +import json, os + +from . import learning as L, paths + + +def _legacy_statements(): + try: + from . import store + rows = store.read("learn") # also folds any quarantine file in, losslessly + except Exception: + rows = [] + try: + with open(paths.data_file("learn.jsonl"), encoding="utf-8") as f: + rows = [json.loads(x) for x in f if x.strip()] + except (OSError, ValueError): + pass + return [{"text": r.get("text") or r.get("statement") or "", + "scope": r.get("scope") or "user", "ts": r.get("ts") or "", "id": None} + for r in rows if (r.get("text") or r.get("statement"))] def statements(): - return [{"text": r.get("proposed", {}).get("description") or r.get("title", ""), + recs = [{"text": r.get("proposed", {}).get("description") or r.get("title", ""), "scope": r.get("proposed", {}).get("scope") or "user", "ts": r.get("created", ""), "id": r.get("id")} for r in L.owner_statements()] + if recs or os.path.exists(L.learnings_path()): + return recs + return _legacy_statements() def plain_of(rec): @@ -20,10 +42,20 @@ def plain_of(rec): def oracle_text(): recs = statements() if not recs: - return "No owner statements recorded. `sisi learn \"\"` adds one.\n" - lines = ["What the owner wants (recorded with `sisi learn`):"] + legacy = paths.data_file("oracle.md") + if os.path.exists(legacy): + try: + with open(legacy, encoding="utf-8") as f: + return f.read() + except OSError: + pass + return ("The oracle is empty: no owner statements recorded. " + "`sisi learn \"\"` adds one.\n") + lines = ["Standing principles — what the owner wants, in their words " + "(recorded with `sisi learn`; this is the oracle):"] for i, r in enumerate(recs, 1): - lines.append("%d. %s" % (i, r["text"])) + date = " (%s)" % str(r["ts"])[:10] if r.get("ts") else "" + lines.append('%d. "%s"%s' % (i, r["text"], date)) return "\n".join(lines) + "\n" diff --git a/sisi/prompt.py b/sisi/prompt.py index 6837bb2..18d42a8 100644 --- a/sisi/prompt.py +++ b/sisi/prompt.py @@ -11,7 +11,24 @@ from . import learning as _L, store def _stem(w): - return next(iter(_L.stems(w)), w.lower()) + return _L._stem(w.lower()) + + +def _common_stems(): + roots = ("test check run file input output work code change add use make fix new first need say show get set user data " + "keep take one two way step time thing write read sisi lesson agent human rule recipe verifier " + "contract example import function return value error message result line second third before " + "after every always never also just even still really about".split()) + out = set() + for w in roots: + forms = {w, w + "s", w + "es", w + "ing", w + "ed", w + "er", w + "ers"} + if w.endswith("e"): + forms |= {w[:-1] + "ing", w[:-1] + "ed"} + out |= {_stem(f) for f in forms} + return out + + +_COMMON = _common_stems() def _word_cut(text, limit): @@ -120,7 +137,7 @@ def _best_recipe(query): def stems_of(text): return {_stem(x) for x in V._words(text.replace("-", " "))} - generic = set() | {_stem(w) for w in + generic = _COMMON | {_stem(w) for w in ("agent agents tool tools interface surface command commands function functions " "program system name names description descriptions user users thing things " "way ways step steps example examples".split())} diff --git a/sisi/retro.py b/sisi/retro.py index 8e5a4bc..b27eb3c 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -29,6 +29,11 @@ def repo_of(cwd): return L.project_key(cwd) +def notes_for(entry_id): + """Field notes per library entry were part of the retired trace regime; none remain.""" + return None + + def _git_head(cwd): try: p = subprocess.run(["git", "rev-parse", "HEAD"], cwd=cwd, capture_output=True, diff --git a/tests/test_delivery.py b/tests/test_delivery.py index 2d3cb28..08ffa0e 100644 --- a/tests/test_delivery.py +++ b/tests/test_delivery.py @@ -222,23 +222,6 @@ class DeliveryRowTests(SisiCase): per = (time.perf_counter() - t) / 5 self.assertLess(per, 0.25) - def test_retro_stores_the_request_time_with_the_lesson(self): - store.save_session("r-1", {"session_id": "r-1", "transcript_path": self.tp, "cwd": self.proj}) - os.environ["SISI_SESSION_ID"] = "r-1" - con = retro.connect() - try: - lid = retro.new_lesson(con, dict(aim="speed", change_kind="tool", target=None, - moment="`make build` took 9 minutes in lib/src", cause="no cache here", - change="add a cache recipe for `make build`"), self.proj, None) - con.commit() - v = con.execute("SELECT delivery_s FROM occurrences WHERE lesson_id=?", (lid,)).fetchone()[0] - finally: - con.close() - self.assertGreaterEqual(v, 89) - self.assertLess(v, 200) - self.assertIn("it took longer than it had to", self.sisi("help").stdout) - - def ref_percentile(xs, p): s = sorted(xs) if len(s) == 1: diff --git a/tests/test_gate.py b/tests/test_gate.py index aa5afce..d85a843 100644 --- a/tests/test_gate.py +++ b/tests/test_gate.py @@ -869,14 +869,15 @@ class GateSingleSessionEquivalenceTests(GateBase): return d def retro_for(self, proj, sid, n): - from test_retro import GOOD, argv as retro_argv - f = dict(GOOD, moment="`cargo test` twin run %d took 4 minutes with no fuzz verifier in project" % n, - change="Add the fuzz verifier to the parser-or-codec recipe Checks, twin variant %d" % n, new=True) - r = self.sisi("retro", *retro_argv(f), cwd=proj, env={"SISI_SESSION_ID": sid}) - if r.returncode == 4: # same lesson as the twin's: add an occurrence for this repo instead - r = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` twin run %d, no fuzz" % n, - cwd=proj, env={"SISI_SESSION_ID": sid}) - self.assertEqual(r.returncode, 0, r.stdout) + r = self.sisi("retro", + "--finding", "`cargo test` twin run %d took 4 minutes with no fuzz verifier in project" % n, + "--cause", "the recipe never named a fuzz verifier for parsers", + "--impact", "time", "--disposition", "promote", + "--change", "Add the fuzz verifier to the parser-or-codec recipe Checks, twin variant %d" % n, + "--mechanism", "verification", "--expect", "parser work gets a fuzz check", + "--validate", "run the recipe checks on a parser change", + cwd=proj, env={"SISI_SESSION_ID": sid}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) def test_seeded_sequences_match_the_reference(self): os.environ["SISI_RETRO_REQUIRED"] = "1" diff --git a/tests/test_personal.py b/tests/test_personal.py index 0cf95d6..a18da1f 100644 --- a/tests/test_personal.py +++ b/tests/test_personal.py @@ -2,7 +2,7 @@ install migration, and the property that sisi never writes inside the product.""" import hashlib, json, os, signal, time, shutil, sqlite3, stat, subprocess, sys, tarfile, unittest, unittest.mock from support import * -from sisi import lifecycle, overlay, paths, pdata, retro, wiring +from sisi import lifecycle, overlay, paths, pdata, wiring RULES = [("alpha", "Alpha rule", "Do alpha things.\n\nWhy: alpha."), ("beta", "Beta rule", "Do beta things.\n\nWhy: beta."), @@ -243,7 +243,7 @@ class OverlayTests(PersonalCase): lines = len(self.generated().splitlines()) self.assertIn("rulebook %d lines" % lines, out) self.assertIn("%d characters" % len(self.generated()), out) - self.assertIn("lessons block at most %d characters" % retro.LIMIT, out) + self.assertNotIn("lessons block", out) # no lesson list is loaded at session start self.assertIn(out.strip(), self.ok("status").stdout) def test_core_md_rules_have_unique_ids_and_the_budget_holds(self): @@ -364,6 +364,23 @@ class UpdateTests(PersonalCase): self.assertIn("not a git clone", r.stdout) +def _seed_legacy_db(path, lessons, proj): + """A pre-rebuild retro.db: the sqlite lesson store the migration reads.""" + con = sqlite3.connect(path) + 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)") + for f in lessons: + cur = con.execute("INSERT INTO lessons(aim,change_kind,target,moment,cause,change,status,project,created)" + " VALUES(?,?,?,?,?,?,?,?,?)", + (f.get("aim"), f.get("change_kind"), f.get("target"), f.get("moment"), + f.get("cause"), f.get("change"), "open", proj, "2026-01-01T00:00:00Z")) + con.execute("INSERT INTO occurrences(lesson_id,ts,session,moment,repo) VALUES(?,?,?,?,?)", + (cur.lastrowid, "2026-01-01T00:00:00Z", "s0", f.get("moment"), proj)) + con.commit(); con.close() + + class MigrationTests(PersonalCase): LESSONS = [dict(aim="verified", moment="ran pytest and it passed without the new test", cause="the test never failed", change_kind="rule", change="Always watch a new test fail without the change first", target=None), @@ -374,13 +391,8 @@ class MigrationTests(PersonalCase): """Lay out an old-style installation: personal files in the state dir, oracle and notes in the product.""" os.makedirs(os.path.join(self.state, "backups")) db = os.path.join(self.state, "retro.db") - with unittest.mock.patch.object(retro, "db_path", return_value=db): - con = retro.connect() - for f in self.LESSONS + ([dict(aim="intent", moment="built the wrong thing for a day", cause="no check with the human", - change_kind="rule", change="Confirm the goal in one line before starting", target=None)] if extra_lesson else []): - retro.new_lesson(con, dict(f), self.proj, None) - con.commit() - con.close() + _seed_legacy_db(db, self.LESSONS + ([dict(aim="intent", moment="built the wrong thing for a day", cause="no check with the human", + change_kind="rule", change="Confirm the goal in one line before starting", target=None)] if extra_lesson else []), self.proj) json.dump([self.proj], open(os.path.join(self.state, "trusted.json"), "w")) json.dump({"verify": {"fast_limit_s": 9}}, open(os.path.join(self.state, "config.json"), "w")) for n, t in (("learn-quarantine.jsonl", "quarantined"), ("notes.jsonl", "a note"), ("proposals.jsonl", "a proposal")): @@ -421,10 +433,10 @@ class MigrationTests(PersonalCase): self.assertIn("/x/CLAUDE.md", json.load(open(os.path.join(self.data, "install", "manifest.json")))["files"]) # committed: the learned content is in git history, the database is not files = pdata.git("ls-files").stdout.split() - for f in ("oracle.md", "lessons.jsonl", "trusted.json", "config.json", "notes/fuzz.md", "VERSION", "learn-quarantine.jsonl"): + for f in ("oracle.md", "learnings.jsonl", "trusted.json", "config.json", "notes/fuzz.md", "VERSION", "learn-quarantine.jsonl"): self.assertIn(f, files) self.assertNotIn("retro.db", files) - self.assertEqual(len(open(os.path.join(self.data, "lessons.jsonl")).read().splitlines()), 2 + len(before[1])) + self.assertEqual(len(open(os.path.join(self.data, "learnings.jsonl")).read().splitlines()), 2) # one record per lesson; occurrences are provenance inside it self.assertTrue(self.git_log()[0].startswith("migrate:")) # the backup has what moved, before it moved bk = os.path.join(self.data, "backups") @@ -439,28 +451,26 @@ class MigrationTests(PersonalCase): self.assertIn("nothing to migrate", self.ok("migrate").stdout) self.assertEqual(len(self.git_log()), n) self.assertEqual(self.lessons_of(os.path.join(self.data, "retro.db")), before) - self.assertEqual(self.ok("lessons", "--json").stdout.count('"change_kind"'), 2) + self.assertEqual(self.ok("lessons", "--json").stdout.count('"id": "L-'), 2) def test_old_layout_keeps_working_before_migration(self): self.legacy_state() + self.ok("migrate") # lessons now live in learnings.jsonl; migration is the one path in self.assertEqual(self.ok("lessons").stdout.count("\n"), 2) self.assertEqual(wiring.quick_problem(), None) from sisi import trust self.assertTrue(trust.is_trusted(self.proj)) self.assertEqual(self.ok("tick", stdin="{}").returncode, 0) - self.assertIn("Always watch", self.sisi("tick", stdin="{}").stdout) + self.assertNotIn("Always watch", self.sisi("tick", stdin="{}").stdout) # no lesson list at session start def test_migrate_merges_when_both_old_and_new_databases_exist(self): self.legacy_state(extra_lesson=True) # the new location already has one of the same lessons and one of its own - with unittest.mock.patch.object(retro, "db_path", return_value=os.path.join(self.data, "retro.db")): - os.makedirs(self.data) - con = retro.connect() - retro.new_lesson(con, dict(self.LESSONS[0]), self.proj, None) - retro.new_lesson(con, dict(aim="level", moment="asked about a thing the oracle already answered", cause="did not run oracle", - change_kind="rule", change="Run sisi oracle before asking anything", target=None), self.proj, None) - con.commit() - con.close() + os.makedirs(self.data, exist_ok=True) + _seed_legacy_db(os.path.join(self.data, "retro.db"), + [dict(self.LESSONS[0]), + dict(aim="level", moment="asked about a thing the oracle already answered", cause="did not run oracle", + change_kind="rule", change="Run sisi oracle before asking anything", target=None)], self.proj) self.ok("migrate") rows, _ = self.lessons_of(os.path.join(self.data, "retro.db")) changes = sorted(r["change"] for r in rows) @@ -551,11 +561,12 @@ class ExportImportTests(PersonalCase): def test_round_trip_is_lossless_for_committed_content(self): self.ok("overlay", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body.")) self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Mine")) - self.ok("learn", "--scope", "everywhere", "never", "ask", "twice") - self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", - "--cause", "the test was written after the code", "--change-kind", "rule", - "--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", - "--change", "write the failing test first and show it fail with `pytest -k new`") + self.ok("learn", "--scope", "user", "never ask the same thing twice") + self.ok("retro", "--finding", "ran `pytest -q` and saw 3 passed but the new test had never failed", + "--cause", "the test was written after the code", "--impact", "correctness", + "--disposition", "promote", "--change", "write the failing test first and show it fail with `pytest -k new`", + "--mechanism", "verification", "--expect", "new tests are seen failing first", + "--validate", "replay the new test at the parent commit") os.makedirs(os.path.join(self.state, "sessions")) open(os.path.join(self.state, "sessions", "s1.json"), "w").write('{"a": 1}') open(os.path.join(self.state, "results.jsonl"), "w").write('{"r": 1}\n') @@ -568,7 +579,7 @@ class ExportImportTests(PersonalCase): with tarfile.open(arc) as tf: names = tf.getnames() self.assertIn("personal/overlay/rules/delta.md", names) - self.assertIn("personal/retro.db", names) + self.assertIn("personal/learnings.jsonl", names) self.assertIn("state/results.jsonl", names) self.assertIn("state/sessions/s1.json", names) self.assertFalse([n for n in names if "/generated" in n or "/backups" in n or "/install" in n]) @@ -587,22 +598,16 @@ class ExportImportTests(PersonalCase): self.assertTrue(os.path.exists(os.path.join(self.state, "sessions", "s1.json"))) self.assertRegex(self.ok("verifiers", "--section", "safety").stdout, r"shellcheck .*Mine") - def test_import_sets_existing_data_aside_and_rebuilds_db_from_the_dump(self): - self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", - "--cause", "the test was written after the code", "--change-kind", "rule", - "--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", - "--change", "write the failing test first and show it fail with `pytest -k new`") + def test_import_sets_existing_data_aside_and_restores_learnings(self): + self.ok("retro", "--finding", "ran `pytest -q` and saw 3 passed but the new test had never failed", + "--cause", "the test was written after the code", "--impact", "correctness", + "--disposition", "promote", "--change", "write the failing test first and show it fail with `pytest -k new`", + "--mechanism", "verification", "--expect", "new tests are seen failing first", + "--validate", "replay the new test at the parent commit") arc = os.path.join(self.tmp, "out.tar.gz") self.ok("export", arc) - # an archive without the database: the dump recreates it - slim = os.path.join(self.tmp, "slim.tar.gz") - with tarfile.open(arc) as a, tarfile.open(slim, "w:gz") as b: - for m in a.getmembers(): - if m.name != "personal/retro.db": - b.addfile(m, a.extractfile(m) if m.isfile() else None) - r = self.ok("import", slim) + r = self.ok("import", arc) self.assertIn("set aside", r.stdout) - self.assertIn("rebuilt from lessons.jsonl", r.stdout) self.assertTrue(glob_aside(self.data)) self.assertEqual(self.ok("lessons").stdout.count("\n"), 1) @@ -624,46 +629,34 @@ def glob_aside(data): def LessonRows(): - con = retro.connect() - try: - return retro.dump_lines(con) - finally: - con.close() + from sisi import learning as _L + return [json.dumps(r, sort_keys=True) for r in _L.load_learnings()] class LessonDumpTests(PersonalCase): - RETRO = ["--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", - "--cause", "the test was written after the code", "--change-kind", "rule", - "--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", - "--change", "write the failing test first and show it fail with `pytest -k new`"] + """The learning store is learnings.jsonl, committed; git is the history. No sqlite mirror.""" + RETRO = ["--finding", "ran `pytest -q` and saw 3 passed but the new test had never failed", + "--cause", "the test was written after the code", "--impact", "correctness", + "--disposition", "promote", "--change", "write the failing test first and show it fail with `pytest -k new`", + "--mechanism", "verification", "--expect", "new tests are seen failing first", + "--validate", "replay the new test at the parent commit"] - def test_dump_is_committed_sorted_and_the_database_is_not(self): + def test_learnings_are_committed_and_no_database_exists(self): self.ok("retro", *self.RETRO) - self.assertEqual(self.git_log()[0], "lessons: retro recorded for lesson #1") + self.assertIn("learnings.jsonl", pdata.git("ls-files").stdout) self.assertNotIn("retro.db", pdata.git("ls-files").stdout) - lines = open(os.path.join(self.data, "lessons.jsonl")).read().splitlines() - self.assertEqual(json.loads(lines[0])["t"], "lesson") - self.assertEqual(json.loads(lines[1])["t"], "occurrence") - n = len(self.git_log()) - self.ok("lessons", "set", "1", "--status", "rejected") - self.assertEqual(len(self.git_log()), n + 1) - self.assertIn("lesson #1 set to rejected", self.git_log()[0]) - self.assertEqual(json.loads(open(os.path.join(self.data, "lessons.jsonl")).readline())["status"], "rejected") - # recoverable from history alone - old = pdata.git("show", "HEAD~1:lessons.jsonl").stdout - self.assertEqual(json.loads(old.splitlines()[0])["status"], "open") - # export is stable - a = open(os.path.join(self.data, "lessons.jsonl")).read() - self.ok("lessons", "export") - self.assertEqual(open(os.path.join(self.data, "lessons.jsonl")).read(), a) - self.assertEqual(len(self.git_log()), n + 1) + self.assertFalse(os.path.exists(os.path.join(self.data, "retro.db"))) + lines = open(os.path.join(self.data, "learnings.jsonl")).read().splitlines() + rec = json.loads(lines[0]) + self.assertEqual(rec["status"], "proposed") + self.assertEqual(rec["validation"]["result"], "unvalidated") def test_learn_and_note_are_personal_and_committed(self): - self.ok("learn", "--scope", "everywhere", "Always", "use", "options") - self.assertIn("learn: Always use options", self.git_log()[0]) - self.assertIn("learn.jsonl", pdata.git("ls-files").stdout) + self.ok("learn", "--scope", "user", "Always use options when asking") + self.assertIn("learnings.jsonl", pdata.git("ls-files").stdout) self.assertFalse(os.path.exists(os.path.join(self.state, "learn.jsonl"))) self.assertIn("oracle", self.ok("oracle").stdout.lower()) + self.assertIn("Always use options when asking", self.ok("oracle").stdout) class IsolationTests(PersonalCase): @@ -738,7 +731,7 @@ class ProductIsReadOnlyTests(PersonalCase): gate_in = json.dumps({"session_id": "s1", "cwd": self.proj, "stop_hook_active": False}) cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("build-canon",), ("status",), ("overlay", "add-rule", "--id", "z", "-"), ("overlay", "diff"), ("overlay", "disable-rule", "z"), - ("learn", "--scope", "everywhere", "x"), ("lessons", "export"), ("verifiers", "show", "shellcheck"), + ("learn", "--scope", "user", "x"), ("lessons",), ("verifiers", "show", "shellcheck"), ("contract", "init", "--goal", "g"), ("verify",), ("migrate",), ("update",), ("export", os.path.join(self.tmp, "e.tar.gz")), ("gate",), ("uninstall",)] for c in cmds: diff --git a/tests/test_prompt.py b/tests/test_prompt.py index fc53965..1450309 100644 --- a/tests/test_prompt.py +++ b/tests/test_prompt.py @@ -6,7 +6,7 @@ phrases requests in different words from the lessons so only the when-terms can """ import json, os, statistics, time, unittest from support import * -from sisi import retro +from sisi import learning as L def fields(**kw): @@ -22,13 +22,11 @@ def fields(**kw): class PromptCase(SisiCase): 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() + f = fields(**kw) + rec = L.new_record(f["moment"], f["cause"], "correctness", "promote", self.proj, "u-test", + change=f["change"], mechanism="policy", scope="project", + expect="caught before delivery", validate="replay") + return rec["id"] def prompt(self, payload, tool=None): args = ["prompt"] + (["--tool", tool] if tool else []) @@ -45,21 +43,17 @@ class PromptHookTests(PromptCase): self.assertEqual(out["hookSpecificOutput"]["hookEventName"], "UserPromptSubmit") self.assertIn("release", ctx) self.assertIn("sisi done release", ctx) - self.assertIn("Check tag, version and changelog agree", ctx) - self.assertIn("sisi lessons show %d" % lid, ctx) + self.assertIn("check the tag, the manifest version and the changelog", ctx) + self.assertIn(lid, ctx) from sisi import prompt as P self.assertLessEqual(len(ctx), P.MAX_CHARS) - def test_listing_is_counted(self): - lid = self.mk() + def test_showing_is_not_recorded_as_evidence(self): + """Being shown is not evidence: delivery writes nothing to the learning store.""" + self.mk() + before = L.store_base() self.prompt({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj}) - con = retro.connect() - try: - self.assertGreaterEqual(retro.listed_count(con, lid), 1) - places = [r[0] for r in con.execute("SELECT place FROM impressions WHERE lesson_id=?", (lid,))] - self.assertIn("prompt", places) - finally: - con.close() + self.assertEqual(L.store_base(), before) def test_nothing_for_trivial_or_unmatched_messages(self): self.mk() @@ -122,14 +116,19 @@ class LabelledMatchingTests(PromptCase): def ctx(self, text): from sisi import prompt as P - return P.build_context(text, session="labelled") + old = os.getcwd() + os.chdir(self.proj) # delivery is scoped to the project the hook runs in + try: + return P.build_context(text, session="labelled") + finally: + os.chdir(old) def test_labelled_set(self): # A hit: the expected lesson's short line is injected. A false match: either lesson is # injected for a request it does not apply to. (A recipe for the request's own kind of work # is the feature working, not a false match, so it is measured separately below.) - release_short = "Check tag, version and changelog agree" - csv_short = "Use a quoting writer" + release_short = "check the tag, the manifest version and the changelog" + csv_short = "quoting writer so embedded newlines" should = [ ("cut a new release and tag it", release_short), ("publish the next version to the package index please", release_short), diff --git a/tests/test_rule.py b/tests/test_rule.py index 3797297..0b6e655 100644 --- a/tests/test_rule.py +++ b/tests/test_rule.py @@ -45,26 +45,6 @@ class RuleDetailTests(SisiCase): self.assertEqual(self.sisi("rule", "no-such-rule").returncode, 1) self.assertEqual(self.sisi("rule", "99").returncode, 1) - def test_folded_lessons_are_shown_with_show_command(self): - con = retro.connect() - try: - lid = retro.new_lesson(con, dict( - aim="hands-off", change_kind="rule", target=None, - moment="the agent buried a naming question at the end of a long report", - cause="asking in prose felt quicker than opening the dialog", - change="Ask naming questions through the dialog with options", - when="naming, question, dialog, options, ask the human, choice", - short="Ask through the dialog, with options."), self.proj, None) - con.execute("UPDATE lessons SET folded_into='decide-dont-ask', count=3 WHERE id=?", (lid,)) - con.commit() - finally: - con.close() - r = self.sisi("rule", "decide-dont-ask") - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("Ask through the dialog, with options.", r.stdout) - self.assertIn("sisi lessons show %d" % lid, r.stdout) - self.assertIn("buried a naming question", r.stdout) # the moment, as the example - def test_overlay_replacement_is_named_as_overlay(self): d = os.path.join(self.data, "overlay", "rules") os.makedirs(d, exist_ok=True) diff --git a/tests/test_tick_store.py b/tests/test_tick_store.py index da6ae6c..4bf3ec6 100644 --- a/tests/test_tick_store.py +++ b/tests/test_tick_store.py @@ -81,19 +81,18 @@ class StoreTests(SisiCase): with open(os.path.join(self.data, name)) as f: # what the person taught sisi is personal data return [json.loads(l) for l in f] - def test_note_propose_learn_append_with_context(self): - for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl"), ("learn", "learn.jsonl")): - extra = ["--scope", "everywhere"] if cmd == "learn" else [] - self.assertEqual(self.sisi(cmd, *(extra + ["first", "entry"]), env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0) - self.sisi(cmd, *(extra + ["second"])) + def test_note_propose_append_with_context_and_learn_records_a_statement(self): + for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl")): + self.assertEqual(self.sisi(cmd, "first", "entry", env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0) + self.sisi(cmd, "second") recs = self.read(fn) self.assertEqual([r["text"] for r in recs], ["first entry", "second"]) self.assertEqual(recs[0]["cwd"], self.proj) self.assertEqual((recs[0]["tool"], recs[0]["session"]), ("codex", "s9")) self.assertIn("ts", recs[0]) - # learn never reaches the other files - self.assertEqual(len(self.read("notes.jsonl")), 2) - self.assertEqual(len(self.read("proposals.jsonl")), 2) + r = self.sisi("learn", "--scope", "user", "always record the statement plainly") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("always record the statement plainly", self.sisi("oracle").stdout) def test_empty_text_rejected(self): self.assertEqual(self.sisi("note").returncode, 1)