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:
1 parent
064cd6f5ca
commit
2a68ead05f
5 files changed
+192
-83
No files matched your search
@@ -92,8 +92,8 @@ its limits are.
|
||||
| `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) |
|
||||
| `sisi retro --later …` | The work is not finished yet |
|
||||
| `sisi learn --level core\|user\|project "…" [--means "…"]` | The person's own words become a rule at once, tagged `[owner]` only when they appear in the person's recent messages in this session. `--means` adds, in the same undoable step, one line saying how the agent will apply it |
|
||||
| `sisi rules move "<start of a rule>" core\|user\|project\|canon [--project PATH]` | Move one rule line, verbatim, to another level in one change one `sisi rules revert` undoes (core is a queue for the product, in force as a user rule until it is added to canon/core.md, then `canon` takes it out of the queue); a level is always named, `project` needs a git repo, and organize also audits placement every `audit_after` (12) retros |
|
||||
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons; an optional `## drops` section can record a reason and matching problem number for any dropped or merged rule, with `none given` recorded when omitted); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `organize`), in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) |
|
||||
| `sisi rules move "<start of a rule>" core\|user\|project\|canon [--project PATH]` | Move one rule line, verbatim, to another level, and print the command that moves it back: `sisi rules revert` does not undo a move (core is a queue for the product, in force as a user rule until it is added to canon/core.md, then `canon` takes it out of the queue); a level is always named, `project` needs a git repo, and organize also audits placement every `audit_after` (12) retros |
|
||||
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons; an optional `## drops` section can record a reason and matching problem number for any dropped or merged rule, with `none given` recorded when omitted); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `organize`), in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; after `sisi rules move`, or an `organize` that moved lines between levels, it changes nothing and prints the command(s) that move them back, which that command also printed; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) |
|
||||
| `sisi models` / `sisi models research [--record FILE]` | The workers table (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it |
|
||||
| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first, `--newest` the newest |
|
||||
| `sisi judge WORKER extend MINUTES "<reason>" [--newest]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest) gets MINUTES more from now, and its late fault clears |
|
||||
|
||||
+3
-3
@@ -22,9 +22,9 @@ The learning loop
|
||||
sisi rules organize [--record FILE]
|
||||
the brief for a cheap worker to audit and organize them; record its answer
|
||||
sisi rules move "<start>" core|user|project|canon [--project PATH]
|
||||
move one rule to another level (canon: out of the queue once it is in canon/core.md)
|
||||
sisi rules revert undo the last learn, retro, organize or move (a second re-applies it); declines if
|
||||
a project file it touched changed since
|
||||
move one rule to another level (canon: out of the queue once in canon/core.md)
|
||||
sisi rules revert undo the last learn, retro or organize (a second re-applies it); declines if the
|
||||
project file changed since; a move is not undone: both print the command back
|
||||
|
||||
Delegation
|
||||
sisi models the workers you have: what each is good at and what it costs
|
||||
|
||||
+59
-68
@@ -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
|
||||
|
||||
|
||||
|
||||
+9
-1
@@ -113,8 +113,8 @@ def git(args, cwd, timeout=15):
|
||||
def commit(message, *paths, put=None):
|
||||
"""One commit in the person's store holding only these paths, so the change can be undone on its own. `put` ({path: text})
|
||||
is written under the lock and committed too: another process's `git add` never reads a file as it is replaced."""
|
||||
history()
|
||||
with lock("store"):
|
||||
os.path.isdir(os.path.join(DATA, ".git")) or git(["init", "-q"], DATA)
|
||||
[write(p, text) for p, text in (put or {}).items()]
|
||||
rel = [os.path.relpath(p, DATA) for p in (*paths, *(put or {}))]
|
||||
return (git(["add", "-A", "--"] + rel, DATA)[0] == 0 and
|
||||
@@ -122,6 +122,14 @@ def commit(message, *paths, put=None):
|
||||
git(["-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "-m", message, "--"] + rel, DATA)[0] == 0))
|
||||
|
||||
|
||||
def history():
|
||||
"""Start the store's git history once, holding the rules as they are, so no undo goes back past them."""
|
||||
if not os.path.isdir(os.path.join(DATA, ".git")):
|
||||
with lock("store"):
|
||||
os.path.isdir(os.path.join(DATA, ".git")) or [git(a, DATA) for a in (["init", "-q"], ["add", "-A", "--", "rules"], [
|
||||
"-c", "user.name=sisi", "-c", "user.email=sisi@localhost", "commit", "-q", "--allow-empty", "-m", "rules before sisi kept history"])]
|
||||
|
||||
|
||||
_roots = {}
|
||||
|
||||
|
||||
|
||||
+119
-9
@@ -3,7 +3,7 @@
|
||||
Learning: work is done, the retro is forced, its improvement is a rule in the next session, the rules are
|
||||
organized and the change can be undone. Delegation: the lead is stopped when it should be delegating, and the
|
||||
models table is researched, read and kept fresh."""
|
||||
import glob, hashlib, json, os, random, re, shutil, subprocess, sys, tempfile, time, unittest
|
||||
import glob, hashlib, json, os, random, re, shlex, shutil, subprocess, sys, tempfile, time, unittest
|
||||
from unittest import mock
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
@@ -1024,7 +1024,7 @@ class Core(unittest.TestCase):
|
||||
self.assertEqual(len(out.strip().splitlines()), 1, (label, out))
|
||||
self.assertEqual(self.read(target), "keep me intact\n", label)
|
||||
self.assertEqual(subprocess.run(["git", "log", "--oneline"], cwd=self.data, capture_output=True, text=True, check=True).stdout, log_before, label)
|
||||
self.assertEqual(subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True, check=True).stdout, "", label)
|
||||
self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True, check=True).stdout, "", label)
|
||||
|
||||
def test_revert_declines_relative_dotdot_and_dotgit_paths(self):
|
||||
self.mkdir(self.data, "rules")
|
||||
@@ -1052,7 +1052,7 @@ class Core(unittest.TestCase):
|
||||
self.assertIn("cannot be undone", out, label)
|
||||
self.assertEqual(self.read(real_file), content, label)
|
||||
self.assertEqual(subprocess.run(["git", "log", "--oneline"], cwd=self.data, capture_output=True, text=True, check=True).stdout, log_before, label)
|
||||
self.assertEqual(subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True, check=True).stdout, "", label)
|
||||
self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True, check=True).stdout, "", label)
|
||||
|
||||
def test_hostile_project_rules_and_agents_files_do_not_hang_or_leak(self):
|
||||
import stat
|
||||
@@ -1213,7 +1213,7 @@ class Core(unittest.TestCase):
|
||||
self.sisi("learn", "--project", "Initial rule before race")
|
||||
rules_file = os.path.join(self.proj, ".sisi", "rules.md")
|
||||
started, second_done, errs = threading.Event(), threading.Event(), []
|
||||
real_commit, count = rules._commit, [0]
|
||||
real_commit, count = store.commit, [0]
|
||||
def wrapped_commit(*a, **kw):
|
||||
count[0] += 1
|
||||
if count[0] == 1:
|
||||
@@ -1233,7 +1233,7 @@ class Core(unittest.TestCase):
|
||||
os.chdir(self.tmp)
|
||||
try:
|
||||
with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \
|
||||
mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(rules, "_commit", wrapped_commit):
|
||||
mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "commit", wrapped_commit):
|
||||
t1 = threading.Thread(target=worker, args=("First concurrent project rule",))
|
||||
t1.start()
|
||||
self.assertTrue(started.wait(15))
|
||||
@@ -4115,7 +4115,7 @@ cli.main(["tick"])
|
||||
def sides(self, *paths):
|
||||
return [self.read(p) if os.path.exists(p) else None for p in paths]
|
||||
|
||||
def test_one_move_is_one_undo_in_every_direction(self): # finding 1, invariant 2
|
||||
def test_a_move_names_the_command_that_moves_it_back_in_every_direction(self): # finding 1, invariant 2; fix review: revert does not undo a move
|
||||
other = self.project("beta")
|
||||
user, core = os.path.join(self.data, "rules", "user.md"), os.path.join(self.data, "rules", "core.md")
|
||||
here, there = os.path.join(self.proj, ".sisi", "rules.md"), os.path.join(other, ".sisi", "rules.md")
|
||||
@@ -4135,8 +4135,11 @@ cli.main(["tick"])
|
||||
moved = self.sides(src, dst)
|
||||
self.assertEqual((moved[0] or "").count(text), 0, (frm, to))
|
||||
self.assertEqual(moved[1].count(text), 1, (frm, to))
|
||||
rc, out, _ = self.sisi("rules", "revert", cwd=lcwd)
|
||||
self.assertEqual(rc, 0, out)
|
||||
rc, back, _ = self.sisi("rules", "revert", cwd=lcwd)
|
||||
self.assertEqual(rc, 1, back)
|
||||
self.assertIn("Nothing was changed", back)
|
||||
self.assertEqual(self.sides(src, dst), moved, (frm, to))
|
||||
self.assertEqual(self.run_back(out), 1)
|
||||
self.assertEqual(self.sides(src, dst)[0], before[0], (frm, to))
|
||||
self.assertEqual((self.sides(src, dst)[1] or "").count(text), 0, (frm, to))
|
||||
|
||||
@@ -4243,6 +4246,10 @@ cli.main(["tick"])
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertEqual(self.read(self.data, "rules", "core.md"), "- Kept user rule [owner 2026-11-20]\n")
|
||||
self.assertEqual(self.read(self.data, "rules", "user.md"), "")
|
||||
rc, back, _ = self.sisi("rules", "revert") # fix review: a move between levels is not undone; its command back is named
|
||||
self.assertEqual((rc, self.read(self.data, "rules", "user.md")), (1, ""), back)
|
||||
self.assertEqual(self.run_back(back), 1)
|
||||
self.assertEqual((self.read(self.data, "rules", "core.md"), self.read(self.data, "rules", "user.md")), ("", "- Kept user rule [owner 2026-11-20]\n"))
|
||||
|
||||
def test_outside_git_the_user_rules_are_organized_and_audited(self): # finding 7, invariant 4
|
||||
notes = self.mkdir(self.tmp, "notes")
|
||||
@@ -4304,9 +4311,112 @@ cli.main(["tick"])
|
||||
self.assertFalse(os.path.exists(os.path.join(self.tmp, ".sisi")))
|
||||
self.assertFalse(os.path.exists(os.path.join(self.tmp, "AGENTS.md")))
|
||||
|
||||
# the fix review (fix-review.md): a change across files is not undone by revert, which names the command that moves it back
|
||||
def run_back(self, out):
|
||||
"""Run each reverse command an output names (`sisi rules move ...`, maybe after `cd DIR &&`); returns how many."""
|
||||
cmds = [l.strip() for l in out.splitlines() if l.startswith(" ") and "sisi rules move " in l]
|
||||
for c in cmds:
|
||||
words = shlex.split(c)
|
||||
cwd = words[1] if words[0] == "cd" else None
|
||||
words = words[words.index("sisi") + 1:]
|
||||
rc, o, e = self.sisi(*words, cwd=cwd)
|
||||
self.assertEqual((rc, e), (0, ""), (c, o))
|
||||
return len(cmds)
|
||||
|
||||
def test_revert_after_a_move_in_a_store_without_history_loses_nothing(self): # fix review 1
|
||||
user, proj = os.path.join(self.data, "rules", "user.md"), os.path.join(self.proj, ".sisi", "rules.md")
|
||||
self.user_file("- Manual user rule [owner 2026-11-20]\n")
|
||||
rc, out, err = self.sisi("rules", "move", "Manual user rule", "project")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertIn("sisi rules move", out)
|
||||
rc, out, _ = self.sisi("rules", "revert")
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn("Nothing was changed", out)
|
||||
self.assertEqual((self.read(user), self.read(proj)), ("", "- Manual user rule [owner 2026-11-20]\n"))
|
||||
self.assertEqual(self.run_back(out), 1)
|
||||
self.assertEqual((self.read(user), self.read(proj)), ("- Manual user rule [owner 2026-11-20]\n", ""))
|
||||
shutil.rmtree(os.path.join(self.data, ".git")) # a first learn into a store with no history: its revert keeps what was there
|
||||
self.assertEqual(self.sisi("learn", "--level", "user", "A new user rule after the manual one")[0], 0)
|
||||
self.assertEqual(self.sisi("rules", "revert")[0], 0)
|
||||
self.assertEqual(self.read(user), "- Manual user rule [owner 2026-11-20]\n")
|
||||
|
||||
def test_revert_after_two_organizes_that_leave_the_project_list_alone(self): # fix review 2
|
||||
user, proj = os.path.join(self.data, "rules", "user.md"), os.path.join(self.mkdir(self.proj, ".sisi"), "rules.md")
|
||||
self.write(proj, "- Keep project rule [owner 2026-11-20]\n")
|
||||
self.user_file("- User rule one [retro 2026-11-20]\n- User rule two [retro 2026-11-20]\n")
|
||||
for n, users in enumerate(("- User rule one merged [retro 2026-11-20]\n", "- User rule one merged again [retro 2026-11-20]\n")):
|
||||
ans = self.write(os.path.join(self.tmp, "a%d.md" % n), "## user\n" + users + "## project\n- Keep project rule [owner 2026-11-20]\n")
|
||||
self.assertEqual(self.sisi("rules", "organize")[0], 0)
|
||||
rc, out, _ = self.sisi("rules", "organize", "--record", ans)
|
||||
self.assertEqual(rc, 0, out)
|
||||
rc, out, _ = self.sisi("rules", "revert")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertEqual(self.read(user), "- User rule one merged [retro 2026-11-20]\n")
|
||||
self.assertEqual(self.read(proj), "- Keep project rule [owner 2026-11-20]\n")
|
||||
|
||||
def test_a_store_path_with_a_trailing_slash_is_still_the_store(self): # fix review 3
|
||||
self.env["SISI_DATA"] = self.data + os.sep
|
||||
self.assertEqual(self.sisi("learn", "--level", "user", "Trailing slash rule stays one rule")[0], 0)
|
||||
rc, out, err = self.sisi("rules", "move", "Trailing slash rule", "project")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertEqual(subprocess.run(["git", "status", "--porcelain", "--", "rules"], cwd=self.data, capture_output=True, text=True).stdout, "")
|
||||
rc, out, _ = self.sisi("rules", "revert")
|
||||
self.assertIn("sisi rules move", out)
|
||||
self.assertEqual(self.read(self.proj, ".sisi", "rules.md").count("Trailing slash rule"), 1)
|
||||
self.assertEqual(self.sisi("learn", "--level", "user", "Another rule with the slash")[0], 0)
|
||||
self.assertEqual(self.sisi("rules", "revert")[0], 0)
|
||||
self.assertNotIn("Another rule", self.read(self.data, "rules", "user.md"))
|
||||
|
||||
def test_revert_after_a_move_between_projects_changes_neither(self): # fix review 4
|
||||
from sisi import rules, store
|
||||
pf, pe = self.project("pf"), self.project("pe")
|
||||
self.assertEqual(self.sisi("learn", "--level", "project", "Rule E already there", cwd=pe)[0], 0)
|
||||
self.assertEqual(self.sisi("learn", "--level", "project", "Rule F to E revert fail", cwd=pf)[0], 0)
|
||||
rc, out, err = self.sisi("rules", "move", "Rule F to E", "project", "--project", pe, cwd=pf)
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
fpath, epath = os.path.join(pf, ".sisi", "rules.md"), os.path.join(pe, ".sisi", "rules.md")
|
||||
before, real = self.sides(fpath, epath), store.write
|
||||
with mock.patch.object(store, "write", lambda p, t: (_ for _ in ()).throw(OSError("disk full")) if p == epath else real(p, t)):
|
||||
why, out = self.in_process(rules.revert)
|
||||
self.assertIn("sisi rules move", out)
|
||||
self.assertEqual(self.sides(fpath, epath), before)
|
||||
self.assertEqual(self.run_back(out), 1)
|
||||
self.assertEqual([(s or "").count("Rule F to E") for s in self.sides(fpath, epath)], [1, 0])
|
||||
|
||||
def test_organize_takes_the_user_lock_and_refuses_a_linked_drops_file(self): # fix review 5
|
||||
from sisi import rules, store
|
||||
self.user_file("- User rule to drop [retro 2026-11-20]\n- User rule kept [owner 2026-11-20]\n")
|
||||
real_lock, keys = store.lock, []
|
||||
ans = self.write(os.path.join(self.tmp, "a.md"), "## user\n- User rule kept [owner 2026-11-20]\n## project\n")
|
||||
self.in_process(rules.organize_brief, self.proj)
|
||||
with mock.patch.object(store, "lock", lambda key, wait=True: keys.append(key) or real_lock(key, wait=wait)):
|
||||
why, out = self.in_process(rules.organize_record, ans, self.proj)
|
||||
self.assertIsNone(why, out)
|
||||
self.assertIn("user", keys)
|
||||
self.assertEqual(self.sisi("rules", "revert")[0], 0)
|
||||
ext = self.write(os.path.join(self.tmp, "elsewhere.jsonl"), '{"outside": 1}\n')
|
||||
dp = os.path.join(self.data, "rules", "drops.jsonl")
|
||||
os.path.lexists(dp) and os.remove(dp)
|
||||
os.symlink(ext, dp)
|
||||
self.assertEqual(self.sisi("rules", "organize")[0], 0)
|
||||
rc, out, err = self.sisi("rules", "organize", "--record", ans)
|
||||
self.assertEqual((rc, err), (1, ""), out)
|
||||
self.assertIn("symlink", out)
|
||||
self.assertTrue(os.path.islink(dp))
|
||||
self.assertEqual(self.read(ext), '{"outside": 1}\n')
|
||||
self.assertIn("User rule to drop", self.read(self.data, "rules", "user.md"))
|
||||
|
||||
def test_rules_usage_names_canon_and_a_bad_file_is_named(self): # fix review 7
|
||||
self.assertIn("|canon", self.sisi("rules", "nonsense")[1])
|
||||
with open(self.user_file(""), "wb") as f:
|
||||
f.write(b"- bad \xff byte [retro 2026-11-20]\n")
|
||||
rc, out, _ = self.sisi("rules", "move", "bad", "project")
|
||||
self.assertEqual(rc, 1, out)
|
||||
self.assertIn("user.md is not valid UTF-8", out)
|
||||
|
||||
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")))
|
||||
self.assertLessEqual(code, 2427, "sisi is two loops. If it needs more than this, find the simpler shape.")
|
||||
self.assertLessEqual(code, 2426, "sisi is two loops. If it needs more than this, find the simpler shape.")
|
||||
rulebook = self.read(REPO, "canon", "core.md")
|
||||
self.assertLess(len(rulebook.splitlines()), 139)
|
||||
self.assertLessEqual(len(rulebook), 10711)
|
||||
|
||||
Reference in new issue
Block a user