Files
sisi/tests/test_problems.py
T
swaitsandClaude Opus 5.5 25b5e90c6b
ci / test (push) Waiting to run
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 <noreply@anthropic.com>
2026-12-01 17:02:03 -07:00

551 lines
32 KiB
Python

"""Tests for retro problem tracking and repeat-miss fault escalation."""
import contextlib
import glob
import hashlib
import io
import json
import os
import shutil
import subprocess
import sys
import tempfile
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, 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")
def tree():
out = hashlib.sha1()
for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))):
if os.path.isfile(p):
with open(p, "rb") as f:
out.update(p.encode() + f.read())
return out.hexdigest()
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"),
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")
os.makedirs(self.proj)
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")
err_f = os.path.join(self.tmp, "stderr.tmp")
with open(out_f, "w+", encoding="utf-8") as fo, open(err_f, "w+", encoding="utf-8") as fe:
r = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi")] + list(args),
cwd=cwd or self.proj, env=env, input=stdin, stdout=fo, stderr=fe, text=True)
fo.seek(0)
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):
return []
with open(p, encoding="utf-8") as f:
return [json.loads(l) for l in f.read().splitlines() if l.strip()]
def test_open_cite_missing_unknown_old_records_and_stable_numbers(self):
# Seed old records without 'problem' field and ensure they stay valid and belong to no problem
os.makedirs(self.data, exist_ok=True)
log = os.path.join(self.data, "retro.jsonl")
with open(log, "w", encoding="utf-8") as f:
f.write(json.dumps({"ts": "2026-11-20T10:00:00", "gap": "old gap without problem",
"cause": "old cause", "improve": "Old rule without problem", "term": "evidence"}) + "\n")
f.write(json.dumps({"ts": "2026-11-21T10:00:00", "no-gap": "all good",
"better": "do something better next time", "term": "time"}) + "\n")
# Missing --problem on --gap is refused with nothing written
rc, out, err = self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export")
self.assertNotEqual(rc, 0, out)
self.assertEqual(len(self.records()), 2)
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi", "rules.md")))
self.assertIn("--problem", out)
# Open problem #1 by words
rc, out, err = self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export",
"--problem", "export drops empty names")
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.records()[-1]["problem"], "export drops empty names")
self.assertNotIn("has come back", out)
# Open problem #2 by words
rc, out, err = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts in output",
"--cause", "clean step was skipped on incremental runs",
"--improve", "Always clean output directory before packaging release",
"--term", "value", "--problem", "stale build artifacts")
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.records()[-1]["problem"], "stale build artifacts")
# Unknown problem numbers refused with nothing written, listing known problems and re-run syntax
for bad_num in ("0", "-1", "3", "99"):
before_count = len(self.records())
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Should not be recorded at all", "--problem", bad_num)
self.assertNotEqual(rc, 0, bad_num)
self.assertEqual(len(self.records()), before_count, bad_num)
self.assertIn("export drops empty names", out)
self.assertIn("stale build artifacts", out)
self.assertIn("--problem", out)
# --no-gap and --later unchanged and refuse --problem
self.assertEqual(self.sisi("retro", "--no-gap", "the export kept every row cleanly",
"--term", "time", "--better", "start the first build sooner than before")[0], 0)
self.assertNotIn("problem", self.records()[-1])
self.assertNotEqual(self.sisi("retro", "--no-gap", "the export kept every row cleanly",
"--term", "time", "--better", "start the first build sooner than before",
"--problem", "1")[0], 0)
self.assertNotEqual(self.sisi("retro", "--later", "waiting for the owner to reply", "--problem", "1")[0], 0)
# Cite problem #1 by number: numbers remain stable (#1 is still export drops empty names)
rc, out, err = self.sisi("retro", *GAP, "--improve", "Add an automated row-count assertion to export tests",
"--problem", "1")
self.assertEqual((rc, err), (0, ""), out)
self.assertEqual(self.records()[-1]["problem"], "export drops empty names")
self.assertIn("problem 1 'export drops empty names' has come back: 1 miss", out)
self.assertNotIn("1 misses", out)
self.assertIn("Compare row counts before and after every export", out)
# Add more non-problem records and cite #2; numbers stay stable
self.assertEqual(self.sisi("retro", "--no-gap", "the build passed cleanly on first run",
"--term", "time", "--better", "parallelize the test suite run here")[0], 0)
rc, out, _ = self.sisi("retro", "--level", "project", "--gap", "build script left stale artifacts again",
"--cause", "incremental cache kept old binary",
"--improve", "Hash inputs before reusing build artifacts",
"--term", "value", "--problem", "2")
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 'stale build artifacts' has come back: 1 miss", out)
self.assertNotIn("1 misses", out)
self.assertIn("Always clean output directory before packaging release", out)
def test_misses_and_fault_escalation_lifecycle(self):
# 1st attempt: 0 misses, no fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "First rule attempt for empty names",
"--problem", "empty name export bug")
self.assertEqual(rc, 0, out)
self.assertEqual(self.sisi("fault")[1].strip(), "no open faults.")
# 2nd attempt: 1 miss, no fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule attempt for empty names",
"--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'empty name export bug' has come back: 1 miss", out)
self.assertNotIn("1 misses", out)
self.assertIn("First rule attempt for empty names", out)
self.assertEqual(self.sisi("fault")[1].strip(), "no open faults.")
# 3rd attempt (2nd miss): opens a fault, records retro and rule
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Third rule attempt for empty names",
"--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'empty name export bug' has come back: 2 misses", out)
self.assertIn("First rule attempt for empty names", out)
self.assertIn("Second rule attempt for empty names", out)
self.assertEqual(len(self.records()), 3)
with open(os.path.join(self.proj, ".sisi", "rules.md"), encoding="utf-8") as f:
self.assertIn("Third rule attempt for empty names", f.read())
faults_out = self.sisi("fault")[1]
self.assertEqual(len(faults_out.strip().splitlines()), 1, faults_out)
self.assertIn("empty name export bug", faults_out)
self.assertIn("2 times", faults_out)
self.assertIn("hook or an automatic check", faults_out)
# 4th attempt while fault is still open (or started): opens NO duplicate fault
self.assertEqual(self.sisi("fault", "--started", "1", "building automatic export test hook")[0], 0)
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fourth rule attempt while fault open",
"--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'empty name export bug' has come back: 3 misses", out)
self.assertEqual(len(self.sisi("fault")[1].strip().splitlines()), 1)
# Fix the fault, then another attempt opens a new fault
self.assertEqual(self.sisi("fault", "--fixed", "1", "added export hook to CI check")[0], 0)
self.assertEqual(self.sisi("fault")[1].strip(), "no open faults.")
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Fifth rule attempt after fix",
"--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'empty name export bug' has come back: 4 misses", out)
faults_after = self.sisi("fault")[1]
self.assertEqual(len(faults_after.strip().splitlines()), 1, faults_after)
self.assertIn("4 times", faults_after)
def test_no_arg_retro_lists_problems_most_recent_first_capped_at_15(self):
for i in range(1, 18):
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Rule number %02d for problem" % i,
"--problem", "problem item %02d" % i)
self.assertEqual(rc, 0, out)
# Re-cite problem 1 so it becomes the most recently cited
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule for problem 01", "--problem", "1")
self.assertEqual(rc, 0, out)
rep = self.sisi("retro")[1]
lines = [l for l in rep.splitlines() if "problem item " in l]
self.assertEqual(len(lines), 15, "\n".join(lines))
# Most recently cited (#1 with 2 attempts) is first, followed by #17 .. #4; #2 and #3 drop off the 15-line cap
self.assertIn("#1:", lines[0])
self.assertIn("problem item 01", lines[0])
self.assertIn("2 attempts", lines[0])
self.assertIn("#17:", lines[1])
self.assertIn("problem item 17", lines[1])
self.assertIn("1 attempt", lines[1])
self.assertNotIn("problem item 02", rep)
self.assertNotIn("problem item 03", rep)
def test_race_derives_number_and_misses_after_append(self):
real_append = store.append
log_path = os.path.join(self.data, "retro.jsonl")
def racing_append(extra_records):
injected = False
def wrapper(path, line, once=False):
nonlocal injected
if not injected and path == log_path:
injected = True
for rec in extra_records:
real_append(path, json.dumps(rec))
return real_append(path, line, once=once)
return wrapper
base_args = list(GAP) + ["--improve", "Always verify export row count in CI checks", "--problem"]
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")):
# Between pre-check (empty log) and append, another session opens a different problem and the same problem
extra = [
{"ts": "2026-11-26T10:00:00", "gap": "other gap", "cause": "other cause",
"improve": "Other rule first", "term": "time", "problem": "other race problem"},
{"ts": "2026-11-26T10:00:01", "gap": "same gap", "cause": "same cause",
"improve": "Earlier racing rule for shared problem", "term": "evidence", "problem": "shared race problem"},
]
out1 = io.StringIO()
with mock.patch.object(store, "append", side_effect=racing_append(extra)), contextlib.redirect_stdout(out1):
rc1 = retro.run(base_args + ["shared race problem"], cwd=self.proj)
self.assertEqual(rc1, 0, out1.getvalue())
self.assertIn("problem 2 'shared race problem' has come back: 1 miss", out1.getvalue())
self.assertNotIn("opened problem 1", out1.getvalue())
rep1 = self.sisi("retro")[1]
self.assertIn("#1: other race problem (1 attempt", rep1)
self.assertIn("#2: shared race problem (2 attempts", rep1)
# Second race: pre-check sees #2 with 2 attempts (1 miss); racing session adds 3rd attempt before append
extra2 = [
{"ts": "2026-11-26T10:05:00", "gap": "third gap", "cause": "third cause",
"improve": "Third racing rule for shared problem", "term": "evidence", "problem": "shared race problem"},
]
out2 = io.StringIO()
with mock.patch.object(store, "append", side_effect=racing_append(extra2)), contextlib.redirect_stdout(out2):
rc2 = retro.run(base_args + ["2"], cwd=self.proj)
self.assertEqual(rc2, 0, out2.getvalue())
self.assertIn("problem 2 'shared race problem' has come back: 3 misses", out2.getvalue())
self.assertIn("opened fault #1", out2.getvalue())
rep2 = self.sisi("retro")[1]
self.assertIn("#2: shared race problem (4 attempts", rep2)
def test_large_log_past_2mb_keeps_problem_numbers_and_attempts(self):
os.makedirs(self.data, exist_ok=True)
log = os.path.join(self.data, "retro.jsonl")
first = json.dumps({"ts": "2026-01-01T10:00:00", "gap": "early gap", "cause": "early cause",
"improve": "Early rule for problem one", "term": "evidence", "problem": "early problem"}) + "\n"
pad_line = json.dumps({"ts": "2026-06-01T10:00:00", "no-gap": "all checks passed cleanly today " + ("x" * 120),
"better": "start the build earlier next time around", "term": "time"}) + "\n"
last = json.dumps({"ts": "2026-11-26T10:00:00", "gap": "late gap", "cause": "late cause",
"improve": "Late rule for problem two", "term": "value", "problem": "late problem"}) + "\n"
repeat_count = (2_100_000 // len(pad_line)) + 1
with open(log, "w", encoding="utf-8") as f:
f.write(first + (pad_line * repeat_count) + last)
self.assertGreater(os.path.getsize(log), 2_000_000)
rep = self.sisi("retro")[1]
self.assertIn("#1: early problem (1 attempt", rep)
self.assertIn("#2: late problem (1 attempt", rep)
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Second rule for early problem", "--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'early problem' has come back: 1 miss", out)
rep2 = self.sisi("retro")[1]
self.assertIn("#1: early problem (2 attempts", rep2)
self.assertIn("#2: late problem (1 attempt", rep2)
def test_wording_refusals_and_miss_singular(self):
# With no problems yet, refusals must not say "numbers above"
for p_args in ((), ("--problem", "1")):
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Should not be written anywhere", *p_args)
self.assertNotEqual(rc, 0)
self.assertIn("none yet", out)
self.assertNotIn("numbers above", out)
self.assertEqual(self.records(), [])
# Problem name over 400 characters is refused with a message mentioning the 400-character limit
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Should not be written anywhere", "--problem", "p" * 401)
self.assertNotEqual(rc, 0)
self.assertIn("400", out)
self.assertEqual(self.records(), [])
# --no-gap with --problem says --problem goes only with --gap
rc, out, _ = self.sisi("retro", "--no-gap", "the export kept every row cleanly",
"--term", "time", "--better", "start the first build sooner than before",
"--problem", "1")
self.assertNotEqual(rc, 0)
self.assertIn("--problem", out)
self.assertIn("--gap", out)
self.assertNotIn("that is not a retro yet", out)
self.assertEqual(self.records(), [])
def test_redacted_problem_names_refused(self):
bad_names = (
"sk-abcdefghijklmnopqrstuvwx",
"0123456789abcdef0123456789abcdef01234567",
"1234567890" * 4,
"api_key=supersecret999 broken",
)
for bad in bad_names:
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Should not record secret problem name", "--problem", bad)
self.assertNotEqual(rc, 0, bad)
self.assertIn("plain words", out)
self.assertNotIn(bad, out)
self.assertEqual(self.records(), [])
self.assertFalse(os.path.exists(os.path.join(self.proj, ".sisi", "rules.md")))
def test_two_problems_each_open_own_fault_and_case_spacing_joins(self):
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Alpha rule one for export", "--problem", "alpha issue")[0], 0)
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Bravo rule one for export", "--problem", "bravo issue")[0], 0)
# Citing by name with different case and spacing joins the same problem
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Alpha rule two by name", "--problem", " ALPHA issue ")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'alpha issue' has come back: 1 miss", out)
self.assertNotIn("1 misses", out)
self.assertEqual(self.sisi("fault")[1].strip(), "no open faults.")
# 2nd miss on problem 1 opens its fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Alpha rule three opens fault", "--problem", "1")
self.assertEqual(rc, 0, out)
self.assertIn("problem 1 'alpha issue' has come back: 2 misses", out)
# Same-length second problem joins via case/spacing then reaches 2 misses and opens its own fault
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Bravo rule two by name", "--problem", " bravo ISSUE ")
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 'bravo issue' has come back: 1 miss", out)
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Bravo rule three opens fault", "--problem", "2")
self.assertEqual(rc, 0, out)
self.assertIn("problem 2 'bravo issue' has come back: 2 misses", out)
faults_lines = self.sisi("fault")[1].strip().splitlines()
self.assertEqual(len(faults_lines), 2, faults_lines)
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()