diff --git a/README.md b/README.md index 9145d80..e612e2b 100644 --- a/README.md +++ b/README.md @@ -24,11 +24,41 @@ is sent to the retro, and any other closes itself. Each record in `retro.jsonl` ``` git clone && cd sisi ./bin/sisi release # runs the tests, then puts a copy in ~/.local/lib/sisi -./bin/sisi install # adds four hooks to Claude Code's settings and the rulebook to its instructions -sisi doctor +./bin/sisi install # the rulebook (and hooks, where the tool has them) into every agent tool installed here +sisi doctor # how each tool stands ``` -Python 3 standard library only. `sisi rollback` goes back to the release before. +Python 3 standard library only. `sisi rollback` goes back to the release before. `sisi uninstall` takes out exactly +what `install` put in. `sisi update` fetches the newest sisi from the repository the release in use was made from +(`sisi release` records that remote: `github`, else `origin`) and releases it, so a checkout is only needed once. + +## Which agent tools + +`sisi install` looks at the tools in `canon/harnesses.json` (plain data: add a tool by adding a line). A tool that is +not installed (its folder is absent) gets nothing created. For a tool that is installed: + +- **The rulebook.** An absent instructions file becomes a link to the generated rulebook. A real file gets the + rulebook in a block between `` and `` at the top, every other byte left alone; + the block is refreshed whenever the rulebook is rebuilt (Claude Code gets an `@import` of the rulebook in the same + block). A link that points anywhere else is not sisi's: it is left alone and reported. +- **The four hooks** (`tick`, `prompt`, `watch`, `gate`), only for tools whose hook files have been confirmed to take + the same shape as Claude Code's: sisi's entries (old or new) are removed from the file and the current ones added; + 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 | + +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 +`canon/tools.json`: add a tool's own names there. `sisi doctor` prints one line per tool with what it has and what +its limits are. ## What the agent does with it @@ -50,10 +80,12 @@ Python 3 standard library only. `sisi rollback` goes back to the release before. - **The product** (this repository): the code in `sisi/`, the rulebook in `canon/core.md`. The same for everyone. `SPEC.md` is what it aims at. -- **Your store** (`~/.local/share/sisi`, a git repository): `rules/user.md` and `rules/projects/*.md` (what +- **Your store** (`$SISI_DATA`, else `$XDG_DATA_HOME/sisi`, else `~/.local/share/sisi`; a git repository): `rules/user.md` and `rules/projects/*.md` (what was learned), `models.md` (your workers), `retro.jsonl` and `outcomes.jsonl` (what happened). All plain text you can read and edit. - **The rulebook every session loads** is generated from the two: `canon/core.md`, then your learned 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`. Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `direct_calls` (8), `direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), diff --git a/bin/sisi b/bin/sisi index 426bbb1..09bfd65 100755 --- a/bin/sisi +++ b/bin/sisi @@ -1,8 +1,8 @@ #!/usr/bin/env python3 import os, sys # sisi never writes inside the product: compiled bytecode goes to the scratch dir instead of next to the code. -_state = os.environ.get("SISI_STATE") or os.path.join(os.environ.get("SISI_HOME") or os.path.expanduser("~"), - ".local", "state", "sisi") +_xdg = os.environ.get("XDG_STATE_HOME") +_state = os.environ.get("SISI_STATE") or os.path.join(_xdg or os.path.join(os.path.expanduser("~"), ".local", "state"), "sisi") sys.pycache_prefix = os.path.join(_state, "pycache") sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from sisi.cli import main diff --git a/canon/core.md b/canon/core.md index e44014e..ca239ea 100644 --- a/canon/core.md +++ b/canon/core.md @@ -3,7 +3,8 @@ You are the engineering organization for the person you work for: they say what they want, and you own getting it right. These rules give direction; work out the tactics yourself. If another agent gave you this work, you are a worker: do it yourself, hold to the checks in your brief, and -report against them. Rule 5 and the retro in rule 8 are the lead's. +report against them. Run `sisi rules` first: it prints the rules learned in this project. Rule 5 and +the retro in rule 8 are the lead's. ## The objective diff --git a/canon/harnesses.json b/canon/harnesses.json new file mode 100644 index 0000000..83dafab --- /dev/null +++ b/canon/harnesses.json @@ -0,0 +1,15 @@ +[ + {"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": "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": "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."} +] diff --git a/canon/tools.json b/canon/tools.json new file mode 100644 index 0000000..4a3e44a --- /dev/null +++ b/canon/tools.json @@ -0,0 +1,8 @@ +{ + "shell": ["bash", "shell", "exec_command", "run_terminal_command", "run_command", "run_shell_command"], + "read": ["read", "read_file", "list_dir"], + "edit": ["edit", "write", "multiedit", "notebookedit", "apply_patch", "patch", "search_replace", "write_file", "edit_file"], + "search": ["grep", "glob", "grep_search", "search"], + "web": ["webfetch", "websearch", "web_fetch", "web_search", "read_url_content", "search_web"], + "delegate": ["agent", "task", "workflow", "spawn_agent", "spawn_subagent", "subagent", "subagent_spawn", "invoke_subagent"] +} diff --git a/sisi/cli.py b/sisi/cli.py index 0dd8337..504ca8b 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -31,18 +31,21 @@ Delegation sisi direct REASON allow yourself more direct tool calls this turn, with the reason Setting up - sisi install | doctor wire the hooks and the rulebook into the agent tool; check them + sisi install | uninstall | doctor + put the rulebook (and hooks, where the tool has them) into every agent tool + installed here; take them out again; show how each tool stands sisi release | rollback make this copy the one the hooks run; go back to the one before + sisi update fetch the newest sisi from where this release came from and release it Hooks (the agent tool calls these): sisi tick | prompt | watch | gate -Your rules, models table and retro log live in ~/.local/share/sisi, a git repository. Settings: "core" in +Your rules, models table and retro log live in ~/.local/share/sisi ($SISI_DATA, else $XDG_DATA_HOME/sisi), a git repository. Settings: "core" in its config.json (gate, meter, direct_calls, direct_extension, rules_lines, rules_chars, organize_after, research_days, shell_workers).""" def main(argv): - from . import hooks, install, models, retro, rules, store + from . import hooks, models, rules, store cmd, args = (argv[0] if argv else "help"), argv[1:] if cmd in ("tick", "prompt", "watch", "gate"): try: @@ -54,10 +57,12 @@ def main(argv): store.append(os.path.join(store.STATE, "core-errors.log"), "%s %s: %r" % (time.strftime("%Y-%m-%dT%H:%M:%S"), cmd, e)) return 0 if cmd == "retro": + from . import retro return retro.run(args) if cmd == "rules": return rules.run(args) if cmd == "done": + from . import retro return retro.done(args) if cmd == "pick": return models.pick(args) @@ -69,7 +74,8 @@ def main(argv): return models.judge(args) if cmd == "direct": return hooks.direct(args) - if cmd in ("install", "release", "rollback", "doctor"): + if cmd in ("install", "uninstall", "release", "update", "rollback", "doctor"): + from . import install return getattr(install, cmd)() if cmd == "rulebook": print(rules.build_rulebook()) diff --git a/sisi/hooks.py b/sisi/hooks.py index 14ff746..29caab3 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -7,8 +7,7 @@ from . import models, rules, store # A delegated session says so in the first lines of its first request (the brief). WORKER = re.compile(r"(?im)^\W*(you are a (worker|subagent|sub-agent|delegate)\b|do this task yourself|do not delegate)") -DIRECT = {"Bash", "Read", "Edit", "Write", "MultiEdit", "NotebookEdit", "Grep", "Glob", "WebFetch", "WebSearch"} -EDITS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} +DIRECT = ("shell", "read", "edit", "search", "web") # the classes of tool call the meter counts OWN = re.compile(r"\s*(\S*/)?sisi\s[^;&|<>`$]*") # a shell command that runs sisi and nothing else METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the rest: `sisi models` lists your " @@ -29,22 +28,53 @@ OPEN = ("sisi: these checks have no verdict yet: %s. Give each one: sisi done -- "\"\". If the work is only pausing: sisi retro --later \"\".") +# The names each host gives a hook's fields; the first one present (and of the right type) wins. +FIELDS = (("session_id", str, ("session_id", "sessionId", "conversation_id", "conversationId")), + ("tool_name", str, ("tool_name", "toolName", "tool", "toolCall.name")), + ("tool_input", dict, ("tool_input", "toolInput", "input", "toolCall.args")), + ("prompt", str, ("prompt", "lastUserInput")), + ("hook_event_name", str, ("hook_event_name", "hookEventName")), + ("cwd", str, ("cwd", "workspace_roots", "workspacePaths"))) +SUBAGENT = ("agent_id", "agentId", "subagent_id", "subagentType", "agent_transcript_path") +_classes = None + + +def normalize(p): + """Any host's hook input as one shape. A field of the wrong type is empty, never an error.""" + def get(name): + v = p + for part in name.split("."): + v = v.get(part) if isinstance(v, dict) else None + return v + out = {} + for key, kind, names in FIELDS: + vals = [get(n) for n in names] + if key == "cwd": + vals = [v[0] if isinstance(v, list) and v else v for v in vals] # workspace_roots is a list + out[key] = next((v for v in vals if isinstance(v, kind) and v), kind()) + out["subagent"] = any(get(n) for n in SUBAGENT) or "/subagents/" in str(get("transcript_path") or "") + return out + + def payload(): try: p = json.load(sys.stdin) - return p if isinstance(p, dict) else {} except ValueError: - return {} + p = None + return normalize(p if isinstance(p, dict) else {}) -def subagent(p): - """The host's own subagents share their parent's session: the hook's input is what tells them apart.""" - return bool(p.get("agent_id") or p.get("agentId") or p.get("agent_transcript_path") - or "/subagents/" in str(p.get("transcript_path") or "")) - - -def delegation(tool): - return tool in ("Agent", "Task", "Workflow") or tool.endswith("delegate_task") +def tool_class(tool): + """shell, read, edit, search, web or delegate, by the table in canon/tools.json; "" for any other tool.""" + global _classes + if _classes is None: + try: + raw = json.loads(store.read(os.path.join(store.ROOT, "canon", "tools.json"))) + _classes = {n: c for c, names in raw.items() for n in names} + except (ValueError, AttributeError, TypeError): + _classes = {} # a missing or broken table meters nothing rather than breaking the session + tool = tool.lower() + return _classes.get(tool) or ("delegate" if tool.endswith("delegate_task") else "") def _begin(state, cwd): @@ -54,7 +84,7 @@ def _begin(state, cwd): def tick(p): """Session start: remember where the work began; print this project's learned rules and what is due.""" - sid, cwd = p.get("session_id"), p.get("cwd") or os.getcwd() + sid, cwd = p["session_id"], p["cwd"] or os.getcwd() if sid: with store.session(sid) as s: _begin(s, cwd) @@ -71,11 +101,11 @@ def tick(p): def prompt(p): """Each request: a new turn begins. The first request tells a delegated worker from a lead.""" - sid = p.get("session_id") + sid = p["session_id"] if sid: with store.session(sid) as s: - _begin(s, p.get("cwd") or os.getcwd()) - if not s.get("prompts") and WORKER.search(str(p.get("prompt") or "")[:2000]): + _begin(s, p["cwd"] or os.getcwd()) + if not s.get("prompts") and WORKER.search(p["prompt"][:2000]): s["worker"] = True s["prompts"] = s.get("prompts", 0) + 1 s["prompts_since"] = s.get("prompts_since", 0) + 1 @@ -85,39 +115,39 @@ def prompt(p): def watch(p): """Before a tool call by the lead: count it, and refuse it when the lead should be delegating.""" - sid, tool = p.get("session_id"), str(p.get("tool_name") or "") - if p.get("hook_event_name") not in (None, "PreToolUse") or not sid or subagent(p): + sid, tool, ti = p["session_id"], p["tool_name"].lower(), p["tool_input"] + if p["hook_event_name"] not in ("", "PreToolUse") or not sid or p["subagent"]: return 0 - ti = p.get("tool_input") if isinstance(p.get("tool_input"), dict) else {} - command, cfg = str(ti.get("command") or ""), store.config() + kind, command, cfg = tool_class(tool), str(ti.get("command") or ""), store.config() with store.session(sid) as s: - _begin(s, p.get("cwd") or os.getcwd()) + _begin(s, p["cwd"] or os.getcwd()) if s.get("worker"): return 0 - if tool == "Bash" and OWN.fullmatch(command): + if kind == "shell" and OWN.fullmatch(command): return 0 - shell = tool == "Bash" and models.is_call(command) + shell = kind == "shell" and models.is_call(command) if shell and not cfg["shell_workers"]: sys.stderr.write(NOSHELL) return 2 - if (delegation(tool) or shell or tool in EDITS) and not s.get("done"): + if (kind in ("delegate", "edit") or shell) and not s.get("done"): sys.stderr.write(NODONE) return 2 - if delegation(tool) or shell: + if kind == "delegate" or shell: target = ti.get("target") if isinstance(ti.get("target"), dict) else {} - text = command if shell else str((target if tool.endswith("delegate_task") else ti).get("model") or "") - if tool != "Workflow" and store.read(models.table()) and not models.claim(s, text): + names = (ti.get("model"),) if tool == "agent" else (ti.get("model"), target.get("model"), ti.get("agent")) + text = command if shell else str(next((n for n in names if n), "")) + if tool != "workflow" and store.read(models.table()) and not models.claim(s, text): sys.stderr.write(NOPICK) return 2 s["delegations_since"] = s.get("delegations_since", 0) + 1 return 0 - if tool not in DIRECT: + if kind not in DIRECT: return 0 limit = cfg["direct_calls"] + s.get("extra", 0) if cfg["meter"] and s.get("direct", 0) >= limit: sys.stderr.write(METER % (s["direct"], limit, cfg["direct_extension"])) return 2 # the tool call is refused and the agent reads the reason - if tool in EDITS: + if kind == "edit": s["changed"] = True s["direct"] = s.get("direct", 0) + 1 s["direct_since"] = s.get("direct_since", 0) + 1 @@ -139,8 +169,8 @@ def direct(args, cwd=None): def gate(p, for_subagent=False): """End of turn: when the lead changed things and has not held the retro, send it back to hold it.""" - sid, cwd = p.get("session_id"), p.get("cwd") or os.getcwd() - if for_subagent or not sid or subagent(p) or not store.config()["gate"]: + sid, cwd = p["session_id"], p["cwd"] or os.getcwd() + if for_subagent or not sid or p["subagent"] or not store.config()["gate"]: return 0 with store.session(sid) as s: _begin(s, cwd) diff --git a/sisi/install.py b/sisi/install.py index a5a195a..afd9ffc 100644 --- a/sisi/install.py +++ b/sisi/install.py @@ -1,55 +1,199 @@ -"""Wiring sisi into the agent tool, and putting a checked copy of the product in place.""" -import json, os, shutil, subprocess, sys, time +"""Wiring sisi into every agent tool on the machine, and putting a checked copy of the product in place. + +The tools are plain data in canon/harnesses.json: where each keeps its always-on instructions (the rulebook goes +there) and, for the ones whose hooks have the same shape, its hooks file. Nothing is written for a tool that is +not installed, and nothing is touched that sisi cannot edit safely: it is left alone and reported.""" +import json, os, re, shutil, subprocess, sys, tempfile, time from . import models, rules, store -# event, the sisi command it runs, the tool matcher it needs -EVENTS = (("SessionStart", "tick", None), ("UserPromptSubmit", "prompt", None), - ("PreToolUse", "watch", "*"), ("Stop", "gate", None)) - - -def _claude(): - return os.environ.get("CLAUDE_CONFIG_DIR") or os.path.join(store.HOME, ".claude") +BLOCK = re.compile(r"\n.*?\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") def _current(): return os.path.join(store.LIB, "current") -def _wired(settings, sub): - entries = (settings.get("hooks") or {}).get({s: e for e, s, _ in EVENTS}[sub]) or [] - return any("bin/sisi %s" % sub in str(h.get("command")) for e in entries for h in e.get("hooks") or []) +def _book(): + return os.path.join(store.DATA, "generated", "core.md") + + +def _table(): + try: + return json.loads(store.read(os.path.join(store.ROOT, "canon", "harnesses.json"))) + except ValueError: + return [] + + +def _dir(h): + """The tool's folder when it is installed, else None.""" + d = os.environ.get(h.get("env", "")) or os.path.expanduser(h["detect"]) + return d if os.path.isdir(d) else None + + +def _read(path): + """The file's text, "" when there is none. A file that cannot be read as text raises, so it is never overwritten.""" + return open(path, encoding="utf-8").read() if os.path.lexists(path) else "" + + +def _save(path, text): + real = os.path.realpath(path) # a link to the real file (a dotfiles repository) stays a link + if os.path.exists(real) and not os.stat(real).st_mode & 0o200: + raise OSError("it is read-only") + store.write(real, text) + + +def _ours(entry): + return isinstance(entry, dict) and bool(SISI.search(str(entry.get("command")))) + + +def _load(path): + """The hooks file's JSON object and its hooks. ValueError when sisi cannot edit it safely.""" + raw = _read(path) + try: + doc = json.loads(raw) if raw.strip() else {} + except ValueError: + raise ValueError("it is not plain JSON (a comment or a trailing comma?)") + hooks = doc.get("hooks", {}) if isinstance(doc, dict) else None + if not isinstance(hooks, dict) or not all(isinstance(v, list) for v in hooks.values()): + raise ValueError("its hooks are not in a shape sisi can edit") + return raw, doc, hooks + + +def _entries(h): + """The hook entries this tool gets, in order: (event, entry).""" + exe, spec = os.path.join(_current(), "bin", "sisi"), h["hooks"] + return [(spec[sub], dict({"matcher": "*"} if sub == "watch" else {}, hooks=[ + {"type": "command", "command": "test -x %s || exit 0 ; %s %s" % (exe, exe, sub)}])) for sub in SUBS] + + +def _sync(path, wanted): + """Take every sisi entry out of a hooks file (under any event), then add `wanted`. Everything else stays.""" + raw, doc, hooks = _load(path) + new = {} + for event, groups in hooks.items(): + kept = [] + for g in groups: + inner = g.get("hooks") if isinstance(g, dict) else None + mine = [x for x in inner if _ours(x)] if isinstance(inner, list) else [] + if not mine: + kept.append(g) + elif len(mine) < len(inner): + kept.append(dict(g, hooks=[x for x in inner if not _ours(x)])) + if kept or not groups: + new[event] = kept + for event, entry in wanted: + new.setdefault(event, []).append(entry) + out = dict(doc, hooks=new) if new or "hooks" in doc else doc + if out == doc: + return "unchanged" + if raw and wanted and not os.path.exists(os.path.realpath(path) + ".before-sisi"): + store.write(os.path.realpath(path) + ".before-sisi", raw) + if not wanted and out in ({}, {"hooks": {}}): + os.remove(os.path.realpath(path)) # nothing but sisi's entries was there + else: + _save(path, json.dumps(out, indent=2, ensure_ascii=False) + "\n") + return "wired" if wanted else "removed" + + +def _hooks(h, d, mode): + return _sync(os.path.join(d, h["hooks"]["file"]), _entries(h) if mode == "add" else []) if h.get("hooks") else "" + + +def _clean(h, d): + """Take out what an older sisi left in this tool: its hook entries in a json file, or a file it generated.""" + done = [] + for rel in h.get("clean", []): + path = os.path.join(d, rel) + if rel.endswith(".json"): + if _sync(path, []) == "removed": + done.append(rel) + elif os.path.isfile(path) and not os.path.islink(path) and "sisi:generated" in _read(path)[:300]: + os.remove(path) + done.append(rel) + return "removed old " + ", ".join(done) if done else "" + + +def _rulebook(h, d, book, mode): + """Deliver the rulebook to the tool's instructions file. mode: add (create it), refresh (only what sisi put + there), remove, or check. Returns how it stands; a file sisi cannot own is left alone and reported.""" + target = os.path.join(d, h["rules"]) + if os.path.islink(target): + if os.path.realpath(target) != os.path.realpath(book): + return "left alone: it is a link to %s, not to the rulebook" % os.path.realpath(target) + if mode == "remove": + os.remove(target) + return "link removed" + return "linked" + text = _read(target) + block = "\n%s\n" % ("@%s\n" % book if h.get("import") else store.read(book)) + found = BLOCK.search(text) + if mode == "remove": + if found: + 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": + 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) + 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" + + +def refresh(book): + """The rulebook was rebuilt: bring the copy that sisi put into a tool's real instructions file up to date.""" + for h in _table(): + try: + if h.get("rules") and _dir(h): + _rulebook(h, _dir(h), book, "refresh") + except (OSError, ValueError): + pass + + +def _apply(mode): + book, bad = rules.build_rulebook() if mode == "add" else _book(), 0 + for h in _table(): + d = _dir(h) + steps = [("hooks", lambda: _hooks(h, d, mode)), ("old files", lambda: _clean(h, d))] + if h.get("rules"): + steps.insert(0, ("rulebook", lambda: _rulebook(h, d, book, mode))) + for label, step in steps if d else (): + try: + msg = step() + except (OSError, ValueError) as e: + msg, bad = "left alone (%s)" % e, 1 + if msg: + print("%s %s: %s" % (h["name"], label, msg)) + return bad def install(): - """Add the four hooks to the tool's settings and the rulebook to its instructions. Safe to repeat.""" - spath = os.path.join(_claude(), "settings.json") - raw = store.read(spath) - try: - settings = json.loads(raw) if raw.strip() else {} - assert isinstance(settings, dict) and isinstance(settings.get("hooks", {}), dict) - except (ValueError, AssertionError): - print("sisi install: %s is not something sisi can edit safely. Fix it first. Nothing was changed." % spath) - return 1 - exe, added = os.path.join(_current(), "bin", "sisi"), [] - for event, sub, matcher in EVENTS: - if not _wired(settings, sub): - entry = {"hooks": [{"type": "command", "command": "test -x %s || exit 0 ; %s %s" % (exe, exe, sub)}]} - if matcher: - entry["matcher"] = matcher - settings.setdefault("hooks", {}).setdefault(event, []).append(entry) - added.append(event) - if added: - if raw: - store.write(spath + ".before-sisi", raw) - store.write(spath, json.dumps(settings, indent=2) + "\n") - book = rules.build_rulebook() - mpath = os.path.join(_claude(), "CLAUDE.md") - md = store.read(mpath) - if "@" + book not in md: - store.write(mpath, (md.rstrip() + "\n\n" if md.strip() else "") + "\n@%s\n\n" % book) - print("hooks added: %s" % (", ".join(added) or "none, all four were there")) - print("rulebook: %s (loaded through %s)" % (book, mpath)) - return 0 + """Rulebook and hooks into every tool that is installed. Safe to repeat.""" + return _apply("add") + + +def uninstall(): + """Take out exactly what install put in.""" + return _apply("remove") + + +def _source(): + """The URL this checkout came from: its github or origin remote, else its first. "" when it has none.""" + names = store.git(["remote"], store.ROOT)[1].split() + for name in [n for n in ("github", "origin") if n in names] + names: + rc, url = store.git(["remote", "get-url", name], store.ROOT) + return url.strip() if rc == 0 else "" + return "" def _switch(dest): @@ -66,9 +210,11 @@ def release(): print("sisi release: the tests fail. Nothing was released.") return 1 folder = os.path.join(store.LIB, "releases") - name = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + name = time.strftime("%Y%m%dT%H%M%S", time.gmtime()) + "%03dZ" % (time.time() % 1 * 1000) # two in one second differ dest = os.path.join(folder, name) shutil.copytree(store.ROOT, dest, ignore=shutil.ignore_patterns(".git", ".agent-work", ".sisi", "__pycache__")) + if _source(): + store.write(os.path.join(dest, "SOURCE"), _source() + "\n") _switch(dest) subprocess.run([os.path.join(dest, "bin", "sisi"), "rulebook"]) for old in sorted(os.listdir(folder))[:-4]: @@ -93,20 +239,52 @@ def rollback(): return 0 -def doctor(cwd=None): +def update(): + """Fetch the newest sisi from where the release in use came from, and release it. No checkout needed.""" + url = store.read(os.path.join(_current(), "SOURCE")).strip() + if not url: + print("sisi update: the release in use does not record where it came from. Run `sisi release` from a checkout that has a remote.") + return 1 + with tempfile.TemporaryDirectory(prefix="sisi-update-") as tmp: + src = os.path.join(tmp, "sisi") + if subprocess.run(["git", "clone", "-q", "--depth", "1", url, src]).returncode: + print("sisi update: could not fetch %s. Nothing was changed." % url) + return 1 + return subprocess.run([sys.executable, os.path.join(src, "bin", "sisi"), "release"]).returncode + + +def _wired(h, d): + """Does the tool's hooks file hold every current sisi entry?""" + hooks = _load(os.path.join(d, h["hooks"]["file"]))[2] + have = {(event, SISI.search(x["command"]).group(1)) for event, groups in hooks.items() for g in groups + if isinstance(g, dict) and isinstance(g.get("hooks"), list) for x in g["hooks"] if _ours(x)} + return {(h["hooks"][sub], sub) for sub in SUBS} <= have + + +def _state(h, d): + if not d: + return "not installed" + if not h.get("rules"): + return "not covered" try: - settings = json.loads(store.read(os.path.join(_claude(), "settings.json")) or "{}") - except ValueError: - settings = {} - book = store.read(os.path.join(store.DATA, "generated", "core.md")) + state = "rulebook " + _rulebook(h, d, _book(), "check") + if h.get("hooks"): + state += "; hooks " + ("wired" if _wired(h, d) else "MISSING (run `sisi install`)") + return state if h.get("hooks") else state + "; rulebook only" + except (OSError, ValueError, TypeError) as e: + return "unreadable (%s)" % e + + +def doctor(cwd=None): + book = store.read(_book()) age = models.age_days() print("this copy: %s" % store.ROOT) 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("hooks: %s" % ", ".join("%s %s" % (e, "wired" if _wired(settings, s) else "MISSING (run `sisi install`)") - for e, s, _ in EVENTS)) 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.lines(rules.path(rules.PROJECT, cwd))))) print("models table: %s" % ("none yet" if age is None else "%d days old" % age)) + for h in _table(): + print("%-13s %s%s" % (h["name"] + ":", _state(h, _dir(h)), ". " + h.get("limits", "") if _dir(h) else "")) return 0 diff --git a/sisi/rules.py b/sisi/rules.py index 2c256eb..6dee939 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -86,6 +86,11 @@ def build_rulebook(): text += "\n" + HEAD_USER + "\n" + "\n".join(mine) + "\n" out = store.data("generated", "core.md") store.write(out, text) + try: # the copies of it that sisi put into a tool's real instructions file follow + from . import install + install.refresh(out) + except Exception: + pass # this runs inside hooks: it must never raise return out diff --git a/sisi/store.py b/sisi/store.py index e93f795..754d46f 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -2,12 +2,18 @@ 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, subprocess +import contextlib, fcntl, hashlib, json, os, stat, subprocess ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) HOME = os.path.expanduser("~") -DATA = os.environ.get("SISI_DATA") or os.path.join(HOME, ".local", "share", "sisi") -STATE = os.environ.get("SISI_STATE") or os.path.join(HOME, ".local", "state", "sisi") +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) + return os.environ.get(own) or (os.path.join(base, "sisi") if base else os.path.join(HOME, *fallback, "sisi")) + + +DATA = _where("SISI_DATA", "XDG_DATA_HOME", (".local", "share")) +STATE = _where("SISI_STATE", "XDG_STATE_HOME", (".local", "state")) LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi") # Every setting there is. The person overrides one under "core" in config.json in their store. @@ -44,6 +50,10 @@ def write(path, text): tmp = "%s.%d.tmp" % (path, os.getpid()) with open(tmp, "w", encoding="utf-8") 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) diff --git a/tests/test_core.py b/tests/test_core.py index f9ff597..028ba6e 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -3,7 +3,7 @@ Learning: work is done, the retro is forced, its improvement is a rule in the next session, the rules are organized and the change can be undone. Delegation: the lead is stopped when it should be delegating, and the models table is researched, read and kept fresh.""" -import glob, hashlib, json, os, random, shutil, subprocess, sys, tempfile, time, unittest +import glob, hashlib, json, os, random, re, shutil, subprocess, sys, tempfile, time, unittest REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GAP = ("--gap", "the export dropped rows with empty names until the person noticed", @@ -45,7 +45,7 @@ class Core(unittest.TestCase): self.data = os.path.join(self.tmp, "data") self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"), CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude")) - for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE"): + for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"): self.env.pop(name, None) self.proj = self.project("alpha") @@ -432,6 +432,323 @@ class Core(unittest.TestCase): self.assertEqual(self.sisi(name, stdin="not json")[0], 0, name) self.assertEqual(self.sisi(name, stdin=json.dumps({"session_id": "s1", "cwd": "/no/such/place"}))[0], 0, name) + # any agent in any harness + + def watch(self, fields, sid="s1"): + return self.sisi("watch", stdin=json.dumps(fields), sid=sid) + + def families(self, sid, tool="Edit", **extra): + """The same pre-tool-use event as three hosts name its fields.""" + c = self.proj + return [dict(session_id=sid, cwd=c, hook_event_name="PreToolUse", tool_name=tool, tool_input=extra), + dict(sessionId=sid, cwd=c, toolName=tool, toolInput=extra), + dict(conversationId=sid, workspacePaths=[c], toolCall={"name": tool, "args": extra}), + dict(conversation_id=sid, workspace_roots=[c, "/elsewhere"], tool=tool, input=extra)] + + def test_every_alias_family_drives_watch_to_the_same_decision(self): + for i, fields in enumerate(self.families("x0")): + sid = "fam%d" % i + fields = json.loads(json.dumps(fields).replace("x0", sid)) + rc, _, err = self.watch(fields, sid) + self.assertEqual((rc, "nothing starts before done" in err), (2, True), fields) # no done yet + self.done(sid) + self.assertEqual(self.watch(fields, sid)[0], 0, fields) + s = self.state(sid) + self.assertEqual((s["direct"], s["changed"]), (1, True), fields) + self.assertTrue(s["project"].startswith("alpha-"), fields) # the cwd was found too + for i, fields in enumerate(self.families("x0", agentId="a1")[:0] + [dict(f, **extra) for f, extra in zip( + self.families("sub"), ({"agent_id": "a"}, {"agentId": "a"}, {"subagentType": "t"}, {"agent_transcript_path": "/t"}))]): + self.assertEqual(self.watch(fields, "sub%d" % i)[0], 0, fields) # a subagent is left alone + self.assertEqual(self.watch(dict(self.families("t")[0], transcript_path="/x/subagents/1.jsonl"), "t")[0], 0) + self.hook("prompt", sid="w", lastUserInput="You are a worker. Do this task yourself.") + self.assertTrue(self.state("w")["worker"]) + + def test_a_field_of_the_wrong_type_is_empty_never_an_error(self): + sys.path.insert(0, REPO) + from sisi import hooks + ugly = {"session_id": 5, "sessionId": ["a"], "cwd": {}, "workspace_roots": [3], "tool_name": [1], "toolCall": "x", + "tool_input": "ls", "toolInput": None, "prompt": 7, "agent_id": 0, "transcript_path": 4, "hook_event_name": []} + self.assertEqual(hooks.normalize(ugly), dict(session_id="", cwd="", tool_name="", tool_input={}, prompt="", + hook_event_name="", subagent=False)) + self.assertEqual(hooks.normalize({"toolCall": {"name": "Bash", "args": {"command": "ls"}}})["tool_input"], {"command": "ls"}) + for name in ("tick", "prompt", "watch", "gate"): + self.assertEqual(self.sisi(name, stdin=json.dumps(ugly))[0], 0, name) + self.assertEqual(self.sisi(name, stdin=json.dumps(dict(ugly, session_id="s9", cwd=self.proj)))[0], 0, name) + self.assertEqual(self.sisi(name, stdin="[1, 2]")[0], 0, name) + self.assertFalse(os.path.exists(os.path.join(self.tmp, "state", "core-errors.log"))) + + def test_tool_classes_come_from_one_table_and_a_broken_table_meters_nothing(self): + sys.path.insert(0, REPO) + from sisi import hooks + for name, kind in (("run_terminal_command", "shell"), ("exec_command", "shell"), ("Bash", "shell"), ("apply_patch", "edit"), + ("search_replace", "edit"), ("MultiEdit", "edit"), ("spawn_agent", "delegate"), ("Agent", "delegate"), + ("mcp__t3__delegate_task", "delegate"), ("read_file", "read"), ("web_search", "web"), ("grep_search", "search"), + ("AskUserQuestion", "")): + self.assertEqual(hooks.tool_class(name), kind, name) + self.hook("tick") + self.hook("prompt", prompt="go") + for name in ("apply_patch", "search_replace", "write_file"): + self.assertEqual(self.tool(name)[0], 2, name) # an edit needs done + self.assertEqual(self.tool("spawn_agent")[0], 2) # so does a delegation + self.done() + self.table(WORKERS) + self.assertEqual(self.tool("spawn_agent", tool_input={"model": "sonnet"})[0], 2) # and then a pick + self.sisi("pick", "hard", sid="s1") + self.assertEqual(self.tool("spawn_agent", tool_input={"model": "sonnet"})[0], 0) + self.sisi("pick", "hard", sid="s1") + self.assertEqual(self.tool("spawn_subagent", tool_input={"target": {"model": "sonnet"}})[0], 0) + self.hook("prompt", prompt="next") + for name in ("run_terminal_command", "exec_command", "Bash", "apply_patch", "search_replace", "read_file", "grep_search", "web_fetch"): + self.assertEqual(self.tool(name, tool_input={"command": "ls"})[0], 0, name) # eight, all metered + rc, _, err = self.tool("exec_command", tool_input={"command": "ls"}) + self.assertEqual((rc, "Delegate the rest" in err), (2, True)) + folder = os.path.join(self.tmp, "broken") + os.makedirs(os.path.join(folder, "canon")) + self.write(os.path.join(folder, "canon", "tools.json"), "{not json") + was = (hooks.store.ROOT, hooks._classes) + hooks.store.ROOT, hooks._classes = folder, None + try: + self.assertEqual((hooks.tool_class("Bash"), hooks.tool_class("x_delegate_task")), ("", "delegate")) + finally: + hooks.store.ROOT, hooks._classes = was + + def harness(self, *names): + """A temporary home holding the folders of these tools, as the person's home would.""" + home = self.env["HOME"] = os.path.join(self.tmp, "home") + self.env.pop("CLAUDE_CONFIG_DIR", None) + for name in names: + os.makedirs(os.path.join(home, name)) + return home + + OLD = "/home/swaits/.local/lib/sisi/current/bin/sisi" + + def old_claude(self): + run = lambda sub: {"type": "command", "command": "%s %s --tool claude-code" % (self.OLD, sub)} + return {"model": "x", "hooks": { + "SessionStart": [{"hooks": [run("tick")]}], "UserPromptSubmit": [{"hooks": [run("prompt")]}], + "PreToolUse": [{"matcher": "*", "hooks": [run("watch")]}], + "Stop": [{"hooks": [{"type": "command", "command": "foreign-b"}, run("gate")]}], + "SubagentStop": [{"hooks": [run("gate --subagent")]}], "PostToolUse": [{"matcher": "*", "hooks": [run("watch")]}], + "PostToolUseFailure": [{"hooks": [run("watch")]}], "Notification": [{"hooks": [{"type": "command", "command": "foreign-a"}]}]}} + + def test_install_replaces_old_claude_entries_with_the_four_current_ones(self): + home = self.harness(".claude") + spath = self.write(os.path.join(home, ".claude", "settings.json"), json.dumps(self.old_claude(), indent=4)) + self.assertEqual(self.sisi("install")[0], 0) + first = self.read(spath) + settings = json.loads(first) + exe = os.path.join(self.env["SISI_LIB"], "current", "bin", "sisi") + self.assertEqual(sorted(settings["hooks"]), ["Notification", "PreToolUse", "SessionStart", "Stop", "UserPromptSubmit"]) + self.assertEqual(settings["hooks"]["Notification"], self.old_claude()["hooks"]["Notification"]) # foreign, untouched + self.assertEqual(settings["hooks"]["Stop"][0], {"hooks": [{"type": "command", "command": "foreign-b"}]}) + commands = [h["command"] for groups in settings["hooks"].values() for g in groups for h in g["hooks"]] + self.assertEqual(sorted(c for c in commands if "bin/sisi" in c), + sorted("test -x %s || exit 0 ; %s %s" % (exe, exe, s) for s in ("tick", "prompt", "watch", "gate"))) + self.assertEqual(settings["hooks"]["PreToolUse"][0]["matcher"], "*") + self.assertEqual(settings["model"], "x") + self.assertEqual(self.sisi("install")[0], 0) + self.assertEqual(self.read(spath), first) # a second install changes nothing + self.assertEqual(json.loads(self.read(spath + ".before-sisi")), self.old_claude()) + + def test_install_reaches_every_installed_tool_and_creates_nothing_for_the_rest(self): + home = self.harness(".codex", ".config/opencode", ".gemini", ".config/muse", ".cursor") + before = sorted(os.path.join(r, n) for r, ds, fs in os.walk(home) for n in ds + fs) + self.assertEqual(self.sisi("install")[0], 0) + book = os.path.join(self.data, "generated", "core.md") + for rel in (".codex/AGENTS.md", ".config/opencode/AGENTS.md", ".gemini/GEMINI.md"): + self.assertEqual(os.path.realpath(os.path.join(home, rel)), os.path.realpath(book), rel) + codex = json.loads(self.read(home, ".codex", "hooks.json"))["hooks"] + self.assertEqual(sorted(codex), ["PreToolUse", "SessionStart", "Stop", "UserPromptSubmit"]) + after = sorted(os.path.join(r, n) for r, ds, fs in os.walk(home) for n in ds + fs) + self.assertEqual(sorted(set(after) - set(before)), sorted(os.path.join(home, p) for p in ( + ".codex/AGENTS.md", ".codex/hooks.json", ".config/opencode/AGENTS.md", ".gemini/GEMINI.md"))) + self.assertEqual(self.sisi("uninstall")[0], 0) + self.assertEqual(sorted(os.path.join(r, n) for r, ds, fs in os.walk(home) for n in ds + fs), before) # all of it gone again + + def test_old_leftovers_are_cleaned_and_only_what_is_sisis(self): + home = self.harness(".config/opencode", ".gemini", ".pi/agent") + plugin = self.write(os.path.join(self.mkdir(home, ".config/opencode/plugins"), "sisi.js"), "// sisi:generated by `sisi install`\n") + own = self.write(os.path.join(self.mkdir(home, ".pi/agent/extensions"), "sisi.ts"), "// my own extension\n") + gem = {"theme": "dark", "hooks": {"BeforeTool": [{"hooks": [{"command": "x/bin/sisi watch --tool gemini"}, {"command": "mine"}]}], + "AfterAgent": [{"hooks": [{"command": "x/bin/sisi gate --tool gemini"}]}]}} + spath = self.write(os.path.join(home, ".gemini", "settings.json"), json.dumps(gem)) + self.assertEqual(self.sisi("install")[0], 0) + self.assertFalse(os.path.exists(plugin)) + self.assertTrue(os.path.exists(own)) # not sisi-generated: kept + self.assertEqual(json.loads(self.read(spath)), {"theme": "dark", "hooks": {"BeforeTool": [{"hooks": [{"command": "mine"}]}]}}) + + def put(self, path, data): + with open(path, "wb") as f: + f.write(data) + + def bytes(self, path): + with open(path, "rb") as f: + return f.read() + + def mkdir(self, *parts): + path = os.path.join(*parts) + os.makedirs(path, exist_ok=True) + return path + + def test_the_rulebook_is_delivered_by_link_or_marked_block_and_follows_the_rules(self): + home = self.harness(".codex", ".config/opencode", ".gemini", ".pi/agent") + mine = self.write(os.path.join(home, ".codex", "AGENTS.md"), "# my notes\nno newline at the end") + elsewhere = self.write(os.path.join(self.tmp, "their-rules.md"), "theirs\n") + os.symlink(elsewhere, os.path.join(home, ".gemini", "GEMINI.md")) + os.symlink(os.path.join(self.data, "generated", "core.md"), os.path.join(home, ".config", "opencode", "AGENTS.md")) # an old install + rc, out, _ = self.sisi("install") + self.assertEqual(rc, 0) + self.assertIn("antigravity rulebook: left alone", out) # reported + self.assertEqual(os.readlink(os.path.join(home, ".gemini", "GEMINI.md")), elsewhere) + self.assertEqual(self.read(elsewhere), "theirs\n") + self.assertTrue(os.path.islink(os.path.join(home, ".pi", "agent", "AGENTS.md"))) # absent: a link, in its subfolder + book = self.read(self.data, "generated", "core.md") + text = self.read(mine) + self.assertEqual(text, "\n%s\n# my notes\nno newline at the end" % book) + self.assertEqual(self.sisi("learn", "Always say which check proved it")[0], 0) # a rebuild refreshes the block + new = self.read(mine) + self.assertIn("Always say which check proved it", new) + self.assertTrue(new.endswith("\n# my notes\nno newline at the end")) + self.assertEqual(new.count("sisi:begin"), 1) + self.assertEqual(self.sisi("uninstall")[0], 0) + self.assertEqual(self.read(mine), "# my notes\nno newline at the end") # exactly as it was + self.assertFalse(os.path.lexists(os.path.join(home, ".pi", "agent", "AGENTS.md"))) + self.assertEqual(os.readlink(os.path.join(home, ".gemini", "GEMINI.md")), elsewhere) + # a rebuild alone never creates anything in a tool + self.sisi("learn", "Name the check that failed first") + 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_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") + ours = lambda s: sum("bin/sisi" in h["command"] for g in json.loads(self.read(s))["hooks"].values() for e in g for h in e["hooks"]) + # a symlinked settings file is edited where it really is, and stays a link + real = self.write(os.path.join(self.tmp, "dotfiles-settings.json"), '{"model": "x"}') + os.symlink(real, spath) + self.assertEqual(self.sisi("install")[0], 0) + self.assertEqual((os.path.islink(spath), ours(real), json.loads(self.read(real))["model"]), (True, 4, "x")) + self.assertEqual(self.sisi("uninstall")[0], 0) + self.assertEqual(ours(real), 0) + os.remove(spath) + # a dangling link, a read-only file, comments, a trailing comma, and shapes sisi cannot edit: left exactly as they were + sisi_twice = {"hooks": {"Stop": [{"hooks": [{"command": "a/bin/sisi gate"}]}, {"hooks": [{"command": "b/bin/sisi gate --tool x"}]}]}} + raw = lambda path, data: self.put(path, data) + for bad in (b'// a comment\n{"model": "x"}', b'{"model": "x",}', b'{"hooks": {"Stop": "mine"}}', b'{"hooks": null}', + b'{"hooks": []}', b'[1]', b"\xff\xfe"): + raw(spath, bad) + self.assertEqual(self.sisi("install")[0], 1, bad) + self.assertEqual(self.bytes(spath), bad) + os.remove(spath) + os.symlink(os.path.join(self.tmp, "nowhere.json"), spath) + self.assertEqual(self.sisi("install")[0], 1) + self.assertFalse(os.path.exists(os.path.join(self.tmp, "nowhere.json"))) + os.remove(spath) + self.write(spath, '{"model": "x"}') + os.chmod(spath, 0o444) + self.assertEqual(self.sisi("install")[0], 1) + self.assertEqual((self.read(spath), os.stat(spath).st_mode & 0o777), ('{"model": "x"}', 0o444)) + os.chmod(spath, 0o600) + # the same entry twice becomes one; a missing hooks key is added; the file keeps its permissions + self.write(spath, json.dumps(sisi_twice)) + self.assertEqual(self.sisi("install")[0], 0) + self.assertEqual((ours(spath), os.stat(spath).st_mode & 0o777), (4, 0o600)) + self.assertEqual(len(json.loads(self.read(spath))["hooks"]["Stop"]), 1) + # the instructions file: a directory, a read-only file, a file that is not text + for make in (lambda: os.mkdir(mpath), lambda: (self.write(mpath, "mine\n"), os.chmod(mpath, 0o444)), + lambda: raw(mpath, b"\xff\xfe")): + if os.path.lexists(mpath): + os.chmod(mpath, 0o600) + shutil.rmtree(mpath) if os.path.isdir(mpath) else os.remove(mpath) + make() + rc, out, _ = self.sisi("install") + self.assertEqual((rc, "claude rulebook: left alone" in out), (1, True)) + self.assertEqual(self.bytes(mpath), b"\xff\xfe") + + def test_paths_follow_the_xdg_folders_and_the_sisi_overrides_win(self): + where = lambda extra: subprocess.run([sys.executable, "-B", "-c", "from sisi import store; print(store.DATA, store.STATE)"], + cwd=REPO, env=dict({k: v for k, v in self.env.items() if not k.startswith("SISI_")}, **extra), + capture_output=True, text=True, stdin=subprocess.DEVNULL).stdout.split() + x = os.path.join(self.tmp, "xdg") + self.assertEqual(where({}), [os.path.join(self.tmp, ".local", "share", "sisi"), os.path.join(self.tmp, ".local", "state", "sisi")]) + self.assertEqual(where({"XDG_DATA_HOME": x + "/d", "XDG_STATE_HOME": x + "/s"}), [x + "/d/sisi", x + "/s/sisi"]) + self.assertEqual(where({"XDG_DATA_HOME": x + "/d", "SISI_DATA": x + "/mine", "SISI_STATE": x + "/st", "XDG_STATE_HOME": x + "/s"}), + [x + "/mine", x + "/st"]) + env = {k: v for k, v in self.env.items() if k != "SISI_STATE"} + subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi"), "version"], env=dict(env, XDG_STATE_HOME=x + "/s"), + cwd=self.proj, capture_output=True, stdin=subprocess.DEVNULL) + self.assertTrue(os.path.isdir(x + "/s/sisi/pycache")) # bin/sisi uses the same scratch folder + + def source(self, version): + """A small git repository holding the product and a test that passes: where `sisi update` fetches from.""" + src = os.path.join(self.tmp, "source") + if not os.path.isdir(src): + for name in ("sisi", "bin", "canon"): + shutil.copytree(os.path.join(REPO, name), os.path.join(src, name), ignore=shutil.ignore_patterns("__pycache__")) + os.makedirs(os.path.join(src, "tests")) + self.write(os.path.join(src, "tests", "test_ok.py"), "import unittest\nclass T(unittest.TestCase):\n def test(self): pass\n") + subprocess.run(["git", "init", "-q"], cwd=src, check=True) + self.write(os.path.join(src, "VERSION"), version + "\n") + subprocess.run(["git", "add", "-A"], cwd=src, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", version], cwd=src, check=True) + return src + + def test_update_releases_the_newest_sisi_from_where_this_one_came_from(self): + env = dict(self.env, TMPDIR=self.mkdir(self.tmp, "tmpdir")) + run = lambda exe, *a: subprocess.run([sys.executable, exe] + list(a), cwd=self.proj, env=env, capture_output=True, text=True, stdin=subprocess.DEVNULL) + src = self.source("1.0.0") + self.assertEqual(run(os.path.join(src, "bin", "sisi"), "update").returncode, 1) # nothing released yet: nothing recorded + self.assertEqual(run(os.path.join(src, "bin", "sisi"), "release").returncode, 0) # a checkout with no remote + self.assertFalse(os.path.exists(os.path.join(self.env["SISI_LIB"], "current", "SOURCE"))) + rc = run(os.path.join(src, "bin", "sisi"), "update") + self.assertEqual((rc.returncode, "does not record where it came from" in rc.stdout), (1, True)) + mine = os.path.join(self.tmp, "mine") + subprocess.run(["git", "clone", "-q", src, mine], check=True, capture_output=True) # the person's checkout, with its remote + self.assertEqual(run(os.path.join(mine, "bin", "sisi"), "release").returncode, 0) + self.assertEqual(self.read(self.env["SISI_LIB"], "current", "SOURCE").strip(), src) + self.sisi("learn", "Always keep what the person wrote") + self.write(os.path.join(self.data, "models.md"), WORKERS) + self.write(os.path.join(self.data, "retro.jsonl"), '{"gap": "g"}\n') + keep = {n: self.read(self.data, n) for n in ("models.md", "retro.jsonl", "rules/user.md")} + self.source("2.0.0") + rc = run(os.path.join(mine, "bin", "sisi"), "update") + self.assertEqual(rc.returncode, 0, rc.stdout + rc.stderr) + self.assertEqual(run(os.path.join(self.env["SISI_LIB"], "current", "bin", "sisi"), "version").stdout.strip(), "2.0.0") + self.assertEqual(self.read(self.env["SISI_LIB"], "current", "SOURCE").strip(), src) # and it can update again + self.assertEqual({n: self.read(self.data, n) for n in keep}, keep) + self.assertIn("Always keep what the person wrote", self.read(self.data, "generated", "core.md")) + self.assertEqual(os.listdir(env["TMPDIR"]), []) # the fetched copy is gone + + def test_doctor_says_how_every_tool_stands(self): + names = [h["name"] for h in json.loads(self.read(REPO, "canon", "harnesses.json"))] + home = self.harness(".claude", ".codex", ".grok", ".config/muse", ".pi") + self.sisi("install") + out = self.sisi("doctor")[1] + lines = {l.split(":")[0]: l for l in out.splitlines() if l.split(":")[0] in names} + self.assertEqual(sorted(lines), sorted(names)) + self.assertIn("rulebook imported; hooks wired", lines["claude"]) + self.assertIn("The built-in Explore and Plan subagents do not load CLAUDE.md", lines["claude"]) + self.assertIn("rulebook linked; hooks wired", lines["codex"]) + self.assertIn("hosted web search is not metered", lines["codex"]) + self.assertIn("rulebook linked; rulebook only", lines["grok"]) + self.assertIn("already runs the hooks in ~/.claude/settings.json", lines["grok"]) + self.assertIn("not covered. No documented global instructions file", lines["muse"]) + self.assertIn("not installed", lines["cursor"]) + self.assertNotIn("MISSING", out) + os.remove(os.path.join(home, ".claude", "settings.json")) + self.assertIn("hooks MISSING", self.sisi("doctor")[1]) + + def test_a_hook_loads_neither_the_installer_nor_the_retro_and_stays_quick(self): + self.hook("tick") # the rulebook exists now + self.tool("Read") # and the bytecode is compiled + r = subprocess.run([sys.executable, "-X", "importtime", os.path.join(REPO, "bin", "sisi"), "watch"], cwd=self.proj, env=self.env, + input=json.dumps({"session_id": "s1", "tool_name": "Read"}), capture_output=True, text=True) + mods = {m[2].strip(): int(m[0]) for m in re.findall(r"import time:\s+(\d+) \|\s+(\d+) \|(.*)", r.stderr)} + ours = {m: t for m, t in mods.items() if m.startswith("sisi")} + self.assertTrue({"sisi.hooks", "sisi.store"} <= set(ours), ours) + self.assertFalse({"sisi.install", "sisi.retro"} & set(ours), ours) + self.assertLess(sum(ours.values()), 20000, ours) # microseconds spent importing our own modules + # the standing constraints def test_the_spec_is_unchanged(self): @@ -442,7 +759,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, 1200, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLess(code, 1360, "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), 7800)