From 5744f3149c2a58e23fc48fa01adc11a0b5dda608 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 03:34:05 -0700 Subject: [PATCH] Gate judges a session by its own edits, measured, not guessed The end-of-turn gate attributes changed files to the session that changed them: edit tool calls by path, and shell commands by a snapshot of the tree before and after. A session answers for failing checks, and is asked for a retrospective, only over its own files. Another agent's work in progress is allowed once, marked unverified, with a note that the work is not done. Single-session behaviour is unchanged, shown by a property test. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 18 ++ docs/design.md | 25 +- docs/harnesses.md | 25 +- sisi/adapters.py | 34 ++- sisi/cli.py | 8 + sisi/gate.py | 508 ++++++++++++++++++++++++++++++++++- sisi/gitutil.py | 34 +++ sisi/hookio.py | 28 ++ sisi/tick.py | 8 + sisi/watch.py | 192 +++++++++++++ sisi/wiring.py | 41 ++- tests/test_adapters.py | 24 ++ tests/test_gate.py | 462 +++++++++++++++++++++++++++++++ tests/test_install_safety.py | 3 +- tests/test_wiring.py | 18 ++ 15 files changed, 1387 insertions(+), 41 deletions(-) create mode 100644 sisi/watch.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 40e4dc2..59e104a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ All notable changes to this project are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/). +## Unreleased + +### Changed + +- The end-of-turn gate now attributes edits to the session that made them. Edit-tool calls are read + incrementally from the session's own transcript (a per-session offset; native subagents' transcripts + under the session count too), and shell commands are measured, not guessed: where the tool has + before/after tool hooks (Claude Code, Codex, Gemini, Copilot, Cursor), `sisi watch` snapshots the + tree (sizes and mtimes only) before and after the command and attributes the changed paths to the + session. A retrospective is required only when this session, or a subagent it started, edited files + since its last retrospective. When checks fail and no path changed since the last passing state is + attributed to this session, the stop is allowed once per distinct tree state with a note that the + contract is not satisfied and the work must not be reported as done, recorded unverified; otherwise + the session is sent back as before. `git commit` and sisi's own commands (except `contract + init/waive/trust`) never count as edits; another agent's write inside this session's command window + is attributed to this session (strict, documented); tools without before/after tool events keep the + command-text classifier. See the known limits in [docs/design.md](docs/design.md). + ## [0.2.0] - 2026-11-23 ### Added diff --git a/docs/design.md b/docs/design.md index e39239f..2b808cf 100644 --- a/docs/design.md +++ b/docs/design.md @@ -303,7 +303,8 @@ Designed, not built: - Replay experiments on the task set before a learned change ships, brief templates, playbooks. (Shipping and removal of learned changes exist in the simpler ship-first-measure-after form described in Part 3.) - The taste judge and rung 5 judging by a model. -- Blocking gates for tools other than Claude Code. +- A blocked turn proven end to end in each tool. Gates are built for the tools whose hooks allow one + (see [harnesses.md](harnesses.md)); most are tested against the documented hook format only. - Harvest sources other than Claude Code. ## Build order @@ -340,5 +341,25 @@ resumes without redoing closed nodes (to be model-checked, then tested). - Experiments at this volume detect large effects only. - The taste judge is worthless until the human has given enough verdicts, and it is trusted per kind of work, not globally. -- Blocking gates outside Claude Code, Muse's instruction path and Codex's hook format are unverified. +- Outside Claude Code and Copilot CLI, a blocked turn has not been run end to end; Muse has no confirmed + instruction path or end-of-turn hook, and OpenCode's plugin events are unproven. +- The end-of-turn gate attributes edits per session. Edit-tool calls are read from the session's own + transcript (incrementally, from a per-session offset), including the transcripts of subagents it + started natively. Shell commands are not judged from their text where the tool has before/after tool + hooks (Claude Code, Codex, Gemini, Copilot and Cursor have them wired): `sisi watch` takes a stat-only + tree snapshot (file sizes and modification times, `.gitignore` honoured, `.git` never included) before + and after the command and attributes exactly the paths that changed to that session, and the session + answers for a failing check only when a path changed since the last passing state is attributed to + it. That measurement has honest limits: another agent changing the tree inside this session's command + window is attributed to this session (it errs strict, the safe side); a change that keeps a file's + size and mtime, a write to a git-ignored file, and a write between the last complete transcript line + and a crash are invisible; `git commit` changes only `.git` and so is never an edit; sisi's own + commands write only personal data and state (except `sisi contract init/waive/trust`) and never count, + so `sisi retro` cannot create the need for another retro. Where a tool has no before/after tool events + (Qwen, Pi, OpenCode), shell commands are still judged by the older command-text classifier, which + over-attributes interpreters and test runners. A missing or unreadable transcript, a corrupt line, an + unparseable shell command, a shell command whose after-record never arrives, and an unread transcript + tail over 64 MB are all treated as "this session edited" — strict — never as "someone else did it". + Attribution decides who is sent back and who owes a retrospective; it never turns a failing check into + a pass — a stop allowed over another session's failing tree is recorded unverified, once per tree state. - This is several months of building. Each phase is useful on its own. diff --git a/docs/harnesses.md b/docs/harnesses.md index 0f1dbef..2b1bf80 100644 --- a/docs/harnesses.md +++ b/docs/harnesses.md @@ -27,17 +27,19 @@ uninstalling makes hooks exit silently instead of erroring on every turn. The pe between each tool's hook JSON and the gate lives in `sisi/hookio.py`; the adapters live in `sisi/adapters.py`; the textual JSON editing lives in `sisi/hookjson.py`. Install also links any skills shipped under `canon/skills` into `~/.agents/skills`; `sisi doctor` reports the linked -state. Hooks fail open: any error lets the agent finish. +state. Hooks fail open: any error lets the agent finish. Where a tool's hook input has no transcript path, the gate falls back to its pre-attribution behaviour (tree-change based, with no per-session edit attribution). Shell commands are attributed by measurement, not by their text, wherever the tool has confirmed before/after tool events (`sisi watch` takes a stat-only tree snapshot before and after the command and attributes the paths that changed to the session; provably read-only commands skip the pair); tools without confirmed before/after tool events keep the command-text classifier described in docs/design.md. ## Claude Code Fully wired, as before: an `@import` line in `~/.claude/CLAUDE.md`, `SessionStart` → `sisi tick`, -`Stop`/`SubagentStop` → `sisi gate` (blocking) in `~/.claude/settings.json`. Nothing for you to do. +`Stop`/`SubagentStop` → `sisi gate` (blocking), and `PreToolUse`/`PostToolUse` with matcher `Bash` → +`sisi watch` (before/after tree measurement) in `~/.claude/settings.json`. Nothing for you to do. ## Codex CLI Rulebook symlink at `~/.codex/AGENTS.md` (or `$CODEX_HOME/AGENTS.md`), plus hooks in -`~/.codex/hooks.json`: `SessionStart` → tick, `Stop`/`SubagentStop` → gate, blocking with +`~/.codex/hooks.json`: `SessionStart` → tick, `Stop`/`SubagentStop` → gate, +`PreToolUse`/`PostToolUse` (matcher `Bash`) → `sisi watch`, blocking with `{"decision":"block","reason":...}`. One step is yours: Codex only runs hooks you have trusted, by exact definition hash. After `sisi install`, open Codex, run `/hooks`, and trust the sisi hooks; repeat after any change to the hook commands (for example after moving the sisi clone). `sisi doctor` cannot verify @@ -50,7 +52,8 @@ file path. ## Gemini CLI Rulebook symlink at `~/.gemini/GEMINI.md`, hooks merged into `~/.gemini/settings.json`: `SessionStart` -→ tick (lessons injected as `additionalContext`), `AfterAgent` → gate (`{"decision":"deny","reason":...}` +→ tick (lessons injected as `additionalContext`), `AfterAgent` → gate, `BeforeTool`/`AfterTool` → +`sisi watch` (`{"decision":"deny","reason":...}` rejects the response and forces a retry). Built from the hooks reference; Gemini is not installed on the development machine, so this has not run live. Gemini has no subagent-stop event in its hook list, so only the main turn is gated. @@ -59,7 +62,7 @@ only the main turn is gated. Rulebook symlink at `~/.copilot/copilot-instructions.md` (or under `$COPILOT_HOME`), hooks in `~/.copilot/hooks/sisi.json`: `sessionStart` → tick (`additionalContext`), `agentStop`/`subagentStop` → -gate (`{"decision":"block","reason":...}` forces another turn). Verified end to end in a throwaway home: +gate (`{"decision":"block","reason":...}` forces another turn), `preToolUse`/`postToolUse` → `sisi watch`. Verified end to end in a throwaway home: a secret planted in session-start context was answered by the model, and a blocking `agentStop` visibly forced a second turn. The cloud coding agent only runs hooks committed in the repository (`.github/hooks/*.json`); sisi does not write repository files, so cloud enforcement needs such a file @@ -72,7 +75,8 @@ Rulebook symlink at `~/.qwen/QWEN.md`, hooks merged into `~/.qwen/settings.json` first run, so run Qwen once before `sisi install`. Verified: the session-start hook was observed firing with its documented payload (a full turn needs an auth type configured). Qwen's question tool is named `ask_user_question` (the rulebook still names Claude Code's dialog; generalising that wording is future -work). +work). Qwen's before/after tool event names are not confirmed, so sisi registers no watch hooks there: +shell edits in Qwen are still judged from the command text. ## Pi @@ -81,12 +85,14 @@ have your own file there) plus a generated extension at `~/.pi/agent/extensions/ runs `sisi tick` on `session_start` and injects the lessons at `before_agent_start`, and runs the gate on `agent_before_settle`, forcing one continuation with the failure report when checks fail (capped by the gate's own three send-backs). Verified: the extension loads in real Pi and tick runs; the blocking -continuation could not be exercised end to end without a model login in the throwaway home. +continuation could not be exercised end to end without a model login in the throwaway home. Pi gets no +watch hooks (its extension has no confirmed before/after shell payload for this), so shell edits there are +still judged from the command text. ## Cursor Hooks merged into `~/.cursor/hooks.json`: `sessionStart` → tick (lessons as `additional_context`), -`stop`/`subagentStop` → gate. Cursor cannot veto a stop; instead a non-empty `followup_message` is +`stop`/`subagentStop` → gate, `preToolUse`/`postToolUse` → `sisi watch`. Cursor cannot veto a stop; instead a non-empty `followup_message` is auto-submitted as the next user message, which is how the gate sends the agent back (Cursor caps this at 5 per script by default; sisi's own cap is 3). Only completed (not aborted/error) stops are gated. There is no confirmed user-global instruction *file* for Cursor, so sisi wires no global rulebook there; @@ -102,7 +108,8 @@ client prompt API where one exists. Be clear about the limits: `session.idle` fi finished and cannot veto anything, and on OpenCode v2.3.2 no plugin event delivery or lesson injection could be confirmed in headless runs (the plugin itself is loaded — verified — and the v1-style hooks and v2 `setup()` registration are both attempted, all fail-open). Treat OpenCode enforcement as unproven -until it is observed on your version; `sisi doctor` says `unknown` on purpose. +until it is observed on your version; `sisi doctor` says `unknown` on purpose. OpenCode gets no watch +hooks either, so shell edits there are still judged from the command text. ## Muse Code diff --git a/sisi/adapters.py b/sisi/adapters.py index 8d67f79..10d0371 100644 --- a/sisi/adapters.py +++ b/sisi/adapters.py @@ -516,6 +516,8 @@ class Codex(Adapter): "SessionStart": {"cmd": _cmd("tick", "codex"), "timeout": 10, "sub": "tick", "matcher": "startup|resume"}, "Stop": {"cmd": _cmd("gate", "codex"), "timeout": _gate_timeout(), "sub": "gate"}, "SubagentStop": {"cmd": _cmd("gate", "codex", True), "timeout": 30, "sub": "gate"}, + "PreToolUse": {"cmd": _cmd("watch", "codex"), "timeout": 60, "sub": "watch", "matcher": "Bash"}, + "PostToolUse": {"cmd": _cmd("watch", "codex"), "timeout": 60, "sub": "watch", "matcher": "Bash"}, } def detect(self): @@ -536,7 +538,8 @@ class Codex(Adapter): % os.path.join(self.dir(), "AGENTS.override.md")) def unwire(self, m, notes): - subs = {"SessionStart": "tick", "Stop": "gate", "SubagentStop": "gate"} + subs = {"SessionStart": "tick", "Stop": "gate", "SubagentStop": "gate", + "PreToolUse": "watch", "PostToolUse": "watch"} unmerge_json(m, self.hooks_file(), "nested", subs, self.spec(), notes, "codex") def shadowed(self): @@ -548,7 +551,8 @@ class Codex(Adapter): hw = nested_wired(_load_obj(self.hooks_file()) or {}, self.spec()) rb = _link_ok(link) missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["SessionStart"]), - ("gate hook", hw["Stop"]), ("subagent hook", hw["SubagentStop"])) if not ok] + ("gate hook", hw["Stop"]), ("subagent hook", hw["SubagentStop"]), + ("watch-before hook", hw.get("PreToolUse", False)), ("watch-after hook", hw.get("PostToolUse", False))) if not ok] if self.shadowed(): st.update(rulebook=False, tick=hw["SessionStart"], wired=False, detail="AGENTS.override.md in %s shadows the AGENTS.md link, so the rulebook will not load; " @@ -575,6 +579,8 @@ class Gemini(Adapter): return { "SessionStart": {"cmd": _cmd("tick", "gemini"), "timeout": 10000, "sub": "tick", "name": "sisi-tick"}, "AfterAgent": {"cmd": _cmd("gate", "gemini"), "timeout": _gate_timeout() * 1000, "sub": "gate", "name": "sisi-gate"}, + "BeforeTool": {"cmd": _cmd("watch", "gemini"), "timeout": 60000, "sub": "watch", "name": "sisi-watch-before"}, + "AfterTool": {"cmd": _cmd("watch", "gemini"), "timeout": 60000, "sub": "watch", "name": "sisi-watch-after"}, } def detect(self): @@ -592,7 +598,8 @@ class Gemini(Adapter): wiring._link(m, os.path.join(self.dir(), "GEMINI.md"), wiring.core(), notes, "gemini") def unwire(self, m, notes): - unmerge_json(m, self.settings(), "nested", {"SessionStart": "tick", "AfterAgent": "gate"}, + unmerge_json(m, self.settings(), "nested", {"SessionStart": "tick", "AfterAgent": "gate", + "BeforeTool": "watch", "AfterTool": "watch"}, self.spec(), notes, "gemini") unlink_ours(os.path.join(self.dir(), "GEMINI.md"), notes) @@ -601,7 +608,8 @@ class Gemini(Adapter): link = os.path.join(self.dir(), "GEMINI.md") hw = nested_wired(_load_obj(self.settings()) or {}, self.spec()) rb = _link_ok(link) - missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["SessionStart"]), ("gate hook", hw["AfterAgent"])) if not ok] + missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["SessionStart"]), ("gate hook", hw["AfterAgent"]), + ("watch-before hook", hw.get("BeforeTool", False)), ("watch-after hook", hw.get("AfterTool", False))) if not ok] st.update(rulebook=rb, tick=hw["SessionStart"], wired=not missing, detail=("missing: " + ", ".join(missing)) if missing else "rulebook link + tick + gate hooks (shared ~/.gemini file also serves Antigravity)") return st @@ -621,6 +629,8 @@ class Copilot(Adapter): "sessionStart": {"cmd": _cmd("tick", "copilot"), "timeout": 10, "sub": "tick"}, "agentStop": {"cmd": _cmd("gate", "copilot"), "timeout": _gate_timeout(), "sub": "gate"}, "subagentStop": {"cmd": _cmd("gate", "copilot", True), "timeout": 30, "sub": "gate"}, + "preToolUse": {"cmd": _cmd("watch", "copilot"), "timeout": 60, "sub": "watch"}, + "postToolUse": {"cmd": _cmd("watch", "copilot"), "timeout": 60, "sub": "watch"}, } def detect(self): @@ -642,7 +652,8 @@ class Copilot(Adapter): wiring._link(m, os.path.join(self.dir(), "copilot-instructions.md"), wiring.core(), notes, "copilot") def unwire(self, m, notes): - subs = {"sessionStart": "tick", "agentStop": "gate", "subagentStop": "gate"} + subs = {"sessionStart": "tick", "agentStop": "gate", "subagentStop": "gate", + "preToolUse": "watch", "postToolUse": "watch"} unmerge_json(m, self.hooks_file(), "flat", subs, self.spec(), notes, "copilot", created_version=1, make_entry=self._entry) unlink_ours(os.path.join(self.dir(), "copilot-instructions.md"), notes) @@ -653,7 +664,8 @@ class Copilot(Adapter): hw = flat_wired(_load_obj(self.hooks_file()) or {}, self.spec()) rb = _link_ok(link) missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["sessionStart"]), - ("gate hook", hw["agentStop"]), ("subagent hook", hw["subagentStop"])) if not ok] + ("gate hook", hw["agentStop"]), ("subagent hook", hw["subagentStop"]), + ("watch-before hook", hw.get("preToolUse", False)), ("watch-after hook", hw.get("postToolUse", False))) if not ok] st.update(rulebook=rb, tick=hw["sessionStart"], wired=not missing, detail=("missing: " + ", ".join(missing)) if missing else "rulebook link + tick + gate hooks in %s (CLI; cloud needs a committed .github/hooks file, not written by sisi)" % self.hooks_file()) return st @@ -702,7 +714,7 @@ class Qwen(Adapter): missing = [n for n, ok in (("rulebook link", rb), ("tick hook", hw["SessionStart"]), ("gate hook", hw["Stop"]), ("subagent hook", hw["SubagentStop"])) if not ok] st.update(rulebook=rb, tick=hw["SessionStart"], wired=not missing, - detail=("missing: " + ", ".join(missing)) if missing else "rulebook link + tick + gate hooks") + detail=("missing: " + ", ".join(missing)) if missing else "rulebook link + tick + gate hooks (no confirmed before/after tool events, so shell edits there are still judged from the command text)") return st @@ -720,6 +732,8 @@ class Cursor(Adapter): "sessionStart": {"cmd": _cmd("tick", "cursor"), "timeout": 10, "sub": "tick"}, "stop": {"cmd": _cmd("gate", "cursor"), "timeout": _gate_timeout(), "sub": "gate"}, "subagentStop": {"cmd": _cmd("gate", "cursor", True), "timeout": 30, "sub": "gate"}, + "preToolUse": {"cmd": _cmd("watch", "cursor"), "timeout": 60, "sub": "watch"}, + "postToolUse": {"cmd": _cmd("watch", "cursor"), "timeout": 60, "sub": "watch"}, } @staticmethod @@ -739,14 +753,16 @@ class Cursor(Adapter): merge_json(m, self.hooks_file(), "flat", self.spec(), notes, "cursor", created_version=1, make_entry=self._entry) def unwire(self, m, notes): - subs = {"sessionStart": "tick", "stop": "gate", "subagentStop": "gate"} + subs = {"sessionStart": "tick", "stop": "gate", "subagentStop": "gate", + "preToolUse": "watch", "postToolUse": "watch"} unmerge_json(m, self.hooks_file(), "flat", subs, self.spec(), notes, "cursor", created_version=1, make_entry=self._entry) def status(self): st = Adapter.status(self) hw = flat_wired(_load_obj(self.hooks_file()) or {}, self.spec()) - missing = [n for n, ok in (("tick hook", hw["sessionStart"]), ("gate hook", hw["stop"]), ("subagent hook", hw["subagentStop"])) if not ok] + missing = [n for n, ok in (("tick hook", hw["sessionStart"]), ("gate hook", hw["stop"]), ("subagent hook", hw["subagentStop"]), + ("watch-before hook", hw.get("preToolUse", False)), ("watch-after hook", hw.get("postToolUse", False))) if not ok] st.update(rulebook=False, tick=hw["sessionStart"], wired=not missing, detail=("missing: " + ", ".join(missing) + "; " if missing else "tick + gate hooks in %s; " % self.hooks_file()) + "no global rulebook file is confirmed for Cursor (project AGENTS.md files still load)") diff --git a/sisi/cli.py b/sisi/cli.py index 6385107..1da5618 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -12,6 +12,7 @@ HELP = """sisi: shared rulebook and enforced definitions of done for every AI co sisi verify --all | --state run both tiers; print only the deep-check state (with --json) sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape) sisi tick [--tool NAME] session-start hook + sisi watch [--before|--after] before/after shell-tool hook: measures whether the command changed the project sisi install [--dry-run] | uninstall | doctor wire sisi into the tools (by reference), undo, inspect; --dry-run only prints what would change sisi release [--deep] run the source's checks, then make the stable copy the tools run (see docs/developing.md) @@ -359,6 +360,13 @@ def main(argv): return hookio.gate_main(t, args) from . import gate return gate.main(args) + if cmd == "watch": + if t and t != "claude-code": + from . import hookio + if hookio.known(t): + return hookio.watch_main(t, args) + from . import watch + return watch.main(args) if cmd == "tick": if t and t != "claude-code": from . import hookio diff --git a/sisi/gate.py b/sisi/gate.py index e823a71..6aa5d82 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -1,8 +1,8 @@ """End-of-turn gate. Claude Code Stop hook: JSON on stdin, block = JSON {"decision":"block","reason":...} on stdout, exit 0. Anything that goes wrong inside sisi allows (fail open) and is logged to the state dir.""" -import hashlib, json, os, sys, time +import hashlib, json, os, re, shlex, sys, time -from . import contract as C, deep as D, gitutil, store, trust, verify as V +from . import contract as C, deep as D, gitutil, paths, store, trust, verify as V def _read_payload(): @@ -71,6 +71,369 @@ class _Ctx: return "block", template.replace("{n}", "%d of %d" % (blocks + 1, maxb)) +# ---------------------------------------------------------------- attribution +# Attribution reads this session's own transcript (Claude-Code-shaped JSONL: assistant records whose +# message.content holds tool_use blocks). Only bytes after the per-session offset stored in the session +# record are read, so a long transcript costs only its new tail; subagent transcripts found under +# /subagents/** are read the same way and count as this session's edits. +# Edit/Write/MultiEdit/NotebookEdit (and any tool whose name says it writes) count, with the file paths +# in their input. Shell (Bash) commands count when they plausibly write: a redirect, tee/dd-of, an +# in-place editor (sed -i, perl -i, awk -i inplace), git apply/checkout/restore/reset/clean/mv/rm, +# patch, cp/mv/rm/touch/mkdir, or any program that is not on the provably read-only list (ls, cat, +# grep, git status/diff/log/..., test runners and interpreters therefore count: they can write). +# Known blind spots: a read-only-looking command that writes through indirection sisi cannot see +# (a script reached by a read-only interpreter flag combination that slips the lists, a daemon, or a +# tool whose transcript shape is not Claude-Code JSONL), and writes made between the last complete +# transcript line and a crash. A missing/unreadable transcript, a corrupt line, or a shell command +# that cannot be tokenised is treated as an edit by this session (fail strict, never fail open here); +# so is an unread tail over 64 MB, which is skipped (offset moved to its end) rather than scanned +# inside the gate's time budget. + +EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} +_READONLY_CMDS = {"ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "ag", "wc", "file", + "stat", "du", "df", "which", "type", "pwd", "date", "env", "printenv", "sort", + "uniq", "cut", "tr", "jq", "yq", "diff", "cmp", "md5sum", "sha1sum", "sha256sum", + "basename", "dirname", "realpath", "readlink", "ps", "top", "free", "uname", + "hostname", "id", "whoami", "less", "more", "man", "help", "history"} +_READONLY_GIT = {"status", "diff", "log", "show", "rev-parse", "ls-files", "ls-tree", "describe", + "blame", "grep", "cat-file", "branch", "tag", "remote", "config", "add", "commit"} +_GH_READ = {("run", "list"), ("run", "view"), ("run", "watch"), ("pr", "list"), ("pr", "view"), + ("pr", "status"), ("pr", "diff"), ("pr", "checks"), ("issue", "list"), ("issue", "view"), + ("issue", "status"), ("repo", "view"), ("repo", "list"), ("release", "list"), + ("release", "view"), ("workflow", "list"), ("workflow", "view"), ("auth", "status")} +_WRITE_WORDS = ("edit", "write", "create", "delete", "move", "rename", "patch", "apply", "insert") +_SHELL_WRITE_RE = re.compile( + r">>?[^=]|\btee\b|\bdd\b[^;&|]*\bof=|\bsed\b[^;&|]*\s-[a-z]*i|\bperl\b[^;&|]*\s-[a-z]*i" + r"|\bawk\b[^;&|]*inplace|\bgit\s+(apply|checkout|restore|reset|clean|mv|rm)\b" + r"|\bpatch\b|\b(cp|mv|rm|touch|mkdir|rmdir|install|ln)\b", re.I) + + +def _shell_may_write(command): + """True: plausibly writes files. False: provably read-only. None: cannot be tokenised.""" + if not isinstance(command, str) or not command.strip(): + return False + if _SHELL_WRITE_RE.search(command): + return True + try: + lex = shlex.shlex(command, posix=True, punctuation_chars=True) + lex.whitespace_split = True + tokens = list(lex) + except ValueError: + return None + segments, cur = [], [] + for tok in tokens: + if tok in (";", "&", "|", "&&", "||"): + segments.append(cur) + cur = [] + else: + cur.append(tok) + segments.append(cur) + for seg in segments: + i = 0 + while i < len(seg) and (re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", seg[i]) or seg[i] in ("sudo", "command", "exec", "time", "nice")): + i += 1 + if i >= len(seg): + continue + prog = os.path.basename(seg[i]) + rest = seg[i + 1:] + if prog in ("cd", "export", "unset", "set", "alias", "umask", "wait", "jobs", "fg", "bg", + "exit", "return", "break", "continue", "shift", "readonly", "local", "declare", + "typeset", "echo", "printf", "true", "false", ":", "test", "[", "[[", "eval"): + if prog == "eval": + return True + continue + if prog == "find": + if any(a in ("-delete", "-exec", "-execdir", "-ok", "-okdir", "-fls", "-fprint") for a in rest): + return True + continue + if prog == "git": + sub = next((a for a in rest if not a.startswith("-")), "") + if sub == "stash": # only listing a stash leaves the tree alone; push/pop/apply change it + tail = rest[rest.index(sub) + 1:] + if not tail or tail[0] in ("list", "show"): + continue + return True + if sub in _READONLY_GIT and not (sub == "config" and any(not a.startswith("-") for a in rest[rest.index(sub) + 1:])): + continue # add/commit touch .git only, never a working-tree file + return True + if prog == "gh": + pair = tuple(a for a in rest if not a.startswith("-"))[:2] + if pair in _GH_READ: + continue + if pair and pair[0] == "api" and not any(a in ("-X", "--method", "-f", "-F", "--field", "--raw-field") + or a.startswith(("-f", "-F")) for a in rest): + continue + return True + if prog == "sisi": + # sisi writes only personal data and state, never the project — except contract + # init/waive/trust, which do record something about (or in) this project. + if rest and rest[0] == "contract": + if len(rest) > 1 and rest[1] in ("init", "waive", "trust", "untrust"): + return True + continue + continue + if prog in _READONLY_CMDS: + if prog in ("sed", "awk", "jq", "yq") and any("inplace" in a or a.startswith("-i") for a in rest): + return True + continue + return True # interpreters, build/test runners, scripts, anything unlisted: can write + return False + + +def _input_files(inp): + out = [] + if isinstance(inp, dict): + for k in ("file_path", "notebook_path", "path", "filename", "filePath"): + if isinstance(inp.get(k), str) and inp[k]: + out.append(inp[k]) + return out + + +def _parse_transcript_chunk(data, measured=False): + """Parse complete JSONL bytes. Returns (edits, files, writing, corrupt, consumed_bytes, shell_edits). + In measured mode Bash calls are not guessed from their text at all: the before/after tree + measurement (sisi/watch.py) has already attributed whatever they actually changed — except + `sisi contract init/waive/trust`, which record project state outside the measured files.""" + if data.endswith(b"\n") or not data: + consumed, body = len(data), data + else: + cut = data.rfind(b"\n") + tail = data[cut + 1:] + try: + json.loads(tail.decode("utf-8", "replace")) + consumed, body = len(data), data # a complete final line without its newline yet + except ValueError: + consumed, body = cut + 1, data[:cut + 1] # partial line: leave it for the next read + edits, files, writing, corrupt, shell_edits = 0, [], False, 0, 0 + for raw in body.split(b"\n"): + if not raw.strip(): + continue + if len(raw) > 131072 and b"tool_use" not in raw and b"Bash" not in raw: + continue # a huge tool-result line: no tool call hides in it worth parsing + try: + d = json.loads(raw.decode("utf-8", "replace")) + except ValueError: + corrupt += 1 + edits += 1 # an unreadable line may be the edit we cannot see: count it + writing = True + continue + if not isinstance(d, dict): + continue + content = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None + for x in content if isinstance(content, list) else []: + if not isinstance(x, dict) or x.get("type") != "tool_use": + continue + name = x.get("name") or "" + inp = x.get("input") if isinstance(x.get("input"), dict) else {} + if name in EDIT_TOOLS or any(w in name.lower() for w in _WRITE_WORDS): + edits += 1 + writing = True + files += _input_files(inp) + elif name in ("Bash", "Shell", "bash", "shell"): + cmd = inp.get("command") if isinstance(inp.get("command"), str) else inp.get("cmd") + if measured: + if isinstance(cmd, str) and re.search(r"\bsisi\s+contract\s+(init|waive|trust|untrust)\b", cmd): + edits += 1 + shell_edits += 1 + writing = True + files.append(".sisi/contract.json") + continue # everything else was measured, not guessed + may = _shell_may_write(cmd) + if may is None: + corrupt += 1 + edits += 1 + shell_edits += 1 + writing = True + elif may: + edits += 1 + shell_edits += 1 + writing = True + return edits, files, writing, corrupt, consumed, shell_edits + + +def _scan_one(sess, store_key, path): + """Advance one transcript's offset in the session record. Returns (edits, files, writing, unknown).""" + offsets = sess.setdefault("attr_sub_offsets", {}) if store_key == "sub" else None + try: + size = os.path.getsize(os.path.expanduser(path)) + except OSError: + return 0, [], False, True, 0 # missing or unreadable: unknown, treated as edited by the caller + if store_key == "sub": + offset = int(offsets.get(path, 0) or 0) + else: + offset = int(sess.get("attr_offset", 0) or 0) + unknown = False + if offset > size: + offset, unknown = 0, True # truncated or replaced: rescan, and do not trust the gap + if size - offset > 64 * 1024 * 1024: + # Too much unread tail to scan inside the gate's budget: skip it and count it as a + # possible edit by this session (strict), rather than guessing it was someone else's. + if store_key == "sub": + offsets[path] = size + else: + sess["attr_offset"] = size + return 1, [], True, True, 0 + edits, files, writing, sh = 0, [], False, 0 + try: + with open(os.path.expanduser(path), "rb") as f: + f.seek(offset) + data = f.read() + except OSError: + return 0, [], False, True, 0 + if data: + e, fl, w, corrupt, consumed, sh = _parse_transcript_chunk(data, measured=bool(sess.get("attr_measured"))) + edits, files, writing = e, fl, w + unknown = unknown or corrupt > 0 + offset += consumed + if store_key == "sub": + offsets[path] = offset + else: + sess["attr_offset"] = offset + return edits, files, writing, unknown, sh + + +def _subagent_transcripts(tp): + """Native subagent transcripts under this session's transcript, Claude Code layout.""" + if not isinstance(tp, str) or not tp.endswith(".jsonl"): + return [] + root = os.path.join(os.path.expanduser(tp)[:-len(".jsonl")], "subagents") + out = [] + for dirpath, dirs, names in os.walk(root): + dirs.sort() + for n in sorted(names): + if n.startswith("agent-") and n.endswith(".jsonl"): + out.append(os.path.join(dirpath, n)) + return out + + +def _update_attribution(sess, tp): + """Refresh this session's edit count from its own (and its native subagents') transcripts. + + Returns {"gen", "writing", "unknown"} or None when no transcript path is known at all + (the caller then falls back to the pre-attribution behaviour). Fails towards edited.""" + if not isinstance(tp, str) or not tp: + return None + if sess.get("attr_tp") != tp: + sess.update(attr_tp=tp, attr_offset=0, attr_gen=0, attr_pass_gen=0, attr_retro_gen=0, + attr_baseline_gen=0, attr_writing=False, attr_files=[], attr_sub_offsets={}) + sess.setdefault("attr_gen", 0) + sess.setdefault("attr_pass_gen", 0) + sess.setdefault("attr_retro_gen", 0) + sess.setdefault("attr_baseline_gen", 0) + unknown = False + total, all_files, shell_total = 0, [], 0 + e, fl, w, unk, sh = _scan_one(sess, "main", tp) + total += e + shell_total += sh + all_files += fl + unknown = unknown or unk + if w: + sess["attr_writing"] = True + for sub in _subagent_transcripts(tp): + e, fl, w, unk, sh = _scan_one(sess, "sub", sub) + total += e + shell_total += sh + all_files += fl + unknown = unknown or unk + if w: + sess["attr_writing"] = True + sess["attr_gen"] = int(sess.get("attr_gen", 0)) + total + if all_files: + have = sess.setdefault("attr_files", []) + for f in all_files: + if f not in have: + have.append(f) + del have[:-500] + if unknown: + sess["attr_writing"] = True + return {"gen": int(sess["attr_gen"]), "writing": bool(sess.get("attr_writing")), "unknown": bool(unknown), + "edits": total, "files": all_files, "shell_edits": shell_total} + + +def _changed_paths(top, cwd, own_files): + """Up to five working-tree paths changed against HEAD that this session did not edit.""" + try: + rels = gitutil.measure(cwd, gitutil.head(cwd))["files"] + except Exception: + return [] + own = set() + for f in own_files or []: + own.add(os.path.normpath(f)) + if top: + try: + own.add(os.path.normpath(os.path.relpath(f, top))) + except ValueError: + pass + out = [] + for r in rels: + if os.path.normpath(r) not in own: + out.append(r) + if len(out) >= 5: + break + return out + + +def _other_sessions(top, cwd, changed, sid, tp): + """Session ids that plausibly made `changed` edits, from session records and sibling transcripts.""" + found = [] + + def note(x): + if x and x != sid and x not in found: + found.append(x) + + def mentions(path, limit=2 * 1024 * 1024): + try: + with open(os.path.expanduser(path), "rb") as f: + f.seek(0, 2) + size = f.tell() + f.seek(max(0, size - limit)) + data = f.read() + except OSError: + return False + return any(os.path.basename(c).encode() in data or c.encode() in data for c in changed) + + try: + names = sorted(os.listdir(os.path.join(paths.state(), "sessions"))) + except OSError: + names = [] + for n in names: + if not n.endswith(".json"): + continue + try: + with open(os.path.join(paths.state(), "sessions", n), encoding="utf-8") as f: + r = json.load(f) + except (OSError, ValueError): + continue + if not isinstance(r, dict): + continue + osid = r.get("session_id") or n[:-5] + if osid == sid: + continue + proj = r.get("req_project") or r.get("cwd") + if top and proj and gitutil.root(proj) not in (top, proj) and os.path.realpath(proj) != os.path.realpath(top): + # a record for another folder says nothing about this tree + if os.path.realpath(proj) != os.path.realpath(cwd): + continue + files = r.get("attr_files") or [] + hit = any(os.path.basename(f) in [os.path.basename(c) for c in changed] or + (top and os.path.normpath(os.path.join(top, c)) == os.path.normpath(f)) for f in files for c in changed) + if hit: + note(osid) + elif isinstance(r.get("transcript_path"), str) and changed and mentions(r["transcript_path"]): + note(osid) + if isinstance(tp, str) and changed: + try: + sibs = sorted(os.listdir(os.path.dirname(os.path.expanduser(tp)) or ".")) + except OSError: + sibs = [] + for n in sibs: + if n.endswith(".jsonl") and os.path.join(os.path.dirname(os.path.expanduser(tp)), n) != os.path.expanduser(tp): + p = os.path.join(os.path.dirname(os.path.expanduser(tp)), n) + if mentions(p): + note(n[:-len(".jsonl")]) + return found[:3] + + def decide(payload): """Return ('allow', message_or_None) or ('block', reason).""" cfg = store.config() @@ -89,6 +452,44 @@ def decide(payload): sess["req_contract"], sess["req_project"] = bool(path), cwd if isinstance(payload.get("transcript_path"), str): sess["transcript_path"] = payload["transcript_path"] # `sisi retro` reads the request's start from it + tp = sess.get("transcript_path") if isinstance(sess.get("transcript_path"), str) else None + try: + attr = _update_attribution(sess, tp) if tp else None + except Exception as e: # attribution must never break the gate: fail towards strict, not open + store.log_error("gate-attribution", e) + attr = {"gen": int(sess.get("attr_gen", 0) or 0), "writing": True, "unknown": True} + if attr is not None: + try: + from . import watch + if watch.consume_pending(sess, sid, cwd): + attr["unknown"] = True # a shell command with a before but no after: strict + except Exception as e: + store.log_error("gate-watch-pending", e) + since_pass = sess.setdefault("attr_since_pass", []) + top0 = gitutil.root(cwd) + for f in attr.get("files") or []: + rel = f + if os.path.isabs(f) and top0: + try: + rel = os.path.relpath(f, top0) + except ValueError: + rel = f + if rel not in since_pass: + since_pass.append(rel) + if attr.get("shell_edits") and not sess.get("attr_measured") and "*shell*" not in since_pass: + since_pass.append("*shell*") # a text-classified shell edit: its paths are unknown + try: + store.save_session(sid, sess) # persist the offset even on an early return below + except Exception: + pass + + def _own_since(key): + if attr is None: + return None # no transcript path known: pre-attribution behaviour + return bool(attr["unknown"] or int(sess.get("attr_gen", 0) or 0) > int(sess.get(key, 0) or 0)) + + own_since_pass = _own_since("attr_pass_gen") + own_since_retro = _own_since("attr_retro_gen") c, errs = None, [] if path: project = C.project_dir(path) @@ -127,9 +528,81 @@ def decide(payload): from . import retro if retro.satisfied(repo_key, since, fp): sess["retro_done"] = True + if attr is not None: + sess["attr_retro_gen"] = int(sess.get("attr_gen", 0) or 0) return False return True + _csp = {} + + def changed_paths_since_pass(): + if "v" not in _csp: + v = None + if attr is not None: + try: + from . import watch + v = watch.changed_since_pass(sid, cwd) + except Exception as e: + store.log_error("gate-watch-diff", e) + _csp["v"] = v if v is not None else _changed_paths(top, cwd, []) + return _csp["v"] + + def own_responsible(): + """This session answers for the failing tree when a path that changed since the last + passing state is attributed to it (edit tool path, or a measured command window), or + when attribution is uncertain. Gen-only fallback when no path differs (e.g. the + contract itself changed, which the stat snapshot does not track).""" + if attr is None: + return True + if attr["unknown"]: + return True + changed = changed_paths_since_pass() + if not changed: + return bool(own_since_pass) + since = set(sess.get("attr_since_pass") or []) + if "*shell*" in since or "*shell-unmeasured*" in since: + return True + return any(p in changed for p in since) + + def other_allow(failing_text, contract_id=None): + """Someone else's failing tree: allow once per distinct tree state, recorded unverified.""" + if sess.get("other_notice_fp") == fp: + return ctx.allow() + sess["other_notice_fp"] = fp + store.append("results", {"ts": store.now(), "contract": contract_id, "project": project if path else repo_key, + "check": "gate", "item": "gate", "kind": None, "rung": None, + "status": "unverified", "duration_s": 0.0, "tool": store.tool(), "session": sid}) + own_paths = set(sess.get("attr_since_pass") or []) + changed = [p for p in changed_paths_since_pass() if p not in own_paths][:5] \ + or _changed_paths(top, cwd, sess.get("attr_files") or []) + others = _other_sessions(top, cwd, changed, sid, tp) + lines = ["sisi: the contract is NOT satisfied, but this session has not edited files since the " + "checks last passed (or since it started), so this turn may end. Do not report this work " + "as done; the result is recorded as UNVERIFIED. Relay this to the human.", + "Failing checks:\n" + failing_text] + if changed: + lines.append("Files changed in the tree that this session did not edit (likely another " + "session's work in progress): " + ", ".join(changed)) + if others: + lines.append("The changed files appear in the transcript/session record of session(s): " + + ", ".join(others)) + else: + lines.append("Files changed by another session are the likely cause; no other session " + "could be identified from the records available.") + return ctx.allow("\n".join(lines)) + + def other_tree_changed(): + """The tree moved since this session's last pass or its start (dirty-vs-HEAD is the + fallback proxy when no start fingerprint was ever recorded for the session).""" + if fp is not None: + if sess.get("attr_pass_fp"): + return fp != sess["attr_pass_fp"] + if sess.get("baseline_fp") is not None: + return fp != sess["baseline_fp"] + if sess.get("last_fp") is not None: + return fp != sess["last_fp"] + return bool(_changed_paths(top, cwd, sess.get("attr_files") or [])) + w = _new_waiver(top, sess) if (top and not path) else None # a fresh waiver re-opens the decision # A turn that changed nothing is not punished and not re-checked. if fp is not None and not w: @@ -161,15 +634,29 @@ def decide(payload): sess["req_check_s"] = float(sess.get("req_check_s", 0.0)) + (time.time() - t_run) V.record(c, project, results, fp) if V.ok(results): + own_before_pass = own_since_pass + responsible_before_pass = own_responsible() if attr is not None else True + other_before_pass = attr is not None and not responsible_before_pass and other_tree_changed() + if attr is not None: + sess["attr_pass_gen"] = int(sess.get("attr_gen", 0) or 0) + sess["attr_pass_fp"] = fp + sess["attr_since_pass"] = [] + try: + from . import watch + watch.save_pass_snapshot(sid, cwd) + except Exception as e: + store.log_error("gate-watch-pass", e) if dfail: tails = "\n".join("- deep check %s [%s]:\n%s" % (i["id"], i["status"], "\n".join(" " + l for l in i["tail"].splitlines()[-15:])) for i in ds["failed"]) + if other_before_pass: + return other_allow(tails[:4000], c["id"] if c else None) return ctx.block("sisi: the fast checks pass, but the deep checks failed on the current tree " "(send-back {n}). Fix the work, then re-run them with `sisi verify --deep " "--background` (see `sisi verify --state`). Do not report this work as done.\n\n%s" % tails[:4000], c["id"], project, kind="deep") changed = fp is None or fp != sess.get("baseline_fp") - if need_retro(changed): + if need_retro(changed if attr is None else bool(own_since_retro)): from . import retro return ctx.block(retro.TEMPLATE, c["id"] if c else None, project, kind="retro") if ds and ds["state"] != "fresh-pass" and sess.get("deep_notice") != (fp or "nofp"): @@ -181,6 +668,8 @@ def decide(payload): return ctx.allow({"message": "sisi: deep checks %s; the work is not yet fully verified" % ds["state"], "context": text}) return ctx.allow() + if attr is not None and not own_responsible() and other_tree_changed(): + return other_allow(V.failure_report(results), c["id"] if c else None) msg = ("sisi: the contract at %s is not satisfied (send-back {n}). Fix the work, then run " "`sisi verify` until it passes. Do not report this work as done.\n\n%s" % (path, V.failure_report(results))) @@ -200,8 +689,12 @@ def decide(payload): if sess.get("baseline") is None: sess.update(baseline=gitutil.measure(cwd), head=gitutil.head(cwd), started=sess.get("started") or store.now()) sess["baseline_fp"] = fp + if attr is not None: + sess["attr_baseline_gen"] = int(sess.get("attr_gen", 0) or 0) store.save_session(sid, sess) return "allow", None + if attr is not None and not _own_since("attr_baseline_gen") and not attr["unknown"]: + return ctx.allow() # this session edited nothing here: no retro, no growth send-back for others' work # Fix 4: growth is measured from the session start, or from the latest waiver. if w: sess["baseline"] = {"lines": w.get("lines", 0), "files": w.get("files", [])} @@ -213,7 +706,7 @@ def decide(payload): dl = max(0, now["lines"] - base["lines"]) df = len(set(now["files"]) - set(base["files"])) if not (dl > int(g.get("growth_lines", 40)) or df > int(g.get("growth_files", 3))): - if need_retro(bool(sess.get("waiver_ns"))): # a waiver in this session means real work happened + if need_retro(bool(sess.get("waiver_ns")) if attr is None else bool(own_since_retro)): from . import retro return ctx.block(retro.TEMPLATE, kind="retro") return ctx.allow() @@ -223,9 +716,6 @@ def decide(payload): "the change needs no checks, run `sisi contract waive \"\"` instead." % (dl, df)) -EDIT_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} - - def subagent_edits(transcript): """(edited_files, start_ts) from a subagent transcript (JSONL). start_ts is in sisi's timestamp format, or None.""" edited, start = False, None @@ -241,6 +731,10 @@ def subagent_edits(transcript): for x in content if isinstance(content, list) else []: if isinstance(x, dict) and x.get("type") == "tool_use" and x.get("name") in EDIT_TOOLS: edited = True + if isinstance(x, dict) and x.get("type") == "tool_use" and x.get("name") in ("Bash", "Shell"): + inp = x.get("input") if isinstance(x.get("input"), dict) else {} + if _shell_may_write(inp.get("command")) is not False: + edited = True return edited, start diff --git a/sisi/gitutil.py b/sisi/gitutil.py index 65b6628..eb94eda 100644 --- a/sisi/gitutil.py +++ b/sisi/gitutil.py @@ -56,6 +56,40 @@ def measure(cwd, base=None, max_untracked=200): return {"lines": lines, "files": sorted(files)[:2000]} +def snapshot(cwd, max_files=200000): + """Stat-only working-tree snapshot: {relative path: [size, mtime_ns]}, [-1, -1] for a tracked + file that is gone. Tracked plus untracked-but-not-ignored files inside a git tree (via + `git ls-files`, so .gitignore is honoured and .git itself never appears — a commit therefore + changes nothing here); a plain directory walk skipping .git outside one. No file content is + read, so a change that keeps both size and mtime is invisible to it.""" + _root = root(cwd) + top = _root or os.path.abspath(cwd) + rels = [] + if _root: + rc, out = _git(top, "ls-files", "-c", "-o", "--exclude-standard", "-z", timeout=10) + if rc == 0: + rels = [r for r in out.split("\0") if r] + if not rels: + for dirpath, dirs, names in os.walk(top): + dirs[:] = sorted(d for d in dirs if d != ".git") + for n in sorted(names): + rels.append(os.path.relpath(os.path.join(dirpath, n), top)) + files = {} + for rel in rels[:max_files]: + try: + st = os.stat(os.path.join(top, rel)) + files[rel] = [st.st_size, st.st_mtime_ns] + except OSError: + files[rel] = [-1, -1] + return {"root": top, "files": files} + + +def snapshot_diff(before, after): + """Sorted relative paths whose stat entry appeared, vanished or changed between snapshots.""" + a, b = (before or {}).get("files", {}), (after or {}).get("files", {}) + return sorted(k for k in set(a) | set(b) if a.get(k) != b.get(k)) + + def fingerprint(cwd, extra_files=()): """Cheap hash of the working-tree state: HEAD, the diff against it, untracked files (path, size, mtime), plus the content of `extra_files` (e.g. the contract, which may be git-ignored). None outside git.""" diff --git a/sisi/hookio.py b/sisi/hookio.py index f43e4a6..39d63f7 100644 --- a/sisi/hookio.py +++ b/sisi/hookio.py @@ -51,6 +51,17 @@ def normalize(tool, d): ): if val: out[key] = val + for key, val in ( + ("hook_event_name", _s(d, "hook_event_name", "hookEventName", "event_name", "event")), + ("tool_name", _s(d, "tool_name", "toolName", "tool", "name")), + ("tool_use_id", _s(d, "tool_use_id", "toolUseId", "tool_id")), + ): + if val: + out[key] = val + for k in ("tool_input", "toolInput", "input"): + if isinstance(d.get(k), dict): + out["tool_input"] = d[k] + break cwd = _s(d, "cwd") if not cwd and isinstance(d.get("workspace_roots"), list): roots = [r for r in d["workspace_roots"] if isinstance(r, str) and r] @@ -132,6 +143,23 @@ def gate_main(tool, args=()): return rc +def watch_main(tool, args=()): + """Before/after tool measurement for the other tools. Always exits 0 (fail open).""" + try: + d = _payload(store.read_stdin()) + if d is not None: + from . import watch + norm = normalize(tool, d) + _t, _c, ev, _cwd, _sid = watch.extract(norm) + if "--before" in args or ev in watch.BEFORE_EVENTS: + watch.before(norm) + elif "--after" in args or ev in watch.AFTER_EVENTS: + watch.after(norm) + except Exception as e: + store.log_error("watch-%s" % tool, e) + return 0 + + def _tick_out(tool, text): text = (text or "").strip("\n") if tool in ("pi", "opencode"): diff --git a/sisi/tick.py b/sisi/tick.py index f2b0ad3..bb8fea8 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -93,6 +93,14 @@ def main(args=()): "source": payload.get("source"), "blocks": 0} if isinstance(payload.get("transcript_path"), str): rec["transcript_path"] = payload["transcript_path"] + # Attribution starts here: the gate reads only transcript bytes after this offset. + rec["attr_tp"] = payload["transcript_path"] + try: + rec["attr_offset"] = os.path.getsize(os.path.expanduser(payload["transcript_path"])) + except OSError: + rec["attr_offset"] = 0 + rec.update(attr_gen=0, attr_pass_gen=0, attr_retro_gen=0, attr_baseline_gen=0, + attr_writing=False, attr_files=[], attr_sub_offsets={}) from . import contract as C, gitutil if gitutil.root(cwd): rec["head"] = gitutil.head(cwd) diff --git a/sisi/watch.py b/sisi/watch.py new file mode 100644 index 0000000..eb6d07f --- /dev/null +++ b/sisi/watch.py @@ -0,0 +1,192 @@ +"""Before/after tool measurement: did this session's shell command actually change the project? + +Registered as PreToolUse/PostToolUse (and each tool's confirmed equivalent) with a Bash/shell +matcher where the tool has one. Before an uncertain shell command, a stat-only tree snapshot +(gitutil.snapshot: sizes and mtimes, .gitignore honoured, .git never included, so `git commit` +changes nothing) is kept in the state dir; after it, the snapshot is taken again and the paths +that differ are attributed to this session in its session record. Provably read-only commands +(gate._shell_may_write is False: ls/cat/grep, read-only git/gh, and sisi's own commands other +than contract init/waive/trust, which write only personal data and state) skip the pair entirely. +Another agent changing the tree inside the command window is attributed to this session too — +that errs strict, which is the safe side. A pending before-record with no after (the command was +killed) is likewise treated as this session having edited, with no known paths (a sentinel). +Both hooks fail open: any error is logged and the tool call proceeds. +""" +import json, os, time + +from . import gitutil, paths, store + +BEFORE_EVENTS = {"PreToolUse", "BeforeTool", "preToolUse", "beforeShellExecution", "tool_call"} +AFTER_EVENTS = {"PostToolUse", "AfterTool", "postToolUse", "afterShellExecution", + "postToolUseFailure", "tool_result"} +SHELL_TOOLS = ("bash", "shell", "command", "terminal", "exec") + + +def _s(d, *keys): + for k in keys: + v = d.get(k) + if isinstance(v, str) and v: + return v + return None + + +def extract(d): + """(tool_name, command, event, cwd, session_id) from any tool's tool-hook payload shape.""" + inp = None + for k in ("tool_input", "toolInput", "input", "tool_input_dict"): + if isinstance(d.get(k), dict): + inp = d[k] + break + cmd = None + if inp: + for k in ("command", "cmd", "script"): + if isinstance(inp.get(k), str): + cmd = inp[k] + break + if cmd is None and isinstance(d.get("command"), str): + cmd = d["command"] + tool = _s(d, "tool_name", "toolName", "tool", "name") or "" + cwd = _s(d, "cwd") or os.getcwd() + return tool, cmd, _s(d, "hook_event_name", "hookEventName", "event_name", "event") or "", \ + cwd, _s(d, "session_id", "sessionId", "conversation_id") or "" + + +def is_shell(tool, cmd): + t = (tool or "").lower() + return bool(cmd) and (not t or any(w in t for w in SHELL_TOOLS)) + + +def _may_write(cmd): + from . import gate + return gate._shell_may_write(cmd) + + +def snap_file(sid, kind): + return os.path.join(paths.state(), "sessions", store.safe_id(sid) + "." + kind + ".json") + + +def _save(path, obj): + os.makedirs(os.path.dirname(path), exist_ok=True) + tmp = path + ".tmp%d" % os.getpid() + with open(tmp, "w", encoding="utf-8") as f: + json.dump(obj, f) + os.replace(tmp, path) + + +def _load(path): + try: + with open(path, encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else None + except (OSError, ValueError): + return None + + +def note_edit(sess, changed_rel, root, sentinel=None): + """Attribute paths (relative to root) to this session in its record.""" + sess["attr_gen"] = int(sess.get("attr_gen", 0) or 0) + 1 + sess["attr_writing"] = True + have = sess.setdefault("attr_files", []) + since = sess.setdefault("attr_since_pass", []) + for rel in changed_rel: + ap = os.path.join(root, rel) if root else rel + if ap not in have: + have.append(ap) + if rel not in since: + since.append(rel) + if sentinel and sentinel not in since: + since.append(sentinel) + + +def _session(sid, d, cwd): + sess = store.load_session(sid) + sess.setdefault("session_id", sid) + sess["attr_measured"] = True + if isinstance(d.get("transcript_path"), str): + sess["transcript_path"] = d["transcript_path"] + sess.setdefault("cwd", cwd) + return sess + + +def before(payload): + tool, cmd, _ev, cwd, sid = extract(payload) + if not is_shell(tool, cmd): + return + sid = sid or "cwd-" + cwd + sess = _session(sid, payload, cwd) + store.save_session(sid, sess) + if _may_write(cmd) is False: + return # provably read-only (incl. sisi's own and git commit): no measurement paid + snap = gitutil.snapshot(cwd) + _save(snap_file(sid, "watch"), {"root": snap["root"], "files": snap["files"], + "command": (cmd or "")[:500], "ts": time.time()}) + + +def after(payload): + tool, cmd, _ev, cwd, sid = extract(payload) + if not is_shell(tool, cmd): + return + sid = sid or "cwd-" + cwd + sess = _session(sid, payload, cwd) + pend = _load(snap_file(sid, "watch")) + if pend is None: + if _may_write(cmd) is not False: + note_edit(sess, [], pend_root(sess, cwd), sentinel="*shell-unmeasured*") + store.save_session(sid, sess) + return + try: + os.unlink(snap_file(sid, "watch")) + except OSError: + pass + root = pend.get("root") or gitutil.root(cwd) or cwd + now = gitutil.snapshot(root) + changed = gitutil.snapshot_diff(pend, now) + if changed: + note_edit(sess, changed, root) + store.save_session(sid, sess) + + +def pend_root(sess, cwd): + return gitutil.root(cwd) or sess.get("req_project") or cwd + + +def consume_pending(sess, sid, cwd): + """A before-record with no after at gate time (command killed): strict. Returns True if one was.""" + p = snap_file(sid, "watch") + pend = _load(p) + if pend is None: + return False + try: + os.unlink(p) + except OSError: + pass + note_edit(sess, [], pend.get("root") or pend_root(sess, cwd), sentinel="*shell-unmeasured*") + return True + + +def save_pass_snapshot(sid, cwd): + snap = gitutil.snapshot(cwd) + _save(snap_file(sid, "pass"), snap) + return snap + + +def changed_since_pass(sid, cwd): + """Paths differing from the last passing snapshot, or None when none was ever recorded.""" + pend = _load(snap_file(sid, "pass")) + if pend is None: + return None + return gitutil.snapshot_diff(pend, gitutil.snapshot(cwd)) + + +def main(args=()): + try: + from . import gate + payload = gate._read_payload() + _tool, _cmd, ev, _cwd, _sid = extract(payload) + if "--before" in args or ev in BEFORE_EVENTS: + before(payload) + elif "--after" in args or ev in AFTER_EVENTS: + after(payload) + except Exception as e: # fail open: a tool call must never be held up by measurement + store.log_error("watch", e) + return 0 diff --git a/sisi/wiring.py b/sisi/wiring.py index 1911cf0..ae65a1e 100644 --- a/sisi/wiring.py +++ b/sisi/wiring.py @@ -229,16 +229,23 @@ def _claude_md_wired(data): # ---- settings.json --------------------------------------------------------- +HOOK_MATCHERS = {"PreToolUse": "Bash", "PostToolUse": "Bash"} + + def hook_cmds(): gate_to = int(store.config()["gate"].get("budget_s", 120)) + 30 + watch = hookjson.fail_open_command(paths.launcher(), "watch", "claude-code") return {"SessionStart": (hookjson.fail_open_command(paths.launcher(), "tick", "claude-code"), 10), "Stop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code"), gate_to), - "SubagentStop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code", True), 30)} + "SubagentStop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code", True), 30), + "PreToolUse": (watch, 60), + "PostToolUse": (watch, 60)} def _claude_spec(): - return {ev: {"cmd": cmd, "timeout": to, - "sub": hookjson.sisi_invocation(cmd)[1]} for ev, (cmd, to) in hook_cmds().items()} + return {ev: dict({"cmd": cmd, "timeout": to, "sub": hookjson.sisi_invocation(cmd)[1]}, + **({"matcher": HOOK_MATCHERS[ev]} if ev in HOOK_MATCHERS else {})) + for ev, (cmd, to) in hook_cmds().items()} def _is_ours(h, sub): @@ -305,7 +312,10 @@ def add_hooks(obj): changed = True hooks[ev] = kept if not found: - kept.append({"hooks": [{"type": "command", "command": cmd, "timeout": to}]}) + group = {"hooks": [{"type": "command", "command": cmd, "timeout": to}]} + if ev in HOOK_MATCHERS: + group = {"matcher": HOOK_MATCHERS[ev], "hooks": group["hooks"]} + kept.append(group) changed = True return changed @@ -315,7 +325,8 @@ def remove_hooks(obj): hooks = obj.get("hooks") if not isinstance(hooks, dict): return False - for ev, sub in (("SessionStart", "tick"), ("Stop", "gate"), ("SubagentStop", "gate")): + for ev, sub in (("SessionStart", "tick"), ("Stop", "gate"), ("SubagentStop", "gate"), + ("PreToolUse", "watch"), ("PostToolUse", "watch")): groups = hooks.get(ev) if not isinstance(groups, list): continue @@ -342,7 +353,8 @@ def remove_hooks(obj): def _hooks_wired(obj): hooks = obj.get("hooks") if isinstance(obj, dict) else None out = {} - for ev, sub, name in (("SessionStart", "tick", "tick"), ("Stop", "gate", "gate"), ("SubagentStop", "gate", "subagent")): + for ev, sub, name in (("SessionStart", "tick", "tick"), ("Stop", "gate", "gate"), ("SubagentStop", "gate", "subagent"), + ("PreToolUse", "watch", "pre"), ("PostToolUse", "watch", "post")): groups = hooks.get(ev) if isinstance(hooks, dict) else None sub, key = sub, name out[key] = False @@ -578,7 +590,8 @@ def uninstall(): elif data is not None: try: text = data.decode("utf-8") - subs = {"SessionStart": "tick", "Stop": "gate", "SubagentStop": "gate"} + subs = {"SessionStart": "tick", "Stop": "gate", "SubagentStop": "gate", + "PreToolUse": "watch", "PostToolUse": "watch"} orig = _read(os.path.join(_idir(), "backups", ent["backup"])) if ent and ent["backup"] else None drop_hooks, _dv = hookjson.backup_drop_flags( orig.decode("utf-8") if orig is not None else None, None) if orig is not None else (True, False) @@ -628,11 +641,12 @@ def doctor(): rows = [] cm, st = _read(L["claude_md"]), _read(L["settings"]) try: - hw = _hooks_wired(_parse_settings(st)[0]) if st is not None else {"tick": False, "gate": False, "subagent": False} + hw = _hooks_wired(_parse_settings(st)[0]) if st is not None else {"tick": False, "gate": False, "subagent": False, "pre": False, "post": False} except (ValueError, UnicodeDecodeError): - hw = {"tick": False, "gate": False, "subagent": False} + hw = {"tick": False, "gate": False, "subagent": False, "pre": False, "post": False} missing = [n for n, ok in (("import line", _claude_md_wired(cm)), ("tick hook", hw["tick"]), - ("gate hook", hw["gate"]), ("subagent hook", hw["subagent"])) if not ok] + ("gate hook", hw["gate"]), ("subagent hook", hw["subagent"]), + ("watch-before hook", hw["pre"]), ("watch-after hook", hw["post"])) if not ok] rows.append({"tool": "claude-code", "status": "not wired" if missing else "wired", "detail": ("missing: " + ", ".join(missing)) if missing else "import + tick + gate registered", "blocking_hook": "yes (Stop)" if hw["gate"] else "no", @@ -717,11 +731,12 @@ def doctor_claude(): L = loc() cm, st = _read(L["claude_md"]), _read(L["settings"]) try: - hw = _hooks_wired(_parse_settings(st)[0]) if st is not None else {"tick": False, "gate": False, "subagent": False} + hw = _hooks_wired(_parse_settings(st)[0]) if st is not None else {"tick": False, "gate": False, "subagent": False, "pre": False, "post": False} except (ValueError, UnicodeDecodeError): - hw = {"tick": False, "gate": False, "subagent": False} + hw = {"tick": False, "gate": False, "subagent": False, "pre": False, "post": False} missing = [n for n, ok in (("import line", _claude_md_wired(cm)), ("tick hook", hw["tick"]), - ("gate hook", hw["gate"]), ("subagent hook", hw["subagent"])) if not ok] + ("gate hook", hw["gate"]), ("subagent hook", hw["subagent"]), + ("watch-before hook", hw["pre"]), ("watch-after hook", hw["post"])) if not ok] return ", ".join(missing) diff --git a/tests/test_adapters.py b/tests/test_adapters.py index c2135fb..7f35597 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -68,6 +68,30 @@ class HookToolTests(AdapterBase): self.assertEqual(self.rows()["gemini"]["status"], "wired") wiring.uninstall() + def test_watch_hooks_registered_per_tool(self): + cases = {"codex": (".codex", ".codex/hooks.json", ("PreToolUse", "PostToolUse"), False), + "gemini": (".gemini", ".gemini/settings.json", ("BeforeTool", "AfterTool"), False), + "copilot": (".copilot", ".copilot/hooks/sisi.json", ("preToolUse", "postToolUse"), True), + "cursor": (".cursor", ".cursor/hooks.json", ("preToolUse", "postToolUse"), True)} + for name, (d, f, events, flat) in cases.items(): + with self.subTest(tool=name): + self.fresh_home() + os.makedirs(self.path(d), exist_ok=True) + if name == "copilot": + os.makedirs(self.path(".copilot", "hooks"), exist_ok=True) + self.cycle() # install x2 idempotent, uninstall exact (in cycle), then installs again below + wiring.install() + obj = json.load(open(self.path(f))) + for ev in events: + cmds = [e.get("bash") or e.get("command") for e in obj["hooks"][ev]] if flat else \ + [h["command"] for g in obj["hooks"][ev] for h in g["hooks"]] + self.assertTrue(any("watch --tool %s" % name in (c or "") for c in cmds), (name, ev, cmds)) + if name == "codex": + for ev in events: + self.assertTrue(any(g.get("matcher") == "Bash" for g in obj["hooks"][ev])) + self.assertEqual(self.rows()[name]["status"], "wired") + wiring.uninstall() + def test_gemini_user_file_not_touched(self): os.makedirs(self.path(".gemini")) self.put(".gemini/GEMINI.md", b"mine\n") diff --git a/tests/test_gate.py b/tests/test_gate.py index 94be718..7d65d35 100644 --- a/tests/test_gate.py +++ b/tests/test_gate.py @@ -452,5 +452,467 @@ class GateGrowthTests(GateBase): self.assertEqual(self.call()[0], "allow") +def _tool_line(name, inp): + return {"type": "assistant", "timestamp": "2026-01-01T00:00:00.000Z", + "message": {"role": "assistant", "content": [{"type": "tool_use", "name": name, "input": inp}]}} + + +def _human_line(): + return {"type": "user", "timestamp": "2026-01-01T00:00:00.000Z", + "message": {"role": "user", "content": "do the work please"}} + + +class GateAttributionTests(GateBase): + """Two sessions, one folder: the gate judges only this session's own edits (scenarios a-e).""" + + def setUp(self): + super().setUp() + os.environ["SISI_RETRO_REQUIRED"] = "1" + self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) + self.git_init() + self.marker = os.path.join(self.proj, "ok") + open(self.marker, "w").close() + with open(os.path.join(self.proj, "work.txt"), "w") as f: + f.write("base\n") + self.write_contract(contract([check("c", "test -f ok")])) + subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "base"], + cwd=self.proj, check=True) + self.tdir = os.path.join(self.tmp, "transcripts") + os.makedirs(self.tdir) + + def transcript(self, name, lines=()): + p = os.path.join(self.tdir, name) + with open(p, "w") as f: + f.write(json.dumps(_human_line()) + "\n") + for ln in lines: + f.write(json.dumps(ln) + "\n") + return p + + def append_line(self, path, line): + with open(path, "a") as f: + f.write((line if isinstance(line, str) else json.dumps(line)) + "\n") + + def tick(self, sid, tp=None): + p = {"session_id": sid, "cwd": self.proj, "source": "startup"} + if tp: + p["transcript_path"] = tp + return self.sisi("tick", stdin=json.dumps(p)) + + def gate_proc(self, sid, tp=None): + p = {"session_id": sid, "cwd": self.proj, "hook_event_name": "Stop"} + if tp: + p["transcript_path"] = tp + return self.sisi_proc("gate", stdin=json.dumps(p), env={"SISI_RETRO_REQUIRED": "1"}) + + def edit_work(self, name="work.txt", text="more\n"): + with open(os.path.join(self.proj, name), "a") as f: + f.write(text) + + def gate_unverified(self): + return [r for r in self.results() if r.get("check") == "gate" and r.get("status") == "unverified"] + + def test_a_other_session_breaks_check_allows_once_per_tree_state(self): + ta = self.transcript("sess-a.jsonl") + tb = self.transcript("sess-b.jsonl") + self.tick("sess-a", ta); self.tick("sess-b", tb) + # B edits and breaks the check; A edited nothing at all. + self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + self.edit_work() + os.remove(self.marker) + r = self.gate_proc("sess-a", ta) + self.assertEqual(r.returncode, 0, r.stdout) + msg = json.loads(r.stdout)["systemMessage"] + self.assertIn("NOT satisfied", msg) + self.assertIn("UNVERIFIED", msg) + self.assertIn("work.txt", msg) + self.assertIn("sess-b", msg) # identified from B's sibling transcript / session record + self.assertIn("Do not report this work as done", msg) + self.assertNotIn("Fix the work", msg) + self.assertNotIn("sisi retro", msg) # A did no work: never asked for a retro + self.assertEqual(len(self.gate_unverified()), 1) + # Same tree again: allowed silently, no second note, no second unverified row. + r = self.gate_proc("sess-a", ta) + self.assertEqual((r.returncode, r.stdout), (0, "")) + self.assertEqual(len(self.gate_unverified()), 1) + # The tree moves again: one more note. + self.edit_work(text="even more\n") + r = self.gate_proc("sess-a", ta) + self.assertIn("NOT satisfied", json.loads(r.stdout)["systemMessage"]) + self.assertEqual(len(self.gate_unverified()), 2) + + def test_a_through_another_tools_hook(self): + # The same logic arrives through hookio: codex carries a transcript path, pi/opencode do not. + ta = self.transcript("sess-a.jsonl") + tb = self.transcript("sess-b.jsonl") + self.tick("sess-a", ta); self.tick("sess-b", tb) + self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + self.edit_work() + os.remove(self.marker) + p = {"session_id": "sess-a", "transcript_path": ta, "cwd": self.proj, "hook_event_name": "Stop"} + r = self.sisi("gate", "--tool", "codex", stdin=json.dumps(p)) + self.assertEqual(r.returncode, 0, r.stdout) + self.assertIn("NOT satisfied", json.loads(r.stdout)["systemMessage"]) + p2 = {"session_id": "sess-pi", "cwd": self.proj} # no transcript path: pre-attribution behaviour + r = self.sisi("gate", "--tool", "pi", stdin=json.dumps(p2)) + self.assertEqual(r.returncode, 2) # pi blocks by exit code, as before + self.assertIn("Fix the work", r.stdout) + + def test_b_own_edit_then_other_breaks_is_sent_back(self): + ta = self.transcript("sess-a.jsonl") + tb = self.transcript("sess-b.jsonl") + self.tick("sess-a", ta); self.tick("sess-b", tb) + self.append_line(ta, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + self.edit_work() + self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + self.edit_work(text="b was here\n") + os.remove(self.marker) + r = self.gate_proc("sess-a", ta) + d = json.loads(r.stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("Fix the work", d["reason"]) + + def test_c_native_subagent_edit_asks_parent_for_retro(self): + ta = self.transcript("sess-a.jsonl") + self.tick("sess-a", ta) + subdir = os.path.join(self.tdir, "sess-a", "subagents") + os.makedirs(subdir) + with open(os.path.join(subdir, "agent-x1.jsonl"), "w") as f: + f.write(json.dumps(_human_line()) + "\n") + f.write(json.dumps(_tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + "\n") + self.edit_work() + r = self.gate_proc("sess-a", ta) + d = json.loads(r.stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("sisi retro", d["reason"]) + + def test_d_shell_edits_count_and_readonly_shell_does_not(self): + cmds = ["sed -i 's/base/changed/' %s" % os.path.join(self.proj, "work.txt"), + "echo hi > %s" % os.path.join(self.proj, "shell-out.txt"), + "git apply changes.diff"] + for i, cmd in enumerate(cmds): + sid = "shell-%d" % i + tp = self.transcript("%s.jsonl" % sid) + self.tick(sid, tp) + self.append_line(tp, _tool_line("Bash", {"command": cmd})) + self.edit_work(text="shell %d\n" % i) # the file change the command made + r = self.gate_proc(sid, tp) + with self.subTest(cmd=cmd): + d = json.loads(r.stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("sisi retro", d["reason"]) # treated as having edited: retro required + sid = "shell-ro" + tp = self.transcript("shell-ro.jsonl") + self.tick(sid, tp) + self.append_line(tp, _tool_line("Bash", {"command": "ls -la; git status --short; cat work.txt"})) + self.edit_work(text="someone else\n") # tree changed, but not by this session + r = self.gate_proc(sid, tp) + self.assertEqual((r.returncode, r.stdout), (0, "")) # passing check, no retro asked + + def test_e_missing_or_corrupt_transcript_is_strict(self): + tb = self.transcript("sess-b.jsonl") + self.tick("sess-b", tb) + self.edit_work() + os.remove(self.marker) + missing = os.path.join(self.tdir, "no-such.jsonl") + r = self.gate_proc("sess-missing", missing) + self.assertEqual(json.loads(r.stdout)["decision"], "block") # not waved through as another's work + bad = os.path.join(self.tdir, "corrupt.jsonl") + with open(bad, "w") as f: + f.write("not json at all\n{{{\n") + r = self.gate_proc("sess-corrupt", bad) + self.assertEqual(json.loads(r.stdout)["decision"], "block") + # and with the check passing again, a corrupt transcript still counts as edited for the retro + open(self.marker, "w").close() + r = self.gate_proc("sess-corrupt2", bad) + d = json.loads(r.stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("sisi retro", d["reason"]) + + def test_shell_classifier(self): + self.assertTrue(gate._shell_may_write("sed -i 's/a/b/' f.txt")) + self.assertTrue(gate._shell_may_write("echo x > out.txt")) + self.assertTrue(gate._shell_may_write("git apply p.diff")) + self.assertTrue(gate._shell_may_write("python3 scripts/build.py")) + self.assertIsNone(gate._shell_may_write("echo 'unterminated")) + self.assertFalse(gate._shell_may_write("ls -la; git status; cat f.txt")) + self.assertFalse(gate._shell_may_write("sisi verify")) + self.assertFalse(gate._shell_may_write("grep -rn foo sisi/")) + + def test_offset_reads_only_the_new_tail(self): + tp = self.transcript("sess-tail.jsonl") + self.tick("sess-tail", tp) + a, _ = gate.decide({"session_id": "sess-tail", "cwd": self.proj, "transcript_path": tp}) + self.assertEqual(a, "allow") + size = os.path.getsize(tp) + self.assertEqual(store.load_session("sess-tail")["attr_offset"], size) + self.append_line(tp, {"type": "user", "message": {"role": "user", "content": "x" * 5000}}) + self.append_line(tp, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + self.edit_work() + a, msg = gate.decide({"session_id": "sess-tail", "cwd": self.proj, "transcript_path": tp}) + self.assertEqual(a, "block") # the edit in the new tail was seen, retro is required + self.assertIn("sisi retro", msg) + self.assertEqual(store.load_session("sess-tail")["attr_gen"], 1) # counted once, not rescanned + + +class GateWatchTests(GateBase): + """Measured shell attribution: before/after tree snapshots, not command-text guesses.""" + + def setUp(self): + super().setUp() + os.environ["SISI_RETRO_REQUIRED"] = "1" + self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) + self.git_init() + self.marker = os.path.join(self.proj, "ok") + open(self.marker, "w").close() + with open(os.path.join(self.proj, "work.txt"), "w") as f: + f.write("base\n") + with open(os.path.join(self.proj, "noop.py"), "w") as f: + f.write("print('nothing written')\n") + with open(os.path.join(self.proj, "gen.py"), "w") as f: + f.write("open('generated.txt', 'w').write('made\\n')\n") + self.write_contract(contract([check("c", "test -f ok")])) + subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "base"], + cwd=self.proj, check=True) + self.tdir = os.path.join(self.tmp, "transcripts") + os.makedirs(self.tdir) + + def transcript(self, name): + p = os.path.join(self.tdir, name) + with open(p, "w") as f: + f.write(json.dumps(_human_line()) + "\n") + return p + + def append_line(self, path, line): + with open(path, "a") as f: + f.write(json.dumps(line) + "\n") + + def tick(self, sid, tp): + return self.sisi("tick", stdin=json.dumps({"session_id": sid, "cwd": self.proj, + "source": "startup", "transcript_path": tp})) + + def gate_proc(self, sid, tp=None): + p = {"session_id": sid, "cwd": self.proj, "hook_event_name": "Stop"} + if tp: + p["transcript_path"] = tp + return self.sisi_proc("gate", stdin=json.dumps(p), env={"SISI_RETRO_REQUIRED": "1"}) + + def watch(self, sid, tp, command, during=None, after=True): + """Simulate the Pre/PostToolUse pair around the command's real effect. Returns nothing.""" + self.append_line(tp, _tool_line("Bash", {"command": command})) + base = {"session_id": sid, "cwd": self.proj, "transcript_path": tp, + "tool_name": "Bash", "tool_input": {"command": command}} + r = self.sisi_proc("watch", stdin=json.dumps(dict(base, hook_event_name="PreToolUse")), + env={"SISI_RETRO_REQUIRED": "1"}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + if during is not None: + during() + if after: + r = self.sisi_proc("watch", stdin=json.dumps(dict(base, hook_event_name="PostToolUse")), + env={"SISI_RETRO_REQUIRED": "1"}) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + def run_in_proj(self, *argv): + return subprocess.run(argv, cwd=self.proj, check=True, capture_output=True, text=True) + + def test_orchestrator_that_only_runs_commands_is_never_the_editor(self): + ta, tb = self.transcript("orch-a.jsonl"), self.transcript("sess-b.jsonl") + self.tick("orch-a", ta); self.tick("sess-b", tb) + self.assertEqual(self.gate_proc("orch-a", ta).stdout, "") # passing stop: records the pass state + cmds = [("python3 noop.py", lambda: self.run_in_proj(sys.executable, "noop.py")), + ("git commit -qm x", lambda: self.run_in_proj("git", "commit", "-q", "--allow-empty", "-m", "x")), + ("gh run list", None), + ("sisi retro --aim speed --moment m", None), + ("python3 ~/.claude/orchestrator/orch.py log --type impl", None)] + for cmd, during in cmds: + self.watch("orch-a", ta, cmd, during=during) + self.assertFalse(store.load_session("orch-a").get("attr_since_pass")) + # Another session edits and breaks the check. + self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + with open(os.path.join(self.proj, "work.txt"), "a") as f: + f.write("worker edit\n") + os.remove(self.marker) + r = self.gate_proc("orch-a", ta) + msg = json.loads(r.stdout)["systemMessage"] + self.assertIn("NOT satisfied", msg) + self.assertIn("work.txt", msg) + self.assertNotIn("Fix the work", msg) + self.assertNotIn("sisi retro", msg) + self.assertEqual(len([x for x in self.results() if x.get("status") == "unverified"]), 1) + self.assertEqual(self.gate_proc("orch-a", ta).stdout, "") # second stop: silent + + def test_command_that_writes_a_project_file_is_an_edit_of_that_path(self): + tp = self.transcript("gen-a.jsonl") + self.tick("gen-a", tp) + self.assertEqual(self.gate_proc("gen-a", tp).stdout, "") + self.watch("gen-a", tp, "python3 gen.py", during=lambda: self.run_in_proj(sys.executable, "gen.py")) + self.assertIn("generated.txt", store.load_session("gen-a").get("attr_since_pass", [])) + tb = self.transcript("sess-b.jsonl") + self.tick("sess-b", tb) + self.append_line(tb, _tool_line("Edit", {"file_path": os.path.join(self.proj, "work.txt")})) + with open(os.path.join(self.proj, "work.txt"), "a") as f: + f.write("worker edit\n") + os.remove(self.marker) + d = json.loads(self.gate_proc("gen-a", tp).stdout) + self.assertEqual(d["decision"], "block") # a path it is attributed with changed since the pass + self.assertIn("Fix the work", d["reason"]) + open(self.marker, "w").close() # checks pass again, and this session edited: retro required + d = json.loads(self.gate_proc("gen-a", tp).stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("sisi retro", d["reason"]) + + def test_command_that_writes_only_outside_the_project_is_not_an_edit(self): + tp = self.transcript("out-a.jsonl") + self.tick("out-a", tp) + self.assertEqual(self.gate_proc("out-a", tp).stdout, "") + outside = os.path.join(self.tmp, "outside.txt") + gen = os.path.join(self.proj, "gen_out.py") + with open(gen, "w") as f: + f.write("open(%r, 'w').write('elsewhere\\n')\n" % outside) + self.watch("out-a", tp, "python3 gen_out.py", during=lambda: self.run_in_proj(sys.executable, "gen_out.py")) + self.assertTrue(os.path.exists(outside)) + self.assertFalse(store.load_session("out-a").get("attr_since_pass")) + self.assertEqual(self.gate_proc("out-a", tp).stdout, "") # no retro asked + + def test_other_agents_write_inside_the_window_is_attributed_to_this_session(self): + tp = self.transcript("win-a.jsonl") + self.tick("win-a", tp) + self.assertEqual(self.gate_proc("win-a", tp).stdout, "") + + def during(): + with open(os.path.join(self.proj, "work.txt"), "a") as f: + f.write("written by another agent mid-command\n") + os.remove(self.marker) + + self.watch("win-a", tp, "python3 noop.py", during=during) + self.assertIn("work.txt", store.load_session("win-a").get("attr_since_pass", [])) + d = json.loads(self.gate_proc("win-a", tp).stdout) + self.assertEqual(d["decision"], "block") # documented strict error: the window is this session's + self.assertIn("Fix the work", d["reason"]) + + def test_missing_after_record_is_strict(self): + tp = self.transcript("kill-a.jsonl") + self.tick("kill-a", tp) + self.assertEqual(self.gate_proc("kill-a", tp).stdout, "") + self.watch("kill-a", tp, "python3 gen.py", after=False) # killed: no PostToolUse ever arrives + with open(os.path.join(self.proj, "work.txt"), "a") as f: + f.write("worker edit\n") + os.remove(self.marker) + d = json.loads(self.gate_proc("kill-a", tp).stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("Fix the work", d["reason"]) + tp2 = self.transcript("kill-b.jsonl") + self.tick("kill-b", tp2) + open(self.marker, "w").close() # tree passes again + self.watch("kill-b", tp2, "python3 gen.py", after=False) + d = json.loads(self.gate_proc("kill-b", tp2).stdout) + self.assertEqual(d["decision"], "block") + self.assertIn("sisi retro", d["reason"]) # strict for the retro too + + def test_snapshot_and_classifier(self): + from sisi import gitutil + s0 = gitutil.snapshot(self.proj) + with open(os.path.join(self.proj, "work.txt"), "a") as f: + f.write("changed\n") + self.assertIn("work.txt", gitutil.snapshot_diff(s0, gitutil.snapshot(self.proj))) + subprocess.run(["git", "add", "-A"], cwd=self.proj, check=True) + s1 = gitutil.snapshot(self.proj) + subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "c"], + cwd=self.proj, check=True) + self.assertEqual(gitutil.snapshot_diff(s1, gitutil.snapshot(self.proj)), []) # commit: .git only + with open(os.path.join(self.proj, ".gitignore"), "w") as f: + f.write("ignored.txt\n") + s2 = gitutil.snapshot(self.proj) + open(os.path.join(self.proj, "ignored.txt"), "w").close() + self.assertNotIn("ignored.txt", gitutil.snapshot_diff(s2, gitutil.snapshot(self.proj))) + self.assertFalse(gate._shell_may_write("git commit -qm x")) + self.assertFalse(gate._shell_may_write("gh run list")) + self.assertFalse(gate._shell_may_write("sisi retro --aim speed --moment m")) + self.assertFalse(gate._shell_may_write("sisi verify")) + self.assertTrue(gate._shell_may_write("sisi contract init")) + self.assertTrue(gate._shell_may_write("python3 ~/.claude/orchestrator/orch.py log --type impl")) + self.assertTrue(gate._shell_may_write("python3 tests/run_parallel.py")) + + +class GateSingleSessionEquivalenceTests(GateBase): + """(f) One session only: with a transcript that records its own edits, every decision matches + the pre-attribution gate (the same decide() called with no transcript path) on a twin project.""" + + def twin(self, name): + d = os.path.join(self.tmp, name) + os.makedirs(d) + self.git_init(d) + with open(os.path.join(d, "work.txt"), "w") as f: + f.write("base\n") + open(os.path.join(d, "ok"), "w").close() + self.write_contract(contract([check("c", "test -f ok")]), d=d) + return d + + def retro_for(self, proj, sid, n): + from test_retro import GOOD, argv as retro_argv + f = dict(GOOD, moment="`cargo test` twin run %d took 4 minutes with no fuzz verifier in project" % n, + change="Add the fuzz verifier to the parser-or-codec recipe Checks, twin variant %d" % n, new=True) + r = self.sisi("retro", *retro_argv(f), cwd=proj, env={"SISI_SESSION_ID": sid}) + if r.returncode == 4: # same lesson as the twin's: add an occurrence for this repo instead + r = self.sisi("retro", "--same-as", "1", "--moment", "again `cargo test` twin run %d, no fuzz" % n, + cwd=proj, env={"SISI_SESSION_ID": sid}) + self.assertEqual(r.returncode, 0, r.stdout) + + def test_seeded_sequences_match_the_reference(self): + os.environ["SISI_RETRO_REQUIRED"] = "1" + self.addCleanup(lambda: os.environ.__setitem__("SISI_RETRO_REQUIRED", "0")) + ref_proj, new_proj = self.twin("refproj"), self.twin("newproj") + tp = os.path.join(self.tmp, "twin-new.jsonl") + with open(tp, "w") as f: + f.write(json.dumps(_human_line()) + "\n") + self.sisi("tick", stdin=json.dumps({"session_id": "twin-ref", "cwd": ref_proj, "source": "startup"})) + self.sisi("tick", stdin=json.dumps({"session_id": "twin-new", "cwd": new_proj, "source": "startup", + "transcript_path": tp})) + n_retro = [0] + + def both(fn): + fn(ref_proj) + fn(new_proj) + + def append_both(text): + for p in (ref_proj, new_proj): + with open(os.path.join(p, "work.txt"), "a") as f: + f.write(text) + + def stop_pair(step): + a_ref, m_ref = gate.decide({"session_id": "twin-ref", "cwd": ref_proj}) + a_new, m_new = gate.decide({"session_id": "twin-new", "cwd": new_proj, "transcript_path": tp}) + self.assertEqual(a_new, a_ref, "step %r" % (step,)) + self.assertEqual(("sisi retro" in (m_new or "")), ("sisi retro" in (m_ref or "")), "step %r" % (step,)) + self.assertEqual(("Fix the work" in (m_new or "")), ("Fix the work" in (m_ref or "")), "step %r" % (step,)) + + for seed in (0, 1, 2): + rng = random.Random(seed) + for step in range(12): + op = rng.choice(["edit", "edit", "break", "fix", "verify", "retro"]) + if op == "edit": + append_both("s%d-%d\n" % (seed, step)) + with open(tp, "a") as f: + f.write(json.dumps(_tool_line("Edit", {"file_path": os.path.join(new_proj, "work.txt")})) + "\n") + elif op == "break": + both(lambda p: os.path.exists(os.path.join(p, "ok")) and os.remove(os.path.join(p, "ok"))) + append_both("break\n") + with open(tp, "a") as f: + f.write(json.dumps(_tool_line("Edit", {"file_path": os.path.join(new_proj, "work.txt")})) + "\n") + elif op == "fix": + both(lambda p: open(os.path.join(p, "ok"), "w").close()) + with open(tp, "a") as f: + f.write(json.dumps(_tool_line("Write", {"file_path": os.path.join(new_proj, "ok")})) + "\n") + elif op == "verify": + self.sisi("verify", cwd=ref_proj) + self.sisi("verify", cwd=new_proj) + elif op == "retro": + n_retro[0] += 1 + self.retro_for(ref_proj, "twin-ref", n_retro[0]) + self.retro_for(new_proj, "twin-new", n_retro[0]) + stop_pair((seed, step, op)) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_install_safety.py b/tests/test_install_safety.py index ceb7763..3ba8fc3 100644 --- a/tests/test_install_safety.py +++ b/tests/test_install_safety.py @@ -463,7 +463,8 @@ class WidenedPropertyTests(SafetyBase): json.dump(obj, open(p, "w"), indent=2) wiring.install() raw = open(p, "rb").read() - self.assertLessEqual(raw.count(b"--tool " + tool.encode()), 4, (tool, raw)) + # tick + gate + subagent gate + watch (registered for both tool events) = at most 5 + self.assertLessEqual(raw.count(b"--tool " + tool.encode()), 5, (tool, raw)) d2 = json.load(open(p)) for ev, entries in d2.get("hooks", {}).items(): flat = [e.get("bash") or e.get("command") for e in entries if isinstance(e, dict)] diff --git a/tests/test_wiring.py b/tests/test_wiring.py index 8f41ccf..3100eb9 100644 --- a/tests/test_wiring.py +++ b/tests/test_wiring.py @@ -227,6 +227,24 @@ class WiringTests(WiringBase): self.assertEqual(self.sisi("uninstall").returncode, 0) +class WatchHookTests(WiringBase): + def test_watch_hooks_registered_with_bash_matcher_and_removed(self): + before = snapshot(self.home) + wiring.install() + d = json.load(open(self.path(".claude/settings.json"))) + for ev in ("PreToolUse", "PostToolUse"): + groups = d["hooks"][ev] + cmds = [h["command"] for g in groups for h in g["hooks"]] + self.assertTrue(any("watch --tool claude-code" in c for c in cmds), (ev, cmds)) + self.assertTrue(any(g.get("matcher") == "Bash" for g in groups), (ev, groups)) + self.assertEqual(wiring.doctor()[0]["status"], "wired") + snap = snapshot(self.home) + wiring.install() + self.assertEqual(snapshot(self.home), snap) # idempotent + wiring.uninstall() + self.assertEqual(snapshot(self.home), before) # removed exactly + + class SubagentHookTests(WiringBase): def test_subagent_stop_registered_idempotent_and_removed(self): before = snapshot(self.home)