Fix cross-module fallout: stemmer, oracle, overlay cost, test fixtures

This commit is contained in:
swaits committed 2026-11-23 11:10:56 -07:00
1 parent ee6fc292d8
commit 2907e7df15
13 files changed
+218 -177

No files matched your search

+1 -1
View File
@@ -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 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 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. reports the counted evidence for that question, and it needs real use to have data.
## How it works ## How it works
+34 -15
View File
@@ -147,17 +147,36 @@ def get(rows, lid):
# ---- derived text (the tool derives search terms, topics, short lines) --------- # ---- derived text (the tool derives search terms, topics, short lines) ---------
def stems(text): def _stem(w):
out = set() """A crude stem so 'parsing', 'parser' and 'parse' meet, as do plurals."""
for w in re.findall(r"[a-z0-9]{3,}", (text or "").lower()): s = w
if w in STOP: if len(s) > 4 and s.endswith("ies"):
continue s = s[:-3] + "y"
for suf in ("ing", "edly", "ed", "es", "s"): else:
if w.endswith(suf) and len(w) - len(suf) >= 3: done = False
w = w[: -len(suf)] 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 break
out.add(w) if not done:
return out 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): 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", "")) \ hay = set(r.get("terms") or []) | stems(r.get("observation", {}).get("evidence", "")) \
| stems(r.get("proposed", {}).get("description", "")) | stems(r.get("proposed", {}).get("description", ""))
inter = len(q & hay) inter = len(q & hay)
if inter >= 3: if inter >= 1:
scored.append((inter / max(1, len(q | hay)), r)) scored.append((inter / max(1, len(q)), inter, r))
scored.sort(key=lambda x: -x[0]) 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) --------------------------------------------- # ---- 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.""" """Learnings in scope, framed as information, never as instructions. No showing is recorded."""
rows = learnings_in_scope(project) rows = learnings_in_scope(project)
if query: if query:
match = similar_learnings(rows, query, limit=5) rows = similar_learnings(rows, query, limit=5) # silence is the default
rows = match if match else rows
rows = [r for r in rows if r.get("status") in rows = [r for r in rows if r.get("status") in
("promoted", "monitored", "proposed", "observed", "implemented", "validated")] ("promoted", "monitored", "proposed", "observed", "implemented", "validated")]
if not rows: if not rows:
+14
View File
@@ -264,6 +264,20 @@ def migrate_learnings():
return [] return []
bdir = snapshot("learning-migration") bdir = snapshot("learning-migration")
lessons, occs, impressions = {}, {}, 0 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): if os.path.exists(src):
with open(src, encoding="utf-8") as f: with open(src, encoding="utf-8") as f:
for line in f: for line in f:
+6 -7
View File
@@ -280,23 +280,22 @@ def is_stale():
def cost(): def cost():
"""Always-loaded size: the generated rulebook and the largest session-start lessons block.""" """Always-loaded size: the generated rulebook. No lesson list is loaded at session start."""
from . import retro
try: try:
lines, chars = size(_read(paths.generated())) lines, chars = size(_read(paths.generated()))
except OSError: except OSError:
lines = chars = None lines = chars = None
return {"rulebook_lines": lines, "rulebook_chars": chars, "rulebook_budget_lines": MAX_LINES, return {"rulebook_lines": lines, "rulebook_chars": chars, "rulebook_budget_lines": MAX_LINES,
"rulebook_budget_chars": MAX_CHARS, "rulebook_budget_chars": MAX_CHARS}
"lessons_block_max_chars": retro.LIMIT, "lessons_block_max_lines": 1 + 8}
def cost_line(c=None): def cost_line(c=None):
c = c or cost() c = c or cost()
if c["rulebook_lines"] is None: 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 not generated yet (run `sisi build-canon`)"
return "rulebook %d lines (budget %d), %d characters (budget %d); session-start lessons block at most %d characters, %d lines" % ( 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), c["lessons_block_max_chars"], c["lessons_block_max_lines"]) c["rulebook_lines"], c["rulebook_budget_lines"], c["rulebook_chars"],
c.get("rulebook_budget_chars", MAX_CHARS))
# ---- library overlay (verifiers, recipes) --------------------------------------- # ---- library overlay (verifiers, recipes) ---------------------------------------
+38 -6
View File
@@ -1,16 +1,38 @@
"""Owner statements, printed by `sisi oracle`. One store: learning records with owner_statement. """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 `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(): 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", "scope": r.get("proposed", {}).get("scope") or "user",
"ts": r.get("created", ""), "id": r.get("id")} "ts": r.get("created", ""), "id": r.get("id")}
for r in L.owner_statements()] for r in L.owner_statements()]
if recs or os.path.exists(L.learnings_path()):
return recs
return _legacy_statements()
def plain_of(rec): def plain_of(rec):
@@ -20,10 +42,20 @@ def plain_of(rec):
def oracle_text(): def oracle_text():
recs = statements() recs = statements()
if not recs: if not recs:
return "No owner statements recorded. `sisi learn \"<what you want>\"` adds one.\n" legacy = paths.data_file("oracle.md")
lines = ["What the owner wants (recorded with `sisi learn`):"] 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 \"<what you want>\"` 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): 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" return "\n".join(lines) + "\n"
+19 -2
View File
@@ -11,7 +11,24 @@ from . import learning as _L, store
def _stem(w): 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): def _word_cut(text, limit):
@@ -120,7 +137,7 @@ def _best_recipe(query):
def stems_of(text): def stems_of(text):
return {_stem(x) for x in V._words(text.replace("-", " "))} 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 " ("agent agents tool tools interface surface command commands function functions "
"program system name names description descriptions user users thing things " "program system name names description descriptions user users thing things "
"way ways step steps example examples".split())} "way ways step steps example examples".split())}
+5
View File
@@ -29,6 +29,11 @@ def repo_of(cwd):
return L.project_key(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): def _git_head(cwd):
try: try:
p = subprocess.run(["git", "rev-parse", "HEAD"], cwd=cwd, capture_output=True, p = subprocess.run(["git", "rev-parse", "HEAD"], cwd=cwd, capture_output=True,
-17
View File
@@ -222,23 +222,6 @@ class DeliveryRowTests(SisiCase):
per = (time.perf_counter() - t) / 5 per = (time.perf_counter() - t) / 5
self.assertLess(per, 0.25) 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): def ref_percentile(xs, p):
s = sorted(xs) s = sorted(xs)
if len(s) == 1: if len(s) == 1:
+9 -8
View File
@@ -869,14 +869,15 @@ class GateSingleSessionEquivalenceTests(GateBase):
return d return d
def retro_for(self, proj, sid, n): def retro_for(self, proj, sid, n):
from test_retro import GOOD, argv as retro_argv r = self.sisi("retro",
f = dict(GOOD, moment="`cargo test` twin run %d took 4 minutes with no fuzz verifier in project" % n, "--finding", "`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) "--cause", "the recipe never named a fuzz verifier for parsers",
r = self.sisi("retro", *retro_argv(f), cwd=proj, env={"SISI_SESSION_ID": sid}) "--impact", "time", "--disposition", "promote",
if r.returncode == 4: # same lesson as the twin's: add an occurrence for this repo instead "--change", "Add the fuzz verifier to the parser-or-codec recipe Checks, twin variant %d" % n,
r = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` twin run %d, no fuzz" % n, "--mechanism", "verification", "--expect", "parser work gets a fuzz check",
cwd=proj, env={"SISI_SESSION_ID": sid}) "--validate", "run the recipe checks on a parser change",
self.assertEqual(r.returncode, 0, r.stdout) cwd=proj, env={"SISI_SESSION_ID": sid})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
def test_seeded_sequences_match_the_reference(self): def test_seeded_sequences_match_the_reference(self):
os.environ["SISI_RETRO_REQUIRED"] = "1" os.environ["SISI_RETRO_REQUIRED"] = "1"
+64 -71
View File
@@ -2,7 +2,7 @@
install migration, and the property that sisi never writes inside the product.""" 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 import hashlib, json, os, signal, time, shutil, sqlite3, stat, subprocess, sys, tarfile, unittest, unittest.mock
from support import * 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."), RULES = [("alpha", "Alpha rule", "Do alpha things.\n\nWhy: alpha."),
("beta", "Beta rule", "Do beta things.\n\nWhy: beta."), ("beta", "Beta rule", "Do beta things.\n\nWhy: beta."),
@@ -243,7 +243,7 @@ class OverlayTests(PersonalCase):
lines = len(self.generated().splitlines()) lines = len(self.generated().splitlines())
self.assertIn("rulebook %d lines" % lines, out) self.assertIn("rulebook %d lines" % lines, out)
self.assertIn("%d characters" % len(self.generated()), 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) self.assertIn(out.strip(), self.ok("status").stdout)
def test_core_md_rules_have_unique_ids_and_the_budget_holds(self): 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) 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): class MigrationTests(PersonalCase):
LESSONS = [dict(aim="verified", moment="ran pytest and it passed without the new test", cause="the test never failed", 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), 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.""" """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")) os.makedirs(os.path.join(self.state, "backups"))
db = os.path.join(self.state, "retro.db") db = os.path.join(self.state, "retro.db")
with unittest.mock.patch.object(retro, "db_path", return_value=db): _seed_legacy_db(db, self.LESSONS + ([dict(aim="intent", moment="built the wrong thing for a day", cause="no check with the human",
con = retro.connect() change_kind="rule", change="Confirm the goal in one line before starting", target=None)] if extra_lesson else []), self.proj)
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()
json.dump([self.proj], open(os.path.join(self.state, "trusted.json"), "w")) 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")) 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")): 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"]) 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 # committed: the learned content is in git history, the database is not
files = pdata.git("ls-files").stdout.split() 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.assertIn(f, files)
self.assertNotIn("retro.db", 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:")) self.assertTrue(self.git_log()[0].startswith("migrate:"))
# the backup has what moved, before it moved # the backup has what moved, before it moved
bk = os.path.join(self.data, "backups") bk = os.path.join(self.data, "backups")
@@ -439,28 +451,26 @@ class MigrationTests(PersonalCase):
self.assertIn("nothing to migrate", self.ok("migrate").stdout) self.assertIn("nothing to migrate", self.ok("migrate").stdout)
self.assertEqual(len(self.git_log()), n) self.assertEqual(len(self.git_log()), n)
self.assertEqual(self.lessons_of(os.path.join(self.data, "retro.db")), before) 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): def test_old_layout_keeps_working_before_migration(self):
self.legacy_state() 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(self.ok("lessons").stdout.count("\n"), 2)
self.assertEqual(wiring.quick_problem(), None) self.assertEqual(wiring.quick_problem(), None)
from sisi import trust from sisi import trust
self.assertTrue(trust.is_trusted(self.proj)) self.assertTrue(trust.is_trusted(self.proj))
self.assertEqual(self.ok("tick", stdin="{}").returncode, 0) 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): def test_migrate_merges_when_both_old_and_new_databases_exist(self):
self.legacy_state(extra_lesson=True) self.legacy_state(extra_lesson=True)
# the new location already has one of the same lessons and one of its own # 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, exist_ok=True)
os.makedirs(self.data) _seed_legacy_db(os.path.join(self.data, "retro.db"),
con = retro.connect() [dict(self.LESSONS[0]),
retro.new_lesson(con, dict(self.LESSONS[0]), self.proj, None) dict(aim="level", moment="asked about a thing the oracle already answered", cause="did not run oracle",
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)
change_kind="rule", change="Run sisi oracle before asking anything", target=None), self.proj, None)
con.commit()
con.close()
self.ok("migrate") self.ok("migrate")
rows, _ = self.lessons_of(os.path.join(self.data, "retro.db")) rows, _ = self.lessons_of(os.path.join(self.data, "retro.db"))
changes = sorted(r["change"] for r in rows) 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): 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", "add-rule", "--id", "delta", "-", stdin=rule_file("Delta", "Body."))
self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Mine")) self.ok("overlay", "replace-verifier", "shellcheck", "-", stdin=self.verifier_text("shellcheck", "Mine"))
self.ok("learn", "--scope", "everywhere", "never", "ask", "twice") self.ok("learn", "--scope", "user", "never ask the same thing twice")
self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", 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", "--change-kind", "rule", "--cause", "the test was written after the code", "--impact", "correctness",
"--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--disposition", "promote", "--change", "write the failing test first and show it fail with `pytest -k new`",
"--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")) 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, "sessions", "s1.json"), "w").write('{"a": 1}')
open(os.path.join(self.state, "results.jsonl"), "w").write('{"r": 1}\n') 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: with tarfile.open(arc) as tf:
names = tf.getnames() names = tf.getnames()
self.assertIn("personal/overlay/rules/delta.md", names) 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/results.jsonl", names)
self.assertIn("state/sessions/s1.json", 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]) 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.assertTrue(os.path.exists(os.path.join(self.state, "sessions", "s1.json")))
self.assertRegex(self.ok("verifiers", "--section", "safety").stdout, r"shellcheck .*Mine") 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): def test_import_sets_existing_data_aside_and_restores_learnings(self):
self.ok("retro", "--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", 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", "--change-kind", "rule", "--cause", "the test was written after the code", "--impact", "correctness",
"--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--disposition", "promote", "--change", "write the failing test first and show it fail with `pytest -k new`",
"--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") arc = os.path.join(self.tmp, "out.tar.gz")
self.ok("export", arc) self.ok("export", arc)
# an archive without the database: the dump recreates it r = self.ok("import", arc)
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)
self.assertIn("set aside", r.stdout) self.assertIn("set aside", r.stdout)
self.assertIn("rebuilt from lessons.jsonl", r.stdout)
self.assertTrue(glob_aside(self.data)) self.assertTrue(glob_aside(self.data))
self.assertEqual(self.ok("lessons").stdout.count("\n"), 1) self.assertEqual(self.ok("lessons").stdout.count("\n"), 1)
@@ -624,46 +629,34 @@ def glob_aside(data):
def LessonRows(): def LessonRows():
con = retro.connect() from sisi import learning as _L
try: return [json.dumps(r, sort_keys=True) for r in _L.load_learnings()]
return retro.dump_lines(con)
finally:
con.close()
class LessonDumpTests(PersonalCase): class LessonDumpTests(PersonalCase):
RETRO = ["--scope", "everywhere", "--aim", "verified", "--moment", "ran `pytest -q` and saw 3 passed but the new test had never failed", """The learning store is learnings.jsonl, committed; git is the history. No sqlite mirror."""
"--cause", "the test was written after the code", "--change-kind", "rule", RETRO = ["--finding", "ran `pytest -q` and saw 3 passed but the new test had never failed",
"--when", "tests, pytest, failing first, regression, test quality, red green", "--pattern", "Reach for the familiar tool instead of the check that fits the claim", "--cause", "the test was written after the code", "--impact", "correctness",
"--change", "write the failing test first and show it fail with `pytest -k new`"] "--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.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) self.assertNotIn("retro.db", pdata.git("ls-files").stdout)
lines = open(os.path.join(self.data, "lessons.jsonl")).read().splitlines() self.assertFalse(os.path.exists(os.path.join(self.data, "retro.db")))
self.assertEqual(json.loads(lines[0])["t"], "lesson") lines = open(os.path.join(self.data, "learnings.jsonl")).read().splitlines()
self.assertEqual(json.loads(lines[1])["t"], "occurrence") rec = json.loads(lines[0])
n = len(self.git_log()) self.assertEqual(rec["status"], "proposed")
self.ok("lessons", "set", "1", "--status", "rejected") self.assertEqual(rec["validation"]["result"], "unvalidated")
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)
def test_learn_and_note_are_personal_and_committed(self): def test_learn_and_note_are_personal_and_committed(self):
self.ok("learn", "--scope", "everywhere", "Always", "use", "options") self.ok("learn", "--scope", "user", "Always use options when asking")
self.assertIn("learn: Always use options", self.git_log()[0]) self.assertIn("learnings.jsonl", pdata.git("ls-files").stdout)
self.assertIn("learn.jsonl", pdata.git("ls-files").stdout)
self.assertFalse(os.path.exists(os.path.join(self.state, "learn.jsonl"))) self.assertFalse(os.path.exists(os.path.join(self.state, "learn.jsonl")))
self.assertIn("oracle", self.ok("oracle").stdout.lower()) self.assertIn("oracle", self.ok("oracle").stdout.lower())
self.assertIn("Always use options when asking", self.ok("oracle").stdout)
class IsolationTests(PersonalCase): class IsolationTests(PersonalCase):
@@ -738,7 +731,7 @@ class ProductIsReadOnlyTests(PersonalCase):
gate_in = json.dumps({"session_id": "s1", "cwd": self.proj, "stop_hook_active": False}) gate_in = json.dumps({"session_id": "s1", "cwd": self.proj, "stop_hook_active": False})
cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("build-canon",), ("status",), cmds = [("install",), ("doctor",), ("tick", "--tool", "t"), ("build-canon",), ("status",),
("overlay", "add-rule", "--id", "z", "-"), ("overlay", "diff"), ("overlay", "disable-rule", "z"), ("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",), ("contract", "init", "--goal", "g"), ("verify",), ("migrate",), ("update",),
("export", os.path.join(self.tmp, "e.tar.gz")), ("gate",), ("uninstall",)] ("export", os.path.join(self.tmp, "e.tar.gz")), ("gate",), ("uninstall",)]
for c in cmds: for c in cmds:
+21 -22
View File
@@ -6,7 +6,7 @@ phrases requests in different words from the lessons so only the when-terms can
""" """
import json, os, statistics, time, unittest import json, os, statistics, time, unittest
from support import * from support import *
from sisi import retro from sisi import learning as L
def fields(**kw): def fields(**kw):
@@ -22,13 +22,11 @@ def fields(**kw):
class PromptCase(SisiCase): class PromptCase(SisiCase):
def mk(self, **kw): def mk(self, **kw):
con = retro.connect() f = fields(**kw)
try: rec = L.new_record(f["moment"], f["cause"], "correctness", "promote", self.proj, "u-test",
lid = retro.new_lesson(con, fields(**kw), self.proj, None) change=f["change"], mechanism="policy", scope="project",
con.commit() expect="caught before delivery", validate="replay")
return lid return rec["id"]
finally:
con.close()
def prompt(self, payload, tool=None): def prompt(self, payload, tool=None):
args = ["prompt"] + (["--tool", tool] if tool else []) args = ["prompt"] + (["--tool", tool] if tool else [])
@@ -45,21 +43,17 @@ class PromptHookTests(PromptCase):
self.assertEqual(out["hookSpecificOutput"]["hookEventName"], "UserPromptSubmit") self.assertEqual(out["hookSpecificOutput"]["hookEventName"], "UserPromptSubmit")
self.assertIn("release", ctx) self.assertIn("release", ctx)
self.assertIn("sisi done release", ctx) self.assertIn("sisi done release", ctx)
self.assertIn("Check tag, version and changelog agree", ctx) self.assertIn("check the tag, the manifest version and the changelog", ctx)
self.assertIn("sisi lessons show %d" % lid, ctx) self.assertIn(lid, ctx)
from sisi import prompt as P from sisi import prompt as P
self.assertLessEqual(len(ctx), P.MAX_CHARS) self.assertLessEqual(len(ctx), P.MAX_CHARS)
def test_listing_is_counted(self): def test_showing_is_not_recorded_as_evidence(self):
lid = self.mk() """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}) self.prompt({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj})
con = retro.connect() self.assertEqual(L.store_base(), before)
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()
def test_nothing_for_trivial_or_unmatched_messages(self): def test_nothing_for_trivial_or_unmatched_messages(self):
self.mk() self.mk()
@@ -122,14 +116,19 @@ class LabelledMatchingTests(PromptCase):
def ctx(self, text): def ctx(self, text):
from sisi import prompt as P 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): def test_labelled_set(self):
# A hit: the expected lesson's short line is injected. A false match: either lesson is # 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 # 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.) # is the feature working, not a false match, so it is measured separately below.)
release_short = "Check tag, version and changelog agree" release_short = "check the tag, the manifest version and the changelog"
csv_short = "Use a quoting writer" csv_short = "quoting writer so embedded newlines"
should = [ should = [
("cut a new release and tag it", release_short), ("cut a new release and tag it", release_short),
("publish the next version to the package index please", release_short), ("publish the next version to the package index please", release_short),
-20
View File
@@ -45,26 +45,6 @@ class RuleDetailTests(SisiCase):
self.assertEqual(self.sisi("rule", "no-such-rule").returncode, 1) self.assertEqual(self.sisi("rule", "no-such-rule").returncode, 1)
self.assertEqual(self.sisi("rule", "99").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): def test_overlay_replacement_is_named_as_overlay(self):
d = os.path.join(self.data, "overlay", "rules") d = os.path.join(self.data, "overlay", "rules")
os.makedirs(d, exist_ok=True) os.makedirs(d, exist_ok=True)
+7 -8
View File
@@ -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 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] return [json.loads(l) for l in f]
def test_note_propose_learn_append_with_context(self): def test_note_propose_append_with_context_and_learn_records_a_statement(self):
for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl"), ("learn", "learn.jsonl")): for cmd, fn in (("note", "notes.jsonl"), ("propose", "proposals.jsonl")):
extra = ["--scope", "everywhere"] if cmd == "learn" else [] self.assertEqual(self.sisi(cmd, "first", "entry", env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0)
self.assertEqual(self.sisi(cmd, *(extra + ["first", "entry"]), env={"SISI_TOOL": "codex", "SISI_SESSION_ID": "s9"}).returncode, 0) self.sisi(cmd, "second")
self.sisi(cmd, *(extra + ["second"]))
recs = self.read(fn) recs = self.read(fn)
self.assertEqual([r["text"] for r in recs], ["first entry", "second"]) self.assertEqual([r["text"] for r in recs], ["first entry", "second"])
self.assertEqual(recs[0]["cwd"], self.proj) self.assertEqual(recs[0]["cwd"], self.proj)
self.assertEqual((recs[0]["tool"], recs[0]["session"]), ("codex", "s9")) self.assertEqual((recs[0]["tool"], recs[0]["session"]), ("codex", "s9"))
self.assertIn("ts", recs[0]) self.assertIn("ts", recs[0])
# learn never reaches the other files r = self.sisi("learn", "--scope", "user", "always record the statement plainly")
self.assertEqual(len(self.read("notes.jsonl")), 2) self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(len(self.read("proposals.jsonl")), 2) self.assertIn("always record the statement plainly", self.sisi("oracle").stdout)
def test_empty_text_rejected(self): def test_empty_text_rejected(self):
self.assertEqual(self.sisi("note").returncode, 1) self.assertEqual(self.sisi("note").returncode, 1)