Move edge cases: exact match, dash-prefixed rules, two-level organize, final canon, rolled-back commit failures
ci / test (push) Canceled after 0s

- move prefers an exact whole-line match over a strict prefix,
  otherwise refuses listing the candidates; a leading '- ' on the
  prefix and extra spaces are accepted by collapsing whitespace.
- organize says plainly when identical lines from two levels become
  one copy, or now sit at two levels, instead of printing move-back
  commands that would lose one copy; those lines are excluded from
  the printed back commands.
- move to canon is final: it is recorded as such, revert says so
  plainly, and refusal messages name the exact command to run.
- A failed store git commit in _apply restores every file (store
  files and last-project.json included) so the store is clean, and
  both move and organize refuse naming the exact command to rerun.
- Tests: seven new reproducers (each watched failing on main), one
  updated commit-failure test whose organize half asserted the old
  leave-it-dirty behavior, size budget 2426 -> 2444.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaits committed 2026-12-01 16:48:01 -07:00
1 parent 1e1f26616e
commit 0660ee13d6
2 files changed
+122 -21

No files matched your search

+32 -14
View File
@@ -213,16 +213,24 @@ _in_store = lambda p: p.startswith(os.path.join(store.DATA, ""))
def _apply(msg, change, record):
"""Write {path: (before, after)}, files outside the store first, then one store commit with `record`; a failed write undoes all."""
try:
[store.write(p, a) for p, (b, a) in change.items() if not _in_store(p) and a is not None and a != b]
ok = store.commit(msg, put={**{p: a for p, (b, a) in change.items() if _in_store(p)}, store.data("rules", "last-project.json"): json.dumps(record)})
except OSError:
for p, (b, a) in change.items():
"""Write {path: (before, after)}, files outside the store first, then one store commit with `record`; a failed write or commit restores every file before reporting."""
rp = store.data("rules", "last-project.json")
backs = list(change.items())
def _undo():
for p, (b, a) in backs:
with contextlib.suppress(OSError):
store.write(p, b) if b is not None else os.path.lexists(p) and os.remove(p)
try:
backs.append((rp, (_text(rp), None)))
[store.write(p, a) for p, (b, a) in change.items() if not _in_store(p) and a is not None and a != b]
ok = store.commit(msg, put={**{p: a for p, (b, a) in change.items() if _in_store(p)}, rp: json.dumps(record)})
except OSError:
_undo()
raise
return "" if ok else "the change is made; it could not be recorded for undo: store git commit failed (%s)" % store.GIT_ERROR
if not ok:
_undo()
return "store git commit failed (%s)" % store.GIT_ERROR
return ""
def _back(line, now, old, lv):
@@ -456,12 +464,15 @@ def organize_record(answer_file, cwd):
change[dp] = (old, _append(old, [json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True) for r, pn, why in recs]))
[_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}
back = [_back(l, home[lv], home[f], f) for lv in now for l in dict.fromkeys(now[lv]) for f in (USER, PROJECT) if f != lv and l in had[f] and l not in now[f] + had.get(lv, [])]
flat = [l for sec in now.values() for l in sec]
over = [l for l in dict.fromkeys(flat) if sum(l in sec for sec in now.values()) > 1]
merged = [l for l in dict.fromkeys(had[USER] + had[PROJECT]) if l in had[USER] and l in had[PROJECT] and 1 <= flat.count(l) < (had[USER] + had[PROJECT]).count(l)]
back = [_back(l, home[lv], home[f], f) for lv in now for l in dict.fromkeys(now[lv]) for f in (USER, PROJECT) if f != lv and l in had[f] and l not in now[f] + had.get(lv, []) and l not in over + merged]
warn = _apply("rules organized" if proj else "rules organized (user only)", change,
{"reverse": back} if back else {"path": pp, "before": before, "after": change[pp][1]} if proj else {})
except OSError as e:
return "could not record the organized rules (%s)" % e
warn and print(warn.replace("the change is made", "the organized rules are in %s" % (pp or up)))
if warn: return "could not record the organized rules (%s); the files are restored, so run `sisi rules organize --record %s` again once the store is free" % (warn, answer_file)
proj and change[pp][1] is not None and note(pp)
with contextlib.suppress(OSError), store.lock("organize"):
cl = {k: v for k, v in _organized(("locks", "organize.json")).items()
@@ -471,6 +482,8 @@ 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("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())
back and print("Moved between levels, which `sisi rules revert` does not undo; to move them back, run:\n" + "\n".join(" " + c for c in back))
return None
@@ -496,6 +509,8 @@ def revert():
if isinstance(snap, dict) and isinstance(snap.get("reverse"), list) and all(isinstance(c, str) for c in snap["reverse"]):
print("to move them back, run:\n" + "\n".join(" " + c for c in snap["reverse"]))
return "the last rule change, `%s`, moved rules between levels, which revert does not undo; the commands above move them back" % subject
if isinstance(snap, dict) and snap.get("final"):
return "the last rule change, `%s`, took the rule into canon/core.md, which is final and cannot be undone" % subject
if snap != {} and (not isinstance(snap, dict) or not {"path", "before", "after"} <= set(snap) or not isinstance(sp := snap["path"], str)
or not os.path.isabs(sp) or os.path.normpath(sp) != sp or not sp.endswith("/.sisi/rules.md") or ".git" in sp.split(os.sep)
or any(snap[k] is not None and not isinstance(snap[k], str) for k in ("before", "after"))):
@@ -567,11 +582,13 @@ def move(args, cwd):
return "--project needs the folder of a git repository (its root)"
if len(args) != 2 or args[1] not in (CORE, USER, PROJECT, "canon"):
return usage
start, to, to_cwd = args[0].strip().removeprefix("- ").strip(), args[1], top or cwd
start, to, to_cwd = " ".join(args[0].split()), args[1], top or cwd
forms = [f for f in ([start, start[2:]] if start.startswith("- ") else [start]) if f]
homes = {path(lv, c): (lv, c) for lv, c in [(CORE, cwd), (USER, cwd)] + [(PROJECT, c) for c in (cwd, top) if c and has_project(c)]}
hits = [(p, lv, l) for p, (lv, c) in homes.items() for l in dict.fromkeys(scope_lines(lv, c) if lv == PROJECT else lines(p)) if l[2:].startswith(start)] if start else []
hits = [(p, lv, l) for p, (lv, c) in homes.items() for l in dict.fromkeys(scope_lines(lv, c) if lv == PROJECT else lines(p)) if any(" ".join(l[2:].split()).startswith(f) for f in forms)]
hits = [h for h in hits if any(" ".join(h[2][2:].split()) == f for f in forms)] or hits
if len(hits) != 1:
return "no rule line starts with that" if not hits else "more than one rule starts with that; give more of it:\n" + "\n".join(" [%s] %s" % (lv, l) for _, lv, l in hits)
return "no rule line starts with that; run `sisi rules` to see the rules" if not hits else "more than one rule starts with that; give more of it:\n" + "\n".join(" [%s] %s" % (lv, l) for _, lv, l in hits)
src, lv, line = hits[0]
dst = path(to, to_cwd) if to != "canon" else None
if to == "canon" and lv != CORE:
@@ -591,12 +608,13 @@ def move(args, cwd):
change = {src: (b_src, "".join(keep))}
dst and change.update({dst: (b_dst, b_dst if line in _parse(b_dst or "") else _append(b_dst, [line]))})
back = dst and _back(line, dst, src, lv)
warn = _apply("rule moved (%s to %s)" % (lv, to), change, {"reverse": [back]} if dst else {})
warn = _apply("rule moved (%s to %s)" % (lv, to), change, {"reverse": [back]} if dst else {"final": "canon"})
except OSError as e:
return "could not move it (%s)" % e
if warn: return "could not move it (%s); the files are restored, so run it again once the store is free: sisi rules move %s %s%s" % (warn, shlex.quote(args[0]), args[1], " --project " + shlex.quote(top) if top else "")
to == PROJECT and note(dst)
build_rulebook()
print(warn or ("moved to %s: %s\nto move it back (`sisi rules revert` does not undo a move), run:\n %s" % (to, line, back) if dst else "removed from the product queue: %s" % line))
print("moved to %s: %s\nto move it back (`sisi rules revert` does not undo a move), run:\n %s" % (to, line, back) if dst else "removed from the product queue into canon/core.md, which is final: %s" % line)
return None