Mechanisms over intentions: request-time lesson delivery, self-referential rules, enforced question dialog
ci / tests (macos-latest, python 3.10) (push) Canceled after 0s
ci / tests (macos-latest, python 3.11) (push) Canceled after 0s
ci / tests (macos-latest, python 3.13) (push) Canceled after 0s
ci / tests (macos-latest, python 3.9) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.10) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.11) (push) Canceled after 0s
ci / tests (ubuntu-latest, python 3.13) (push) Canceled after 0s

sisi prompt hands the matching recipe and lessons to the agent when the
human's request arrives. Every rule ends with the command that prints its
reasons, history, lessons and enforcement; sisi rule lists what enforces each
rule. Ending a turn by asking in reply text instead of the question dialog is
sent back. Rulebook budget raised to 200 lines and 12,000 characters.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 08:22:57 -07:00
1 parent f7bc6eded1
commit 11be8e3664
21 files changed
+1087 -44

No files matched your search

+30
View File
@@ -355,6 +355,36 @@ class MergePropertyTests(AdapterBase):
self.cycle()
class PromptHookTests(AdapterBase):
def test_prompt_hooks_registered_and_removed_per_tool(self):
cases = {"codex": (".codex", ".codex/hooks.json", "UserPromptSubmit", False),
"gemini": (".gemini", ".gemini/settings.json", "BeforeAgent", False),
"copilot": (".copilot", ".copilot/hooks/sisi.json", "userPromptSubmitted", True)}
for name, (d, f, ev, 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, prompt hook included
wiring.install()
obj = json.load(open(self.path(f)))
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("prompt --tool %s" % name in (c or "") for c in cmds), (name, ev, cmds))
self.assertEqual(self.rows()[name]["status"], "wired")
wiring.uninstall()
def test_pi_extension_carries_prompt_call(self):
self.assertIn(b'"prompt", "--tool", "pi"', adapters._pi_extension())
def test_no_prompt_hook_where_injection_is_unconfirmed(self):
for a in adapters.ADAPTERS:
spec = a.spec() if hasattr(a, "spec") else {}
if a.name in ("qwen", "cursor"):
self.assertFalse(any(s.get("sub") == "prompt" for s in spec.values()), a.name)
class GeneratedScriptTests(AdapterBase):
def test_opencode_plugin_parses_as_javascript(self):
node = shutil.which("node")
+4 -2
View File
@@ -463,8 +463,10 @@ class WidenedPropertyTests(SafetyBase):
json.dump(obj, open(p, "w"), indent=2)
wiring.install()
raw = open(p, "rb").read()
# tick + gate + subagent gate + watch (registered for both tool events) = at most 5
self.assertLessEqual(raw.count(b"--tool " + tool.encode()), 5, (tool, raw))
# exactly one registration per event in the tool's spec (tick, prompt where wired,
# gate, subagent gate, watch before/after), however many duplicates were planted
adapter = next(a for a in adapters.ADAPTERS if a.name == tool)
self.assertLessEqual(raw.count(b"--tool " + tool.encode()), len(adapter.spec()), (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)]
+3 -2
View File
@@ -160,14 +160,15 @@ class OverlayTests(PersonalCase):
def test_size_budget_refuses_and_changes_nothing(self):
self.ok("build-canon")
gen0, log0 = self.generated(), self.git_log()
big = rule_file("Big", "\n".join("line %d" % i for i in range(150)))
room = overlay.MAX_LINES - len(gen0.splitlines())
big = rule_file("Big", "\n".join("line %d" % i for i in range(room + 30)))
r = self.sisi("overlay", "add-rule", "--id", "big", "-", stdin=big)
self.assertEqual(r.returncode, 1)
self.assertIn("budget", r.stderr)
self.assertEqual((self.generated(), self.git_log()), (gen0, log0))
self.assertFalse(os.path.exists(os.path.join(self.data, "overlay", "rules", "big.md")))
# fits after something is made shorter or replaced
fill = rule_file("Fill", "\n".join("x%d" % i for i in range(80)))
fill = rule_file("Fill", "\n".join("x%d" % i for i in range(room - 20)))
self.ok("overlay", "add-rule", "--id", "fill", "-", stdin=fill)
self.assertLessEqual(len(self.generated().splitlines()), overlay.MAX_LINES)
r = self.sisi("overlay", "add-rule", "--id", "more", "-", stdin=rule_file("More", "\n".join("y%d" % i for i in range(30))))
+157
View File
@@ -0,0 +1,157 @@
"""`sisi prompt`: request-time delivery of the matching recipe and lessons on the human's message.
The hook must never block or fail a turn, must stay silent when nothing strictly matches, and must be
fast. Matching reuses the strict "likely to apply" test from retro.delivery; the labelled set below
phrases requests in different words from the lessons so only the when-terms can bridge them.
"""
import json, os, statistics, time, unittest
from support import *
from sisi import retro
def fields(**kw):
f = dict(aim="verified", change_kind="recipe", target="release",
moment="the tagged build shipped with a changelog for the previous version",
cause="nobody compared the tag, the manifest version and the changelog before publishing",
change="Before publishing, check the tag, the manifest version and the changelog agree",
when="release, tagging, version, publish, changelog, package, ship it",
short="Check tag, version and changelog agree before publishing.")
f.update(kw)
return f
class PromptCase(SisiCase):
def mk(self, **kw):
con = retro.connect()
try:
lid = retro.new_lesson(con, fields(**kw), self.proj, None)
con.commit()
return lid
finally:
con.close()
def prompt(self, payload, tool=None):
args = ["prompt"] + (["--tool", tool] if tool else [])
return self.sisi(*args, stdin=json.dumps(payload))
class PromptHookTests(PromptCase):
def test_release_request_gets_recipe_and_lesson_with_full_text_commands(self):
lid = self.mk()
r = self.prompt({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj})
self.assertEqual(r.returncode, 0, r.stderr)
out = json.loads(r.stdout)
ctx = out["hookSpecificOutput"]["additionalContext"]
self.assertEqual(out["hookSpecificOutput"]["hookEventName"], "UserPromptSubmit")
self.assertIn("release", ctx)
self.assertIn("sisi done release", ctx)
self.assertIn("Check tag, version and changelog agree", ctx)
self.assertIn("sisi lessons show %d" % lid, ctx)
from sisi import prompt as P
self.assertLessEqual(len(ctx), P.MAX_CHARS)
def test_listing_is_counted(self):
lid = self.mk()
self.prompt({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj})
con = retro.connect()
try:
self.assertGreaterEqual(retro.listed_count(con, lid), 1)
places = [r[0] for r in con.execute("SELECT place FROM impressions WHERE lesson_id=?", (lid,))]
self.assertIn("prompt", places)
finally:
con.close()
def test_nothing_for_trivial_or_unmatched_messages(self):
self.mk()
for text in ("yes", "no thanks", "/clear", "what time is it?", "ok",
"rename the local variable in the slug helper to something clearer"):
with self.subTest(text=text):
r = self.prompt({"prompt": text, "session_id": "s1", "cwd": self.proj})
self.assertEqual(r.returncode, 0)
self.assertEqual(r.stdout.strip(), "")
def test_garbage_input_exits_zero_silently(self):
for stdin in ("not json", "", "[]", '{"prompt": 42}'):
with self.subTest(stdin=stdin):
r = self.sisi("prompt", stdin=stdin)
self.assertEqual(r.returncode, 0)
def test_other_tool_shapes(self):
self.mk()
payload = {"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj}
r = self.prompt(payload, tool="copilot")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("sisi done release", json.loads(r.stdout)["additionalContext"])
r = self.prompt(payload, tool="gemini")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("sisi done release",
json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"])
r = self.prompt(payload, tool="pi")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("sisi done release", r.stdout)
def test_fast_enough_median_of_twenty(self):
skip_timing_if_busy(self)
self.mk()
payload = json.dumps({"prompt": "cut a new release and tag it", "session_id": "s1", "cwd": self.proj})
times = []
for _ in range(20):
t0 = time.time()
r = self.sisi_proc("prompt", stdin=payload)
times.append(time.time() - t0)
self.assertEqual(r.returncode, 0)
med = statistics.median(times)
self.assertLess(med, 1.0, "median prompt-hook run %.3fs over 20 runs" % med)
class LabelledMatchingTests(PromptCase):
"""Requests rephrased away from the lessons' own wording. A hit means the lesson's short line (or
the recipe it targets) is in the injected context; a false match means context was injected for a
request it does not apply to."""
def setUp(self):
super().setUp()
self.release_id = self.mk()
self.csv_id = self.mk(
target=None, change_kind="rule",
moment="a spreadsheet export broke on a field containing a newline",
cause="rows were joined by hand instead of with a quoting writer",
change="Write delimited files with a quoting writer so embedded newlines survive",
when="csv, tsv, spreadsheet, tabular data, export, delimited file, quoting",
short="Use a quoting writer for delimited exports.")
def ctx(self, text):
from sisi import prompt as P
return P.build_context(text, session="labelled")
def test_labelled_set(self):
# A hit: the expected lesson's short line is injected. A false match: either lesson is
# injected for a request it does not apply to. (A recipe for the request's own kind of work
# is the feature working, not a false match, so it is measured separately below.)
release_short = "Check tag, version and changelog agree"
csv_short = "Use a quoting writer"
should = [
("cut a new release and tag it", release_short),
("publish the next version to the package index please", release_short),
("ship it: bump the version and push the tag", release_short),
("export the table as a spreadsheet file", csv_short),
("write these rows out as a delimited file for the spreadsheet", csv_short),
]
should_not = [
"rename the helper that formats release notes headings in the docs",
"why is the test suite slow on this machine",
"add a dark mode toggle to the settings page",
"fix the off-by-one in the pagination control",
"explain how the quoting in this shell one-liner works",
]
hits = sum(1 for t, want in should if want in self.ctx(t))
false_alarms = sum(1 for t in should_not
if release_short in self.ctx(t) or csv_short in self.ctx(t))
self.assertEqual((hits, false_alarms), (len(should), 0),
"lesson hits %d/%d, false matches %d/%d" % (hits, len(should), false_alarms, len(should_not)))
# the release request also names the right recipe, not a neighbour
self.assertIn("sisi done release", self.ctx("cut a new release and tag it"))
if __name__ == "__main__":
unittest.main()
+103
View File
@@ -0,0 +1,103 @@
"""Rule 5 enforcement: ending a turn by asking the human a question in reply text sends the agent back
once, where a question dialog exists and was not used in that turn (Claude Code)."""
import json, os, unittest
from support import *
from sisi import gate
ASK = [
"All checks pass. Should I also update the changelog?",
"Done. Do you want the button blue or grey?",
"The migration is ready.\n\nWhich name should the new column have?",
"Implemented and verified. Shall I open the pull request now?",
"Fixed. What do you think of the new layout?",
"Tests are green. Would you like me to remove the old parser too?",
"Ready when you are. Can I go ahead and delete the legacy table?",
"The export works. Do we need the legacy format as well?",
"All set. Is Thursday still the target for this?",
"The build passes. Should we ship it?",
]
NOT_ASK = [
"All checks pass. The changelog is updated.",
"Who wouldn't want a faster build?",
"The issue asked: \"why does it crash on startup?\" and the fix answers it.",
"Done.\n\n```\nresult = value if ready else fallback # what about None?\n```",
"> Should we cache this?\n\nNo: the data changes on every request, so I left it uncached.",
"Fixed the `a ? b : c` case and the suite passes.",
"What could possibly go wrong? Quite a lot, so the change is behind a flag.",
"The report ends with the customer's words: \"can you fix it by Friday?\"",
"Verified: rung 3, 41 examples, all passing.",
"Why did it fail? Because the fixture was stale; it is regenerated now and checks pass.",
"Shipped. The remaining question of naming is recorded as an assumption in the contract.",
"Isn't it obvious in hindsight? The guard was inverted; fixed and pinned by a test.",
]
class DetectionTests(unittest.TestCase):
def test_labelled_set(self):
hits = [t for t in ASK if gate.ends_with_question(t)]
alarms = [t for t in NOT_ASK if gate.ends_with_question(t)]
self.assertEqual(len(hits), len(ASK), "missed: %r" % [t for t in ASK if t not in hits])
self.assertEqual(alarms, [], "false alarms: %r" % alarms)
def transcript(path, final_text, dialog=False):
recs = [
{"type": "user", "timestamp": "2026-01-01T00:00:00Z",
"message": {"role": "user", "content": "please fix the widget"}},
]
if dialog:
recs.append({"type": "assistant", "timestamp": "2026-01-01T00:01:00Z",
"message": {"role": "assistant", "content": [
{"type": "tool_use", "name": "AskUserQuestion", "input": {"questions": []}}]}})
recs.append({"type": "assistant", "timestamp": "2026-01-01T00:02:00Z",
"message": {"role": "assistant", "content": [{"type": "text", "text": final_text}]}})
with open(path, "w") as f:
for r in recs:
f.write(json.dumps(r) + "\n")
class GateQuestionTests(SisiCase):
def setUp(self):
super().setUp()
self.git_init()
self.tp = os.path.join(self.tmp, "t.jsonl")
os.environ["SISI_TOOL"] = "claude-code"
def payload(self, **kw):
p = {"session_id": "qsess", "cwd": self.proj, "transcript_path": self.tp}
p.update(kw)
return p
def test_asking_in_prose_sends_back_once(self):
transcript(self.tp, "Fixed and verified. Should I also update the docs?")
action, msg = gate.decide(self.payload())
self.assertEqual(action, "block", msg)
self.assertIn("dialog", msg.lower())
action2, _ = gate.decide(self.payload())
self.assertEqual(action2, "allow", "second stop on the same message must not trap the session")
def test_dialog_used_in_turn_is_exempt(self):
transcript(self.tp, "Fixed and verified. Should I also update the docs?", dialog=True)
action, _ = gate.decide(self.payload())
self.assertEqual(action, "allow")
def test_plain_finish_is_allowed(self):
transcript(self.tp, "Fixed and verified. All checks pass.")
action, _ = gate.decide(self.payload())
self.assertEqual(action, "allow")
def test_subagent_is_exempt(self):
transcript(self.tp, "Fixed and verified. Should I also update the docs?")
action, _ = gate.decide(self.payload(agent_id="agent-1"))
self.assertEqual(action, "allow")
def test_tool_without_dialog_is_exempt(self):
os.environ["SISI_TOOL"] = "cursor"
transcript(self.tp, "Fixed and verified. Should I also update the docs?")
action, _ = gate.decide(self.payload())
self.assertEqual(action, "allow")
if __name__ == "__main__":
unittest.main()
+96
View File
@@ -0,0 +1,96 @@
"""`sisi rule`: every rule points at its own detail, and the enforcement column comes from code facts."""
import json, os, unittest
from support import *
from sisi import overlay, retro
class RuleTableTests(SisiCase):
def test_table_lists_every_rule_with_enforcement(self):
r = self.sisi("rule")
self.assertEqual(r.returncode, 0, r.stderr)
_, rules = overlay.base_rules()
for rule in rules:
self.assertIn(rule["id"], r.stdout)
self.assertIn(rule["title"], r.stdout)
self.assertIn("not enforced", r.stdout) # at least one rule is honestly only an intention
def test_every_base_rule_has_an_enforcement_entry(self):
from sisi import rulecmd
_, rules = overlay.base_rules()
for rule in rules:
self.assertIn(rule["id"], rulecmd.ENFORCEMENT, rule["id"])
self.assertTrue(rulecmd.enforcement_for(rule["id"]).strip())
def test_enforcement_wording_names_real_mechanisms(self):
from sisi import rulecmd
self.assertIn("end-of-turn", rulecmd.enforcement_for("know-done"))
self.assertIn("retro", rulecmd.enforcement_for("retro-every-time").lower())
ask = rulecmd.enforcement_for("decide-dont-ask").lower()
self.assertTrue("dialog" in ask or "asking" in ask, ask)
class RuleDetailTests(SisiCase):
def test_rule_by_number_and_by_id(self):
by_num = self.sisi("rule", "5")
by_id = self.sisi("rule", "decide-dont-ask")
self.assertEqual(by_num.returncode, 0, by_num.stderr)
self.assertEqual(by_id.returncode, 0, by_id.stderr)
for out in (by_num.stdout, by_id.stdout):
self.assertIn("Decide, do not ask", out)
self.assertIn("Why:", out)
self.assertIn("AskUserQuestion", out)
self.assertIn("base", out.lower())
def test_unknown_rule_fails(self):
self.assertEqual(self.sisi("rule", "no-such-rule").returncode, 1)
self.assertEqual(self.sisi("rule", "99").returncode, 1)
def test_folded_lessons_are_shown_with_show_command(self):
con = retro.connect()
try:
lid = retro.new_lesson(con, dict(
aim="hands-off", change_kind="rule", target=None,
moment="the agent buried a naming question at the end of a long report",
cause="asking in prose felt quicker than opening the dialog",
change="Ask naming questions through the dialog with options",
when="naming, question, dialog, options, ask the human, choice",
short="Ask through the dialog, with options."), self.proj, None)
con.execute("UPDATE lessons SET folded_into='decide-dont-ask', count=3 WHERE id=?", (lid,))
con.commit()
finally:
con.close()
r = self.sisi("rule", "decide-dont-ask")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("Ask through the dialog, with options.", r.stdout)
self.assertIn("sisi lessons show %d" % lid, r.stdout)
self.assertIn("buried a naming question", r.stdout) # the moment, as the example
def test_overlay_replacement_is_named_as_overlay(self):
d = os.path.join(self.data, "overlay", "rules")
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, "deliver-quickly.md"), "w") as f:
f.write("## Deliver quickly\n\nReplacement body written by the owner.\n\nWhy: a test.\n")
r = self.sisi("rule", "deliver-quickly")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("Replacement body", r.stdout)
self.assertIn("overlay", r.stdout.lower())
class MoreLineTests(SisiCase):
def test_generated_rulebook_points_each_rule_at_its_detail(self):
text = overlay.render()
_, rules = overlay.effective()
for n, rule in enumerate(rules, 1):
self.assertIn("More: `sisi rule %d`" % n, text, rule["id"])
lines, chars = overlay.size(text)
self.assertLessEqual(lines, overlay.MAX_LINES)
self.assertLessEqual(chars, overlay.MAX_CHARS)
def test_help_names_rule_and_prompt(self):
out = self.sisi("help").stdout
self.assertIn("sisi rule", out)
self.assertIn("sisi prompt", out)
if __name__ == "__main__":
unittest.main()