Item 3: an agent cannot approve its own proposals: the before-tool hook refuses sisi approve in any wrapping; a decision needs the typed word read from the controlling terminal; refused attempts are recorded with the session. done / next: items 4 and 9 (backlog and pending-approval statuses, main-repo origin)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-23 14:09:11 -07:00
1 parent 4418136d01
commit 11554b759a
7 files changed
+405 -28

No files matched your search

+45
View File
@@ -56,6 +56,12 @@ class SisiCase(unittest.TestCase):
for k in ("SISI_TOOL", "SISI_SESSION_ID"):
os.environ.pop(k, None)
# no test may talk to the terminal it is run from: `sisi approve` finds none unless the test says so
from unittest import mock as _mock
_no_tty = _mock.patch("sisi.cycle._open_terminal", return_value=None)
_no_tty.start()
self.addCleanup(_no_tty.stop)
def restore():
for k, v in saved.items():
if v is None:
@@ -143,3 +149,42 @@ def skip_timing_if_busy(case):
return
if load > cpus:
case.skipTest("machine overloaded (load %.0f on %d processors): speed not measured" % (load, cpus))
class FakeTerminal:
"""What `sisi approve` reads its decision from. Writes are kept; the line it answers with is the
word the prompt asked for (or `typed`, to type something else, or None to type nothing)."""
def __init__(self, typed="the word"):
self.out, self.typed = [], typed
def write(self, text):
self.out.append(text)
def flush(self):
pass
def readline(self):
if self.typed is None:
return ""
if self.typed != "the word":
return self.typed + "\n"
import re
m = re.search(r"Type the word (\w+)", "".join(self.out))
return (m.group(1) if m else "") + "\n"
def close(self):
pass
@property
def text(self):
return "".join(self.out)
def terminal(typed="the word"):
"""Patch: the process has a controlling terminal, and the owner types `typed` at it."""
from unittest import mock
t = FakeTerminal(typed)
p = mock.patch("sisi.cycle._open_terminal", return_value=t)
p.fake = t
return p
+184 -1
View File
@@ -3,7 +3,7 @@
Each test is an abuse case: the cycle file's author (an agent, untrusted) tries to get something
to run, validate or take effect that nobody approved.
"""
import json, os, subprocess, sys
import json, os, subprocess, sys, unittest
from support import SisiCase
from test_learning_loop import Base, PROMOTE, FINDING, CAUSE, _contract
@@ -130,3 +130,186 @@ class Replay(Base):
r = self.apply([self.cmd_action("grep -q fixed f.txt")])
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(self.rows()[0]["validation"]["result"], "validated")
def _shell_payload(cmd, sid="sess-hook"):
return {"hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": cmd},
"session_id": sid, "cwd": os.getcwd()}
class Approval(Base):
"""R-11.5-11, R-14.3-2, R-16-11, R-16-8 (item 3): an agent cannot approve its own proposals."""
def park(self):
_contract(self)
self.git_init()
self.retro(*PROMOTE[1:])
self.apply([{"action": "promote", "learning": "L-0001", "mechanism_kind": "command-check",
"cmd": "make deploy --force-everything"}])
self.assertEqual(len(self.pending()), 1)
def hook(self, cmd, sid="sess-hook"):
"""Run the before-tool hook on a shell command. Returns the exit code the hook ends with."""
import contextlib, io
from sisi import watch
try:
with contextlib.redirect_stderr(io.StringIO()):
watch.before(_shell_payload(cmd, sid))
except SystemExit as e:
return e.code
return 0
def test_the_before_tool_hook_refuses_every_wrapping_of_approve(self):
"""R-14.3-2 (item 3a): script, sh -c, env, expect, a path to the launcher and python -m sisi."""
self.park()
wrapped = [
'script -qec "sisi approve P-0001 --yes" /dev/null </dev/null',
"sh -c 'sisi approve P-0001 --yes'",
"/path/to/bin/sisi approve P-0001 --yes",
"python3 -m sisi approve P-0001 --yes",
"env SISI_SESSION_ID=x sisi approve P-0001 --no",
"expect -c 'spawn sisi approve P-0001 --yes; expect eof'",
"echo P-0001 | xargs sisi approve --yes",
"bash -lc \"cd /tmp && sisi approve P-0001 --yes\"",
"s\\isi 'app'rove P-0001 --yes",
"sisi${IFS}approve${IFS}P-0001${IFS}--yes",
"cd x; sisi approve P-0001 --yes; echo done",
"a=approve; sisi $a P-0001 --yes",
]
for cmd in wrapped:
with self.subTest(cmd=cmd):
self.assertEqual(self.hook(cmd), 2, cmd)
self.assertEqual(len(self.pending()), 1)
refused = [r for r in L.load_approvals() if r.get("decision") == "refused"]
self.assertEqual(len(refused), len(wrapped))
self.assertTrue(all(r["session"] == "sess-hook" and r["how"] == "hook" for r in refused))
self.assertEqual(refused[0]["id"], "P-0001")
def test_the_listing_and_other_commands_are_allowed_through_the_hook(self):
"""R-14.3-2 (item 3a): `sisi approve` with no arguments is the listing; nothing else is touched."""
for cmd in ("sisi approve", "/path/to/bin/sisi approve", "sisi approve | head -20", "python3 -m sisi approve;",
"sisi cycle apply f.json", "sisi cycle check c.json", "echo approve the plan",
"git commit -m 'approve the design'", "ls"):
with self.subTest(cmd=cmd):
self.assertEqual(self.hook(cmd), 0, cmd)
self.assertEqual(L.load_approvals(), [])
def test_the_hook_is_one_for_main_threads_and_workers(self):
"""R-16-10 (item 3a): a subagent's shell command goes through the same refusal."""
payload = _shell_payload("sisi approve P-0001 --yes", "sess-w")
payload["agent_id"] = "worker-1"
import contextlib, io
from sisi import watch
with self.assertRaises(SystemExit) as cm, contextlib.redirect_stderr(io.StringIO()):
watch.before(payload)
self.assertEqual(cm.exception.code, 2)
def test_the_hook_process_exits_2_with_the_reason_and_fails_open_on_error(self):
"""R-16-9 (item 3a): `sisi watch --before` refuses with exit 2 and says whom to ask; an error in
the check lets the command through."""
r = self.sisi_proc("watch", "--before", stdin=json.dumps(_shell_payload("sisi approve P-0001 --yes")))
self.assertEqual(r.returncode, 2, r.stderr)
self.assertIn("owner's alone", r.stderr)
self.assertIn("give him the command", r.stderr)
import unittest.mock
from sisi import watch
with unittest.mock.patch.object(watch, "_APPROVE", None):
self.assertEqual(self.hook("sisi approve P-0001 --yes"), 0)
def test_a_decision_needs_the_word_typed_at_the_terminal(self):
"""R-14.3-2 (item 3b): the full action and a word are printed to the terminal; the word read
back from it decides. A wrong word, no word, or words on standard input decide nothing."""
from support import terminal
self.park()
t = terminal("wrong")
with t:
r = self.sisi("approve", "P-0001", "--yes", env={"SISI_SESSION_ID": "sess-9"})
self.assertEqual(r.returncode, 2)
self.assertIn("make deploy --force-everything", t.fake.text) # the full action, on the terminal
self.assertIn("Type the word", t.fake.text)
self.assertEqual(len(self.pending()), 1)
self.assertFalse(self.exists("overlay/enforced.json"))
t = terminal(None)
with t:
self.assertEqual(self.sisi("approve", "P-0001", "--no").returncode, 2)
self.assertEqual(len(self.pending()), 1)
refused = [r for r in L.load_approvals() if r.get("decision") == "refused"]
self.assertEqual(len(refused), 2)
self.assertEqual(refused[0]["session"], "sess-9")
with terminal():
r = self.sisi("approve", "P-0001", "--yes")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertTrue(self.exists("overlay/enforced.json"))
def test_no_controlling_terminal_means_refused_and_stdin_cannot_stand_in(self):
"""R-14.3-2 (item 3b): the word is not read from standard input."""
import unittest.mock
self.park()
with unittest.mock.patch("sisi.cycle._open_terminal", return_value=None):
r = self.sisi("approve", "P-0001", "--yes", stdin="pagaso\nyes\n", env={"SISI_SESSION_ID": "s-1"})
self.assertEqual(r.returncode, 2)
self.assertIn("controlling terminal", r.stderr)
self.assertEqual(len(self.pending()), 1)
self.assertEqual([x["session"] for x in L.load_approvals()], ["s-1"])
# a real process in its own session has no controlling terminal at all
p = subprocess.run([sys.executable, os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),
"bin", "sisi"), "approve", "P-0001", "--yes"],
cwd=self.proj, input="pagaso\n", capture_output=True, text=True, timeout=60,
start_new_session=True, env=dict(os.environ))
self.assertEqual(p.returncode, 2, p.stderr)
self.assertEqual(len(self.pending()), 1)
@unittest.skipUnless(os.path.exists("/usr/bin/script") or os.path.exists("/bin/script"), "no script(1)")
def test_script_gives_a_terminal_but_not_the_owners_hands(self):
"""R-14.3-2 (item 3b): the evidence case, `script -qec "sisi approve ..." /dev/null </dev/null`."""
self.park()
bin_ = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "bin", "sisi")
p = subprocess.run(["script", "-qec", "%s %s approve P-0001 --yes" % (sys.executable, bin_), "/dev/null"],
cwd=self.proj, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60,
env=dict(os.environ))
self.assertEqual(len(self.pending()), 1, p.stdout + p.stderr)
self.assertFalse(self.exists("overlay/enforced.json"))
def test_a_person_at_a_real_terminal_can_decide(self):
"""R-14.3-2 (item 3b): through a real pseudo-terminal, typing the word approves."""
try:
import pty
except ImportError:
self.skipTest("no pty")
self.park()
bin_ = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "bin", "sisi")
pid, fd = pty.fork()
if pid == 0:
os.chdir(self.proj)
os.execv(sys.executable, [sys.executable, bin_, "approve", "P-0001", "--yes"])
out = b""
import re, select, time
sent, end = False, time.time() + 60
while time.time() < end:
ready, _w, _x = select.select([fd], [], [], 1)
if not ready:
continue
try:
d = os.read(fd, 4096)
except OSError:
break
if not d:
break
out += d
m = re.search(rb"Type the word (\w+) to decide", out)
if m and not sent:
os.write(fd, m.group(1) + b"\n")
sent = True
_p, status = os.waitpid(pid, 0)
self.assertTrue(sent, out)
self.assertEqual(os.waitstatus_to_exitcode(status), 0, out)
self.assertTrue(self.exists("overlay/enforced.json"))
self.assertEqual(self.pending(), [])
def test_security_says_plainly_what_this_stops_and_does_not(self):
"""R-16-1 (item 3): SECURITY.md names the hook, the typed word, and what neither stops."""
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "SECURITY.md")) as f:
text = f.read()
low = text.lower()
for needle in ("typed word", "before-tool hook", "controlling terminal", "does not stop"):
self.assertIn(needle, low)
+3 -3
View File
@@ -7,7 +7,7 @@ one unit, approves from a non-terminal, adds a row to the store by hand).
"""
import json, os, stat, subprocess, sys, unittest.mock
from support import SisiCase
from support import SisiCase, terminal
from sisi import learning as L
@@ -83,7 +83,7 @@ class Base(SisiCase):
return self.sisi("cycle", "apply", self.cycle_file(actions, **kw))
def tty(self):
return unittest.mock.patch("sisi.cycle._stdin_is_tty", return_value=True)
return terminal()
def other_project(self, name="other"):
d = os.path.join(self.tmp, name)
@@ -789,7 +789,7 @@ class Approval(Base):
self.assertIn("terminal", r.stderr)
self.assertEqual(len(self.pending()), 1)
self.assertFalse(self.exists("overlay/enforced.json"))
self.assertEqual(L.load_approvals(), [])
self.assertEqual([a["decision"] for a in L.load_approvals()], ["refused", "refused"]) # attempts are recorded
def test_a_terminal_decision_is_recorded_with_when_session_and_terminal(self):
"""The record keeps when, the session if known, and that standard input was a terminal."""
+1 -1
View File
@@ -66,7 +66,7 @@ class PersonalCase(SisiCase):
r = self.ok(*a, **kw)
self.assertTrue(L.load_pending(), "the change should be waiting for the owner")
for item in L.load_pending():
with unittest.mock.patch("sisi.cycle._stdin_is_tty", return_value=True):
with terminal():
self.ok("approve", item["id"], "--yes")
return r