rules move and organize never lose or duplicate a rule; one move is one undo
ci / test (push) Waiting to run
ci / test (push) Waiting to run
Validate source and target before any write; write project files then one store commit carrying every project file's undo record, rolling all back on a failed write. Queued core rules load as user rules until moved to canon. Organize records user-only work outside git so the level audit runs there. Fixes the ten findings of the strict-placement review, each with an acceptance test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
058d6e3e56
commit
064cd6f5ca
6 files changed
+343
-103
No files matched your search
+133
-92
@@ -7,7 +7,7 @@ import contextlib, hashlib, json, os, re, 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, never loaded);
|
||||
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)]
|
||||
@@ -101,7 +101,7 @@ 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 or move it (sisi rules move)." % (n, "" if n == 1 else "s") if n else ""
|
||||
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):
|
||||
@@ -134,7 +134,7 @@ def _append(text, 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), ".sisi", True), (p, ".sisi/rules.md", False)):
|
||||
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:
|
||||
@@ -194,7 +194,7 @@ def _migrate(cwd=None, wait=True):
|
||||
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):
|
||||
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
|
||||
@@ -212,11 +212,43 @@ def scope_lines(scope, cwd=None, migrate=True):
|
||||
|
||||
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")
|
||||
put = dict(put or {}, **({store.data("rules", "last-project.json"): json.dumps(dict(zip(("path", "before", "after"), snap)))} if snap else {}))
|
||||
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)
|
||||
|
||||
|
||||
def _holds(p, text):
|
||||
try:
|
||||
with open(p, "rb") as f:
|
||||
return f.read() == (text or "").encode() if text is not None else False
|
||||
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
|
||||
|
||||
|
||||
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):
|
||||
@@ -243,7 +275,7 @@ def add(text, scope, source, cwd=None, log=None, means="", raw=None):
|
||||
warn = ""
|
||||
except OSError as e:
|
||||
warn = "the rule is in %s; it could not be recorded for undo: %s" % (dest, e)
|
||||
scope == USER and build_rulebook()
|
||||
scope != PROJECT and build_rulebook()
|
||||
return line, warn
|
||||
|
||||
|
||||
@@ -266,7 +298,7 @@ def delivered(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 = delivered(path(USER))
|
||||
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")
|
||||
@@ -305,11 +337,11 @@ 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):
|
||||
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 has_project(cwd) and len(store.read(store.data("retro.jsonl")).splitlines()) - int(seen.get("retros", 0)) >= cfg["audit_after"]
|
||||
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:
|
||||
@@ -357,7 +389,7 @@ def _evidence(probs, drops, cap_p=15, cap_c=5000, cap_f=180):
|
||||
|
||||
def organize_brief(cwd):
|
||||
from . import retro
|
||||
cfg, u, p = store.config(), lines(path(USER)), scope_lines(PROJECT, cwd)
|
||||
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)
|
||||
@@ -366,7 +398,7 @@ def organize_brief(cwd):
|
||||
"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)",
|
||||
"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())}
|
||||
|
||||
@@ -393,16 +425,17 @@ def organize_record(answer_file, cwd):
|
||||
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)))
|
||||
up, pp, cp = path(USER), path(PROJECT, cwd), path(CORE)
|
||||
if not has_project(cwd):
|
||||
return "no project here, so there is no project list to organize; run it from inside a git project"
|
||||
if not pp or os.path.islink(os.path.dirname(pp)):
|
||||
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 store.lock(pp):
|
||||
msg = _move(pp, _legacy(cwd))
|
||||
with _locks(pp or "user"):
|
||||
msg = proj and _move(pp, _legacy(cwd))
|
||||
if msg:
|
||||
return msg.removeprefix("sisi: ")
|
||||
had = {USER: lines(up), PROJECT: scope_lines(PROJECT, cwd, migrate=False)}
|
||||
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
|
||||
@@ -415,33 +448,28 @@ def organize_record(answer_file, cwd):
|
||||
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 any(had.values()):
|
||||
if not any(got.values()) and not core and any(had.values()):
|
||||
return "the answer holds no rules at all"
|
||||
try:
|
||||
before = _text(pp)
|
||||
after = "".join(l + "\n" for l in got[PROJECT]) if got[PROJECT] or before is not None else None
|
||||
after is not None and _check_writable(pp)
|
||||
wrote = after is not None and after != before
|
||||
wrote and store.write(pp, after)
|
||||
except OSError as e:
|
||||
return "could not write %s (%s)" % (pp, e)
|
||||
after is not None and note(pp)
|
||||
utext = "".join(l + "\n" for l in got[USER])
|
||||
try:
|
||||
seen = _organized()
|
||||
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]))})
|
||||
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)
|
||||
dp, ts = store.data(DROPS), time.strftime("%Y-%m-%dT%H:%M:%S")
|
||||
for r, pn, why in recs:
|
||||
store.append(dp, json.dumps({"ts": ts, "rule": r, "problem": pn, "reason": why}, sort_keys=True))
|
||||
_commit("rules organized", *([dp] if recs else []), snap=(pp, before, after), put={up: utext, **({cp: "".join(l + "\n" for l in dict.fromkeys(lines(cp) + core))} if core else {}), store.data("rules", "organized.json"): json.dumps(seen)})
|
||||
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]
|
||||
warn = _apply("rules organized" if proj else "rules organized (user only)", change)
|
||||
except OSError as e:
|
||||
(wrote_u := store.regular(up, True)[1] == utext.encode()) and build_rulebook()
|
||||
if not wrote and not wrote_u:
|
||||
return "could not write %s (%s)" % (up, e)
|
||||
print("the organized rules are in %s; they could not be recorded for undo: %s" % (pp if wrote else up, e))
|
||||
return None
|
||||
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))}
|
||||
@@ -465,32 +493,39 @@ 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
|
||||
snap = {}
|
||||
if "rules/last-project.json" in changed or "(project," in subject or "organized" in subject:
|
||||
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:
|
||||
snap = json.loads(raw)
|
||||
snaps = json.loads(raw)
|
||||
except ValueError:
|
||||
snap = None
|
||||
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)
|
||||
p, (now, want) = snap.get("path"), (snap.get("before"), snap.get("after"))[::1 if redo else -1]
|
||||
with store.lock(p or "user"), store.lock("store"):
|
||||
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"):
|
||||
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:
|
||||
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))
|
||||
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)
|
||||
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))
|
||||
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))
|
||||
return "could not undo `%s`%s" % (subject, advice)
|
||||
build_rulebook()
|
||||
print("undone: %s" % subject)
|
||||
@@ -501,7 +536,7 @@ 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))), ("Learned, this project", proj)):
|
||||
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))
|
||||
@@ -529,38 +564,48 @@ def run(args, cwd=None):
|
||||
|
||||
|
||||
def move(args, cwd):
|
||||
"""`sisi rules move "<start of a rule line>" LEVEL [--project PATH]`: one line, verbatim, to another level. Returns why not, or None."""
|
||||
top = None
|
||||
"""`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."""
|
||||
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")
|
||||
top, args = os.path.abspath((args[i + 1:i + 2] or [""])[0]), args[:i] + args[i + 2:]
|
||||
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):
|
||||
return 'usage: sisi rules move "<start of a rule line>" core|user|project [--project PATH]'
|
||||
start, to = args[0].strip().removeprefix("- ").strip(), args[1]
|
||||
homes = [(CORE, cwd), (USER, cwd)] + [(PROJECT, c) for c in dict.fromkeys(c for c in (cwd if has_project(cwd) else None, top) if c)]
|
||||
hits = [(lv, c, l) for lv, c in homes for l in dict.fromkeys(scope_lines(lv, c, migrate=False) if lv == PROJECT else lines(path(lv))) if l[2:].startswith(start)] if start else []
|
||||
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)
|
||||
lv, c, line = hits[0]
|
||||
to_cwd = top or cwd
|
||||
if path(lv, c) == path(to, to_cwd):
|
||||
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 why := refuse_level(to, to_cwd, "sisi rules move"):
|
||||
if dst and (why := refuse_level(to, to_cwd, "sisi rules move")):
|
||||
return why.split(": `")[0]
|
||||
add(line, to, "move", to_cwd, raw=line)
|
||||
src = path(lv, c)
|
||||
with store.lock(src if lv == PROJECT else "user"):
|
||||
keep = (_text(src) or "").splitlines(True)
|
||||
keep.remove(next(x for x in keep if x.rstrip("\r\n") == line))
|
||||
if lv == PROJECT:
|
||||
_check_writable(src)
|
||||
store.write(src, "".join(keep))
|
||||
else:
|
||||
_commit("rule moved (%s to %s)" % (lv, to), put={src: "".join(keep)})
|
||||
lv == USER and build_rulebook()
|
||||
print("moved to %s: %s" % (to, line))
|
||||
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)
|
||||
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]))})
|
||||
warn = _apply("rule moved (%s to %s)" % (lv, to), change)
|
||||
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))
|
||||
return None
|
||||
|
||||
|
||||
@@ -580,17 +625,13 @@ def _said(words, cwd):
|
||||
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)
|
||||
args, means = list(args[:i]), " ".join(args[i + 1:])
|
||||
scope, words, i = PROJECT if "--project" in args else None, [], 0
|
||||
while i < len(args):
|
||||
if args[i] in ("--level", "--scope") and i + 1 < len(args):
|
||||
scope, i = args[i + 1], i + 2
|
||||
else:
|
||||
words += [args[i]] * (args[i] != "--project")
|
||||
i += 1
|
||||
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 (means and len(means.split()) < 3) or any(w.startswith("--") for w in words):
|
||||
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'):
|
||||
@@ -604,6 +645,6 @@ def learn(args, cwd=None):
|
||||
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, not in force: %s") % line)
|
||||
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
|
||||
Reference in new issue
Block a user