Fix AGENTS.md note handling, snapshot cost/false-alarm, and read-only doctor

This commit is contained in:
swaits committed 2026-11-24 19:12:25 -07:00
1 parent c1cd6d7ee3
commit a540bd45ff
5 files changed
+243 -54

No files matched your search

+14 -12
View File
@@ -6,6 +6,7 @@ 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")
@@ -126,21 +127,22 @@ def _rulebook(h, d, book, mode):
return "link removed"
return "linked"
text = _read(target)
body = "@%s\n" % book if h.get("import") else store.read(book)
found = store.BLOCK.search(text)
block = "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n" % ("@%s\n" % book if h.get("import") else store.read(book))
found = BLOCK.search(text)
if mode == "remove":
if found:
rest = store.BLOCK.sub("", text, count=1)
rest = 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" 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)
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)
found = True
elif found and mode != "check":
(new := BLOCK.sub(lambda m: block, text, count=1)) != text and _save(target, new)
if not found:
return "MISSING (run `sisi install`)"
return "imported" if h.get("import") else "in a marked block"
@@ -304,8 +306,8 @@ 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)))
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 = len(rules.scope_lines(rules.PROJECT, cwd, migrate=False))
print("learned rules: %d for all projects, %d for this one%s" % (len(rules.lines(rules.path(rules.USER))), proj_n, " (waiting to be moved from store)" if os.path.isfile(rules._legacy(cwd)) else ""))
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)"))
+10 -8
View File
@@ -96,16 +96,18 @@ def note(where, write=True):
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])
if write and os.path.exists(target) and not (os.stat(target).st_mode & 0o200):
raise OSError("it is read-only")
text = open(target, "rb").read().decode("utf-8") if os.path.exists(target) else ""
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, 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):
@@ -134,8 +136,8 @@ def _migrate(cwd=None, add_note=True):
return list(dict.fromkeys(cur + old)), "sisi: could not move this project's rules to %s (%s); keeping the copy in your store." % (dest, e)
def scope_lines(scope, cwd=None):
return lines(path(USER)) if scope == USER else _migrate(cwd)[0]
def scope_lines(scope, cwd=None, migrate=True):
return lines(path(USER)) if scope == USER else _migrate(cwd)[0] if migrate else list(dict.fromkeys(lines(path(PROJECT, cwd)) + lines(_legacy(cwd))))
def add(text, scope, source, cwd=None):
+21 -27
View File
@@ -6,9 +6,8 @@ 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?")
NOTE_RE = re.compile(r"^<!-- sisi:begin -->\r?\n" + re.escape(NOTE) + r"\r?\n<!-- sisi:end -->(?:\r?\n|$)", re.M)
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)
@@ -64,23 +63,16 @@ 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", newline="") as f:
f.write(text)
try:
os.chmod(tmp, stat.S_IMODE(os.stat(path).st_mode)) # a rewritten file keeps its permissions
except OSError:
pass
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)
with open(tmp, "w", encoding="utf-8", newline="") as f:
f.write(text)
with contextlib.suppress(OSError):
os.chmod(tmp, stat.S_IMODE(os.stat(path).st_mode)) # a rewritten file keeps its permissions
os.replace(tmp, path)
except BaseException:
with contextlib.suppress(OSError):
os.remove(tmp)
raise
def append(path, line):
@@ -122,24 +114,26 @@ def project_key(cwd=None):
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)
real, link = os.path.realpath(agents) if os.path.islink(agents) else os.path.join(real_root, "AGENTS.md"), os.path.islink(agents)
rel = os.path.relpath(real, real_root) if link else "AGENTS.md"
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 a symlink into " + rel.split(os.sep)[0] if link and rel.split(os.sep)[0] in (".git", ".sisi")
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), "")
return (None, "", why) if why else (real, rel, "")
def snapshot(cwd):
"""A fingerprint of the working tree: the commit, what is uncommitted, what is untracked. "" outside git."""
rc, top = git(["rev-parse", "--path-format=absolute", "--show-toplevel"], cwd)
if rc != 0:
rc, out = git(["rev-parse", "--path-format=absolute", "--show-toplevel", "HEAD"], cwd)
top = (out.splitlines() or [""])[0]
if not top:
return ""
real, rel, _ = agents_target(top.strip())
real, rel, _ = agents_target(top)
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]
head, status, diff = (out if rc == 0 else ""), git(["status", "--porcelain"] + spec, cwd)[1], git(["diff", "HEAD"] + spec, cwd)[1]
body = NOTE_RE.sub("", read(real)).rstrip("\r\n") if real and os.path.isfile(real) else ""
return hashlib.sha1((head + status + diff + "\0" + body).encode()).hexdigest()[:16]
def _session_path(sid):