Merge duplicate problems via rules organize alias map
ci / test (push) Canceled after 0s

- 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>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-12-01 17:02:03 -07:00
1 parent 68b6226aa6
commit 25b5e90c6b
5 files changed
+270 -25

No files matched your search

+36 -12
View File
@@ -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
- <old rule> | #<N or -> | <reason> (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