From db8106027967c8851eb6c5ff499798cb91df0938 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:16:15 -0700 Subject: [PATCH] Item 2: the before-tool hook refuses the first building step without a valid, session-bound unit (floor of target + paths already changed; trivial, .sisi/ and outside-project never refused; slips caught by the snapshot). done / next: item 3 (delegating a build) Co-Authored-By: Claude Sonnet 5.5 --- config.default.json | 3 + sisi/unitguard.py | 80 +++++++++++-- sisi/watch.py | 5 + tests/test_unitguard.py | 241 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 318 insertions(+), 11 deletions(-) diff --git a/config.default.json b/config.default.json index 784dd43..5371fa5 100644 --- a/config.default.json +++ b/config.default.json @@ -10,5 +10,8 @@ }, "retro": { "required": true + }, + "unit": { + "stale_hours": 12 } } diff --git a/sisi/unitguard.py b/sisi/unitguard.py index 836a6af..41812e0 100644 --- a/sisi/unitguard.py +++ b/sisi/unitguard.py @@ -24,7 +24,7 @@ refusal) and `after(payload)`. For the gate and `sisi unit pause`: `bound_fresh` """ import fnmatch, hashlib, json, os, re, shlex, sys, time -from . import assure, contract as C, gitutil, paths as P, risk, store, trust +from . import assure, contract as C, paths as P, risk, store CLAIM_RE = re.compile(r"\bsisi\b[^\n;&|]*?\b(?:contract\s+init|unit\s+(?:continue|resume|park))\b") MAX_LINES = 12 @@ -207,9 +207,34 @@ def age_text(epoch): return "%d days ago" % round(s / 86400) -def open_unit(cwd): +def git_top(cwd): + """The repository root above cwd, found by looking for `.git` (no process started: this runs before every + counted tool call). None outside a repository.""" + d = os.path.abspath(cwd) + while True: + if os.path.exists(os.path.join(d, ".git")): + return d + up = os.path.dirname(d) + if up == d: + return None + d = up + + +def find_contract(cwd, top): + """Nearest .sisi/contract.json from cwd up to the repository root (what C.find does, without asking git).""" + d = os.path.abspath(cwd) + while True: + p = os.path.join(d, C.REL) + if os.path.isfile(p): + return p + if d == top or os.path.dirname(d) == d: + return None + d = os.path.dirname(d) + + +def open_unit(cwd, top=None): """(contract, path, project) of the open unit (not closed) found from cwd, else (None, None, None).""" - p = C.find(cwd) + p = find_contract(cwd, top or git_top(cwd)) if not p: return None, None, None try: @@ -256,8 +281,39 @@ def _is_sisi(rel): return r == ".sisi" or r.startswith(".sisi/") +def _floor_sig(project): + """Which risk tables are in force: a change to any of them makes every remembered floor stale.""" + parts = [] + for f in (P.canon("risk.json"), P.data_file("risk.json"), P.overlay_dir("risk-adjustments.json"), + os.path.join(project, ".sisi", "risk.json")): + try: + st = os.stat(f) + parts.append("%s:%d:%d" % (f, st.st_mtime_ns, st.st_size)) + except OSError: + parts.append(f + ":-") + return hashlib.sha1("|".join(parts).encode()).hexdigest()[:16] + + def floor_of(rels, project): - prof, reasons = risk.assess([r for r in rels if r], patterns=risk.load_patterns(project)) + """(floor, reasons) of these paths by `risk.assess`. Matching a path against the whole table takes tens of + milliseconds, so an answer is remembered (per table version) for the next call that asks about the same paths.""" + clean = sorted({r for r in rels if r}) + key, sig = "\n".join(clean), _floor_sig(project) + cache_path = os.path.join(P.state(), "unitguard-floor.json") + cache = _load(cache_path) + if cache.get("sig") != sig: + cache = {"sig": sig, "floors": {}} + hit = cache["floors"].get(key) + if hit: + return hit[0], hit[1] + prof, reasons = risk.assess(clean, patterns=risk.load_patterns(project)) + if len(cache["floors"]) > 300: + cache["floors"] = {} + cache["floors"][key] = [prof, reasons] + try: + _save(cache_path, cache) + except OSError: + pass return prof, reasons @@ -357,7 +413,7 @@ def _profile_needs(profile): def refusal_text(v, what, floor_reasons=None): profile = v["profile"] - lines = ["sisi refused: %s; that is a %s change and there is no valid unit for this work (rule 3: the contract comes first)." + lines = ["sisi refused: %s. The risk profile is `%s` and there is no valid unit for this work (rule 3: the contract comes first)." % (what, profile)] c = v.get("unit") if v["state"] == "none": @@ -583,7 +639,7 @@ def _before(payload): sess = store.load_session(sid) if sess.get("subagent"): return False - top = gitutil.root(cwd) + top = git_top(cwd) if top is None: return False # nothing to measure outside a repository rels, outside = [], False @@ -606,7 +662,7 @@ def _before(payload): return False if kind == "edit" and not rels: return False # only outside the project - c, cpath, project = open_unit(cwd) + c, cpath, project = open_unit(cwd, top) project = project or top if any(_is_contract_target(r) for r in rels): return _guard_contract_write(sid, sess, c, project, cwd, kind) @@ -626,6 +682,7 @@ def _before(payload): store.save_session(sid, sess) return False v = verdict(sid, sess, cwd, floor, c, cpath, project) + v.setdefault("project", project) if v["state"] == "ok": _cover(sess) store.save_session(sid, sess) @@ -634,8 +691,9 @@ def _before(payload): if kind == "delegate": what = "delegating this work to a worker" else: - shown = (rels[0] if rels else paths_all[0]) - what = ("this call would change `%s`" % shown) if rels else ("earlier changes (`%s`) were made with no unit" % paths_all[0]) + focus = next((x for x in paths_all if floor_of([x], project)[0] != "trivial"), paths_all[0]) + what = ("this call would change `%s`" % focus) if focus in rels else \ + ("this session already changed `%s` with no unit behind it" % focus) msg = refusal_text(v, what) if kind == "delegate": msg = msg.replace("Then retry the call.", "The contract is where the worker's brief takes its acceptance from. Then retry.") @@ -680,11 +738,11 @@ def _after(payload): if not sess: return dirty = False - top = gitutil.root(cwd) + top = git_top(cwd) if sess.get("ug_will_bind"): project = sess.pop("ug_will_bind") dirty = True - c, _p, proj = open_unit(project) + c, _p, proj = open_unit(project, project) if c is not None: bind(sid, proj, c, "wrote") sess = store.load_session(sid) diff --git a/sisi/watch.py b/sisi/watch.py index 5634941..865b0e0 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -219,6 +219,9 @@ def main(args=()): payload = gate._read_payload() _tool, _cmd, ev, _cwd, _sid = extract(payload) if "--before" in args or ev in BEFORE_EVENTS: + from . import unitguard + if unitguard.before(payload): # refused (rule 3: no valid unit): the call must not run, nothing to measure + return 0 before(payload) try: line = commit_notice(payload) @@ -230,6 +233,8 @@ def main(args=()): store.log_error("watch-commit-notice", e) elif "--after" in args or ev in AFTER_EVENTS: after(payload) + from . import unitguard + unitguard.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/tests/test_unitguard.py b/tests/test_unitguard.py index 303dc7d..8443739 100644 --- a/tests/test_unitguard.py +++ b/tests/test_unitguard.py @@ -229,5 +229,246 @@ class BindingTests(GuardCase): self.assertIn("no parked unit", r.stdout) +class RefusalTests(GuardCase): + """Item 2: the first building step is refused without a valid unit for this work (R-9-1, R-5.3-1).""" + + def refused(self, msg, *needles): + self.assertIsNotNone(msg, "the call was let through") + self.assertLessEqual(len(msg.splitlines()), 12, msg) + for n in needles: + self.assertIn(n, msg) + return msg + + def foreign_unit(self, ago_s=3 * 86400, goal="redo the old report"): + c = good_contract(goal=goal, id="old-report") + self.write_contract(c) + self.age_unit(c, ago_s, sid="someone-else") + return C.load(self.contract_path) + + # ---- no unit at all + def test_a_source_edit_with_no_unit_is_refused_naming_what_to_run(self): + msg = self.refused(self.edit(), "sisi contract init", "src/app.py", "isolated", "rule 3") + self.assertIn("goal", msg) + self.assertIn("Then retry", msg) + + def test_the_refusal_is_stored_with_what_and_when(self): + self.edit() + (r,) = self.refusals() + self.assertEqual((r["state"], r["unit"], r["session"]), ("none", None, "me")) + self.assertIn("src/app.py", r["what"]) + self.assertRegex(r["ts"], r"^\d{4}-\d\d-\d\dT") + + def test_a_trivial_change_is_never_refused(self): + self.assertIsNone(self.edit("README.md")) + self.assertIsNone(self.edit("docs/notes.md")) + self.assertEqual(self.refusals(), []) + + def test_writes_under_dot_sisi_and_outside_the_project_are_never_refused(self): + self.assertIsNone(self.before("Write", {"file_path": os.path.join(self.proj, ".sisi", "risk.json"), "content": "{}"})) + self.assertIsNone(self.before("Write", {"file_path": os.path.join(self.tmp, "elsewhere", "x.py"), "content": "x"})) + self.assertIsNone(self.bash("echo x > %s" % os.path.join(self.tmp, "elsewhere.py"))) + self.assertIsNone(self.bash("echo x > .sisi/notes.py")) + self.assertEqual(self.refusals(), []) + + def test_reading_tools_and_read_only_commands_are_not_counted(self): + self.assertIsNone(self.before("Read", {"file_path": os.path.join(self.proj, SRC)})) + self.assertIsNone(self.before("Grep", {"pattern": "greet"})) + self.assertIsNone(self.bash("git status && ls src")) + self.assertIsNone(self.bash("python3 -m pytest -q")) # runs tests: no known write target + + def test_sisi_commands_that_resolve_a_refusal_are_never_refused(self): + self.assertIsNone(self.bash("sisi contract init --goal 'x'")) + self.assertIsNone(self.bash("sisi unit park 'why' && sisi unit continue")) + + # ---- a valid unit + def test_with_a_valid_bound_unit_the_edit_goes_through(self): + self.open_unit() + self.assertIsNone(self.edit()) + self.assertEqual(self.refusals(), []) + + # ---- abuse: a stale or foreign unit from other work + def test_a_stale_unit_from_another_session_is_named_with_its_goal_and_age_and_the_three_ways_on(self): + self.foreign_unit() + msg = self.refused(self.edit(), "old-report", "redo the old report", "3 days ago", "sisi unit continue", + "sisi unit park", "sisi unit close --abandon", "sisi contract init") + self.assertNotIn("c1", msg, "it must not list the foreign unit's checks") + self.assertEqual(C.load(self.contract_path)["goal"], "redo the old report") + + def test_a_fresh_unit_another_session_opened_is_foreign_too(self): + self.write_contract(good_contract()) + G.bind("someone-else", self.proj, C.load(self.contract_path), "init") + self.refused(self.edit(), "sisi unit continue") + + def test_continue_then_the_edit_goes_through_and_a_bound_but_stale_unit_asks_for_continue_again(self): + c = self.foreign_unit() + self.refused(self.edit(), "sisi unit continue") + self.assertEqual(self.sisi("unit", "continue", env={"SISI_SESSION_ID": "me"}).returncode, 0) + self.assertIsNone(self.edit()) + self.age_unit(C.load(self.contract_path), 20 * 3600, "me") + self.refused(self.edit(), "no activity since", "sisi unit continue") + + def test_the_refusal_is_recorded_against_the_unit_the_session_holds(self): + c = self.open_unit(good_contract(checks=[dict(real("c1"), cmd="true")])) # a vacuous check: invalid + self.edit() + (r,) = self.refusals() + self.assertEqual((r["unit"], r["state"]), ("work", "invalid")) + + # ---- abuse: an invalid contract + def test_contract_init_that_leaves_the_placeholder_checks_is_still_refused(self): + r = self.sisi("contract", "init", "--goal", "make the app greet", env={"SISI_SESSION_ID": "me"}) + self.assertEqual(r.returncode, 0) + self.refused(self.edit(), "placeholder") + + def test_one_placeholder_check_left_among_real_ones_is_refused(self): + self.sisi("contract", "init", "--goal", "make the app greet", env={"SISI_SESSION_ID": "me"}) + c = C.load(self.contract_path) + c["checks"][0] = real("c1") + c["risk"]["profile"] = "isolated" + C.save(self.contract_path, c) # the deep placeholder is still there + self.refused(self.edit(), "placeholder") + c["checks"] = c["checks"][:1] + C.save(self.contract_path, c) + self.assertIsNone(self.edit()) + + def test_a_placeholder_goal_is_refused(self): + self.open_unit(good_contract(goal="TODO: one sentence describing the outcome")) + self.refused(self.edit(), "goal") + + def test_a_vacuous_check_is_refused_with_contract_check_named(self): + self.open_unit(good_contract(checks=[dict(real("c1"), cmd="true")])) + self.refused(self.edit(), "cannot fail") + + def test_declaring_trivial_on_a_source_path_with_no_reason_is_still_refused(self): + self.open_unit(good_contract(profile="trivial")) + self.refused(self.edit(), "below the floor", "risk") + c = C.load(self.contract_path) + c["risk"]["why"] = "a one-word string change that cannot affect behaviour" + C.save(self.contract_path, c) + self.assertIsNone(self.edit(), "a reason on the record lowers it, as the gate allows") + + def test_integration_work_needs_the_requirement_list_the_risk_note_and_the_approach_before_building(self): + c = good_contract() + c["checks"] = [real("c1")] + self.open_unit(c) + msg = self.refused(self.edit("package.json"), "requirement list", "risk note", "approach") + self.assertNotIn("independent", msg) + self.open_unit(full_contract()) + self.assertIsNone(self.edit("package.json")) + + def test_independent_evidence_and_the_retro_are_not_asked_before_building(self): + self.open_unit(full_contract(risk={"profile": "data", "blast_radius": "the stored rows", "rollback": "restore backup"})) + self.assertIsNone(self.edit("db/schema.sql")) + + # ---- abuse: shell writes + def test_a_shell_redirect_tee_sed_and_a_heredoc_are_refused(self): + for cmd in ("echo 'x = 1' > src/app.py", "echo x | tee src/app.py", "sed -i 's/hi/yo/' src/app.py", + "cat > src/app.py <<'EOF'\nx = 1\nEOF", "cp /tmp/new.py src/app.py", "printf x >> src/app.py"): + self.refused(self.bash(cmd), "src/app.py", "sisi contract init") + + def test_python_dash_c_slips_past_the_text_but_the_snapshot_refuses_the_next_call(self): + cmd = "python3 -c \"open('src/app.py', 'w').write('x = 1')\"" + self.assertIsNone(self.bash(cmd)) + payload = self.payload("Bash", {"command": cmd}) + watch.before(payload) # the stat-only snapshot before it ran + self.put(SRC, "x = 1\n") + watch.after(payload) + G.after(payload) + self.refused(self.edit("README.md"), "src/app.py", "sisi contract init") + self.refused(self.bash("echo hi > notes.py")) + + def test_the_slip_is_forgiven_once_a_valid_unit_stands_behind_it(self): + cmd = "python3 -c \"open('src/app.py', 'w').write('x = 1')\"" + payload = self.payload("Bash", {"command": cmd}) + watch.before(payload) + self.put(SRC, "x = 1\n") + watch.after(payload) + G.after(payload) + self.refused(self.edit("README.md")) + self.open_unit() + self.assertIsNone(self.edit("README.md")) + self.assertEqual(store.load_session("me").get("ug_paths"), []) + + def test_a_slip_by_a_read_only_followup_is_not_refused(self): + payload = self.payload("Bash", {"command": "python3 gen.py"}) + watch.before(payload) + self.put("gen_out.py", "x = 1\n") + watch.after(payload) + G.after(payload) + self.assertIsNone(self.before("Read", {"file_path": os.path.join(self.proj, SRC)})) + self.assertIsNone(self.bash("git status")) + + def test_build_output_that_a_run_leaves_behind_is_not_a_slip(self): + payload = self.payload("Bash", {"command": "python3 gen.py"}) + watch.before(payload) + self.put("src/__pycache__/app.cpython-312.pyc", "bin") + watch.after(payload) + G.after(payload) + self.assertIsNone(self.edit("README.md")) + + # ---- abuse: rewriting another unit's contract + def test_writing_the_contract_file_of_a_unit_the_session_does_not_hold_is_refused(self): + self.foreign_unit() + msg = self.refused(self.before("Write", {"file_path": self.contract_path, "content": "{}"}), + "old-report", "sisi unit park") + self.assertEqual(C.load(self.contract_path)["goal"], "redo the old report") + self.refused(self.bash("echo '{}' > .sisi/contract.json"), "sisi unit park") + self.refused(self.before("Edit", {"file_path": self.contract_path, "old_string": "a", "new_string": "b"})) + + def test_writing_a_contract_when_none_is_open_is_allowed_and_binds_the_writer(self): + self.assertIsNone(self.before("Write", {"file_path": self.contract_path, "content": "{}"})) + self.write_contract(good_contract()) + G.after(self.payload("Write", {"file_path": self.contract_path, "content": "{}"})) + self.assertTrue(G.is_bound(store.load_session("me"), self.proj, C.load(self.contract_path))) + self.assertIsNone(self.before("Edit", {"file_path": self.contract_path, "old_string": "a", "new_string": "b"})) + + # ---- who is exempt, and failure + def test_worker_and_subagent_sessions_are_never_refused(self): + self.assertIsNone(self.edit(agent_id="a1")) + self.assertIsNone(self.edit(agent_transcript_path="/x/subagents/agent-a1.jsonl")) + self.tick("sub", subagent=None) + s = store.load_session("sub") + s["subagent"] = True + store.save_session("sub", s) + self.assertIsNone(self.edit(sid="sub")) + with mock.patch.dict(os.environ, {"SISI_WORKER_RUN": "1"}): + self.assertIsNone(self.edit()) + self.assertEqual(self.refusals(), []) + + def test_an_error_inside_the_guard_lets_the_call_through(self): + with mock.patch.object(G, "verdict", side_effect=RuntimeError("boom")): + self.assertIsNone(self.edit()) + with mock.patch.object(G, "_before", side_effect=RuntimeError("boom")): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertFalse(G.before(self.payload("Edit", {"file_path": os.path.join(self.proj, SRC)}))) + self.assertEqual(out.getvalue(), "") + r = self.sisi("watch", "--before", stdin=json.dumps(self.payload("Edit", {"file_path": os.path.join(self.proj, SRC)}))) + self.assertEqual(r.returncode, 0) + + def test_outside_a_repository_nothing_is_measured_and_nothing_is_refused(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "a.py") + out = io.StringIO() + with contextlib.redirect_stdout(out): + refused = G.before({"session_id": "me", "cwd": d, "tool_name": "Write", "tool_input": {"file_path": p}}) + self.assertFalse(refused) + + def test_the_real_hook_command_prints_the_hosts_refusal_and_runs_nothing_else(self): + r = self.sisi("watch", "--before", stdin=json.dumps(self.payload("Write", {"file_path": os.path.join(self.proj, SRC), "content": "x"}))) + self.assertEqual(r.returncode, 0, r.stderr) + d = json.loads(r.stdout)["hookSpecificOutput"] + self.assertEqual(d["permissionDecision"], "deny") + self.assertIn("sisi contract init", d["permissionDecisionReason"]) + r = self.sisi("watch", "--before", stdin=json.dumps(self.payload("Write", {"file_path": os.path.join(self.proj, "README.md"), "content": "x"}))) + self.assertEqual(r.stdout, "") + + def test_the_refusal_is_not_longer_than_twelve_lines_in_any_state(self): + for build in (lambda: None, lambda: self.foreign_unit(), + lambda: self.open_unit(good_contract(profile="critical", checks=[dict(real("c1"), cmd="true")]))): + build() + self.assertLessEqual(len((self.edit("auth/login.py") or "").splitlines()), 12) + + if __name__ == "__main__": unittest.main()