Files
sisi/sisi/rules.py
T
swaitsandClaude Opus 5.5 2a68ead05f 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>
2026-12-01 16:28:30 -07:00

642 lines
37 KiB
Python

"""Learned rules: what retros and the person add to the instructions.
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, shlex, time
from . import store
USER, PROJECT, CORE = "user", "project", "core"
LEVELS = """The three levels: core = the sisi product itself, for every sisi user anywhere, nothing personal (queued for its maintainers, loaded as a user rule until then);
user = how this person works across all projects, their machine, accounts, providers; project = this one git repo only (its .sisi/rules.md)."""
OWNER = re.compile(r"\[owner\b[^\]]*\]")
_owner, _retro = lambda l: bool(OWNER.search(l)), lambda ls: [l for l in ls if not _owner(l)]
_snap = lambda u, p: hashlib.sha1(("\n".join(u) + "\0" + "\n".join(p)).encode()).hexdigest()[:16]
_TAGS = " [owner] lines are the person's words; [agent ...] lines are an agent's reading, which a later owner statement or a measurement overrides."
HEAD_USER = "## Learned here\n\nAdded by retros and by the person. These add to the rules above and never relax them." + _TAGS + "\n"
HEAD_PROJECT = "sisi: learned in this project (these add to the rules and never relax them)." + _TAGS
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())
ORGANIZE = """You are a worker. Do this task yourself; do not delegate it further.
Audit and organize the learned rules below. They are instructions an AI engineering agent reads at the start
of every session: the first list in every project, the second only in the project "%(name)s". Retros add to
them one line at a time, so they pile up, repeat and go stale.
The objective the rules serve: %(objective)s
Rewrite both lists so they serve that objective best:
- Merge rules that say the same thing. Drop fragments, rules that are stale or contradicted by a later one,
and rules too specific to come up again.
- Word each rule as a direct instruction with its reason, on one line, standing on its own.
- Audit where each rule is filed. %(levels)s Move a rule that sits at the wrong level, in either direction,
with its words byte-identical: a user line about one project goes to `## project` (this one; if it names another
project leave it and flag it); a project line that applies to all the person's work goes to `## user`; a line
that applies to every sisi user goes under `## core` (a queue for the product's maintainers). [owner ...] lines
may move between levels too, never reworded.
- Lines marked [owner ...] are the person's own words: copy every one of them verbatim, unchanged by even
one character (you may reorder them). Only the other lines ([retro ...], [agent ...]) may be merged, reworded or dropped.
- Flag, but do not change, any [owner ...] line whose text does not read as the person's own words (a paraphrase, an
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.
- 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').
Answer with exactly this shape and nothing else:
## user
- ...
## project
- ...
## core
- ... (only lines moved to the product queue)
## drops
- <old rule> | #<N or -> | <reason> (optional; only if any non-owner rules were dropped)
## flags
- ... (only if there are any)
=== The first list now (all projects) ===
%(user)s
=== The second list now (project "%(name)s") ===
%(project)s
=== Flagged for the person (likely wrong; propose a fix) ===
%(flagged)s
=== What recent retros found, newest last (context only) ===
%(retros)s%(evidence)s
"""
def path(scope, cwd=None):
"""Where a list is kept; for a project "" inside a git directory or bare repository, where none is kept."""
top, inside = store.root(cwd) if scope == PROJECT else ("", False)
return store.data("rules", scope + ".md") if scope in (USER, CORE) else "" if inside else os.path.join(top, ".sisi", "rules.md")
def has_project(cwd=None):
"""True inside a git repository whose root is not the home folder: the only place a project list may be written."""
top, inside = store.root(cwd)
return not inside and os.path.lexists(os.path.join(top, ".git")) and os.path.realpath(top) != os.path.realpath(store.HOME)
def refuse_level(level, cwd, cmd):
"""Why a rule may not be filed at this level (with the command to rerun), or ""."""
if level not in (CORE, USER, PROJECT):
return "name the level of this rule. %s\nRerun with --level core|user|project, e.g. `%s --level user ...`." % (LEVELS, cmd)
return "no project here (not inside a git repository, or it is the home folder), use user: `%s --level user ...`." % cmd if level == PROJECT and not has_project(cwd) else ""
def filed(level, text, cwd):
return 'filed as %s rule in %s. Wrong level? sisi rules move "%s" core|user|project' % (level, path(level, cwd), " ".join(text.split()[:5]))
def core_note(cwd):
"""At session start in the sisi repo itself: how many rules wait in the product queue."""
top = store.project_root(cwd)
n = len(lines(path(CORE))) if all(os.path.isfile(os.path.join(top, *f)) for f in (("canon", "core.md"), ("sisi", "rules.py"))) else 0
return "sisi: %d rule%s proposed for the product: add each to canon/core.md, then `sisi rules move \"<start>\" canon`; or move it elsewhere." % (n, "" if n == 1 else "s") if n else ""
def _legacy(cwd=None):
return os.path.join(store.DATA, "rules", "projects", store.project_key(cwd) + ".md")
def _parse(text):
return [l.rstrip() for l in text.lstrip("\ufeff").splitlines() if l.startswith("- ")]
def lines(p):
return _parse(store.read(p))
def _text(p):
"""What a regular file holds now, None when absent; OSError when unusable or not UTF-8."""
why, raw = store.regular(p, True)
if why:
raise OSError("%s is %s" % (p, why))
try:
return None if raw is None else raw.decode("utf-8")
except UnicodeDecodeError:
raise OSError("%s is not valid UTF-8" % p)
def _append(text, new):
return (text or "") + ("\n" if text and not text.endswith("\n") else "") + "".join(l + "\n" for l in new)
def _check_writable(p):
if not p:
raise OSError("this folder is inside a git directory or a bare repository")
for t, label, folder in ((os.path.dirname(p), os.path.basename(os.path.dirname(p)), True), (p, os.path.join(*p.split(os.sep)[-2:]), False)):
why = (("a symlink" if os.path.islink(t) else "not a directory" if os.path.lexists(t) and not os.path.isdir(t) else "") if folder
else store.regular(t)[0]) or ("read-only" if os.path.exists(t) and not os.access(t, os.W_OK) else "")
if why:
raise OSError("%s is %s" % (label, why))
if not os.path.exists(os.path.dirname(p)) and not os.access(os.path.dirname(os.path.dirname(p)), os.W_OK):
raise OSError("the project folder cannot be written")
def note(where, write=True):
"""Keep one marked note in `AGENTS.md` (write=True), or report whether it is there (write=False)."""
root = os.path.dirname(os.path.dirname(where if write else path(PROJECT, where))) or where
target, _, why = store.agents_target(root)
try:
if not target:
raise OSError(why)
if write and os.path.exists(target) and not (os.stat(target).st_mode & 0o200):
raise OSError("it is read-only")
text = _text(target) or ""
if not write:
return "in AGENTS.md" if store.NOTE_RE.search(text) else "missing from AGENTS.md"
if not store.NOTE_RE.search(text):
nl = "\r\n" if "\r\n" in text else "\n"
sep = "" if not text or text.endswith(nl * 2) else nl if text.endswith(nl) else nl * 2
store.write(target, "%s%s<!-- sisi:begin -->%s%s%s<!-- sisi:end -->%s" % (text, sep, nl, store.NOTE, nl, nl))
except OSError as e:
why = "it is not valid UTF-8" if "UTF-8" in str(e) else str(e)
return print("sisi: could not add the rules note to %s (%s)." % (os.path.join(root, "AGENTS.md"), why)) if write else "missing (%s)" % why
def _move(dest, old):
"""Move the store's old file into `.sisi/rules.md` under the project lock. Returns a warning, or ""."""
if not os.path.isfile(old):
return ""
raw = store.read(old)
try:
_check_writable(dest)
before = _text(dest)
extra = [l for l in dict.fromkeys(_parse(raw)) if l not in set(_parse(before or ""))]
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)
os.remove(old)
if not store.commit("project rules moved to .sisi/rules.md", old):
raise OSError("could not commit store")
except OSError as e:
not os.path.exists(old) and store.write(old, raw)
return "sisi: could not move this project's rules to %s (%s); keeping the copy in your store." % (dest, e)
return ""
def _migrate(cwd=None, wait=True):
"""Move this project's rules out of the store if an old file exists. Returns (rules, warning)."""
dest, old = path(PROJECT, cwd), _legacy(cwd)
msg = ("sisi: project rules are not kept inside a git directory or a bare repository." if not dest
else "sisi: %s is a link, and sisi does not use a linked .sisi; its rules are not read." % d if os.path.islink(d := os.path.dirname(dest))
else "sisi: %s is %s; its rules are not read." % (dest, why) if not os.path.isfile(old) and (why := "not a directory" if os.path.lexists(d) and not os.path.isdir(d) else store.regular(dest)[0]) else "")
if not msg and os.path.isfile(old) and os.path.realpath(store.project_root(cwd)) != os.path.realpath(store.HOME):
with store.lock(dest, wait=wait) as ok:
msg = _move(dest, old) if ok else ""
return scope_lines(PROJECT, cwd, migrate=False), msg
def scope_lines(scope, cwd=None, migrate=True):
if scope == USER:
return lines(path(USER))
if migrate:
return _migrate(cwd)[0]
dest, old = path(PROJECT, cwd), _legacy(cwd)
raw = store.regular(dest, True)[1] if dest and not os.path.islink(os.path.dirname(dest)) else None
return list(dict.fromkeys((_parse(raw.decode("utf-8", "replace")) if raw is not None else []) + lines(old)))
_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():
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):
st = contextlib.ExitStack()
[st.enter_context(store.lock(k)) for k in sorted(set(keys))]
return st
def add(text, scope, source, cwd=None, log=None, means="", raw=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
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]]
else:
_check_writable(dest)
msg = _move(dest, _legacy(cwd))
msg and print(msg)
before = _text(dest)
after = _append(before, [line, *more])
store.write(dest, after)
note(dest)
try:
log and store.append(*log)
extra = ([dest] if scope != PROJECT else []) + ([log[0]] if log else [])
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 = 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
def _fit(ls):
cfg, keep, n, chars = store.config(), set(), 0, 0
for i in range(len(ls) - 1, -1, -1):
if not _owner(ls[i]):
if n >= cfg["rules_lines"] or chars + len(ls[i]) > cfg["rules_chars"]:
break
keep.add(i)
n, chars = n + 1, chars + len(ls[i])
return [l for i, l in enumerate(ls) if _owner(l) or i in keep]
def delivered(p):
"""The newest rules that fit the budget, oldest first. The rest wait for organizing."""
return _fit(lines(p))
def build_rulebook():
"""Write the always-loaded instructions: the product's rulebook, then the person's learned rules."""
text = store.read(os.path.join(store.ROOT, "canon", "core.md")).rstrip() + "\n"
mine = _fit(lines(path(USER)) + lines(path(CORE))) # a rule queued for the product is in force here until it is in canon
if mine:
text += "\n" + HEAD_USER + "\n" + "\n".join(mine) + "\n"
out = store.data("generated", "core.md")
store.write(out, text)
try: # the copies of it that sisi put into a tool's real instructions file follow
from . import install
install.refresh(out)
except Exception:
pass # this runs inside hooks: it must never raise
return out
def project_text(cwd):
ls, note = _migrate(cwd, wait=False)
mine = _fit(ls)
return "\n".join(x for x in (note, HEAD_PROJECT + "\n" + "\n".join(mine) if mine else "") if x)
def objective():
m = re.search(r"(?ms)^## The objective\s*\n(.*?)(?=^## )", store.read(os.path.join(store.ROOT, "canon", "core.md")))
return " ".join(m.group(1).split()) if m else ""
def _organized(rel=("rules", "organized.json")):
try:
return json.loads(store.read(os.path.join(store.DATA, *rel)) or "{}")
except ValueError:
return {}
def _mark_key(scope, cwd=None):
return "rules/user.md" if scope == USER else os.path.realpath(path(PROJECT, cwd))
def due(cwd, claim=False):
"""One line when the learned rules need organizing, else ""."""
cfg, seen, cl, now, need = store.config(), _organized(), _organized(("locks", "organize.json")), time.time(), []
active = lambda c, k: type(c.get("claim:" + k)) in (int, float) and 0 <= now - c["claim:" + k] < 1800
for scope in (USER, PROJECT)[:2 if has_project(cwd) else 1]:
ls, k = _retro(scope_lines(scope, cwd, migrate=False)), _mark_key(scope, cwd)
prev = int(seen.get(k, seen.get("rules/projects/%s.md" % store.project_key(cwd), 0) if scope == PROJECT else 0))
over = len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > cfg["rules_chars"]
audit = scope == USER and len(store.read(store.data("retro.jsonl")).splitlines()) - int(seen.get("retros", 0)) >= cfg["audit_after"]
if not active(cl, k) and (over or audit or len(ls) - prev >= cfg["organize_after"]):
need.append((k, "%s rules: %d lines, %s" % (scope, len(ls), "over the budget" if over else "%d new" % (len(ls) - prev) if len(ls) - prev >= cfg["organize_after"] else "time to audit their levels")))
if not need:
return ""
if claim:
with store.lock("organize", wait=False) as ok:
cl = _organized(("locks", "organize.json")) if ok else {}
if not ok or not (need := [(k, m) for k, m in need if not active(cl, k)]):
return ""
cl.update({"claim:" + k: now for k, _ in need})
with contextlib.suppress(OSError):
store.write(store.data("locks", "organize.json"), json.dumps(cl))
return ("sisi: the learned rules need organizing (%s). In the background, give the output of "
"`sisi rules organize` to a cheap worker and record its answer with `sisi rules organize --record FILE`."
% "; ".join(m for _, m in need))
def drops_for(num=None):
return [d for d in store.records(DROPS) if num is None or d.get("problem") == num]
def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
if not probs:
return ""
cut = lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..."
head = ("\n\n=== Known problems and prior rule attempts (most recent first) ===\n"
"How to use this evidence:\n"
"- Problem has 0 misses: it has not come back yet, keep it. Has misses: the sentence did not hold, keep the latest attempt and note it in `## flags` (do not just reword).\n"
"- When merging, keep the cause; never drop a rule as redundant while its problem keeps coming back. [owner ...] rules stay verbatim.\n")
out, used = [head], len(head)
for p in sorted(probs, key=lambda x: (-x["last_idx"], -x["num"]))[:cap_p]:
n = len(p["attempts"])
ls = (["#%d: %s (opened %s, %d attempt%s, %d miss%s, last %s)" % (p["num"], cut(p["name"]), p["opened"], n, "" if n == 1 else "s", n - 1, "" if n == 2 else "es", p["last"])]
+ [" attempt [%s] cause: %s | rule: %s" % (a["date"], cut(a["cause"]), cut(a["improve"])) for a in p["attempts"]]
+ [" earlier dropped: [%s] %s -- reason: %s" % (str(d.get("ts") or "")[:10] or "?", cut(d.get("rule", "")), cut(d.get("reason", ""))) for d in reversed(drops) if d.get("problem") == p["num"]])
blk = "\n".join(ls) + "\n"
if used + len(blk) > cap_c:
for l in (ls if len(out) == 1 else ()):
if used + len(l) + 1 <= cap_c:
out.append(l + "\n"); used += len(l) + 1
break
out.append(blk); used += len(blk)
return "".join(out).rstrip("\n")
def organize_brief(cwd):
from . import retro
cfg, u, p = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd) if has_project(cwd) else []
with contextlib.suppress(OSError), store.lock("organize"):
cl = _organized(("locks", "organize.json"))
cl["snap:" + _mark_key(PROJECT, cwd)] = _snap(u, p)
store.write(store.data("locks", "organize.json"), json.dumps(cl))
return ORGANIZE % {
"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)",
"retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)",
"evidence": _evidence(retro._problems(), drops_for())}
def organize_record(answer_file, cwd):
"""Replace both lists with the worker's answer. Returns why not, or None when it is done."""
cfg = store.config()
secs = re.split(r"(?m)^(#{2,3}[ \t]*(?i:drops)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project|core)[ \t]*|## [^\n]*)$", store.read(answer_file))
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("- ")]
elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
flags += chunk
elif re.match(r"(?i)#{2,3}[ \t]*drops\b", h):
for l in chunk.splitlines():
if (m := _DROP.match(l.strip())) and (rk := _DKEY(m[1])) and (why := store.clean(m[3])[:300]):
drops.setdefault(rk, (m[2], why))
core = got.pop(CORE, [])
if set(got) != {USER, PROJECT}:
return "the answer needs a `## user` section and a `## project` section, each a list of `- ` lines"
for scope, ls in got.items():
r = _retro(ls)
if len(r) > cfg["rules_lines"] or sum(map(len, r)) > cfg["rules_chars"]:
return "the %s list is over the budget of %d lines and %d characters (it has %d and %d)" % (
scope, cfg["rules_lines"], cfg["rules_chars"], len(r), sum(map(len, r)))
proj = has_project(cwd) # outside a git project only the user list is organized
up, pp, cp = path(USER), path(PROJECT, cwd) if proj else None, path(CORE)
if not proj and got[PROJECT]:
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(USER, *filter(None, [pp])):
msg = proj and _move(pp, _legacy(cwd))
if msg:
return msg.removeprefix("sisi: ")
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False) if proj else []}
if (want := _organized(("locks", "organize.json")).get("snap:" + _mark_key(PROJECT, cwd))) and _snap(had[USER], had[PROJECT]) != want:
return "the rules changed since `sisi rules organize` ran; run `sisi rules organize` again"
every = got[USER] + got[PROJECT] + core # an owner line may change level, never a word
if miss := [l for l in had[USER] + had[PROJECT] if _owner(l) and every.count(l) < (had[USER] + had[PROJECT]).count(l)]:
return "owner rule missing or changed: %s" % miss[0]
kept = every[:]
dropped = [r for r in had[USER] + had[PROJECT] if not _owner(r) and not (r in kept and kept.remove(r) is None)]
from . import retro
nprobs = len(retro._problems()) if dropped else 0
pnum = lambda s: n if s.isascii() and s.isdigit() and len(s) <= 6 and 1 <= (n := int(s)) <= nprobs else None
recs = [(store.clean(r)[:300], pnum(h[0]), h[1]) if (h := drops.get(_DKEY(r))) else (store.clean(r)[:300], None, "none given") for r in dropped]
no_why = sum(_DKEY(r) not in drops for r in dropped)
if not any(got.values()) and not core and any(had.values()):
return "the answer holds no rules at all"
try:
seen, op, dp, ts = _organized(), store.data("rules", "organized.json"), store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S")
seen["retros"] = len(store.read(store.data("retro.jsonl")).splitlines())
seen.update({_mark_key(USER): len(_retro(got[USER])), **({_mark_key(PROJECT, cwd): len(_retro(got[PROJECT]))} if proj else {})})
seen.pop("rules/projects/%s.md" % store.project_key(cwd), None)
change = {up: (_text(up), "".join(l + "\n" for l in got[USER])), op: (_text(op), json.dumps(seen))}
if proj:
before = _text(pp)
change[pp] = (before, "".join(l + "\n" for l in got[PROJECT]) if got[PROJECT] or before is not None else None)
if core:
change[cp] = (cb := _text(cp), "".join(l + "\n" for l in dict.fromkeys(_parse(cb or "") + core)))
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 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)))
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()
if k not in ("claim:" + _mark_key(USER), "claim:" + _mark_key(PROJECT, cwd), "snap:" + _mark_key(PROJECT, cwd))}
store.write(store.data("locks", "organize.json"), json.dumps(cl))
build_rulebook()
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"))
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 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():
return "the store has uncommitted rule changes, so the previous change cannot be undone" + advice
rc, out = store.git(["log", "-1", "--format=%H %s", "--name-only", "--", *files], store.DATA)
if rc != 0 or not out.strip():
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
# 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"
try:
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)
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)
return None
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)"))
if due(cwd):
print("\n" + due(cwd))
def run(args, cwd=None):
cwd = cwd or os.getcwd()
if not args:
show(cwd)
return 0
if args[0] == "organize" and len(args) == 1:
print(organize_brief(cwd))
return 0
if args[0] == "organize" and len(args) == 3 and args[1] == "--record":
why = organize_record(args[2], cwd)
elif args[:1] == ["move"]:
why = move(args[1:], cwd)
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|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
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); 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")
if i + 1 >= len(args):
return usage
top, args = os.path.abspath(args[i + 1]), args[:i] + args[i + 2:]
if not has_project(top) or os.path.realpath(store.root(top)[0]) != os.path.realpath(top):
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
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 []
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)
src, lv, line = hits[0]
dst = path(to, to_cwd) if to != "canon" else None
if to == "canon" and lv != CORE:
return "only a rule queued for the product goes to canon, after it is added to canon/core.md; this is a %s rule" % lv
if src == dst:
return "that rule is already a %s rule" % to
if dst and (why := refuse_level(to, to_cwd, "sisi rules move")):
return why.split(": `")[0]
try:
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
if len(keep) == len(rows):
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]))})
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\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
_norm = lambda t: " ".join(re.sub(r"[\W_]+", " ", t.lower()).split())
def _said(words, cwd):
"""True when the words are a quotation of one of the person's recent messages in this session."""
try:
sid = store.current_session(cwd)
said = json.loads(store.read(store._session_path(sid)) or "{}").get("said") if sid else None
except (OSError, ValueError, AttributeError):
return False
return isinstance(said, list) and any(" %s " % _norm(words) in " %s " % _norm(m) for m in said if isinstance(m, str))
def learn(args, cwd=None):
"""`sisi learn --level core|user|project "<the person's exact words>" [--means "<how I will apply it>"]`: a rule at once; the
owner tag only when the words are found in the person's recent messages, else the agent's own tag."""
args, scope = list(args), PROJECT if "--project" in args else None
while (j := next((j for j, a in enumerate(args[:-1]) if a in ("--level", "--scope")), None)) is not None:
scope, args[j:j + 2] = args[j + 1], []
i = args.index("--means") if "--means" in args else len(args)
words, means = [a for a in args[:i] if a != "--project"], " ".join(args[i + 1:])
text = " ".join(words).strip()
if len(text.split()) < 3 or (i < len(args) and len(means.split()) < 3) or any(w.startswith("--") for w in words):
print('usage: sisi learn --level core|user|project "<what the person said, in their words>" [--means "<how I will apply it>"]')
return 1
if why := refuse_level(scope, cwd, 'sisi learn'):
print("sisi learn: " + why)
return 1
heard = _said(text, cwd)
log = os.path.join(store.DATA, "rules", "owner.log") # their exact words are kept, whatever organizing later does to the rule
try:
line, warn = add(text, scope, "owner" if heard else "agent, attributed to owner", cwd, (log, "%s %s %s" % (time.strftime("%Y-%m-%d"), scope, " ".join(text.split()))), means)
except OSError as e:
print("sisi learn: could not write %s (%s). Nothing was changed, and your words were not kept." % (path(scope, cwd) or cwd or os.getcwd(), e))
return 1
heard or print("sisi learn: these words were not found in the person's recent messages, so the rule carries the weaker tag [agent, attributed to owner]; a later owner statement or a measurement overrides it.")
print(warn or ("in force from the next session: %s" if scope != CORE else "queued for the product, in force as a user rule until then: %s") % line)
print(filed(scope, text, cwd))
return 0