Keep a marked .sisi/rules.md note in project root AGENTS.md
This commit is contained in:
1 parent
de58a13e82
commit
c1cd6d7ee3
6 files changed
+237
-43
No files matched your search
+13
-16
@@ -6,7 +6,6 @@ not installed, and nothing is touched that sisi cannot edit safely: it is left a
|
||||
import json, os, re, shutil, subprocess, sys, tempfile, time
|
||||
from . import models, rules, store
|
||||
|
||||
BLOCK = re.compile(r"<!-- sisi:begin -->\n.*?<!-- sisi:end -->\n?", re.S)
|
||||
SISI = re.compile(r"bin/sisi (tick|prompt|watch|gate)\b") # what marks a hook entry as sisi's, old or new
|
||||
SUBS = ("tick", "prompt", "watch", "gate")
|
||||
|
||||
@@ -127,24 +126,21 @@ def _rulebook(h, d, book, mode):
|
||||
return "link removed"
|
||||
return "linked"
|
||||
text = _read(target)
|
||||
block = "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n" % ("@%s\n" % book if h.get("import") else store.read(book))
|
||||
found = BLOCK.search(text)
|
||||
body = "@%s\n" % book if h.get("import") else store.read(book)
|
||||
found = store.BLOCK.search(text)
|
||||
if mode == "remove":
|
||||
if found:
|
||||
rest = BLOCK.sub("", text, count=1)
|
||||
rest = store.BLOCK.sub("", text, count=1)
|
||||
os.remove(target) if not rest else _save(target, rest)
|
||||
return "removed" if found else ""
|
||||
if not found and mode == "add":
|
||||
if not os.path.exists(target) and not h.get("import"):
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
os.symlink(book, target)
|
||||
return "linked"
|
||||
_save(target, block + text)
|
||||
if not found and mode == "add" and not os.path.exists(target) and not h.get("import"):
|
||||
os.makedirs(os.path.dirname(target), exist_ok=True)
|
||||
os.symlink(book, target)
|
||||
return "linked"
|
||||
if mode != "check" and (found or mode == "add"):
|
||||
new = store.put_block(text, body)
|
||||
new != text and _save(target, new)
|
||||
found = True
|
||||
elif found and mode != "check":
|
||||
new = BLOCK.sub(lambda m: block, text, count=1)
|
||||
if new != text:
|
||||
_save(target, new)
|
||||
if not found:
|
||||
return "MISSING (run `sisi install`)"
|
||||
return "imported" if h.get("import") else "in a marked block"
|
||||
@@ -308,8 +304,9 @@ def doctor(cwd=None):
|
||||
print("release in use: %s" % (os.path.realpath(_current()) if os.path.lexists(_current()) else "none: run `sisi release`"))
|
||||
print("your store: %s" % store.DATA)
|
||||
print("rulebook: %d lines, %d characters" % (len(book.splitlines()), len(book)))
|
||||
print("learned rules: %d for all projects, %d for this one" % (
|
||||
len(rules.lines(rules.path(rules.USER))), len(rules.scope_lines(rules.PROJECT, cwd))))
|
||||
proj_n = len(rules.scope_lines(rules.PROJECT, cwd))
|
||||
print("learned rules: %d for all projects, %d for this one" % (len(rules.lines(rules.path(rules.USER))), proj_n))
|
||||
proj_n and print("project note: %s" % rules.note(cwd, write=False))
|
||||
print("models table: %s" % ("none yet" if age is None else "%d days old" % age))
|
||||
print("sisi on PATH: %s" % (shutil.which("sisi") or "no: add ~/.local/bin to PATH (`sisi install` links it there)"))
|
||||
for h in _table():
|
||||
|
||||
+28
-6
@@ -89,7 +89,26 @@ def _check_writable(p):
|
||||
raise OSError("project folder is read-only")
|
||||
|
||||
|
||||
def _migrate(cwd=None):
|
||||
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 rules_root(where)
|
||||
target, _, why = store.agents_target(root)
|
||||
try:
|
||||
if not target:
|
||||
raise OSError(why)
|
||||
bad = (target, "it is read-only") if os.path.exists(target) else (root, "project folder is read-only")
|
||||
if write and os.path.exists(bad[0]) and not (os.stat(bad[0]).st_mode & 0o200):
|
||||
raise OSError(bad[1])
|
||||
text = open(target, "rb").read().decode("utf-8") if os.path.exists(target) else ""
|
||||
except (OSError, UnicodeDecodeError) as e:
|
||||
why = "it is not valid UTF-8" if isinstance(e, UnicodeDecodeError) 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
|
||||
if not write:
|
||||
return "in AGENTS.md" if (m := store.BLOCK.search(text)) and store.NOTE in m.group(0) else "missing from AGENTS.md"
|
||||
(new := store.put_block(text, store.NOTE, append=True)) != text and store.write(target, new)
|
||||
|
||||
|
||||
def _migrate(cwd=None, add_note=True):
|
||||
"""Move a legacy store rule file into `.sisi/rules.md`. Returns (lines, warning)."""
|
||||
dest, old_path = path(PROJECT, cwd), _legacy(cwd)
|
||||
cur = [] if os.path.islink(os.path.dirname(dest)) or os.path.islink(dest) else lines(dest)
|
||||
@@ -103,6 +122,7 @@ def _migrate(cwd=None):
|
||||
if extra or not os.path.exists(dest):
|
||||
raw = store.read(dest) if os.path.exists(dest) else ""
|
||||
store.write(dest, raw + ("\n" if raw and not raw.endswith("\n") else "") + "".join(l + "\n" for l in extra))
|
||||
add_note and note(dest)
|
||||
cur = cur + extra
|
||||
rel = os.path.relpath(old_path, store.DATA)
|
||||
if not os.path.isdir(os.path.join(store.DATA, ".git")) or store.git(["status", "--porcelain", "--", rel], store.DATA)[1].strip():
|
||||
@@ -127,11 +147,12 @@ def add(text, scope, source, cwd=None):
|
||||
store.commit("rule added (%s, %s)" % (scope, source), p)
|
||||
build_rulebook()
|
||||
return line
|
||||
_, note = _migrate(cwd)
|
||||
note and print(note)
|
||||
_, msg = _migrate(cwd, False)
|
||||
msg and print(msg)
|
||||
p = path(PROJECT, cwd)
|
||||
_check_writable(p)
|
||||
store.append(p, line)
|
||||
note(p)
|
||||
return line
|
||||
|
||||
|
||||
@@ -227,9 +248,9 @@ def organize_record(answer_file, cwd):
|
||||
if len(ls) > cfg["rules_lines"] or sum(map(len, ls)) > 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(ls), sum(map(len, ls)))
|
||||
_, note = _migrate(cwd)
|
||||
if note:
|
||||
return note.removeprefix("sisi: ")
|
||||
_, msg = _migrate(cwd, False)
|
||||
if msg:
|
||||
return msg.removeprefix("sisi: ")
|
||||
had = {scope: scope_lines(scope, cwd) for scope in got}
|
||||
if not any(got.values()) and any(had.values()):
|
||||
return "the answer holds no rules at all"
|
||||
@@ -242,6 +263,7 @@ def organize_record(answer_file, cwd):
|
||||
store.write(pp, after_proj)
|
||||
except OSError as e:
|
||||
return "could not write %s (%s)" % (pp, e)
|
||||
note(pp)
|
||||
store.write(up, "".join(l + "\n" for l in got[USER]))
|
||||
seen = _organized()
|
||||
seen[_mark_key(USER)], seen[_mark_key(PROJECT, cwd)] = len(got[USER]), len(got[PROJECT])
|
||||
|
||||
+32
-6
@@ -2,10 +2,13 @@
|
||||
|
||||
Three places: the product (this copy, never written at run time), the person's store (learned rules, the
|
||||
models table, the retro log; a git repository, so every change can be undone), and scratch (session state)."""
|
||||
import contextlib, fcntl, hashlib, json, os, stat, subprocess
|
||||
import contextlib, fcntl, hashlib, json, os, re, stat, subprocess
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
HOME = os.path.expanduser("~")
|
||||
BLOCK = re.compile(r"<!-- sisi:begin -->\r?\n.*?<!-- sisi:end -->\r?\n?", re.S)
|
||||
NOTE = "This project's learned rules are in `.sisi/rules.md`. Read that file before any work here and follow it."
|
||||
_NOTE_RE = re.compile(r"(?:\r?\n)*<!-- sisi:begin -->\r?\n" + re.escape(NOTE) + r"\r?\n<!-- sisi:end -->\r?\n?")
|
||||
def _where(own, xdg, fallback):
|
||||
"""The folder in the environment variable `own`, else `xdg`/sisi, else the default under the home."""
|
||||
base = os.environ.get(xdg)
|
||||
@@ -61,7 +64,7 @@ def records(name):
|
||||
def write(path, text):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
tmp = "%s.%d.tmp" % (path, os.getpid())
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
with open(tmp, "w", encoding="utf-8", newline="") as f:
|
||||
f.write(text)
|
||||
try:
|
||||
os.chmod(tmp, stat.S_IMODE(os.stat(path).st_mode)) # a rewritten file keeps its permissions
|
||||
@@ -70,6 +73,16 @@ def write(path, text):
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def put_block(text, body, append=False):
|
||||
"""Insert or refresh the marked sisi block in `text`, collapsing duplicates."""
|
||||
nl = "\r\n" if "\r\n" in text else "\n"
|
||||
block = "<!-- sisi:begin -->%s%s%s<!-- sisi:end -->%s" % (nl, body.rstrip("\r\n"), nl, nl)
|
||||
it = iter((block,))
|
||||
new, n = BLOCK.subn(lambda m: next(it, ""), text)
|
||||
sep = "" if not append or not text or text.endswith(nl * 2) else nl if text.endswith(nl) else nl * 2
|
||||
return new if n else (text + sep + block) if append else (block + text)
|
||||
|
||||
|
||||
def append(path, line):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
@@ -106,14 +119,27 @@ def project_key(cwd=None):
|
||||
return "%s-%s" % (os.path.basename(root) or "root", hashlib.sha1(root.encode()).hexdigest()[:8])
|
||||
|
||||
|
||||
def agents_target(root):
|
||||
"""(real_path, rel_path, "") for `root/AGENTS.md` when safe, else (None, "", reason)."""
|
||||
agents, real_root = os.path.join(root, "AGENTS.md"), os.path.realpath(root)
|
||||
real, link = os.path.realpath(agents) if os.path.islink(agents) else agents, os.path.islink(agents)
|
||||
why = ("it is a dangling symlink" if link and not os.path.exists(agents) else "it is a directory" if os.path.isdir(agents)
|
||||
else "it is a symlink outside the project" if link and os.path.commonpath([real_root, real]) != real_root
|
||||
else "it is not a regular file" if os.path.lexists(agents) and not os.path.isfile(agents) else "")
|
||||
return (None, "", why) if why else (real, os.path.relpath(real, real_root), "")
|
||||
|
||||
|
||||
def snapshot(cwd):
|
||||
"""A fingerprint of the working tree: the commit, what is uncommitted, what is untracked. "" outside git."""
|
||||
spec = ["--", ":(top)", ":(top,exclude).sisi"]
|
||||
rc, status = git(["status", "--porcelain"] + spec, cwd)
|
||||
rc, top = git(["rev-parse", "--path-format=absolute", "--show-toplevel"], cwd)
|
||||
if rc != 0:
|
||||
return ""
|
||||
head, diff = git(["rev-parse", "HEAD"], cwd)[1], git(["diff", "HEAD"] + spec, cwd)[1]
|
||||
return hashlib.sha1((head + status + diff).encode()).hexdigest()[:16]
|
||||
real, rel, _ = agents_target(top.strip())
|
||||
spec = ["--", ":(top)", ":(top,exclude).sisi"] + ([":(top,exclude)" + rel] if rel else [])
|
||||
head, status, diff = git(["rev-parse", "HEAD"], cwd)[1], git(["status", "--porcelain"] + spec, cwd)[1], git(["diff", "HEAD"] + spec, cwd)[1]
|
||||
staged = git(["diff", "--cached", "--", ":(top)" + rel], cwd)[1] if rel else ""
|
||||
body = _NOTE_RE.sub("", read(real)).rstrip("\r\n") if real and os.path.isfile(real) else ""
|
||||
return hashlib.sha1((head + status + diff + staged + "\0" + body).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def _session_path(sid):
|
||||
|
||||
Reference in new issue
Block a user