revert no longer undoes moves between levels; it names the command back

A change that moves rules between levels (sisi rules move, or an organize
that moves lines across levels) prints the exact reverse command when it
succeeds, and revert after it changes nothing and prints the same command.
Revert keeps undoing learn, retro and single-level organize. The multi-file
undo record and its restore loop are gone.

Fixes the five findings of the fix review: a store with no .git starts its
history with the rules as they are (no undo goes past them); revert reads the
undo record even when its bytes did not change; a trailing slash in SISI_DATA
is still the store; organize takes the user lock and refuses a linked
drops.jsonl. Also: rules usage names canon; a non-UTF-8 file is named.
Product code 2427 -> 2426 lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-12-01 16:28:30 -07:00
1 parent 064cd6f5ca
commit 2a68ead05f
5 files changed
+192 -83

No files matched your search

+59 -68
View File
@@ -3,7 +3,7 @@
A rule is one line. It is in force as soon as it is added: rules for all of the person's work become the last
section of the rulebook every session loads, and a project's rules live in `.sisi/rules.md` at its root.
Now and then a cheap worker audits and organizes them. Store changes are committed and can be undone."""
import contextlib, hashlib, json, os, re, time
import contextlib, hashlib, json, os, re, shlex, time
from . import store
USER, PROJECT, CORE = "user", "project", "core"
@@ -124,7 +124,7 @@ def _text(p):
try:
return None if raw is None else raw.decode("utf-8")
except UnicodeDecodeError:
raise OSError(".sisi/rules.md is not valid UTF-8")
raise OSError("%s is not valid UTF-8" % p)
def _append(text, new):
@@ -173,9 +173,8 @@ def _move(dest, old):
_check_writable(dest)
before = _text(dest)
extra = [l for l in dict.fromkeys(_parse(raw)) if l not in set(_parse(before or ""))]
rel = os.path.relpath(old, store.DATA)
uncommitted = not os.path.isdir(os.path.join(store.DATA, ".git")) or store.git(["status", "--porcelain", "--", rel], store.DATA)[1].strip()
if uncommitted and not store.commit("project rules before move to .sisi/rules.md", old):
store.history()
if store.git(["status", "--porcelain", "--", old], store.DATA)[1].strip() and not store.commit("project rules before move to .sisi/rules.md", old):
raise OSError("could not commit store")
extra and store.write(dest, _append(before, extra))
(extra or _parse(raw)) and note(dest)
@@ -210,37 +209,26 @@ def scope_lines(scope, cwd=None, migrate=True):
return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old)))
def _commit(msg, *paths, snap=None, put=None):
# `put` and the undo snapshot are written inside the store lock: another process's `git add` read them mid-replace ("short read")
snap = [dict(zip(("path", "before", "after"), s)) for s in ([snap] if isinstance(snap, tuple) else snap or [])]
put = dict(put or {}, **({store.data("rules", "last-project.json"): json.dumps(snap[0] if len(snap) == 1 else snap)} if snap else {}))
if not store.commit(msg, *paths, put=put):
raise OSError("store git commit failed (%s)" % store.GIT_ERROR)
_in_store = lambda p: p.startswith(os.path.join(store.DATA, ""))
def _holds(p, text):
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:
with open(p, "rb") as f:
return f.read() == (text or "").encode() if text is not None else False
[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:
return text is None
def _apply(msg, change):
"""Make {path: (before, after)} one change undone by one revert: the project files, then one store commit holding the
store files and the project files' undo record. A failed write puts every file back and raises; a failed commit alone warns."""
proj = [(p, b, a) for p, (b, a) in change.items() if not p.startswith(store.DATA + os.sep)]
try:
[store.write(p, a) for p, b, a in proj if a is not None and a != b]
_commit(msg, snap=proj, put={p: a for p, (b, a) in change.items() if p.startswith(store.DATA + os.sep)})
return ""
except OSError as e:
if all(_holds(p, a) for p, (b, a) in change.items()):
return "the change is made; it could not be recorded for undo: %s" % e
for p, (b, a) in change.items():
with contextlib.suppress(OSError):
store.write(p, b) if b is not None else os.path.lexists(p) and os.remove(p)
raise
return "" if ok else "the change is made; it could not be recorded for undo: store git commit failed (%s)" % store.GIT_ERROR
def _back(line, now, old, lv):
"""The command that moves `line` from file `now` back to file `old`, at level `lv`."""
here, there = [] if _in_store(now) else [os.path.dirname(os.path.dirname(now))], [os.path.dirname(os.path.dirname(old))] if lv == PROJECT else []
return ("cd %s && " % shlex.quote(here[0]) if here and there else "") + "sisi rules move %s %s" % (shlex.quote(line[2:]), lv) + "".join(" --project " + shlex.quote(r) for r in there or here)
def _locks(*keys):
@@ -257,6 +245,7 @@ def add(text, scope, source, cwd=None, log=None, means="", raw=None):
line, more = (raw, []) if raw else (line, more)
dest = path(scope, cwd)
scope == PROJECT and not dest and _check_writable(dest)
store.history()
with store.lock(dest if scope == PROJECT else "user"):
if scope != PROJECT:
[store.append(dest, l) for l in [line, *more]]
@@ -271,10 +260,11 @@ def add(text, scope, source, cwd=None, log=None, means="", raw=None):
try:
log and store.append(*log)
extra = ([dest] if scope != PROJECT else []) + ([log[0]] if log else [])
_commit("rule added (%s, %s)" % (scope, source), *extra, snap=(dest, before, after) if scope == PROJECT else None)
warn = ""
rec = {store.data("rules", "last-project.json"): json.dumps({"path": dest, "before": before, "after": after})} if scope == PROJECT else {}
warn = "" if store.commit("rule added (%s, %s)" % (scope, source), *extra, put=rec) else "store git commit failed (%s)" % store.GIT_ERROR
except OSError as e:
warn = "the rule is in %s; it could not be recorded for undo: %s" % (dest, e)
warn = str(e)
warn = warn and "the rule is in %s; it could not be recorded for undo: %s" % (dest, warn)
scope != PROJECT and build_rulebook()
return line, warn
@@ -431,7 +421,7 @@ def organize_record(answer_file, cwd):
return "no project here, so `## project` must be empty: put those lines under `## user`, or record it inside their git project"
if proj and (not pp or os.path.islink(os.path.dirname(pp))):
return _migrate(cwd)[1].removeprefix("sisi: ")
with _locks(pp or "user"):
with _locks(USER, *filter(None, [pp])):
msg = proj and _move(pp, _legacy(cwd))
if msg:
return msg.removeprefix("sisi: ")
@@ -464,8 +454,11 @@ 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]))
[_check_writable(p) for p in change if change[p][1] is not None and p != dp]
warn = _apply("rules organized" if proj else "rules organized (user only)", change)
[_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, [])]
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)))
@@ -479,11 +472,12 @@ def organize_record(answer_file, cwd):
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"))
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
def revert():
"""Undo the last rule change (learn, retro or organize): a project's list only while it holds what that change left."""
"""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)
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():
@@ -493,39 +487,36 @@ def revert():
return "there is no change to the learned rules to undo"
(commit, _, subject), changed = out.splitlines()[0].partition(" "), out.splitlines()[1:]
redo = len(re.match(r'(Revert ")*', subject).group(0)) // 8 % 2
snaps = []
if "rules/last-project.json" in changed or re.search(r'\(project,|organized"*$', subject):
raw = store.git(["show", commit + "^" * redo + ":rules/last-project.json"], store.DATA)[1] if "rules/last-project.json" in changed else ""
try:
snaps = json.loads(raw)
except ValueError:
snaps = None
snaps = snaps if isinstance(snaps, list) and snaps else [snaps]
for snap in snaps:
if (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"))):
return "the undo record for `%s` is missing, corrupt or outside .sisi/rules.md, so it cannot be undone%s" % (subject, advice)
with _locks(*([s["path"] for s in snaps] or ["user"])), store.lock("store"):
# every change that writes a project list or moves a rule writes this record, so it is read even when its bytes did not change
raw = store.git(["show", commit + "^" * redo + ":rules/last-project.json"], store.DATA)[1] if "rules/last-project.json" in changed or re.search(r'\(project,|organized"*$|^rule moved', subject) else "{}"
try:
snap = json.loads(raw)
except ValueError:
snap = None
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 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"))):
return "the undo record for `%s` is missing, corrupt or outside .sisi/rules.md, so it cannot be undone%s" % (subject, advice)
if store.git(["rev-parse", "-q", "--verify", commit + "^"], store.DATA)[0]:
return "there is no change to the learned rules to undo" # the first commit holds the rules from before sisi kept history
p, (now, want) = snap.get("path"), (snap.get("before"), snap.get("after"))[::1 if redo else -1]
with _locks(USER, *filter(None, [p])), store.lock("store"):
if store.git(["log", "-1", "--format=%H", "--", *files], store.DATA)[1].strip() != commit:
return "another rule change finished while waiting; run `sisi rules revert` again"
todo = []
try:
for snap in snaps:
p, (now, want) = snap["path"], (snap["before"], snap["after"])[::1 if redo else -1]
cur = _text(p)
if cur != now or not os.path.isdir(os.path.dirname(os.path.dirname(p))):
return "%s has changed since `%s`, or its folder moved or is gone, so that change cannot be undone%s" % (p, subject, advice)
_check_writable(p)
todo.append((p, cur, want))
for p, cur, want in todo:
os.remove(p) if want is None and cur is not None else want != cur and store.write(p, want)
cur = p and _text(p)
if p and (cur != now or not os.path.isdir(os.path.dirname(os.path.dirname(p)))):
return "%s has changed since `%s`, or its folder moved or is gone, so that change cannot be undone%s" % (p, subject, advice)
p and _check_writable(p)
p and (os.remove(p) if want is None and cur is not None else want != cur and store.write(p, want))
except OSError as e:
return "could not restore %s (%s)%s" % (p, e, advice)
if store.git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "revert", "--no-edit", commit], store.DATA)[0]:
store.git(["revert", "--abort"], store.DATA)
for p, cur, want in todo:
want != cur and (store.write(p, cur) if cur is not None else os.path.lexists(p) and os.remove(p))
p and want != cur and (store.write(p, cur) if cur is not None else os.path.lexists(p) and os.remove(p))
return "could not undo `%s`%s" % (subject, advice)
build_rulebook()
print("undone: %s" % subject)
@@ -557,7 +548,7 @@ def run(args, cwd=None):
elif args == ["revert"]:
why = revert()
else:
why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules move \"<start of a rule>\" core|user|project [--project PATH] | sisi rules revert"
why = "usage: sisi rules | sisi rules organize [--record FILE] | sisi rules move \"<start of a rule>\" core|user|project|canon [--project PATH] | sisi rules revert"
if why:
print("sisi rules: %s. Nothing was changed." % why if not why.startswith("usage") else why)
return 1 if why else 0
@@ -565,7 +556,7 @@ def run(args, cwd=None):
def move(args, cwd):
"""`sisi rules move "<start of a rule line>" LEVEL|canon [--project PATH]`: one line, verbatim, to another level (canon: out of
the product queue, once it is in canon/core.md), in one change one revert undoes. Returns why not, or None."""
the product queue, once it is in canon/core.md); it prints the command that moves it back. Returns why not, or None."""
top, usage = None, 'usage: sisi rules move "<start of a rule line>" core|user|project|canon [--project PATH]'
if "--project" in args:
i = args.index("--project")
@@ -590,9 +581,8 @@ def move(args, cwd):
if dst and (why := refuse_level(to, to_cwd, "sisi rules move")):
return why.split(": `")[0]
try:
with _locks(*("user" if p.startswith(store.DATA + os.sep) else p for p in filter(None, (src, dst)))):
for p in filter(None, (src, dst)):
_check_writable(p)
with _locks(*(USER if _in_store(p) else p for p in filter(None, (src, dst)))):
[_check_writable(p) for p in filter(None, (src, dst))]
b_src, b_dst = _text(src), dst and _text(dst)
rows = (b_src or "").lstrip("\ufeff").splitlines(True)
keep = [x for x in rows if x.rstrip() != line] # every copy of the line: one rule
@@ -600,12 +590,13 @@ def move(args, cwd):
return "that line is in %s only in an older copy; run `sisi rules` once, then move it" % src
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]))})
warn = _apply("rule moved (%s to %s)" % (lv, to), change)
back = dst and _back(line, dst, src, lv)
warn = _apply("rule moved (%s to %s)" % (lv, to), change, {"reverse": [back]} if dst else {})
except OSError as e:
return "could not move it (%s)" % e
to == PROJECT and note(dst)
build_rulebook()
print(warn or ("moved to %s: %s" % (to, line) if dst else "removed from the product queue: %s" % line))
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))
return None