Merge branch 'p4-rule-problem'

# Conflicts:
#	tests/test_core.py
This commit is contained in:
swaits committed 2026-12-01 16:50:48 -07:00
commit 6edfa6d860
3 files changed
+175 -12

No files matched your search

+1 -1
View File
@@ -303,7 +303,7 @@ def run(args, cwd=None):
print("opened problem %d '%s'." % (prob["num"], prob["name"])) print("opened problem %d '%s'." % (prob["num"], prob["name"]))
like and print("this looks like problem %d '%s'; if it is, record it with --problem %d next time" % (like["num"], like["name"], like["num"])) like and print("this looks like problem %d '%s'; if it is, record it with --problem %d next time" % (like["num"], like["name"], like["num"]))
try: try:
added, warn = rules.add(opt["improve"], scope, "retro", cwd) added, warn = rules.add(opt["improve"], scope, "retro", cwd, problem=prob["num"])
print(warn or ("recorded. In force from the next session%s: %s" % ( print(warn or ("recorded. In force from the next session%s: %s" % (
" in every project" if scope == rules.USER else " in this project", added) if scope != rules.CORE else "recorded, queued for the product: %s" % added)) " in every project" if scope == rules.USER else " in this project", added) if scope != rules.CORE else "recorded, queued for the product: %s" % added))
print(rules.filed(scope, opt["improve"], cwd)) print(rules.filed(scope, opt["improve"], cwd))
+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)") 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 = "rules/drops.jsonl"
_DROP = re.compile(r"^(?:[-*]|\d+\.)\s+(.+?)\s*\|\s*#(\d+|-)\s*\|\s*(\S.*)$") _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. 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 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 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. 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>]. - 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. - 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'). - 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').
@@ -245,11 +247,12 @@ def _locks(*keys):
return st 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.""" """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): if scope == PROJECT and not has_project(cwd):
raise OSError("no project here, use user") 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) line, more = (raw, []) if raw else (line, more)
dest = path(scope, cwd) dest = path(scope, cwd)
scope == PROJECT and not dest and _check_writable(dest) scope == PROJECT and not dest and _check_writable(dest)
@@ -385,9 +388,39 @@ def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
return "".join(out).rstrip("\n") 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): def organize_brief(cwd):
from . import retro 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"): with contextlib.suppress(OSError), store.lock("organize"):
cl = _organized(("locks", "organize.json")) cl = _organized(("locks", "organize.json"))
cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p) cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p)
@@ -396,9 +429,10 @@ def organize_brief(cwd):
"name": os.path.basename(store.project_root(cwd)), "levels": LEVELS.replace("\n", " "), "objective": objective(), "name": os.path.basename(store.project_root(cwd)), "levels": LEVELS.replace("\n", " "), "objective": objective(),
"lines": cfg["rules_lines"], "chars": cfg["rules_chars"], "lines": cfg["rules_lines"], "chars": cfg["rules_chars"],
"flagged": "\n".join(l for l in u + p if SMELL.search(l)) or "(none)", "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)", "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): def organize_record(answer_file, cwd):
@@ -408,7 +442,7 @@ def organize_record(answer_file, cwd):
got, flags, drops = {}, "", {} got, flags, drops = {}, "", {}
for h, chunk in ((secs[i], secs[i + 1]) for i in range(1, len(secs) - 1, 2)): 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): 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): elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
flags += chunk flags += chunk
elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h): elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h):
@@ -542,8 +576,11 @@ def show(cwd):
print("rulebook (loaded in every session): %s" % store.data("generated", "core.md")) print("rulebook (loaded in every session): %s" % store.data("generated", "core.md"))
proj, note = _migrate(cwd) proj, note = _migrate(cwd)
note and print("\n" + note) 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)): 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))
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(ls) or " (none)")) 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): if due(cwd):
print("\n" + due(cwd)) print("\n" + due(cwd))
+127 -1
View File
@@ -4497,9 +4497,135 @@ cli.main(["tick"])
self.assertEqual(rc, 1, out) self.assertEqual(rc, 1, out)
self.assertIn("user.md is not valid UTF-8", out) self.assertIn("user.md is not valid UTF-8", out)
def test_gap_retro_writes_problem_tag_and_loaded_text_has_no_recurrence_note(self):
from sisi import rules
rc, out, _ = self.sisi("retro", *GAP, "--improve", "Compare row counts before every export", sid="p1")
self.assertEqual(rc, 0, out)
self.assertRegex(self.read(self.proj, ".sisi", "rules.md").strip(), r"Compare row counts before every export \[retro \d{4}-\d{2}-\d{2} p1\]$")
rc, out, _ = self.sisi("retro", *GAP[:-4], "--problem", "stale cache key", "--level", "user",
"--improve", "Bust cache keys on every schema bump", sid="p1")
self.assertEqual(rc, 0, out)
self.assertRegex(self.read(self.data, "rules", "user.md").strip(), r"Bust cache keys on every schema bump \[retro \d{4}-\d{2}-\d{2} p2\]$")
rc, out, _ = self.sisi("retro", *GAP[:-4], "--problem", "1", "--level", "core",
"--improve", "Check row counts in every product export", sid="p1")
self.assertEqual(rc, 0, out)
self.assertRegex(self.read(self.data, "rules", "core.md").strip(), r"Check row counts in every product export \[retro \d{4}-\d{2}-\d{2} p1\]$")
self.assertEqual(self.sisi("learn", "--level", "user", "Keep learned rules short and clear", sid="p1")[0], 0)
self.assertNotRegex(self.read(self.data, "rules", "user.md").splitlines()[-1], r"\bp\d+\]")
self.in_process(rules.build_rulebook)
book = self.read(self.data, "generated", "core.md")
tick = self.hook("tick", sid="p2")[1]
for loaded in (book, tick):
self.assertNotIn("came back", loaded)
self.assertNotIn("not seen since", loaded)
self.assertRegex(book, r"Bust cache keys on every schema bump \[retro \d{4}-\d{2}-\d{2} p2\]")
self.assertRegex(tick, r"Compare row counts before every export \[retro \d{4}-\d{2}-\d{2} p1\]")
def test_rules_listing_and_organize_brief_show_problem_recurrence_since_rule_date(self):
from sisi import rules
os.makedirs(self.data, exist_ok=True)
retro_rows = [
{"ts": "2026-11-20T10:00:00", "problem": "export drops empty names", "cause": "c1", "improve": "r1"},
{"ts": "2026-11-21T10:00:00", "problem": "stale cache key", "cause": "c2", "improve": "r2"},
{"ts": "2026-11-22T10:00:00", "problem": "export drops empty names", "cause": "c3", "improve": "r3"},
{"ts": "2026-11-23T10:00:00", "problem": "missing lock cleanup", "cause": "c4", "improve": "r4"},
{"ts": "2026-11-23T15:00:00", "problem": "missing lock cleanup", "cause": "c4b", "improve": "r4b"},
{"problem": "missing lock cleanup", "cause": "c4c", "improve": "r4c"},
{"ts": "2026-11-24T10:00:00", "problem": "stale cache key", "cause": "c5", "improve": "r5"},
{"ts": "2026-11-25T10:00:00", "problem": "export drops empty names", "cause": "c6", "improve": "r6"},
]
self.write(os.path.join(self.data, "retro.jsonl"), "".join(json.dumps(r) + "\n" for r in retro_rows))
self.write(os.path.join(self.mkdir(self.data, "rules"), "user.md"), "\n".join([
"- User rule for p1 early [retro 2026-11-20 p1]",
"- User rule for p1 middle [retro 2026-11-22 p1]",
"- User rule for p1 latest [retro 2026-11-25 p1]",
]) + "\n")
self.write(os.path.join(self.data, "rules", "core.md"), "- Core rule for p2 early [retro 2026-11-21 p2]\n")
self.write(os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md"), "\n".join([
"- Project rule for p2 latest [retro 2026-11-24 p2]",
"- Project rule for p3 same day [retro 2026-11-23 p3]",
]) + "\n")
_, listing_inproc = self.in_process(rules.show, self.proj)
rc, listing_cli, err = self.sisi("rules")
self.assertEqual((rc, err), (0, ""), listing_cli)
rc_b, brief, err_b = self.sisi("rules", "organize")
self.assertEqual((rc_b, err_b), (0, ""), brief)
for out in (listing_inproc, listing_cli):
self.assertIn("- User rule for p1 early [retro 2026-11-20 p1] (p1: came back 2x since)", out)
self.assertIn("- User rule for p1 middle [retro 2026-11-22 p1] (p1: came back 1x since)", out)
self.assertIn("- User rule for p1 latest [retro 2026-11-25 p1] (p1: not seen since)", out)
self.assertIn("- Core rule for p2 early [retro 2026-11-21 p2] (p2: came back 1x since)", out)
self.assertIn("- Project rule for p2 latest [retro 2026-11-24 p2] (p2: not seen since)", out)
self.assertIn("- Project rule for p3 same day [retro 2026-11-23 p3] (p3: not seen since)", out)
self.assertIn("- User rule for p1 early [retro 2026-11-20 p1] (p1: came back 2x since)", brief)
self.assertIn("- User rule for p1 latest [retro 2026-11-25 p1] (p1: not seen since)", brief)
self.assertIn("- Project rule for p2 latest [retro 2026-11-24 p2] (p2: not seen since)", brief)
self.assertIn("came back", brief.split("=== The first list now")[0])
self.in_process(rules.build_rulebook)
book = self.read(self.data, "generated", "core.md")
tick = self.hook("tick", sid="rec1")[1]
for loaded in (book, tick):
self.assertNotIn("came back", loaded)
self.assertNotIn("not seen since", loaded)
def test_old_tags_without_problem_and_organize_merge_keeps_problem_tags(self):
os.makedirs(self.data, exist_ok=True)
retro_rows = [
{"ts": "2026-11-20T10:00:00", "problem": "export drops empty names", "cause": "c1", "improve": "r1"},
{"ts": "2026-11-21T10:00:00", "problem": "stale cache key", "cause": "c2", "improve": "r2"},
{"ts": "2026-11-22T10:00:00", "problem": "export drops empty names", "cause": "c3", "improve": "r3"},
{"ts": "2026-11-24T10:00:00", "problem": "stale cache key", "cause": "c4", "improve": "r4"},
{"ts": "2026-11-25T10:00:00", "problem": "export drops empty names", "cause": "c5", "improve": "r5"},
]
self.write(os.path.join(self.data, "retro.jsonl"), "".join(json.dumps(r) + "\n" for r in retro_rows))
own = "- Owner rule stays verbatim [owner 2026-11-20]"
old_u = "- Old user rule without problem [retro 2026-11-20]"
old_m = "- Old merged rule without problem [retro 2026-11-20, 2026-11-21]"
p1_a = "- Check row counts before export [retro 2026-11-20 p1]"
p1_b = "- Check row counts after export [retro 2026-11-22 p1]"
p2_a = "- Clear cache on schema change [retro 2026-11-21 p2]"
self.write(os.path.join(self.mkdir(self.data, "rules"), "user.md"), "\n".join([own, old_u, old_m, p1_a, p1_b]) + "\n")
self.write(os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md"), "\n".join([p2_a, "- Old project rule [retro 2026-11-20]"]) + "\n")
listing = self.sisi("rules")[1]
for plain in (own, old_u, old_m, "- Old project rule [retro 2026-11-20]"):
self.assertIn(plain + "\n", listing + "\n")
self.assertNotIn(plain + " (p", listing)
brief = self.sisi("rules", "organize")[1]
self.assertIn(p1_a + " (p1: came back 2x since)", brief)
self.assertIn(p2_a + " (p2: came back 1x since)", brief)
# Worker merges p1_a + p1_b keeping p1, merges p1 + p2 keeping both, and accidentally copies a (pN: ...) note on a kept line and drop line
ans = self.write(os.path.join(self.tmp, "merge.md"), "\n".join([
"## user",
own,
old_u,
"- Check row counts before and after export [retro 2026-11-20, 2026-11-22 p1]",
"## project",
"- Check export counts and clear cache [retro 2026-11-20 p1, 2026-11-21 p2] (p1: came back 2x since; p2: came back 1x since)",
"## drops",
"- %s | #- | old merged replaced" % old_m[2:],
"- %s (p1: came back 2x since) | #1 | merged into combined count check" % p1_a[2:],
"- %s | #1 | merged into combined count check" % p1_b[2:],
"- %s (p2: came back 1x since) | #2 | merged with count check" % p2_a[2:],
"- Old project rule [retro 2026-11-20] | #- | obsolete",
]) + "\n")
rc, out, err = self.sisi("rules", "organize", "--record", ans)
self.assertEqual((rc, err), (0, ""), out)
self.assertNotIn("no reason recorded", out)
user_after = self.read(self.data, "rules", "user.md")
proj_after = self.read(self.proj, ".sisi", "rules.md")
book_after = self.read(self.data, "generated", "core.md")
self.assertIn("- Check row counts before and after export [retro 2026-11-20, 2026-11-22 p1]", user_after)
self.assertIn("- Check export counts and clear cache [retro 2026-11-20 p1, 2026-11-21 p2]", proj_after)
for saved in (user_after, proj_after, book_after):
self.assertNotIn("came back", saved)
self.assertNotIn("not seen since", saved)
listing2 = self.sisi("rules")[1]
self.assertIn("- Check row counts before and after export [retro 2026-11-20, 2026-11-22 p1] (p1: came back 1x since)", listing2)
self.assertIn("- Check export counts and clear cache [retro 2026-11-20 p1, 2026-11-21 p2] (p1: came back 2x since; p2: came back 1x since)", listing2)
def test_the_product_stays_small(self): 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"))) code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py")))
self.assertLessEqual(code, 2472, "sisi is two loops. If it needs more than this, find the simpler shape.") self.assertLessEqual(code, 2509, "sisi is two loops. If it needs more than this, find the simpler shape.")
rulebook = self.read(REPO, "canon", "core.md") rulebook = self.read(REPO, "canon", "core.md")
self.assertLess(len(rulebook.splitlines()), 139) self.assertLess(len(rulebook.splitlines()), 139)
self.assertLessEqual(len(rulebook), 10711) self.assertLessEqual(len(rulebook), 10711)