Files
sisi/sisi/rules.py
T
2026-12-02 13:27:54 -07:00

725 lines
43 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, PROBLEMS = "rules/drops.jsonl", "rules/problems.json"
_DROP = re.compile(r"^(?:[-*]|\d+\.)\s+(.+?)\s*\|\s*#(\d+|-)\s*\|\s*(\S.*)$")
_NOTE = re.compile(r"(?:\s+\(p\d+: (?:came back \d+x|not seen) since(?:; p\d+: (?:came back \d+x|not seen) since)*\))+$")
_RETRO_TAG, _DATE = re.compile(r"(?:\s*\[retro\b[^\]]*\])+$"), re.compile(r"\d{4}-\d{2}-\d{2}")
_DKEY = lambda s: " ".join(re.sub(r"(?i)(?:\s*\[(?:retro|agent)\b[^\]]*\])+$", "", _NOTE.sub("", re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s.replace("`", "")).strip())).lower().split())
ORGANIZE = """sisi chore: rules 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 (and any pN tag, including on merged rules) at the end of every line, without any trailing (pN: ...) note. A rule whose problem came back after it was written should be reworked or turned into a check.
- A `better` that recurs across retros has earned a rule: add it, worded as an instruction, marked [retro <date>].
- 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)
## same problems
N = M (optional; merge duplicate problem M into older N)
## 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)
ls = lines(old) # store copy first: writers fill the project file before removing it, so a no-wait read never misses both
raw = store.regular(dest, True)[1] if dest and not os.path.islink(os.path.dirname(dest)) else None
return list(dict.fromkeys(ls + ((_parse(raw.decode("utf-8", "replace"))) if raw is not None else [])))
_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 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
if not ok:
_undo()
return "store git commit failed (%s)" % store.GIT_ERROR
return ""
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, problem=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")
d = time.strftime("%Y-%m-%d")
line, *more = ["- %s [%s %s%s]" % (" ".join(str(t).split()), src, d, " p%d" % p if p else "") for t, src, p in ((text, source, problem), (means, "agent reading", None)) if t] # one commit holds both
line, more = (raw, []) if raw else (line, more)
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, delegate just the first line of the output of "
"`sisi rules organize` plus \"Run `sisi chore show <id>` and do what it says\" 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):
from . import retro
amap = retro._aliases() if num is not None else {}
return [d for d in store.records(DROPS) if num is None or amap.get(d.get("problem"), d.get("problem")) == num]
def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
canon = [p for p in probs if not p.get("into")]
if not canon:
return ""
amap, cut = {p["num"]: p["into"] for p in probs if p.get("into")}, lambda s: s if len(s) <= cap_f else s[:cap_f - 3] + "..."
all_p = "\n\n=== Every known problem (list duplicates under ## same problems as N = M, older first) ===\n" + "\n".join(
"#%d: %s | cause: %s" % (p["num"], cut(p["name"]), cut(next((a["cause"] for a in p["attempts"] if a["cause"]), "") or "(none)")) for p in canon)
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(canon, 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 amap.get(d.get("problem"), 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 all_p + "".join(out).rstrip("\n")
def _rule_probs(line):
"""Return [(problem_num, rule_date), ...] from trailing [retro ...] tags, or []."""
m = _RETRO_TAG.search(line)
dates = _DATE.findall(m.group(0)) if m else []
if not dates:
return []
cur, out = max(dates), {}
for d, p in re.findall(r"(\d{4}-\d{2}-\d{2})|\bp(\d{1,6})\b", m.group(0)):
if d:
cur = d
elif (n := int(p)) >= 1:
out[n] = max(out.get(n, ""), cur)
return list(out.items())
def _annotate(ls, probs):
"""Append per-rule problem recurrence notes for display in `sisi rules` and `organize_brief`."""
out = []
for l in ls:
if not (ps := _rule_probs(l)):
out.append(l)
continue
notes = []
for n, d in ps:
p = probs[n - 1] if 1 <= n <= len(probs) else None
p = probs[p["into"] - 1] if p and p.get("into") else p
c = sum(bool(_DATE.fullmatch(a["date"])) and a["date"] > d for a in (p["attempts"] if p else ()))
notes.append("p%d: came back %dx since" % (n, c) if c else "p%d: not seen since" % n)
out.append("%s (%s)" % (l, "; ".join(notes)))
return out
def organize_brief(cwd):
from . import retro
cfg, u, p, probs = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd) if has_project(cwd) else [], retro._problems()
with contextlib.suppress(OSError), store.lock("organize"):
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(_annotate(u, probs)) or "(none)",
"project": "\n".join(_annotate(p, probs)) or "(none)" if has_project(cwd) else "(not in a git project: leave `## project` empty)",
"retros": "\n".join(store.read(store.data("retro.jsonl")).splitlines()[-40:]) or "(none)",
"evidence": _evidence(probs, 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|same problems)\b[^\n]*|##[ \t]*(?i:flags)[ \t]*|## (?:user|project|core)[ \t]*|## [^\n]*)$", store.read(answer_file))
got, flags, drops, same_lines = {}, "", {}, []
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 if _owner(l) else _NOTE.sub("", l) for l in (x.rstrip() for x in chunk.splitlines() if x.startswith("- "))]
elif re.fullmatch(r"(?i)##[ \t]*flags[ \t]*", h):
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))
elif re.match(r"(?i)#{2,3}[ \t]*same problems\b", h):
same_lines += [x.strip() for x in chunk.splitlines() if x.strip() and x.strip().lower() not in ("none", "(none)") and not x.strip().startswith("```")]
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 or same_lines 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)
old_amap = retro._aliases() if same_lines else {}
amap, bad_same = dict(old_amap), []
for raw_l in same_lines:
m = re.fullmatch(r"(?:[-*]\s+)?#?(\d{1,6})\s*=\s*#?(\d{1,6})(?:\s+(?:#|\(|//|-).*|\s*\|.*)?", raw_l)
n, k = (int(m[1]), int(m[2])) if m else (0, 0)
rn = retro._alias_root(amap, n) if m else 0
why_bad = ("expected N = M" if not m else "unknown problem number" if not (1 <= n <= nprobs and 1 <= k <= nprobs)
else "cycle" if rn == k else "already merged" if k in amap and retro._alias_root(amap, k) != rn else "")
bad_same.append((raw_l, why_bad)) if why_bad else amap.__setitem__(k, rn)
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]))
if amap != old_amap:
ap = store.data(PROBLEMS)
change[ap] = (_text(ap), json.dumps({str(k): v for k, v in sorted(amap.items())}, sort_keys=True))
[_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}
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
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()
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"))
[print("skipped same problems line '%s' (%s)" % b) for b in bad_same]
[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
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, PROBLEMS)
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 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"))):
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)
groups = (("Learned, all projects", lines(path(USER))), ("Queued for the product (in force as user rules until then)", lines(path(CORE))), ("Learned, this project", proj))
from . import retro
probs = retro._problems() if any(_rule_probs(l) for _, ls in groups for l in ls) else []
for title, ls in groups:
print("\n%s (%d):\n%s" % (title, len(ls), "\n".join(_annotate(ls, probs)) or " (none)"))
if due(cwd):
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:
from . import plan
plan.issue("rules organize", organize_brief(cwd), 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 = " ".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)]}
dst = path(to, to_cwd) if to != "canon" else None
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
hits = [h for h in hits if h[0] != dst] or hits
if len(hits) != 1:
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]
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 {"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("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
_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