Tag retro rules with problem number and show recurrence in rules listing and organize brief

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-12-01 16:50:15 -07:00
1 parent 1e1f26616e
commit 9f167f8f50
3 files changed
+175 -12

No files matched your search

+47 -10
View File
@@ -18,7 +18,9 @@ HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never
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"
_DROP = re.compile(r"^(?:[-*]|\d+\.)\s+(.+?)\s*\|\s*#(\d+|-)\s*\|\s*(\S.*)$")
_DKEY = lambda s: " ".join(re.sub(r"(?i)(?:\s*\[(?:retro|agent)\b[^\]]*\])+$", "", re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s.replace("`", "")).strip()).lower().split())
_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}")
_DKEY = lambda s: " ".join(re.sub(r"(?i)(?:\s*\[(?:retro|agent)\b[^\]]*\])+$", "", _NOTE.sub("", re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s.replace("`", "")).strip())).lower().split())
ORGANIZE = """You are a worker. Do this task yourself; do not delegate it further.
@@ -43,7 +45,7 @@ Rewrite both lists so they serve that objective best:
agent's conclusion, third person), and any rule that limits builds, tests or workers to one at a time or tells
checkouts to share one build folder. List each under a final `## flags` section with its proposed corrected or
retagged form, for the person to accept.
- Keep the [source date] mark at the end of every line.
- Keep the [source date] mark (and any pN tag, including on merged rules) at the end of every line, without any trailing (pN: ...) note. A rule whose problem came back after it was written should be reworked or turned into a check.
- A `better` that recurs across retros has earned a rule: add it, worded as an instruction, marked [retro <date>].
- Non-owner ([retro ...]) lines in each list: at most %(lines)d lines and %(chars)d characters. Fewer is better.
- When you drop or merge away a non-owner rule, you can list `- <old rule copied as it is> | #<N or -> | <reason>` under `## drops` (#- if no problem matches; optional: a missing line is recorded as 'none given').
@@ -237,11 +239,12 @@ def _locks(*keys):
return st
def add(text, scope, source, cwd=None, log=None, means="", raw=None):
def add(text, scope, source, cwd=None, log=None, means="", raw=None, problem=None):
"""Put one rule in force; returns (line, warning). Raises OSError before writing when the list cannot be written."""
if scope == PROJECT and not has_project(cwd):
raise OSError("no project here, use user")
line, *more = ["- %s [%s %s]" % (" ".join(str(t).split()), src, time.strftime("%Y-%m-%d")) for t, src in ((text, source), (means, "agent reading")) if t] # one commit holds both
d = time.strftime("%Y-%m-%d")
line, *more = ["- %s [%s %s%s]" % (" ".join(str(t).split()), src, d, " p%d" % p if p else "") for t, src, p in ((text, source, problem), (means, "agent reading", None)) if t] # one commit holds both
line, more = (raw, []) if raw else (line, more)
dest = path(scope, cwd)
scope == PROJECT and not dest and _check_writable(dest)
@@ -377,9 +380,39 @@ def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
return "".join(out).rstrip("\n")
def _rule_probs(line):
"""Return [(problem_num, rule_date), ...] from trailing [retro ...] tags, or []."""
m = _RETRO_TAG.search(line)
dates = _DATE.findall(m.group(0)) if m else []
if not dates:
return []
cur, out = max(dates), {}
for d, p in re.findall(r"(\d{4}-\d{2}-\d{2})|\bp(\d{1,6})\b", m.group(0)):
if d:
cur = d
elif (n := int(p)) >= 1:
out[n] = max(out.get(n, ""), cur)
return list(out.items())
def _annotate(ls, probs):
"""Append per-rule problem recurrence notes for display in `sisi rules` and `organize_brief`."""
out = []
for l in ls:
if not (ps := _rule_probs(l)):
out.append(l)
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 ()))
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
def organize_brief(cwd):
from . import retro
cfg, u, p = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd) if has_project(cwd) else []
cfg, u, p, probs = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd) if has_project(cwd) else [], retro._problems()
with contextlib.suppress(OSError), store.lock("organize"):
cl = _organized(("locks", "organize.json"))
cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p)
@@ -388,9 +421,10 @@ def organize_brief(cwd):
"name": os.path.basename(store.project_root(cwd)), "levels": LEVELS.replace("\n", " "), "objective": objective(),
"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)" if has_project(cwd) else "(not in a git project: leave `## project` empty)",
"user": "\n".join(_annotate(u, probs)) or "(none)",
"project": "\n".join(_annotate(p, probs)) or "(none)" if has_project(cwd) else "(not in a git project: leave `## project` empty)",
"retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)",
"evidence": _evidence(retro._problems(), drops_for())}
"evidence": _evidence(probs, drops_for())}
def organize_record(answer_file, cwd):
@@ -400,7 +434,7 @@ def organize_record(answer_file, cwd):
got, flags, drops = {}, "", {}
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.rstrip() for l in chunk.splitlines() if l.startswith("- ")]
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("- "))]
elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
flags += chunk
elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h):
@@ -527,8 +561,11 @@ def show(cwd):
print("rulebook (loaded in every session): %s" % store.data("generated", "core.md"))
proj, note = _migrate(cwd)
note and print("\n" + note)
for title, ls in (("Learned, all projects", lines(path(USER))), ("Queued for the product (in force as user rules until then)", lines(path(CORE))), ("Learned, this project", proj)):
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(ls) or " (none)"))
groups = (("Learned, all projects", lines(path(USER))), ("Queued for the product (in force as user rules until then)", lines(path(CORE))), ("Learned, this project", proj))
from . import retro
probs = retro._problems() if any(_rule_probs(l) for _, ls in groups for l in ls) else []
for title, ls in groups:
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(_annotate(ls, probs)) or " (none)"))
if due(cwd):
print("\n" + due(cwd))