Fix AGENTS.md note handling, snapshot cost/false-alarm, and read-only doctor
This commit is contained in:
1 parent
c1cd6d7ee3
commit
a540bd45ff
5 files changed
+243
-54
No files matched your search
@@ -98,8 +98,12 @@ Rules live at three levels:
|
||||
- **Each project** (`.sisi/rules.md` at the project root, never in a subfolder): rules specific to one project. You choose
|
||||
whether to check `.sisi/` into git or ignore it (sisi works either way, and never commits or stages it for you). Whenever
|
||||
sisi writes `.sisi/rules.md`, it also puts a marked note (`<!-- sisi:begin -->` ... `<!-- sisi:end -->`) in the project
|
||||
root's `AGENTS.md` pointing to `.sisi/rules.md`, so the note is in the file those tools read. To remove the note, delete
|
||||
the marked block from `AGENTS.md`.
|
||||
root's `AGENTS.md` pointing to `.sisi/rules.md`, so the note is in the file those tools read. It is skipped with a
|
||||
one-line reason when `AGENTS.md` is read-only, a folder, not UTF-8, a link that is broken or points outside the project
|
||||
or into `.git` or `.sisi`, or if writing fails. Deleting the block removes it only until the next rule is written, when
|
||||
sisi puts it back. If `AGENTS.md` is checked in, git shows it as modified until you commit it (sisi never commits it),
|
||||
and if `.sisi/` is git-ignored, people who clone the project get a note pointing at a file they do not have. A
|
||||
hard-linked `AGENTS.md` is replaced by a separate file.
|
||||
- **The rulebook every session loads** (`generated/core.md`) is built from the product (`canon/core.md`) and your user
|
||||
rules (`rules/user.md`). Project rules are not in the generated rulebook; they are printed at session start by the `tick`
|
||||
hook (for tools whose session-start output reaches the agent), pointed to by the `AGENTS.md` note, and shown by `sisi rules`.
|
||||
|
||||
+14
-12
@@ -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
@@ -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
@@ -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):
|
||||
|
||||
+192
-5
@@ -425,10 +425,10 @@ class Core(unittest.TestCase):
|
||||
self.assertEqual(self.read(a_nonl), "# No final newline\n\n" + self.NOTE_BLOCK)
|
||||
|
||||
p_dup = self.project("dup")
|
||||
a_dup = self.write(os.path.join(p_dup, "AGENTS.md"),
|
||||
"# Two\n\n<!-- sisi:begin -->\nold one\n<!-- sisi:end -->\n<!-- sisi:begin -->\nold two\n<!-- sisi:end -->\n")
|
||||
self.assertEqual(self.sisi("learn", "--project", "Collapse duplicate marked blocks to one", cwd=p_dup)[0], 0)
|
||||
self.assertEqual(self.read(a_dup), "# Two\n\n" + self.NOTE_BLOCK)
|
||||
own_blocks = "# Two\n\n<!-- sisi:begin -->\nold one\n<!-- sisi:end -->\n<!-- sisi:begin -->\nold two\n<!-- sisi:end -->\n"
|
||||
a_dup = self.write(os.path.join(p_dup, "AGENTS.md"), own_blocks)
|
||||
self.assertEqual(self.sisi("learn", "--project", "Leave user marked blocks untouched", cwd=p_dup)[0], 0)
|
||||
self.assertEqual(self.read(a_dup), own_blocks + "\n" + self.NOTE_BLOCK)
|
||||
|
||||
def test_retro_organize_and_migration_each_add_agents_note(self):
|
||||
p_retro = self.project("retro-note")
|
||||
@@ -536,6 +536,178 @@ class Core(unittest.TestCase):
|
||||
out_present = self.sisi("doctor")[1]
|
||||
self.assertRegex(out_present, r"project note:.*in AGENTS\.md")
|
||||
|
||||
def test_stray_and_user_markers_in_agents_md_are_preserved(self):
|
||||
cases = [
|
||||
("stray-begin", "# Doc\n<!-- sisi:begin -->\nmy text\nmore\n"),
|
||||
("stray-both", "<!-- sisi:end -->\nhello\n<!-- sisi:begin -->\nkeep me\n"),
|
||||
("own-block", "# T\n<!-- sisi:begin -->\nMY OWN IMPORTANT TEXT\n<!-- sisi:end -->\nafter\n"),
|
||||
("fenced", "# Doc\n```\n<!-- sisi:begin -->\nexample\n<!-- sisi:end -->\n```\n"),
|
||||
("inline-marker", "x<!-- sisi:begin -->\n" + self.NOTE_BLOCK.split("\n", 1)[1]),
|
||||
]
|
||||
for name, initial in cases:
|
||||
p = self.project("markers-" + name)
|
||||
a = self.write(os.path.join(p, "AGENTS.md"), initial)
|
||||
expected = initial + ("\n" if initial.endswith("\n") else "\n\n") + self.NOTE_BLOCK
|
||||
for n in ("one", "two", "three"):
|
||||
rc, out, _ = self.sisi("learn", "--project", "a rule about x " + n, cwd=p)
|
||||
self.assertEqual(rc, 0, (name, n, out))
|
||||
self.assertEqual(self.read(a), expected, (name, n))
|
||||
|
||||
def test_duplicate_exact_note_blocks_stay_untouched(self):
|
||||
p = self.project("dup-exact")
|
||||
initial = "a\n\n" + self.NOTE_BLOCK + "\n" + self.NOTE_BLOCK + "\nz\n"
|
||||
a = self.write(os.path.join(p, "AGENTS.md"), initial)
|
||||
self.assertEqual(self.sisi("learn", "--project", "Duplicate exact blocks stay untouched", cwd=p)[0], 0)
|
||||
self.assertEqual(self.read(a), initial)
|
||||
|
||||
def test_agents_symlink_into_git_or_sisi_is_refused(self):
|
||||
p_git = self.project("sym-git")
|
||||
git_cfg = os.path.join(p_git, ".git", "config")
|
||||
before_cfg = self.read(git_cfg)
|
||||
os.symlink(".git/config", os.path.join(p_git, "AGENTS.md"))
|
||||
rc, out, _ = self.sisi("learn", "--project", "a rule about gitconf x", cwd=p_git)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("a rule about gitconf x", self.read(p_git, ".sisi", "rules.md"))
|
||||
self.assertEqual(self.read(git_cfg), before_cfg)
|
||||
self.assertEqual(subprocess.run(["git", "status", "--porcelain"], cwd=p_git, capture_output=True, text=True).returncode, 0)
|
||||
self.assertEqual(len([l for l in out.splitlines() if "could not add" in l.lower()]), 1, out)
|
||||
|
||||
p_sisi = self.project("sym-sisi")
|
||||
self.mkdir(p_sisi, ".sisi")
|
||||
rules_f = self.write(os.path.join(p_sisi, ".sisi", "rules.md"), "")
|
||||
os.symlink(".sisi/rules.md", os.path.join(p_sisi, "AGENTS.md"))
|
||||
rc, out, _ = self.sisi("learn", "--project", "a rule about sisiconf x", cwd=p_sisi)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertNotIn("sisi:begin", self.read(rules_f))
|
||||
self.assertEqual(len([l for l in out.splitlines() if "could not add" in l.lower()]), 1, out)
|
||||
|
||||
def test_failed_agents_note_write_never_raises_or_leaves_tmp(self):
|
||||
from unittest import mock
|
||||
from sisi import store
|
||||
|
||||
# store.write removes its temp file when os.replace fails
|
||||
p_tmp = self.project("replace-fail")
|
||||
with mock.patch("os.replace", side_effect=OSError("replace failed")):
|
||||
with self.assertRaises(OSError):
|
||||
store.write(os.path.join(p_tmp, "AGENTS.md"), "hello\n")
|
||||
self.assertEqual([n for n in os.listdir(p_tmp) if ".tmp" in n], [])
|
||||
|
||||
def ro_proj(name):
|
||||
p = self.project(name)
|
||||
self.mkdir(p, ".sisi")
|
||||
self.write(os.path.join(p, ".sisi", "rules.md"), "- existing rule [owner 2026-11-24]\n")
|
||||
os.chmod(p, 0o555)
|
||||
self.addCleanup(os.chmod, p, 0o755)
|
||||
return p
|
||||
|
||||
p_learn = ro_proj("ro-learn")
|
||||
rc, out, err = self.sisi("learn", "--project", "a rule about rc x", cwd=p_learn)
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertIn("a rule about rc x", self.read(p_learn, ".sisi", "rules.md"))
|
||||
self.assertIn("rules note", out.lower())
|
||||
|
||||
p_org = ro_proj("ro-org")
|
||||
ans = self.write(os.path.join(self.tmp, "ro-ans.md"), "## user\n- user rule kept [owner 2026-11-24]\n## project\n- organized rule [owner 2026-11-24]\n")
|
||||
rc, out, err = self.sisi("rules", "organize", "--record", ans, cwd=p_org)
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertIn("user rule kept", self.read(self.data, "rules", "user.md"))
|
||||
self.assertIn("rules note", out.lower())
|
||||
os.chmod(p_org, 0o755)
|
||||
self.assertEqual(self.sisi("rules", "revert", cwd=p_org)[0], 0)
|
||||
self.assertIn("existing rule", self.read(p_org, ".sisi", "rules.md"))
|
||||
|
||||
p_ret = ro_proj("ro-retro")
|
||||
self.hook("tick", sid="ro-r", cwd=p_ret)
|
||||
rc, out, err = self.sisi("retro", *GAP, "--improve", "Record retro rule when dir is read only", cwd=p_ret, sid="ro-r")
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertNotIn("could not write", out.lower())
|
||||
self.assertIn("rules note", out.lower())
|
||||
|
||||
p_mig = ro_proj("ro-mig")
|
||||
legacy_dir = self.mkdir(self.data, "rules", "projects")
|
||||
legacy = self.write(os.path.join(legacy_dir, self.project_key_for(p_mig) + ".md"), "- migrated rule under ro dir [owner 2026-11-24]\n")
|
||||
rc, out, err = self.hook("tick", sid="ro-m", cwd=p_mig)
|
||||
self.assertEqual((rc, err), (0, ""), out)
|
||||
self.assertFalse(os.path.exists(legacy))
|
||||
self.assertNotIn("could not move", out.lower())
|
||||
self.assertIn("rules note", out.lower())
|
||||
|
||||
def test_note_pattern_speed_and_trailing_blank_equivalence(self):
|
||||
from sisi import rules, store
|
||||
|
||||
p = self.project("perf")
|
||||
a = os.path.join(p, "AGENTS.md")
|
||||
self.write(a, "\n" * 200000 + self.NOTE_BLOCK)
|
||||
t0 = time.monotonic()
|
||||
fp1 = store.snapshot(p)
|
||||
self.assertLess(time.monotonic() - t0, 0.5)
|
||||
self.write(a, "u\n\n\n" + self.NOTE_BLOCK)
|
||||
fp2 = store.snapshot(p)
|
||||
self.write(a, "u\n")
|
||||
self.assertEqual(fp2, store.snapshot(p))
|
||||
self.assertNotEqual(fp1, fp2)
|
||||
|
||||
p_begins = self.project("perf-begins")
|
||||
begins = "<!-- sisi:begin -->\n" * 8000
|
||||
a_begins = self.write(os.path.join(p_begins, "AGENTS.md"), begins)
|
||||
t1 = time.monotonic()
|
||||
rules.note(os.path.join(p_begins, ".sisi", "rules.md"))
|
||||
self.assertLess(time.monotonic() - t1, 0.5)
|
||||
self.assertEqual(self.read(a_begins), begins + "\n" + self.NOTE_BLOCK)
|
||||
|
||||
def test_git_add_agents_md_does_not_change_snapshot_and_process_count_is_three(self):
|
||||
from unittest import mock
|
||||
from sisi import store
|
||||
|
||||
p = self.project("snap")
|
||||
a = self.write(os.path.join(p, "AGENTS.md"), "# Tracked\n")
|
||||
subprocess.run(["git", "add", "AGENTS.md"], cwd=p, check=True, capture_output=True)
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init"], cwd=p, check=True, capture_output=True)
|
||||
self.assertEqual(self.sisi("learn", "--project", "Add note to tracked AGENTS.md", cwd=p)[0], 0)
|
||||
fp_before = store.snapshot(p)
|
||||
subprocess.run(["git", "add", "AGENTS.md"], cwd=p, check=True, capture_output=True)
|
||||
self.assertEqual(store.snapshot(p), fp_before)
|
||||
self.write(a, self.read(a) + "\nHand edit.\n")
|
||||
fp_edit = store.snapshot(p)
|
||||
self.assertNotEqual(fp_edit, fp_before)
|
||||
subprocess.run(["git", "add", "AGENTS.md"], cwd=p, check=True, capture_output=True)
|
||||
self.assertEqual(store.snapshot(p), fp_edit)
|
||||
|
||||
empty = self.mkdir(self.tmp, "empty-repo")
|
||||
subprocess.run(["git", "init", "-q"], cwd=empty, check=True, capture_output=True)
|
||||
nongit = self.mkdir(self.tmp, "non-git-snap")
|
||||
for folder, max_calls, expect_empty in ((p, 3, False), (empty, 3, False), (nongit, 1, True)):
|
||||
real_run = subprocess.run
|
||||
calls = []
|
||||
def counting(*args, **kwargs):
|
||||
calls.append(args[0])
|
||||
return real_run(*args, **kwargs)
|
||||
with mock.patch("subprocess.run", side_effect=counting):
|
||||
fp = store.snapshot(folder)
|
||||
self.assertLessEqual(len(calls), max_calls, (folder, calls))
|
||||
self.assertEqual(fp == "", expect_empty, (folder, fp))
|
||||
fp_empty = store.snapshot(empty)
|
||||
self.write(os.path.join(empty, "hello.txt"), "hi\n")
|
||||
self.assertNotEqual(store.snapshot(empty), fp_empty)
|
||||
|
||||
def test_doctor_is_read_only_with_legacy_store_file(self):
|
||||
p = self.project("doc-ro")
|
||||
legacy_dir = self.mkdir(self.data, "rules", "projects")
|
||||
legacy = self.write(os.path.join(legacy_dir, self.project_key_for(p) + ".md"),
|
||||
"- Legacy rule waiting in store [owner 2026-11-24]\n")
|
||||
subprocess.run(["git", "init", "-q"], cwd=self.data, check=True, capture_output=True)
|
||||
subprocess.run(["git", "add", "-A"], cwd=self.data, check=True, capture_output=True)
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "legacy"], cwd=self.data, check=True, capture_output=True)
|
||||
commits_before = subprocess.run(["git", "rev-list", "--count", "HEAD"], cwd=self.data, capture_output=True, text=True, check=True).stdout.strip()
|
||||
listing_before = sorted(os.listdir(p))
|
||||
rc, out, _ = self.sisi("doctor", cwd=p)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertTrue(os.path.isfile(legacy))
|
||||
self.assertEqual(self.read(legacy), "- Legacy rule waiting in store [owner 2026-11-24]\n")
|
||||
self.assertEqual(sorted(os.listdir(p)), listing_before)
|
||||
self.assertEqual(subprocess.run(["git", "rev-list", "--count", "HEAD"], cwd=self.data, capture_output=True, text=True, check=True).stdout.strip(), commits_before)
|
||||
self.assertRegex(out, r"waiting to be moved")
|
||||
|
||||
# delegation
|
||||
|
||||
def test_the_lead_is_stopped_when_it_should_be_delegating(self):
|
||||
@@ -1356,6 +1528,21 @@ class Core(unittest.TestCase):
|
||||
self.assertFalse(os.path.lexists(os.path.join(home, ".pi", "agent", "AGENTS.md")))
|
||||
self.assertEqual(self.read(mine), "# my notes\nno newline at the end")
|
||||
|
||||
def test_installer_preserves_second_marked_block_in_global_instructions(self):
|
||||
home = self.harness(".codex")
|
||||
target = os.path.join(home, ".codex", "AGENTS.md")
|
||||
second = "<!-- sisi:begin -->\nsecond block kept\n<!-- sisi:end -->\n"
|
||||
self.write(target, "<!-- sisi:begin -->\nold rulebook\n<!-- sisi:end -->\n# my notes\n" + second)
|
||||
self.assertEqual(self.sisi("install")[0], 0)
|
||||
book = self.read(self.data, "generated", "core.md")
|
||||
self.assertEqual(self.read(target), "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n# my notes\n%s" % (book, second))
|
||||
self.assertEqual(self.sisi("learn", "Keep second marked block in global instructions")[0], 0)
|
||||
new_book = self.read(self.data, "generated", "core.md")
|
||||
self.assertIn("Keep second marked block in global instructions", new_book)
|
||||
self.assertEqual(self.read(target), "<!-- sisi:begin -->\n%s<!-- sisi:end -->\n# my notes\n%s" % (new_book, second))
|
||||
self.assertEqual(self.sisi("uninstall")[0], 0)
|
||||
self.assertEqual(self.read(target), "# my notes\n" + second)
|
||||
|
||||
def test_hostile_files_are_handled_or_refused_and_never_damaged(self):
|
||||
home = self.harness(".claude")
|
||||
spath, mpath = os.path.join(home, ".claude", "settings.json"), os.path.join(home, ".claude", "CLAUDE.md")
|
||||
@@ -1931,7 +2118,7 @@ class Core(unittest.TestCase):
|
||||
|
||||
def test_the_product_stays_small(self):
|
||||
code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py")))
|
||||
self.assertLess(code, 1690, "sisi is two loops. If it needs more than this, find the simpler shape.")
|
||||
self.assertLess(code, 1688, "sisi is two loops. If it needs more than this, find the simpler shape.")
|
||||
rulebook = self.read(REPO, "canon", "core.md")
|
||||
self.assertLess(len(rulebook.splitlines()), 120)
|
||||
self.assertLess(len(rulebook), 8360)
|
||||
|
||||
Reference in new issue
Block a user