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
@@ -52,14 +52,16 @@ not installed (its folder is absent) gets nothing created. For a tool that is in
|
||||
everything else in the file is kept. A file sisi cannot edit safely (comments, a trailing comma, a symlink to
|
||||
nowhere, read-only, hooks of an unexpected shape) is left alone and reported.
|
||||
|
||||
| Tool | Rulebook (in its folder) | Hooks |
|
||||
|---|---|---|
|
||||
| Claude Code | `~/.claude/CLAUDE.md` | `settings.json` |
|
||||
| Codex | `~/.codex/AGENTS.md` | `hooks.json` (the person trusts them once in Codex's `/hooks`) |
|
||||
| Qwen Code | `~/.qwen/QWEN.md` | `settings.json` |
|
||||
| Grok | `~/.grok/AGENTS.md` | none: Grok runs the hooks in `~/.claude/settings.json` |
|
||||
| OpenCode, Antigravity (`~/.gemini`), Pi, Kiro, Copilot, Crush, Amp | their global instructions file | none: not confirmed |
|
||||
| Muse, Cursor | none documented | not covered |
|
||||
| Tool | Rulebook (in its folder) | Hooks | Project rules |
|
||||
|---|---|---|---|
|
||||
| Claude Code | `~/.claude/CLAUDE.md` | `settings.json` | session-start print (reads `AGENTS.md` only without `CLAUDE.md`) |
|
||||
| Codex | `~/.codex/AGENTS.md` | `hooks.json` (the person trusts them once in Codex's `/hooks`) | session-start print; `AGENTS.md` note is in the file it reads |
|
||||
| Qwen Code | `~/.qwen/QWEN.md` | `settings.json` | session-start print; `AGENTS.md` note is in the file it reads |
|
||||
| Grok | `~/.grok/AGENTS.md` | none: Grok runs the hooks in `~/.claude/settings.json` | `AGENTS.md` note is in the file it reads |
|
||||
| OpenCode, Antigravity (`~/.gemini`), Pi, Kiro, Copilot, Amp | their global instructions file | none: not confirmed | `AGENTS.md` note is in the file the tool reads |
|
||||
| Crush | `~/.config/crush/CRUSH.md` | none: not confirmed | `AGENTS.md` note is read only when started at project root |
|
||||
| Cursor | none documented | not covered | `AGENTS.md` note is in the file Cursor CLI reads |
|
||||
| Muse | none documented | not covered | unconfirmed |
|
||||
|
||||
Hooks read a tool's input under whichever field names it uses (`session_id`, `sessionId`, `conversationId`,
|
||||
`toolCall.name`, …), and the class of each tool call (shell, read, edit, search, web, delegate) comes from
|
||||
@@ -94,10 +96,13 @@ Rules live at three levels:
|
||||
`retro_seconds`, counts, goal, term) and `outcomes.jsonl` (each judged delegation: session, `project_key`, `model`,
|
||||
`started`/`ended`, minutes, verdict, why). All plain text you can read and edit.
|
||||
- **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).
|
||||
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`.
|
||||
- **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 and shown by `sisi rules`.
|
||||
hook (for tools whose session-start output reaches the agent), pointed to by the `AGENTS.md` note, and shown by `sisi rules`.
|
||||
- **Scratch** (session state, bytecode): `$SISI_STATE`, else `$XDG_STATE_HOME/sisi`, else `~/.local/state/sisi`.
|
||||
Releases live in `$SISI_LIB`, else `~/.local/lib/sisi`.
|
||||
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
{"name": "claude", "detect": "~/.claude", "env": "CLAUDE_CONFIG_DIR", "rules": "CLAUDE.md", "import": true, "hooks": {"file": "settings.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "The built-in Explore and Plan subagents do not load CLAUDE.md."},
|
||||
{"name": "codex", "detect": "~/.codex", "env": "CODEX_HOME", "rules": "AGENTS.md", "hooks": {"file": "hooks.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "Hooks run only after the person trusts them once in Codex's /hooks; AGENTS.override.md shadows the rulebook; hosted web search is not metered."},
|
||||
{"name": "qwen", "detect": "~/.qwen", "rules": "QWEN.md", "hooks": {"file": "settings.json", "tick": "SessionStart", "prompt": "UserPromptSubmit", "watch": "PreToolUse", "gate": "Stop"}, "limits": "A tool Qwen names differently from canon/tools.json is not metered."},
|
||||
{"name": "grok", "detect": "~/.grok", "rules": "AGENTS.md", "limits": "Grok already runs the hooks in ~/.claude/settings.json; its session-start and prompt output is discarded, so project rules do not reach it at session start."},
|
||||
{"name": "grok", "detect": "~/.grok", "rules": "AGENTS.md", "limits": "Grok already runs the hooks in ~/.claude/settings.json; its session-start and prompt output is discarded, though it reads the project's AGENTS.md note."},
|
||||
{"name": "opencode", "detect": "~/.config/opencode", "rules": "AGENTS.md", "clean": ["plugins/sisi.js"], "limits": "Its plugin hooks are unverified, so none are wired."},
|
||||
{"name": "antigravity", "detect": "~/.gemini", "rules": "GEMINI.md", "clean": ["settings.json"], "limits": "Its global hooks file location is unconfirmed, so none are wired."},
|
||||
{"name": "pi", "detect": "~/.pi", "rules": "agent/AGENTS.md", "clean": ["agent/extensions/sisi.ts"], "limits": "Its extension hooks are unverified, so none are wired."},
|
||||
{"name": "kiro", "detect": "~/.kiro", "rules": "steering/AGENTS.md", "limits": "Hook support is unconfirmed, so none are wired."},
|
||||
{"name": "copilot", "detect": "~/.copilot", "rules": "copilot-instructions.md", "limits": "Hook support is unconfirmed, so none are wired."},
|
||||
{"name": "crush", "detect": "~/.config/crush", "rules": "CRUSH.md", "limits": "Hook support is unconfirmed, so none are wired."},
|
||||
{"name": "crush", "detect": "~/.config/crush", "rules": "CRUSH.md", "limits": "Hook support is unconfirmed, so none are wired; it reads project AGENTS.md only from the folder it is started in, not from a subfolder."},
|
||||
{"name": "amp", "detect": "~/.config/amp", "rules": "AGENTS.md", "limits": "Hook support is unconfirmed, so none are wired."},
|
||||
{"name": "muse", "detect": "~/.config/muse", "limits": "No documented global instructions file."},
|
||||
{"name": "cursor", "detect": "~/.cursor", "limits": "No global instructions file, and CLI hook support is unconfirmed."}
|
||||
{"name": "muse", "detect": "~/.config/muse", "limits": "No documented global instructions file; whether it reads project AGENTS.md is unconfirmed."},
|
||||
{"name": "cursor", "detect": "~/.cursor", "limits": "No global instructions file, and CLI hook support is unconfirmed; Cursor CLI reads project AGENTS.md."}
|
||||
]
|
||||
+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):
|
||||
|
||||
+145
-1
@@ -392,6 +392,150 @@ class Core(unittest.TestCase):
|
||||
self.assertIn("Rules travel with the project folder when moved", self.hook("tick", sid="mv1", cwd=moved)[1])
|
||||
self.assertIn("Rules travel with the project folder when moved", self.sisi("rules", cwd=moved)[1])
|
||||
|
||||
NOTE_BLOCK = ("<!-- sisi:begin -->\n"
|
||||
"This project's learned rules are in `.sisi/rules.md`. Read that file before any work here and follow it.\n"
|
||||
"<!-- sisi:end -->\n")
|
||||
|
||||
def test_project_rule_adds_agents_note_idempotently_and_preserves_bytes(self):
|
||||
agents = os.path.join(self.proj, "AGENTS.md")
|
||||
self.assertEqual(self.sisi("learn", "--project", "First rule creates the agents note")[0], 0)
|
||||
self.assertEqual(self.read(agents), self.NOTE_BLOCK)
|
||||
|
||||
p1 = self.project("existing")
|
||||
a1 = self.write(os.path.join(p1, "AGENTS.md"), "# My project\nKeep it clean.\n")
|
||||
self.assertEqual(self.sisi("learn", "--project", "Rule one for existing file", cwd=p1)[0], 0)
|
||||
expected = "# My project\nKeep it clean.\n\n" + self.NOTE_BLOCK
|
||||
self.assertEqual(self.read(a1), expected)
|
||||
mtime = os.stat(a1).st_mtime_ns
|
||||
for n in ("two", "three"):
|
||||
time.sleep(0.01)
|
||||
self.assertEqual(self.sisi("learn", "--project", "Rule %s leaves file untouched" % n, cwd=p1)[0], 0)
|
||||
self.assertEqual(self.read(a1), expected)
|
||||
self.assertEqual(os.stat(a1).st_mtime_ns, mtime)
|
||||
|
||||
p_crlf = self.project("crlf")
|
||||
a_crlf = os.path.join(p_crlf, "AGENTS.md")
|
||||
self.put(a_crlf, b"# Line 1\r\nLine 2\r\n")
|
||||
self.assertEqual(self.sisi("learn", "--project", "Keep CRLF line endings intact", cwd=p_crlf)[0], 0)
|
||||
self.assertEqual(self.bytes(a_crlf), b"# Line 1\r\nLine 2\r\n\r\n" + self.NOTE_BLOCK.replace("\n", "\r\n").encode())
|
||||
|
||||
p_nonl = self.project("nonl")
|
||||
a_nonl = self.write(os.path.join(p_nonl, "AGENTS.md"), "# No final newline")
|
||||
self.assertEqual(self.sisi("learn", "--project", "Handle missing trailing newline", cwd=p_nonl)[0], 0)
|
||||
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)
|
||||
|
||||
def test_retro_organize_and_migration_each_add_agents_note(self):
|
||||
p_retro = self.project("retro-note")
|
||||
self.hook("tick", sid="rn1", cwd=p_retro)
|
||||
self.assertEqual(self.sisi("retro", *GAP, "--improve", "Compare row counts before every export", cwd=p_retro, sid="rn1")[0], 0)
|
||||
self.assertEqual(self.read(p_retro, "AGENTS.md"), self.NOTE_BLOCK)
|
||||
|
||||
os.remove(os.path.join(p_retro, "AGENTS.md"))
|
||||
answer = self.write(os.path.join(self.tmp, "org-note.md"),
|
||||
"## user\n## project\n- Compare row counts before every export [retro 2026-11-24]\n")
|
||||
self.assertEqual(self.sisi("rules", "organize", "--record", answer, cwd=p_retro)[0], 0)
|
||||
self.assertEqual(self.read(p_retro, "AGENTS.md"), self.NOTE_BLOCK)
|
||||
|
||||
p_mig = self.project("mig-note")
|
||||
legacy_dir = self.mkdir(self.data, "rules", "projects")
|
||||
self.write(os.path.join(legacy_dir, self.project_key_for(p_mig) + ".md"),
|
||||
"- Legacy project rule triggers note creation [owner 2026-11-24]\n")
|
||||
self.assertEqual(self.hook("tick", sid="mn1", cwd=p_mig)[0], 0)
|
||||
self.assertEqual(self.read(p_mig, "AGENTS.md"), self.NOTE_BLOCK)
|
||||
|
||||
def test_learn_from_subfolder_and_reading_empty_project_behave_right(self):
|
||||
for fn in (lambda: self.hook("tick", sid="empty1"), lambda: self.sisi("rules"), lambda: self.sisi("doctor")):
|
||||
self.assertEqual(fn()[0], 0)
|
||||
self.assertFalse(os.path.lexists(os.path.join(self.proj, "AGENTS.md")))
|
||||
|
||||
commits_before = subprocess.run(["git", "rev-list", "--count", "HEAD"], cwd=self.proj, capture_output=True, text=True, check=True).stdout.strip()
|
||||
sub = self.mkdir(self.proj, "pkg", "sub")
|
||||
self.assertEqual(self.sisi("learn", "--project", "Write note at root from subfolder", cwd=sub)[0], 0)
|
||||
self.assertEqual(self.read(self.proj, "AGENTS.md"), self.NOTE_BLOCK)
|
||||
self.assertFalse(os.path.lexists(os.path.join(sub, "AGENTS.md")))
|
||||
self.assertFalse(os.path.lexists(os.path.join(self.proj, "pkg", "AGENTS.md")))
|
||||
self.assertEqual(subprocess.run(["git", "rev-list", "--count", "HEAD"], cwd=self.proj, capture_output=True, text=True, check=True).stdout.strip(), commits_before)
|
||||
staged = [l for l in subprocess.run(["git", "status", "--porcelain"], cwd=self.proj, capture_output=True, text=True, check=True).stdout.splitlines() if not l.startswith("??")]
|
||||
self.assertEqual(staged, [])
|
||||
|
||||
def test_agents_note_against_hostile_state_and_internal_symlink(self):
|
||||
outside = self.write(os.path.join(self.tmp, "outside.md"), "untouched\n")
|
||||
cases = ("dir", "dangling", "outside", "readonly", "bad-utf8")
|
||||
for kind in cases:
|
||||
p = self.project("hostile-" + kind)
|
||||
a = os.path.join(p, "AGENTS.md")
|
||||
if kind == "dir":
|
||||
os.mkdir(a)
|
||||
elif kind == "dangling":
|
||||
os.symlink(os.path.join(self.tmp, "nowhere.md"), a)
|
||||
elif kind == "outside":
|
||||
os.symlink(outside, a)
|
||||
elif kind == "readonly":
|
||||
self.write(a, "# Read only\n")
|
||||
os.chmod(a, 0o444)
|
||||
self.addCleanup(os.chmod, a, 0o644)
|
||||
elif kind == "bad-utf8":
|
||||
self.put(a, b"\xff\xfe\x00")
|
||||
rc, out, _ = self.sisi("learn", "--project", "Rule succeeds despite hostile %s state" % kind, cwd=p)
|
||||
self.assertEqual(rc, 0, (kind, out))
|
||||
self.assertIn("Rule succeeds despite hostile %s state" % kind, self.read(p, ".sisi", "rules.md"))
|
||||
note_lines = [l for l in out.splitlines() if "could not add" in l.lower()]
|
||||
self.assertEqual(len(note_lines), 1, (kind, out))
|
||||
self.assertEqual(self.read(outside), "untouched\n")
|
||||
self.assertEqual(self.bytes(os.path.join(self.tmp, "hostile-bad-utf8", "AGENTS.md")), b"\xff\xfe\x00")
|
||||
self.assertEqual(self.read(os.path.join(self.tmp, "hostile-readonly", "AGENTS.md")), "# Read only\n")
|
||||
self.assertTrue(os.path.isdir(os.path.join(self.tmp, "hostile-dir", "AGENTS.md")))
|
||||
self.assertFalse(os.path.exists(os.path.join(self.tmp, "nowhere.md")))
|
||||
|
||||
p_link = self.project("symlinked")
|
||||
claude = self.write(os.path.join(p_link, "CLAUDE.md"), "# Claude\n")
|
||||
a_link = os.path.join(p_link, "AGENTS.md")
|
||||
os.symlink("CLAUDE.md", a_link)
|
||||
rc, out, _ = self.sisi("learn", "--project", "Symlink to CLAUDE.md receives the block", cwd=p_link)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertTrue(os.path.islink(a_link))
|
||||
self.assertEqual(os.readlink(a_link), "CLAUDE.md")
|
||||
self.assertEqual(self.read(claude), "# Claude\n\n" + self.NOTE_BLOCK)
|
||||
|
||||
def test_gate_ignores_sisi_agents_note_but_catches_hand_edit_to_agents_md(self):
|
||||
self.hook("tick", sid="g1")
|
||||
self.hook("prompt", sid="g1", prompt="remember a rule")
|
||||
self.assertEqual(self.sisi("learn", "--project", "Own note and rule file do not trip the gate", sid="g1")[0], 0)
|
||||
self.assertEqual(self.read(self.proj, "AGENTS.md"), self.NOTE_BLOCK)
|
||||
self.assertEqual(self.hook("gate", sid="g1")[1], "")
|
||||
|
||||
p_tracked = self.project("tracked-agents")
|
||||
self.write(os.path.join(p_tracked, "AGENTS.md"), "# Tracked")
|
||||
for args in (["add", "AGENTS.md"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "agents"]):
|
||||
subprocess.run(["git"] + args, cwd=p_tracked, check=True, capture_output=True)
|
||||
self.hook("tick", sid="g2", cwd=p_tracked)
|
||||
self.hook("prompt", sid="g2", cwd=p_tracked, prompt="remember another rule")
|
||||
self.assertEqual(self.sisi("learn", "--project", "Tracked AGENTS.md note does not trip the gate", cwd=p_tracked, sid="g2")[0], 0)
|
||||
self.assertEqual(self.read(p_tracked, "AGENTS.md"), "# Tracked\n\n" + self.NOTE_BLOCK)
|
||||
self.assertEqual(self.hook("gate", sid="g2", cwd=p_tracked)[1], "")
|
||||
|
||||
self.hook("prompt", sid="g2", cwd=p_tracked, prompt="now edit AGENTS.md by hand")
|
||||
self.write(os.path.join(p_tracked, "AGENTS.md"), self.read(p_tracked, "AGENTS.md") + "\nHand edited line.\n")
|
||||
self.assertIn('"block"', self.hook("gate", sid="g2", cwd=p_tracked)[1])
|
||||
|
||||
def test_doctor_reports_project_agents_note_without_writing(self):
|
||||
self.assertNotIn("project note:", self.sisi("doctor")[1])
|
||||
self.mkdir(self.proj, ".sisi")
|
||||
self.write(os.path.join(self.proj, ".sisi", "rules.md"), "- Project rule without note yet [owner 2026-11-24]\n")
|
||||
out_missing = self.sisi("doctor")[1]
|
||||
self.assertRegex(out_missing, r"project note:.*missing")
|
||||
self.assertFalse(os.path.lexists(os.path.join(self.proj, "AGENTS.md")))
|
||||
|
||||
self.assertEqual(self.sisi("learn", "--project", "Add a rule so doctor sees the note")[0], 0)
|
||||
out_present = self.sisi("doctor")[1]
|
||||
self.assertRegex(out_present, r"project note:.*in AGENTS\.md")
|
||||
|
||||
# delegation
|
||||
|
||||
def test_the_lead_is_stopped_when_it_should_be_delegating(self):
|
||||
@@ -1787,7 +1931,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, 1645, "sisi is two loops. If it needs more than this, find the simpler shape.")
|
||||
self.assertLess(code, 1690, "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