diff --git a/README.md b/README.md index 0815789..5fd1a0f 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ its limits are. | `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) | | `sisi retro --later …` | The work is not finished yet | | `sisi learn [--project] "…" [--means "…"]` | The person's own words become a rule at once, tagged `[owner]` only when they appear in the person's recent messages in this session. `--means` adds, in the same undoable step, one line saying how the agent will apply it | -| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them; undo the last rule change made with `learn`, a retro or `organize`, in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) | +| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons, and requiring a `## drops` reason and matching problem number for every dropped or merged rule); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `organize`), in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) | | `sisi models` / `sisi models research [--record FILE]` | The workers table (the shared baseline table ships with sisi in `canon/models.md`); have a worker rebuild it | | `sisi judge WORKER good\|bad "…" [--minutes N] [--newest]` | How a delegation went; the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first, `--newest` the newest | | `sisi judge WORKER extend MINUTES "" [--newest]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest) gets MINUTES more from now, and its late fault clears | @@ -102,7 +102,8 @@ Rules live at three levels: - **The product** (this repository): the code in `sisi/`, and the rulebook in `canon/core.md` — rules useful to everyone using sisi, the same for all users. `SPEC.md` is what it aims at. - **Your store** (`$SISI_DATA`, else `$XDG_DATA_HOME/sisi`, else `~/.local/share/sisi`; a git repository): `rules/user.md` - (how you like to work, across all your projects), `models.md` (your workers), `retro.jsonl` (each piece of work: session, + (how you like to work, across all your projects), `rules/drops.jsonl` (rules dropped or merged away during `organize`, + with date, matching problem number, and reason), `models.md` (your workers), `retro.jsonl` (each piece of work: session, `retro_seconds`, counts, goal, term, problem) and `outcomes.jsonl` (each judged delegation: session, `project_key`, `model`, `started`/`ended`, minutes, verdict, why). All plain text you can read and edit. - **Each project** (`.sisi/rules.md` in the project's folder: in a git repository, the root of its main checkout, shared by diff --git a/sisi/retro.py b/sisi/retro.py index 9c322ed..13a0c25 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -247,6 +247,8 @@ def run(args, cwd=None): print("problem %d '%s' has come back: %d misses" % (prob["num"], prob["name"], misses)) for a in prior: print(" - [%s] %s" % (a["date"], a["improve"] or a["cause"] or "(no improvement recorded)")) + for d in rules.drops_for(prob["num"]): + print(" - dropped [%s] %s (%s)" % (str(d.get("ts") or "")[:10] or "?", d.get("rule", ""), d.get("reason", ""))) else: print("opened problem %d '%s'." % (prob["num"], prob["name"])) try: diff --git a/sisi/rules.py b/sisi/rules.py index 9fd2fe3..2414acc 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -14,6 +14,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" ORGANIZE = """You are a worker. Do this task yourself; do not delegate it further. @@ -38,6 +39,7 @@ Rewrite both lists so they serve that objective best: - Keep the [source date] mark at the end of every line. - A `better` that recurs across retros has earned a rule: add it, worded as an instruction, marked [retro ]. - Non-owner ([retro ...]) lines in each list: at most %(lines)d lines and %(chars)d characters. Fewer is better. +- For every non-owner rule you drop or merge away, end with a `## drops` section listing `- | # | ` (#- if no problem matches). Answer with exactly this shape and nothing else: ## user @@ -57,7 +59,7 @@ Answer with exactly this shape and nothing else: %(flagged)s === What recent retros found, newest last (context only) === -%(retros)s +%(retros)s%(evidence)s """ @@ -288,7 +290,36 @@ def due(cwd, claim=False): % "; ".join(m for _, m in need)) +def drops_for(num=None): + return [d for d in store.records(DROPS) if num is None or d.get("problem") == num] + + +def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180): + if not probs: + return "" + cut = lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..." + head = ("\n\n=== Known problems and prior rule attempts (most recent first) ===\n" + "How to use this evidence:\n" + "- Problem has 0 misses: its rule is holding, keep it. Has misses: the sentence did not hold, keep the latest attempt and say so (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]: + 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"]] + + [" dropped [%s] %s | reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in drops if 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 ()): + if used + len(l) + 1 <= cap_c: + out.append(l + "\n"); used += len(l) + 1 + break + out.append(blk); used += len(blk) + return "".join(out).rstrip("\n") + + def organize_brief(cwd): + from . import retro cfg, u, p = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd) with contextlib.suppress(OSError), store.lock("organize"): cl = _organized(("locks", "organize.json")) @@ -299,14 +330,20 @@ def organize_brief(cwd): "lines": cfg["rules_lines"], "chars": cfg["rules_chars"], "flagged": "\n".join(l for l in u + p if SMELL.search(l)) or "(none)", "user": "\n".join(u) or "(none)", "project": "\n".join(p) or "(none)", - "retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)"} + "retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)", + "evidence": _evidence(retro._problems(), drops_for())} 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() - body, *flags = re.split(r"(?im)^##\s*flags\s*$", store.read(answer_file), 1) # the flags are for the person, not rules - flags = "".join(flags) + secs = re.split(r"(?im)^##[ \t]*(flags|drops)[ \t]*$", store.read(answer_file)) + body, flags, drops = secs[0], "".join(secs[i + 1] for i in range(1, len(secs) - 1, 2) if secs[i].lower() == "flags"), {} + for l in (l.rstrip() for i in range(1, len(secs) - 1, 2) if secs[i].lower() == "drops" for l in secs[i + 1].splitlines() if l.strip()): + ps = l[2:].rsplit("|", 2) if l.startswith("- ") else [] + if len(ps) != 3 or not (m := re.fullmatch(r"#(\d+|-)", ps[1].strip())) or not (why := ps[2].strip()) or not (rk := ps[0].strip()): + return "each drop needs `- | # | `" + drops[rk if rk.startswith("- ") else "- " + rk] = (None if m.group(1) == "-" else int(m.group(1)), why) parts = re.split(r"(?m)^## (user|project)[ \t]*$", body) got = {parts[i]: [l.rstrip() for l in parts[i + 1].splitlines() if l.startswith("- ")] for i in range(1, len(parts) - 1, 2)} @@ -330,6 +367,10 @@ def organize_record(answer_file, cwd): for scope in (USER, PROJECT): if miss := [l for l in had[scope] if _owner(l) and got[scope].count(l) < had[scope].count(l)]: return "owner rule missing or changed (%s): %s" % (scope, miss[0]) + kept = list(got[USER]) + list(got[PROJECT]) + dropped = [r for r in had[USER] + had[PROJECT] if not _owner(r) and not (r in kept and kept.remove(r) is None)] + if want and (miss := [r for r in dropped if r not in drops]): + return "dropped or merged rule missing a reason in `## drops`: %s" % miss[0] if not any(got.values()) and any(had.values()): return "the answer holds no rules at all" try: @@ -350,7 +391,10 @@ def organize_record(answer_file, cwd): seen.pop("rules/projects/%s.md" % store.project_key(cwd), None) marks = store.data("rules", "organized.json") store.write(marks, json.dumps(seen)) - _commit("rules organized", marks, up, snap=(pp, before, after)) + dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S") + for r, (pnum, why) in drops.items(): + store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pnum, "reason": why}, sort_keys=True)) + _commit("rules organized", marks, up, *([dp] if drops else []), snap=(pp, before, after)) except OSError as e: wrote_u and build_rulebook() if not wrote and not wrote_u: @@ -370,7 +414,7 @@ def organize_record(answer_file, cwd): def revert(): """Undo the last rule change (learn, retro or organize): a project's list only while it holds what that change left.""" - files = ("rules/user.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json") + files = ("rules/user.md", "rules/last-project.json", "rules/owner.log", "rules/organized.json", DROPS) 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 fe6473c..1e62a7d 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -237,8 +237,9 @@ class Core(unittest.TestCase): for bad in ("no sections at all", "## user\n## project\n" + "- one more rule [retro 2026-01-01]\n" * 31, "## user\n## project\n"): self.assertEqual(self.sisi("rules", "organize", "--record", self.write(answer, bad))[0], 1, bad[:20]) self.assertEqual(self.read(path), before) + drops = "".join("- %s | #1 | merged into single map test rule\n" % l[2:] for l in before.splitlines()) self.write(answer, "## user\n- Work from the checklist the person gave [owner 2026-01-01]\n" - "## project\n- Run the map tests before a commit [retro 2026-01-01]\n") + "## project\n- Run the map tests before a commit [retro 2026-01-01]\n## drops\n" + drops) self.assertEqual(self.sisi("rules", "organize", "--record", answer)[0], 0) self.assertEqual(self.read(path), "- Run the map tests before a commit [retro 2026-01-01]\n") self.assertIn("Work from the checklist", self.read(self.data, "generated", "core.md")) @@ -3417,7 +3418,10 @@ cli.main(["tick"]) self.assertIn(own2, out) self.assertEqual(self.read(self.data, "rules", "user.md"), before_u) # reordered owner rules + merged two retro rules -> accepted - merged = "## user\n%s\n%s\n- Check row counts before and after exporting tables [retro 2026-11-25]\n## project\n- Project retro rule one [retro 2026-11-24]\n" % (own2, own1) + merged = ("## user\n%s\n%s\n- Check row counts before and after exporting tables [retro 2026-11-25]\n" + "## project\n- Project retro rule one [retro 2026-11-24]\n" + "## drops\n- %s | #- | merged into combined check\n- %s | #- | merged into combined check\n" + % (own2, own1, ret1[2:], ret2[2:])) rc, out, _ = self.sisi("rules", "organize", "--record", self.write(ans, merged)) self.assertEqual(rc, 0, out) self.assertIn(own1, self.read(self.data, "rules", "user.md")) @@ -3657,7 +3661,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, 2161, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 2207, "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()), 137) self.assertLessEqual(len(rulebook), 10530) diff --git a/tests/test_organize_evidence.py b/tests/test_organize_evidence.py new file mode 100644 index 0000000..e4de5ab --- /dev/null +++ b/tests/test_organize_evidence.py @@ -0,0 +1,237 @@ +"""Tests for organize evidence, drop reasons, and revert consistency.""" +import glob +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +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") + + +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 OrganizeEvidence(unittest.TestCase): + def setUp(self): + before = tree() + self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) + self.tmp = tempfile.mkdtemp(prefix="sisi-orgev-") + 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")) + 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 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 write(self, path, text): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + return path + + def read(self, *parts): + with open(os.path.join(*parts), encoding="utf-8") as f: + return f.read() + + def test_brief_has_problem_evidence_and_respects_caps(self): + self.assertEqual(self.sisi("retro", "--gap", "export dropped rows with empty names in table", + "--cause", "first cause missed null guard", + "--improve", "Check null names before exporting rows", + "--term", "evidence", "--problem", "row count mismatch")[0], 0) + self.assertEqual(self.sisi("retro", "--gap", "export dropped rows again on blank fields", + "--cause", "second cause forgot whitespace trim", + "--improve", "Strip whitespace and assert total row count matches", + "--term", "evidence", "--problem", "1")[0], 0) + rc, brief, err = self.sisi("rules", "organize") + self.assertEqual((rc, err), (0, ""), brief) + self.assertIn("row count mismatch", brief) + self.assertIn("2 attempts", brief) + self.assertIn("1 miss", brief) + self.assertIn("first cause missed null guard", brief) + self.assertIn("Check null names before exporting rows", brief) + self.assertIn("second cause forgot whitespace trim", brief) + self.assertIn("Strip whitespace and assert total row count matches", brief) + self.assertIn("keep the latest attempt", brief) + self.assertIn("keep the cause", brief) + + # Add 17 more problems (18 total > 15 cap) and a 5000-char cause on problem 18 + long_cause = "word " * 1000 + for i in range(2, 19): + cause = long_cause if i == 18 else "cause number %02d in batch" % i + self.assertEqual(self.sisi("retro", "--gap", "gap number %02d failed verification check" % i, + "--cause", cause, + "--improve", "Rule number %02d for problem" % i, + "--term", "evidence", "--problem", "problem item %02d" % i)[0], 0) + # Re-cite problem 1 so it is most recently cited + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Latest rule for row count mismatch", + "--problem", "1")[0], 0) + rc, brief2, _ = self.sisi("rules", "organize") + self.assertEqual(rc, 0) + ev = brief2.split("=== Known problems")[1] + self.assertLessEqual(len(ev), 5050) + self.assertIn("row count mismatch", ev) + self.assertIn("problem item 18", ev) + self.assertNotIn(long_cause, ev) + self.assertNotIn("problem item 02", ev) + self.assertNotIn("problem item 03", ev) + self.assertNotIn("problem item 04", ev) + + def test_no_problems_brief_is_minimal_and_organize_works(self): + self.assertEqual(self.sisi("learn", "--project", "Keep project outputs deterministic always")[0], 0) + self.assertEqual(self.sisi("retro", "--no-gap", "the run passed every check cleanly", + "--term", "time", "--better", "start the verification step much earlier")[0], 0) + rc, brief, _ = self.sisi("rules", "organize") + self.assertEqual(rc, 0) + self.assertNotIn("=== Known problems", brief) + self.assertIn("## drops", brief) + # No-problems brief equals main's ORGANIZE template (32 lines) plus 1 bullet line + self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 33) + 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" + "## drops\n- %s | #- | reworded for clarity\n" % proj_line[2:]) + rc, out, err = self.sisi("rules", "organize", "--record", ans) + self.assertEqual((rc, err), (0, ""), out) + recs = [json.loads(l) for l in self.read(self.data, "rules", "drops.jsonl").splitlines() if l.strip()] + self.assertEqual(len(recs), 1) + self.assertIsNone(recs[0]["problem"]) + self.assertEqual(recs[0]["reason"], "reworded for clarity") + + def test_drop_reasons_accepted_and_missing_reason_rejected_as_malformed(self): + self.assertEqual(self.sisi("retro", *GAP, "--improve", "First rule for empty names", + "--problem", "empty names")[0], 0) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second rule for empty names", + "--problem", "1")[0], 0) + rules_path = os.path.join(self.proj, ".sisi", "rules.md") + before = self.read(rules_path) + r1, r2 = before.splitlines() + self.assertEqual(self.sisi("rules", "organize")[0], 0) + + ans = os.path.join(self.tmp, "ans.md") + for bad in ( + "## user\n## project\n%s\n" % r2, + "## user\n## project\n%s\n## drops\n- %s | #1 | \n" % (r2, r1[2:]), + "## user\n## project\n%s\n## drops\n- %s\n" % (r2, r1[2:]), + ): + rc, out, _ = self.sisi("rules", "organize", "--record", self.write(ans, bad)) + self.assertEqual(rc, 1, bad) + self.assertIn("Nothing was changed", out) + self.assertEqual(self.read(rules_path), before) + self.assertFalse(os.path.exists(os.path.join(self.data, "rules", "drops.jsonl"))) + + good = "## user\n## project\n%s\n## drops\n- %s | #1 | superseded by second rule\n" % (r2, r1[2:]) + rc, out, err = self.sisi("rules", "organize", "--record", self.write(ans, good)) + self.assertEqual((rc, err), (0, ""), out) + self.assertEqual(self.read(rules_path), r2 + "\n") + recs = [json.loads(l) for l in self.read(self.data, "rules", "drops.jsonl").splitlines() if l.strip()] + self.assertEqual(len(recs), 1) + self.assertEqual(recs[0]["problem"], 1) + self.assertEqual(recs[0]["rule"], r1) + self.assertEqual(recs[0]["reason"], "superseded by second rule") + + def test_owner_rules_stay_verbatim_with_drops_format(self): + self.sisi("prompt", sid="o1", stdin=json.dumps({"session_id": "o1", "cwd": self.proj, "prompt": "Always keep the owner rule verbatim"})) + self.assertEqual(self.sisi("learn", "Always keep the owner rule verbatim", sid="o1")[0], 0) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Check row counts before export", "--problem", "empty names")[0], 0) + own = self.read(self.data, "rules", "user.md").splitlines()[0] + ret = self.read(self.proj, ".sisi", "rules.md").splitlines()[0] + self.assertEqual(self.sisi("rules", "organize")[0], 0) + + ans = os.path.join(self.tmp, "ans.md") + # Dropping an owner rule even with a ## drops entry is refused + bad_drop = "## user\n## project\n%s\n## drops\n- %s | #- | tried to drop owner\n" % (ret, own[2:]) + rc, out, _ = self.sisi("rules", "organize", "--record", self.write(ans, bad_drop)) + self.assertEqual(rc, 1, out) + self.assertIn("owner rule missing or changed", out) + self.assertIn(own, self.read(self.data, "rules", "user.md")) + + # Rewording an owner rule is still refused + bad_edit = "## user\n- Keep owner rule [owner 2026-11-26]\n## project\n%s\n" % ret + rc, out, _ = self.sisi("rules", "organize", "--record", self.write(ans, bad_edit)) + self.assertEqual(rc, 1, out) + self.assertIn("owner rule missing or changed", out) + + # Keeping owner verbatim while dropping retro rule with reason succeeds + good = "## user\n%s\n## project\n- Export verifies row counts [retro 2026-11-26]\n## drops\n- %s | #1 | replaced with stronger rule\n" % (own, ret[2:]) + rc, out, err = self.sisi("rules", "organize", "--record", self.write(ans, good)) + self.assertEqual((rc, err), (0, ""), out) + self.assertIn(own, self.read(self.data, "rules", "user.md")) + + def test_recorded_drop_appears_in_next_brief_and_retro_has_come_back(self): + self.assertEqual(self.sisi("retro", *GAP, "--improve", "First attempt rule to drop", "--problem", "empty names")[0], 0) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second attempt rule to keep", "--problem", "1")[0], 0) + r1, r2 = self.read(self.proj, ".sisi", "rules.md").splitlines() + self.assertEqual(self.sisi("rules", "organize")[0], 0) + ans = self.write(os.path.join(self.tmp, "ans.md"), + "## user\n## project\n%s\n## drops\n- %s | #1 | too vague to prevent bug\n" % (r2, r1[2:])) + self.assertEqual(self.sisi("rules", "organize", "--record", ans)[0], 0) + + rc, brief, _ = self.sisi("rules", "organize") + self.assertEqual(rc, 0) + self.assertIn("dropped [", brief) + self.assertIn(r1, brief) + self.assertIn("too vague to prevent bug", brief) + + rc, retro_out, _ = self.sisi("retro", *GAP, "--improve", "Third attempt rule after drop", "--problem", "1") + self.assertEqual(rc, 0, retro_out) + self.assertIn("problem 1 'empty names' has come back: 2 misses", retro_out) + self.assertIn("dropped [", retro_out) + self.assertIn(r1, retro_out) + self.assertIn("too vague to prevent bug", retro_out) + + def test_revert_after_organize_undoes_and_redoes_drop_reasons(self): + self.assertEqual(self.sisi("retro", *GAP, "--improve", "First rule before organize", "--problem", "empty names")[0], 0) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Second rule before organize", "--problem", "1")[0], 0) + rules_path = os.path.join(self.proj, ".sisi", "rules.md") + before = self.read(rules_path) + r1, r2 = before.splitlines() + self.assertEqual(self.sisi("rules", "organize")[0], 0) + ans = self.write(os.path.join(self.tmp, "ans.md"), + "## user\n## project\n%s\n## drops\n- %s | #1 | dropped during organize\n" % (r2, r1[2:])) + self.assertEqual(self.sisi("rules", "organize", "--record", ans)[0], 0) + self.assertIn("dropped during organize", self.read(self.data, "rules", "drops.jsonl")) + + rc, out, _ = self.sisi("rules", "revert") + self.assertEqual(rc, 0, out) + self.assertEqual(self.read(rules_path), before) + drops_path = os.path.join(self.data, "rules", "drops.jsonl") + self.assertFalse(os.path.exists(drops_path) and "dropped during organize" in self.read(drops_path)) + self.assertNotIn("dropped during organize", self.sisi("rules", "organize")[1]) + + # Second revert re-applies both the organized rules and the drop reason + rc, out, _ = self.sisi("rules", "revert") + self.assertEqual(rc, 0, out) + self.assertEqual(self.read(rules_path), r2 + "\n") + self.assertIn("dropped during organize", self.read(drops_path)) + self.assertIn("dropped during organize", self.sisi("rules", "organize")[1]) + + +if __name__ == "__main__": + unittest.main()