From 25b5e90c6bcdc793888419781db5724ea91d0ced Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Tue, 1 Dec 2026 17:02:03 -0700 Subject: [PATCH] Merge duplicate problems via rules organize alias map - List every canonical problem (number, name, one cause) in organize_brief and ask for optional `## same problems` lines `N = M`. - Record validated aliases into `rules/problems.json` with the organize commit, skipping unknown numbers, cycles, and bad lines with messages while still recording the rest of the organize; include `rules/problems.json` in `rules.revert()`. - Resolve cited numbers, names, misses, 2nd-miss faults, drop lookups, and per-rule recurrence notes through the alias map while preserving existing problem numbers; show merged names under their canonical problem in `sisi retro`. - Add tests with 3 real duplicate pairs from the blind set (watched failing on main first), update `test_the_product_stays_small` (2481 -> 2530, +49), and add CLAUDE.md guards to all touched test classes. Co-Authored-By: Claude Opus 5.5 --- sisi/retro.py | 41 +++++-- sisi/rules.py | 48 ++++++-- tests/test_core.py | 2 +- tests/test_organize_evidence.py | 9 +- tests/test_problems.py | 195 +++++++++++++++++++++++++++++++- 5 files changed, 270 insertions(+), 25 deletions(-) diff --git a/sisi/retro.py b/sisi/retro.py index 2b5f79e..dc35457 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -78,23 +78,47 @@ def trend(): return ["measured (pieces of work with numbers):"] + out if len(units) >= 2 else [] +def _alias_root(amap, n, seen=()): + while n in amap and n not in seen: + seen, n = (*seen, n), amap[n] + return n + + +def _aliases(): + why, raw = store.regular(store.data(rules.PROBLEMS), True) + try: + doc = json.loads(raw.decode("utf-8", "replace")) if not why and raw else {} + except ValueError: + doc = {} + amap = {int(k): v for k, v in doc.items() if str(k).isascii() and str(k).isdigit() and type(v) is int and int(k) >= 1 and v >= 1 and int(k) != v} if isinstance(doc, dict) else {} + return {k: r for k in amap if (r := _alias_root(amap, k)) != k} + + def _problems(recs=None): - """Known problems derived from retro.jsonl in order of first appearance (1-based number).""" + """Known problems derived from retro.jsonl in order of first appearance (1-based number), folding merged aliases.""" by_key, out = {}, [] for idx, r in enumerate(store.records("retro.jsonl", 64000000) if recs is None else recs): if not (isinstance(r.get("problem"), str) and (name := clean(r["problem"]))): continue date, key = str(r.get("ts") or "")[:10] or "?", name.lower() - p = by_key.get(key) or by_key.setdefault(key, {"num": len(out) + 1, "name": name, "opened": date, "attempts": []}) + p = by_key.get(key) or by_key.setdefault(key, {"num": len(out) + 1, "name": name, "opened": date, "attempts": [], "merged": []}) p not in out and out.append(p) - p["attempts"].append({"date": date, "cause": str(r.get("cause") or ""), "improve": str(r.get("improve") or "")}) + p["attempts"].append({"idx": idx, "date": date, "cause": str(r.get("cause") or ""), "improve": str(r.get("improve") or "")}) p["last"], p["last_idx"] = date, idx + for m, n in (_aliases() if recs is None else {}).items(): + if m <= len(out) and n <= len(out): + src, dst = out[m - 1], out[n - 1] + src["into"] = n + dst["merged"].append((m, src["name"])) + dst["attempts"] = sorted(dst["attempts"] + src["attempts"], key=lambda a: a["idx"]) + dst["last"], dst["last_idx"] = dst["attempts"][-1]["date"], dst["attempts"][-1]["idx"] return out def _problem_lines(probs): - recent = sorted(probs, key=lambda p: (-p["last_idx"], -p["num"]))[:15] - return [" #%d: %s (%d attempt%s, last %s)" % (p["num"], p["name"], n := len(p["attempts"]), "" if n == 1 else "s", p["last"]) for p in recent] + recent = sorted((p for p in probs if not p.get("into")), key=lambda p: (-p["last_idx"], -p["num"]))[:15] + return [l for p in recent for n in [len(p["attempts"])] + for l in [" #%d: %s (%d attempt%s, last %s)" % (p["num"], p["name"], n, "" if n == 1 else "s", p["last"]), *[" merged: %s (#%d)" % (name, m) for m, name in p["merged"]]]] def _resolve_problem(problem, probs): @@ -104,10 +128,11 @@ def _resolve_problem(problem, probs): return None, "sisi retro: name the problem in plain words (no secrets, tokens, or long hex/digit strings)." if len(norm) > 400: return None, "sisi retro: problem name is at most 400 characters." + canon = lambda p: probs[p["into"] - 1] if p and p.get("into") else p if re.fullmatch(r"[+-]?\d+", norm): n = int(norm) - return (probs[n - 1], "") if 1 <= n <= len(probs) else (None, "sisi retro: problem #%s does not exist." % norm) - return next((p for p in probs if p["name"].lower() == norm.lower()), {"num": len(probs) + 1, "name": norm, "attempts": []}), "" + return (canon(probs[n - 1]), "") if 1 <= n <= len(probs) else (None, "sisi retro: problem #%s does not exist." % norm) + return canon(next((p for p in probs if p["name"].lower() == norm.lower()), None)) or {"num": len(probs) + 1, "name": norm, "attempts": []}, "" def report(sid, cwd): @@ -261,7 +286,7 @@ def run(args, cwd=None): elif kind != "later": record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt) if kind == "gap": - found = next((p for p in _problems() if p["name"].lower() == opt["problem"].lower()), None) + found = next((p for p in _problems() if not p.get("into") and p["name"].lower() == opt["problem"].lower()), None) prior = found["attempts"][:-1] if found else prob["attempts"] prob, misses = found or prob, len(prior) if misses: diff --git a/sisi/rules.py b/sisi/rules.py index f7e5fde..1b33a99 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -16,7 +16,7 @@ _TAGS = " [owner] lines are the person's words; [agent ...] lines are an agent's HEAD_USER = "## Learned here\n\nAdded by retros and by the person. These add to the rules above and never relax them." + _TAGS + "\n" HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never relax them)." + _TAGS SMELL = re.compile(r"(?i)\bone (?:build|test|run|worker|job)\b.{0,60}\bat a time|\bflock\b|\b(?:shared?|one)\b.{0,30}\bbuild (?:folder|dir)") -DROPS = "rules/drops.jsonl" +DROPS, PROBLEMS = "rules/drops.jsonl", "rules/problems.json" _DROP = re.compile(r"^(?:[-*]|\d+\.)\s+(.+?)\s*\|\s*#(\d+|-)\s*\|\s*(\S.*)$") _NOTE = re.compile(r"(?:\s+\(p\d+: (?:came back \d+x|not seen) since(?:; p\d+: (?:came back \d+x|not seen) since)*\))+$") _RETRO_TAG, _DATE = re.compile(r"(?:\s*\[retro\b[^\]]*\])+$"), re.compile(r"\d{4}-\d{2}-\d{2}") @@ -59,6 +59,8 @@ Answer with exactly this shape and nothing else: - ... (only lines moved to the product queue) ## drops - | # | (optional; only if any non-owner rules were dropped) +## same problems +N = M (optional; merge duplicate problem M into older N) ## flags - ... (only if there are any) @@ -361,23 +363,28 @@ def due(cwd, claim=False): def drops_for(num=None): - return [d for d in store.records(DROPS) if num is None or d.get("problem") == num] + from . import retro + amap = retro._aliases() if num is not None else {} + return [d for d in store.records(DROPS) if num is None or amap.get(d.get("problem"), d.get("problem")) == num] def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180): - if not probs: + canon = [p for p in probs if not p.get("into")] + if not canon: return "" - cut = lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..." + amap, cut = {p["num"]: p["into"] for p in probs if p.get("into")}, lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..." + all_p = "\n\n=== Every known problem (list duplicates under ## same problems as N = M, older first) ===\n" + "\n".join( + "#%d: %s | cause: %s" % (p["num"], cut(p["name"]), cut(next((a["cause"] for a in p["attempts"] if a["cause"]), "") or "(none)")) for p in canon) head = ("\n\n=== Known problems and prior rule attempts (most recent first) ===\n" "How to use this evidence:\n" "- Problem has 0 misses: it has not come back yet, keep it. Has misses: the sentence did not hold, keep the latest attempt and note it in `## flags` (do not just reword).\n" "- When merging, keep the cause; never drop a rule as redundant while its problem keeps coming back. [owner ...] rules stay verbatim.\n") out, used = [head], len(head) - for p in sorted(probs, key=lambda x: (-x["last_idx"], -x["num"]))[:cap_p]: + for p in sorted(canon, key=lambda x: (-x["last_idx"], -x["num"]))[:cap_p]: n = len(p["attempts"]) ls = (["#%d: %s (opened %s, %d attempt%s, %d miss%s, last %s)" % (p["num"], cut(p["name"]), p["opened"], n, "" if n == 1 else "s", n - 1, "" if n == 2 else "es", p["last"])] + [" attempt [%s] cause: %s | rule: %s" % (a["date"], cut(a["cause"]), cut(a["improve"])) for a in p["attempts"]] - + [" earlier dropped: [%s] %s -- reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in reversed(drops) if d.get("problem") == p["num"]]) + + [" earlier dropped: [%s] %s -- reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in reversed(drops) if amap.get(d.get("problem"), d.get("problem")) == p["num"]]) blk = "\n".join(ls) + "\n" if used + len(blk) > cap_c: for l in (ls if len(out) == 1 else ()): @@ -385,7 +392,7 @@ def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180): out.append(l + "\n"); used += len(l) + 1 break out.append(blk); used += len(blk) - return "".join(out).rstrip("\n") + return all_p + "".join(out).rstrip("\n") def _rule_probs(line): @@ -412,7 +419,9 @@ def _annotate(ls, probs): continue notes = [] for n, d in ps: - c = sum(bool(_DATE.fullmatch(a["date"])) and a["date"] > d for a in (probs[n - 1]["attempts"] if n <= len(probs) else ())) + p = probs[n - 1] if 1 <= n <= len(probs) else None + p = probs[p["into"] - 1] if p and p.get("into") else p + c = sum(bool(_DATE.fullmatch(a["date"])) and a["date"] > d for a in (p["attempts"] if p else ())) notes.append("p%d: came back %dx since" % (n, c) if c else "p%d: not seen since" % n) out.append("%s (%s)" % (l, "; ".join(notes))) return out @@ -438,8 +447,8 @@ def organize_brief(cwd): def organize_record(answer_file, cwd): """Replace both lists with the worker's answer. Returns why not, or None when it is done.""" cfg = store.config() - secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project|core)[ \t]*|## [^\n]*)$", store.read(answer_file)) - got, flags, drops = {}, "", {} + secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops|same problems)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project|core)[ \t]*|## [^\n]*)$", store.read(answer_file)) + got, flags, drops, same_lines = {}, "", {}, [] for h, chunk in ((secs[i], secs[i + 1]) for i in range(1, len(secs) - 1, 2)): if re.fullmatch(r"## (user|project|core)[ \t]*", h): got[h[3:].strip()] = [l if _owner(l) else _NOTE.sub("", l) for l in (x.rstrip() for x in chunk.splitlines() if x.startswith("- "))] @@ -449,6 +458,8 @@ def organize_record(answer_file, cwd): for l in chunk.splitlines(): if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]): drops.setdefault(rk, (m[2], why)) + elif re.match(r"(?i)#{2,3}[ \t]*same problems\b", h): + same_lines += [x.strip() for x in chunk.splitlines() if x.strip() and x.strip().lower() not in ("none", "(none)") and not x.strip().startswith("```")] core = got.pop(CORE, []) if set(got) != {USER, PROJECT}: return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines" @@ -476,10 +487,19 @@ def organize_record(answer_file, cwd): kept = every[:] dropped = [r for r in had[USER] + had[PROJECT] if not _owner(r) and not (r in kept and kept.remove(r) is None)] from . import retro - nprobs = len(retro._problems()) if dropped else 0 + nprobs = len(retro._problems()) if dropped or same_lines else 0 pnum = lambda s: n if s.isascii() and s.isdigit() and len(s) <= 6 and 1 <= (n := int(s)) <= nprobs else None recs = [(store.clean(r)[:300], pnum(h[0]), h[1]) if (h := drops.get(_DKEY(r))) else (store.clean(r)[:300], None, "none given") for r in dropped] no_why = sum(_DKEY(r) not in drops for r in dropped) + old_amap = retro._aliases() if same_lines else {} + amap, bad_same = dict(old_amap), [] + for raw_l in same_lines: + m = re.fullmatch(r"(?:[-*]\s+)?#?(\d{1,6})\s*=\s*#?(\d{1,6})(?:\s+(?:#|\(|//|-).*|\s*\|.*)?", raw_l) + n, k = (int(m[1]), int(m[2])) if m else (0, 0) + rn = retro._alias_root(amap, n) if m else 0 + why_bad = ("expected N = M" if not m else "unknown problem number" if not (1 <= n <= nprobs and 1 <= k <= nprobs) + else "cycle" if rn == k else "already merged" if k in amap and retro._alias_root(amap, k) != rn else "") + bad_same.append((raw_l, why_bad)) if why_bad else amap.__setitem__(k, rn) if not any(got.values()) and not core and any(had.values()): return "the answer holds no rules at all" try: @@ -496,6 +516,9 @@ def organize_record(answer_file, cwd): if recs: old = store.read(dp) if os.path.exists(dp) else None change[dp] = (old, _append(old, [json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True) for r, pn, why in recs])) + if amap != old_amap: + ap = store.data(PROBLEMS) + change[ap] = (_text(ap), json.dumps({str(k): v for k, v in sorted(amap.items())}, sort_keys=True)) [_check_writable(p) for p in change if change[p][1] is not None and (p != dp or os.path.islink(dp))] # the drops log may pass 64,000 bytes now, home = {USER: got[USER], PROJECT: got[PROJECT], CORE: core}, {USER: up, PROJECT: pp, CORE: cp} flat = [l for sec in now.values() for l in sec] @@ -516,6 +539,7 @@ def organize_record(answer_file, cwd): for scope in (USER, PROJECT): print("%s rules: %d lines (were %d)" % (scope, len(got[scope]), len(had[scope]))) no_why and print("%d dropped rule%s had no reason recorded" % (no_why, "" if no_why == 1 else "s")) + [print("skipped same problems line '%s' (%s)" % b) for b in bad_same] [print("the same rule was in both user and project and is now one copy in %s: %s; add it back by hand if you want it at both levels (run `sisi rules` to see the lists)" % (next(lv for lv in now if l in now[lv]), l)) for l in merged] [print("the same rule now sits at two levels, so `sisi rules move` cannot pick one copy: %s; remove the copy you do not want by hand (run `sisi rules` to see the lists)" % l) for l in over if l not in merged] flags.strip() and print("Flagged for you (not changed):" + flags.rstrip()) @@ -525,7 +549,7 @@ def organize_record(answer_file, cwd): def revert(): """Undo the last learn, retro or organize (a project's list only while it holds what that change left); not a move between levels.""" - files = ("rules/user.md", "rules/core.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS) + files = ("rules/user.md", "rules/core.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS, PROBLEMS) advice = " (edit by hand or restore with git)" if os.path.isdir(os.path.join(store.DATA, ".git")) and store.git(["status", "--porcelain", "--", *files], store.DATA)[1].strip(): return "the store has uncommitted rule changes, so the previous change cannot be undone" + advice diff --git a/tests/test_core.py b/tests/test_core.py index 7e226f1..61e37df 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -4625,7 +4625,7 @@ cli.main(["tick"]) def test_the_product_stays_small(self): code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py"))) - self.assertLessEqual(code, 2481, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 2530, "sisi is two loops. If it needs more than this, find the simpler shape.") rulebook = self.read(REPO, "canon", "core.md") self.assertLess(len(rulebook.splitlines()), 139) self.assertLessEqual(len(rulebook), 10711) diff --git a/tests/test_organize_evidence.py b/tests/test_organize_evidence.py index 79600d4..21f1b6a 100644 --- a/tests/test_organize_evidence.py +++ b/tests/test_organize_evidence.py @@ -10,6 +10,7 @@ import tempfile import unittest REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +REAL_HOME = os.path.expanduser("~") GAP = ("--gap", "the export dropped rows with empty names until the person noticed", "--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project") @@ -27,6 +28,9 @@ class OrganizeEvidence(unittest.TestCase): def setUp(self): before = tree() self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) + book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md") + mine = self.read(book) if os.path.exists(book) else None + self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file")) self.tmp = tempfile.mkdtemp(prefix="sisi-orgev-") self.addCleanup(shutil.rmtree, self.tmp, True) self.data = os.path.join(self.tmp, "data") @@ -115,8 +119,9 @@ class OrganizeEvidence(unittest.TestCase): self.assertIn("copied as it is", brief) shape = brief.split("Answer with exactly this shape")[1].split("===")[0] self.assertLess(shape.index("## project"), shape.index("## drops")) - self.assertLess(shape.index("## drops"), shape.index("## flags")) - self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 40) + self.assertLess(shape.index("## drops"), shape.index("## same problems")) + self.assertLess(shape.index("## same problems"), shape.index("## flags")) + self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 42) proj_line = self.read(self.proj, ".sisi", "rules.md").splitlines()[0] ans = self.write(os.path.join(self.tmp, "ans.md"), "## user\n## project\n- Kept project rule [retro 2026-11-26]\n" diff --git a/tests/test_problems.py b/tests/test_problems.py index 7380a8c..f31ae5e 100644 --- a/tests/test_problems.py +++ b/tests/test_problems.py @@ -13,8 +13,9 @@ import unittest from unittest import mock REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +REAL_HOME = os.path.expanduser("~") sys.path.insert(0, REPO) -from sisi import retro, store +from sisi import retro, rules, store GAP = ("--gap", "the export dropped rows with empty names until the person noticed", "--cause", "no check compared the row counts before and after", "--term", "evidence", "--level", "project") @@ -32,11 +33,15 @@ class Problems(unittest.TestCase): def setUp(self): before = tree() self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) + book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md") + mine = self.read(book) if os.path.exists(book) else None + self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file")) self.tmp = tempfile.mkdtemp(prefix="sisi-prob-") self.addCleanup(shutil.rmtree, self.tmp, True) self.data = os.path.join(self.tmp, "data") self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, - SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib")) + SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"), + CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude")) for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"): self.env.pop(name, None) self.proj = os.path.join(self.tmp, "alpha") @@ -44,6 +49,17 @@ class Problems(unittest.TestCase): for args in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "start"]): subprocess.run(["git"] + args, cwd=self.proj, check=True, stdin=subprocess.DEVNULL, capture_output=True) + def in_process(self, fn, *args): + out, here = io.StringIO(), os.getcwd() + os.chdir(self.tmp) + try: + with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \ + mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "HOME", self.tmp), \ + mock.patch.dict(os.environ, {k: self.env[k] for k in ("HOME", "CLAUDE_CONFIG_DIR")}), contextlib.redirect_stdout(out): + return fn(*args), out.getvalue() + finally: + os.chdir(here) + def sisi(self, *args, cwd=None, sid=None, stdin=""): env = dict(self.env, SISI_SESSION_ID=sid) if sid else self.env out_f = os.path.join(self.tmp, "stdout.tmp") @@ -55,6 +71,10 @@ class Problems(unittest.TestCase): fe.seek(0) return r.returncode, fo.read(), fe.read() + def read(self, *parts): + with open(os.path.join(*parts), encoding="utf-8") as f: + return f.read() + def records(self): p = os.path.join(self.data, "retro.jsonl") if not os.path.exists(p): @@ -354,6 +374,177 @@ class Problems(unittest.TestCase): self.assertTrue(any("alpha issue" in l for l in faults_lines), faults_lines) self.assertTrue(any("bravo issue" in l for l in faults_lines), faults_lines) + def test_organize_brief_lists_every_problem_and_same_problems_section(self): + self.assertEqual(self.sisi("retro", "--level", "project", + "--gap", "stated a remembered tool behaviour without running the command", + "--cause", "stated a remembered tool behaviour without checking", + "--improve", "Run the command before stating tool behaviour", + "--term", "evidence", + "--problem", "claimed tool behaviour or timing from memory in a question or fault brief")[0], 0) + for i in range(2, 18): + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Rule number %02d for problem" % i, + "--problem", "distinct item %02d" % i)[0], 0) + self.assertEqual(self.sisi("retro", "--level", "project", + "--gap", "inferred driver behaviour from defaults without testing", + "--cause", "Inferred driver behaviour from lpoptions defaults instead of running the filter chain", + "--improve", "Push a known test page before claiming driver behaviour", + "--term", "evidence", + "--problem", "Unmeasured claims about tool behaviour")[0], 0) + brief, _ = self.in_process(rules.organize_brief, self.proj) + self.assertIn("## same problems", brief) + self.assertIn("N = M", brief) + # All 18 problems (beyond the 15-problem cap in _evidence) appear with number, name, and cause + self.assertIn("#1:", brief) + self.assertIn("claimed tool behaviour or timing from memory in a question or fault brief", brief) + self.assertIn("stated a remembered tool behaviour without checking", brief) + self.assertIn("#18:", brief) + self.assertIn("Unmeasured claims about tool behaviour", brief) + self.assertIn("Inferred driver behaviour from lpoptions defaults instead of running the filter chain", brief) + self.assertIn("#2:", brief) + self.assertIn("distinct item 02", brief) + + def test_merge_problems_counts_misses_opens_fault_and_shows_in_report(self): + p1_a = "claimed tool behaviour or timing from memory in a question or fault brief" + p1_b = "Unmeasured claims about tool behaviour" + p2_a = "push not gated on the test run's exit code" + p2_b = "a gating command's exit status was hidden by a display filter" + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Run the command before claiming behaviour", "--problem", p1_a)[0], 0) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Gate every push on the test exit code", "--problem", p2_a)[0], 0) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Test the filter chain on a known page first", "--problem", p1_b)[0], 0) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Never pipe a gating command into a filter", "--problem", p2_b)[0], 0) + + self.in_process(rules.organize_brief, self.proj) + proj_rules = [l for l in self.read(self.proj, ".sisi", "rules.md").splitlines() if l.startswith("- ")] + ans = os.path.join(self.tmp, "merge.md") + with open(ans, "w", encoding="utf-8") as f: + f.write("## user\n## project\n" + "\n".join(proj_rules) + "\n## same problems\n1 = 3\n2 = 4\n") + why, out = self.in_process(rules.organize_record, ans, self.proj) + self.assertIsNone(why, out) + + rep = self.sisi("retro")[1] + self.assertIn("#1: " + p1_a + " (2 attempts", rep) + self.assertIn("#2: " + p2_a + " (2 attempts", rep) + self.assertNotIn("#3: " + p1_b, rep) + self.assertNotIn("#4: " + p2_b, rep) + self.assertIn(p1_b, rep) + self.assertIn(p2_b, rep) + self.assertLess(rep.index("#1: " + p1_a), rep.index(p1_b)) + self.assertLess(rep.index("#2: " + p2_a), rep.index(p2_b)) + + # Existing numbering stays valid: a new problem gets #5, not #3 + rc, out, _ = self.sisi("retro", *GAP, "--improve", "Separate problem rule five", "--problem", "separate fifth issue") + self.assertEqual(rc, 0, out) + self.assertIn("opened problem 5 'separate fifth issue'", out) + + # Citing merged number 3 counts as 2nd miss of #1 and opens its fault + rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule via merged number three", "--problem", "3") + self.assertEqual(rc, 0, out) + self.assertIn("problem 1 '%s' has come back: 2 misses" % p1_a, out) + self.assertIn("opened fault #1", out) + + # Citing merged name p2_b counts as 2nd miss of #2 and opens its fault + rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule via merged name p2_b", "--problem", p2_b) + self.assertEqual(rc, 0, out) + self.assertIn("problem 2 '%s' has come back: 2 misses" % p2_a, out) + self.assertIn("opened fault #2", out) + + # Citing merged number 4 a second time (event happens twice) counts 3 misses on #2 without opening a duplicate fault + rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fifth rule via merged number four", "--problem", "4") + self.assertEqual(rc, 0, out) + self.assertIn("problem 2 '%s' has come back: 3 misses" % p2_a, out) + self.assertEqual(len(self.sisi("fault")[1].strip().splitlines()), 2) + + # Citing #5 still resolves to #5 + rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule for fifth issue", "--problem", "5") + self.assertEqual(rc, 0, out) + self.assertIn("problem 5 'separate fifth issue' has come back: 1 miss", out) + + def test_per_rule_note_counts_citations_through_alias(self): + p3_a = "a long real-data run started without its read-only admission check" + p3_b = "untested script left for unattended run" + os.makedirs(self.data, exist_ok=True) + retro_rows = [ + {"ts": "2026-11-20T10:00:00", "problem": p3_a, "cause": "no admission check", "improve": "Run read-only admission check first"}, + {"ts": "2026-11-21T10:00:00", "problem": p3_b, "cause": "never dry-ran script", "improve": "Dry-run one item end to end first"}, + ] + with open(os.path.join(self.data, "retro.jsonl"), "w", encoding="utf-8") as f: + f.write("".join(json.dumps(r) + "\n" for r in retro_rows)) + os.makedirs(os.path.join(self.proj, ".sisi"), exist_ok=True) + with open(os.path.join(self.proj, ".sisi", "rules.md"), "w", encoding="utf-8") as f: + f.write("\n".join([ + "- Run read-only admission check first [retro 2026-11-20 p1]", + "- Dry-run one item end to end first [retro 2026-11-21 p2]", + ]) + "\n") + ans = os.path.join(self.tmp, "merge3.md") + with open(ans, "w", encoding="utf-8") as f: + f.write("## user\n## project\n- Run read-only admission check first [retro 2026-11-20 p1]\n- Dry-run one item end to end first [retro 2026-11-21 p2]\n## same problems\n1 = 2\n") + self.in_process(rules.organize_brief, self.proj) + why, out = self.in_process(rules.organize_record, ans, self.proj) + self.assertIsNone(why, out) + + rc, retro_out, _ = self.sisi("retro", *GAP, "--improve", "Verify one sample output before batching", "--problem", "2") + self.assertEqual(rc, 0, retro_out) + self.assertIn("problem 1 '%s' has come back: 2 misses" % p3_a, retro_out) + + _, listing_inproc = self.in_process(rules.show, self.proj) + listing_cli = self.sisi("rules")[1] + brief = self.sisi("rules", "organize")[1] + for out_txt in (listing_inproc, listing_cli, brief): + self.assertIn("[retro 2026-11-20 p1] (p1: came back 2x since)", out_txt) + self.assertIn("[retro 2026-11-21 p2] (p2: came back 1x since)", out_txt) + self.in_process(rules.build_rulebook) + book = self.read(self.data, "generated", "core.md") + self.assertNotIn("came back", book) + + def test_bad_same_problems_skipped_and_revert_undoes_aliases(self): + p_a = "a long real-data run started without its read-only admission check" + p_b = "untested script left for unattended run" + self.assertEqual(self.sisi("retro", *GAP, "--improve", "First rule before bad merge", "--problem", p_a)[0], 0) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second rule before bad merge", "--problem", p_b)[0], 0) + rules_path = os.path.join(self.proj, ".sisi", "rules.md") + before = self.read(rules_path) + self.in_process(rules.organize_brief, self.proj) + ans = os.path.join(self.tmp, "bad_merge.md") + with open(ans, "w", encoding="utf-8") as f: + f.write("\n".join([ + "## user", + "- Kept organized user rule [retro 2026-11-26]", + "## project", + "- Combined organized project rule [retro 2026-11-26 p1]", + "## same problems", + "1 = 99", + "0 = 1", + "1 = 1", + "1 = 2", + "2 = 1", + "not a valid pair", + ]) + "\n") + why, out = self.in_process(rules.organize_record, ans, self.proj) + self.assertIsNone(why, out) + self.assertIn("99", out) + self.assertIn("0 = 1", out) + self.assertIn("1 = 1", out) + self.assertIn("2 = 1", out) + self.assertIn("not a valid pair", out) + # Rest of organize recorded + self.assertIn("Combined organized project rule", self.read(rules_path)) + self.assertIn("Kept organized user rule", self.read(self.data, "rules", "user.md")) + # Valid 1 = 2 took effect + rep = self.sisi("retro")[1] + self.assertIn("#1: " + p_a + " (2 attempts", rep) + self.assertNotIn("#2: " + p_b, rep) + + # Revert undoes the organize AND removes the alias + rc, rev_out, _ = self.sisi("rules", "revert") + self.assertEqual(rc, 0, rev_out) + self.assertEqual(self.read(rules_path), before) + rep_after = self.sisi("retro")[1] + self.assertIn("#1: " + p_a + " (1 attempt", rep_after) + self.assertIn("#2: " + p_b + " (1 attempt", rep_after) + rc, out, _ = self.sisi("retro", *GAP, "--improve", "Post-revert citation of two", "--problem", "2") + self.assertEqual(rc, 0, out) + self.assertIn("problem 2 '%s' has come back: 1 miss" % p_b, out) + if __name__ == "__main__": unittest.main()