Delegation records, repeat-failure stop, orchestration in the unit record and rule 6, all-tool hooks with migration and per-host meter notes. done: items 4-7 code and tests / next: item 9 fallback, docs, timing, repeat runs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
80af7b0d0e
commit
9e8f80bbb7
7 files changed
+430
-26
No files matched your search
@@ -1,16 +1,38 @@
|
||||
{
|
||||
"_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error. `evidence` says how sure this entry is.",
|
||||
"_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error, `none` means the meter only counts there. `evidence` says how sure this entry is.",
|
||||
"claude-code": {
|
||||
"refuse": "json-deny",
|
||||
"evidence": "observed live (tools/live_orchestration_check.py)",
|
||||
"delegation": {
|
||||
"Task": {"model": "model", "brief": "prompt"},
|
||||
"Agent": {"model": "model", "brief": "prompt"}
|
||||
"Task": {
|
||||
"model": "model",
|
||||
"brief": "prompt"
|
||||
},
|
||||
"Agent": {
|
||||
"model": "model",
|
||||
"brief": "prompt"
|
||||
}
|
||||
},
|
||||
"exempt": {
|
||||
"dialog": ["AskUserQuestion"],
|
||||
"planning": ["TodoWrite", "EnterPlanMode", "ExitPlanMode", "TaskCreate", "TaskUpdate", "TaskList", "TaskGet", "TaskOutput", "TaskStop"],
|
||||
"messaging": ["SendMessage", "SendUserMessage", "PushNotification"]
|
||||
"dialog": [
|
||||
"AskUserQuestion"
|
||||
],
|
||||
"planning": [
|
||||
"TodoWrite",
|
||||
"EnterPlanMode",
|
||||
"ExitPlanMode",
|
||||
"TaskCreate",
|
||||
"TaskUpdate",
|
||||
"TaskList",
|
||||
"TaskGet",
|
||||
"TaskOutput",
|
||||
"TaskStop"
|
||||
],
|
||||
"messaging": [
|
||||
"SendMessage",
|
||||
"SendUserMessage",
|
||||
"PushNotification"
|
||||
]
|
||||
}
|
||||
},
|
||||
"codex": {
|
||||
@@ -18,8 +40,12 @@
|
||||
"evidence": "from the host's hook documentation; not run live here",
|
||||
"delegation": {},
|
||||
"exempt": {
|
||||
"dialog": ["request_user_input"],
|
||||
"planning": ["update_plan"],
|
||||
"dialog": [
|
||||
"request_user_input"
|
||||
],
|
||||
"planning": [
|
||||
"update_plan"
|
||||
],
|
||||
"messaging": []
|
||||
}
|
||||
},
|
||||
@@ -28,28 +54,50 @@
|
||||
"evidence": "from the host's hook documentation; not run live here",
|
||||
"delegation": {},
|
||||
"exempt": {
|
||||
"dialog": ["ask_user"],
|
||||
"planning": ["write_todos"],
|
||||
"dialog": [
|
||||
"ask_user"
|
||||
],
|
||||
"planning": [
|
||||
"write_todos"
|
||||
],
|
||||
"messaging": []
|
||||
}
|
||||
},
|
||||
"copilot": {
|
||||
"refuse": "exit-2",
|
||||
"evidence": "from the host's hook documentation; not run live here",
|
||||
"delegation": {"task": {"model": "model", "brief": "prompt"}},
|
||||
"refuse": "none",
|
||||
"evidence": "the host's before-tool refusal contract is not confirmed here; counts only",
|
||||
"delegation": {
|
||||
"task": {
|
||||
"model": "model",
|
||||
"brief": "prompt"
|
||||
}
|
||||
},
|
||||
"exempt": {
|
||||
"dialog": ["ask_user"],
|
||||
"planning": ["update_todo"],
|
||||
"dialog": [
|
||||
"ask_user"
|
||||
],
|
||||
"planning": [
|
||||
"update_todo"
|
||||
],
|
||||
"messaging": []
|
||||
}
|
||||
},
|
||||
"cursor": {
|
||||
"refuse": "exit-2",
|
||||
"evidence": "from the host's hook documentation; not run live here",
|
||||
"delegation": {"Task": {"model": "model", "brief": "prompt"}},
|
||||
"delegation": {
|
||||
"Task": {
|
||||
"model": "model",
|
||||
"brief": "prompt"
|
||||
}
|
||||
},
|
||||
"exempt": {
|
||||
"dialog": ["AskQuestion"],
|
||||
"planning": ["TodoWrite"],
|
||||
"dialog": [
|
||||
"AskQuestion"
|
||||
],
|
||||
"planning": [
|
||||
"TodoWrite"
|
||||
],
|
||||
"messaging": []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +145,8 @@ def cmd_wiring(name, args=()):
|
||||
w = max(len(r["tool"]) for r in rows)
|
||||
for r in rows:
|
||||
line = "%-*s %-9s blocking hook: %-8s %s" % (w, r["tool"], r["status"], r["blocking_hook"][:60], r["detail"])
|
||||
if r.get("meter"):
|
||||
line += " | orchestration meter: " + r["meter"]
|
||||
if r.get("action"):
|
||||
line += " | you need to: " + r["action"]
|
||||
print(line)
|
||||
|
||||
+15
-2
@@ -38,13 +38,13 @@ def cfg():
|
||||
|
||||
|
||||
def hosts():
|
||||
if not _HOSTS:
|
||||
if not _HOSTS: # a failed read is not remembered: the next call tries again
|
||||
try:
|
||||
with open(paths.canon("orchestration-tools.json"), encoding="utf-8") as f:
|
||||
d = json.load(f)
|
||||
_HOSTS.update({k: v for k, v in d.items() if isinstance(v, dict)})
|
||||
except (OSError, ValueError):
|
||||
_HOSTS["_none"] = {}
|
||||
return {}
|
||||
return _HOSTS
|
||||
|
||||
|
||||
@@ -56,6 +56,19 @@ def refuse_style(host):
|
||||
return host_data(host).get("refuse")
|
||||
|
||||
|
||||
def meter_note(tool, wired):
|
||||
"""One honest line for `sisi doctor`: what the meter can do in this host, from what its hooks support."""
|
||||
hd = host_data(tool) if tool in hosts() else {}
|
||||
if not hd:
|
||||
return "cannot run (no before-tool hook is wired for this tool)"
|
||||
if not wired:
|
||||
return "not running (this tool's hooks are not wired: `sisi install`)"
|
||||
style = hd.get("refuse")
|
||||
how = {"json-deny": "can refuse a call (permission-deny output)",
|
||||
"exit-2": "can refuse a call (exit status 2 with the reason)"}.get(style, "only counts (cannot refuse)")
|
||||
return "%s; %s" % (how, hd.get("evidence") or "evidence not stated")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- classifying a call
|
||||
|
||||
def _exempt_names(hd):
|
||||
|
||||
+26
-3
@@ -109,12 +109,35 @@ def _deliver_fast():
|
||||
judgement=["parallel work, background checks, handing over early, changing approach when stuck"])
|
||||
|
||||
|
||||
def _pre_tool_wired():
|
||||
try:
|
||||
from . import wiring
|
||||
return "PreToolUse" in wiring.hook_cmds() and not wiring.HOOK_MATCHERS.get("PreToolUse")
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _orchestrate():
|
||||
meter = _pre_tool_wired() and _has("orchestration", "before", "cmd_direct")
|
||||
return _say(enforced=["a delegation brief without outcome, acceptance or files it may change is refused (`sisi delegate`)"
|
||||
if _has("workers", "cmd_delegate") and _has("brief", "missing_required") else None],
|
||||
if _has("workers", "cmd_delegate") and _has("brief", "missing_required") else None,
|
||||
"the before-tool hook counts the main thread's direct tool calls and result characters for every tool, and "
|
||||
"refuses the next one past the budget (`orchestrate.direct_calls`, `orchestrate.direct_chars`), naming the router's "
|
||||
"workers; `sisi unit direct \"<reason>\"` extends the turn with a specific reason (a generic one is refused)"
|
||||
if meter else None,
|
||||
"a delegation that names no model, or the session's own model, is refused with the router's pick; an allowed "
|
||||
"one has its brief checked and is written to the ledger as a run"
|
||||
if meter and _has("orchestration", "_before_delegation") else None,
|
||||
"the end-of-turn gate asks for the judgement of each finished delegation, once per set of runs"
|
||||
if _gate_wired() and _has("orchestration", "judgement_sendback") else None,
|
||||
"a shell command that failed three times in a row with no file changed is refused once (rule 5)"
|
||||
if meter else None],
|
||||
measured=["the delegation ledger and `sisi delegate judge`, `sisi route` recommends the worker from that record"
|
||||
if _has("routing", "choose") and _has("workers", "cmd_delegate") else None],
|
||||
judgement=["who gets the task, how much to check what comes back, recording the judgement"])
|
||||
if _has("routing", "choose") and _has("workers", "cmd_delegate") else None,
|
||||
"the unit record and `sisi status` show direct calls and characters, refusals, extensions with their reasons, "
|
||||
"delegations started, judged and unjudged, and the share of tool calls delegated"
|
||||
if _has("orchestration", "telemetry") else None],
|
||||
judgement=["who gets the task, how much to check what comes back, the quality of a brief"])
|
||||
|
||||
|
||||
def _report_plainly():
|
||||
|
||||
+9
-2
@@ -611,6 +611,11 @@ def uninstall():
|
||||
|
||||
|
||||
# ---- doctor ----------------------------------------------------------------
|
||||
def _meter(pair):
|
||||
from . import orchestration
|
||||
return orchestration.meter_note(*pair)
|
||||
|
||||
|
||||
def doctor():
|
||||
L = loc()
|
||||
rows = []
|
||||
@@ -627,6 +632,7 @@ def doctor():
|
||||
rows.append({"tool": "claude-code", "status": "not wired" if missing else "wired",
|
||||
"detail": ("missing: " + ", ".join(missing)) if missing else "import + tick + prompt + gate registered",
|
||||
"blocking_hook": "yes (Stop)" if hw["gate"] else "no",
|
||||
"meter": _meter(("claude-code", hw["pre"] and hw["post"] and hw.get("postfail", False))),
|
||||
"rulebook": not missing and _claude_md_wired(cm), "tick": hw["tick"],
|
||||
"enforcement": "blocks", "action": None})
|
||||
from . import adapters
|
||||
@@ -640,13 +646,14 @@ def doctor():
|
||||
"sends a follow-up (%s)" % st["via"] if enf == "sends a follow-up" else enf)
|
||||
tool_rows.append({"tool": st["tool"], "status": "wired" if st["wired"] else "not wired",
|
||||
"detail": st["detail"], "blocking_hook": blocking, "rulebook": st["rulebook"],
|
||||
"tick": st["tick"], "enforcement": enf, "action": st["action"]})
|
||||
"tick": st["tick"], "enforcement": enf, "action": st["action"],
|
||||
"meter": _meter((st["tool"], st["wired"]))})
|
||||
rows += tool_rows
|
||||
anti = adapters.antigravity_status()
|
||||
if anti["detected"]:
|
||||
rows.append({"tool": "antigravity", "status": "not wired", "detail": anti["detail"],
|
||||
"blocking_hook": "unknown", "rulebook": anti["rulebook"], "tick": False,
|
||||
"enforcement": "unknown", "action": None})
|
||||
"enforcement": "unknown", "action": None, "meter": _meter(("antigravity", False))})
|
||||
_providers = {"claude-code", "codex", "opencode", "cursor", "pi", "muse", "gemini", "copilot", "qwen", "grok"}
|
||||
wired_names = [n for n in ([r["tool"] for r in tool_rows if r["status"] == "wired"]
|
||||
+ (["claude-code"] if rows[0]["status"] == "wired" else [])) if n in _providers]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import json, os, random, shutil, stat, subprocess, sys, unittest
|
||||
import contextlib, io, json, os, random, shutil, stat, subprocess, sys, unittest
|
||||
from unittest import mock
|
||||
from support import *
|
||||
from test_wiring import WiringBase, snapshot
|
||||
@@ -547,3 +547,116 @@ class WidenedPropertyTests(SafetyBase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
real_cmds = wiring.hook_cmds # the registration as this version makes it, kept before any test patches it
|
||||
|
||||
|
||||
class AllToolsHookMigrationTests(SafetyBase):
|
||||
"""Item 7: an installed shell-only configuration becomes all-tool hooks, span-preserving, and uninstall restores
|
||||
the original bytes (R-7.1-1 / R-6.3-1: the meter must see every tool)."""
|
||||
|
||||
ORIGINAL = (b'{\n "theme": "dark", \n "hooks": {\n "PreToolUse": [\n'
|
||||
b' {"matcher": "Edit", "hooks": [{"type": "command", "command": "echo mine"}]}\n ]\n },\n'
|
||||
b' "model": "x"\n}\n')
|
||||
|
||||
def settings(self):
|
||||
return self.path(".claude/settings.json")
|
||||
|
||||
def install_old_style(self):
|
||||
"""What the previous release wrote: shell-only matchers on the tool hooks and no failure hook."""
|
||||
old = {"PreToolUse": "Bash", "PostToolUse": "Bash"}
|
||||
with mock.patch.object(wiring, "HOOK_MATCHERS", old), \
|
||||
mock.patch.object(wiring, "hook_cmds", lambda: {k: v for k, v in real_cmds().items() if k != "PostToolUseFailure"}):
|
||||
rc, notes = wiring.install()
|
||||
self.assertEqual(rc, 0, notes)
|
||||
|
||||
def groups(self, ev):
|
||||
return json.load(open(self.settings()))["hooks"][ev]
|
||||
|
||||
def test_shell_only_install_is_migrated_and_uninstall_restores_the_original_bytes(self):
|
||||
self.put(".claude/settings.json", self.ORIGINAL)
|
||||
self.install_old_style()
|
||||
self.assertTrue(any(g.get("matcher") == "Bash" for g in self.groups("PreToolUse")))
|
||||
self.assertNotIn("PostToolUseFailure", json.load(open(self.settings()))["hooks"])
|
||||
self.assertIn("watch-failure hook", wiring.doctor_claude()) # doctor says what is missing
|
||||
rc, notes = wiring.install() # `sisi install` again, with this version
|
||||
self.assertEqual(rc, 0, notes)
|
||||
for ev in ("PreToolUse", "PostToolUse", "PostToolUseFailure"):
|
||||
mine = [g for g in self.groups(ev) if any("watch --tool" in h["command"] for h in g["hooks"])]
|
||||
self.assertEqual(len(mine), 1, ev)
|
||||
self.assertFalse(mine[0].get("matcher"), (ev, mine)) # every tool: no matcher
|
||||
user = [g for g in self.groups("PreToolUse") if g.get("matcher") == "Edit"]
|
||||
self.assertEqual(user, [{"matcher": "Edit", "hooks": [{"type": "command", "command": "echo mine"}]}])
|
||||
self.assertEqual(wiring.doctor_claude(), "")
|
||||
before = open(self.settings(), "rb").read()
|
||||
wiring.install()
|
||||
self.assertEqual(open(self.settings(), "rb").read(), before) # idempotent
|
||||
wiring.uninstall()
|
||||
self.assertEqual(open(self.settings(), "rb").read(), self.ORIGINAL) # the original bytes, spelling and all
|
||||
|
||||
def test_a_group_shared_with_a_users_own_hook_is_split_not_widened(self):
|
||||
"""Our entry sharing a Bash-matcher group with a user's hook must not widen the user's hook to every tool."""
|
||||
cmd = real_cmds()["PreToolUse"][0]
|
||||
shared = {"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [
|
||||
{"type": "command", "command": "echo mine"}, {"type": "command", "command": cmd, "timeout": 60}]}]}}
|
||||
self.put(".claude/settings.json", json.dumps(shared, indent=2).encode() + b"\n")
|
||||
wiring.install()
|
||||
groups = self.groups("PreToolUse")
|
||||
user = [g for g in groups if any(h["command"] == "echo mine" for h in g["hooks"])]
|
||||
self.assertEqual(len(user), 1)
|
||||
self.assertEqual(user[0]["matcher"], "Bash")
|
||||
self.assertEqual(len(user[0]["hooks"]), 1)
|
||||
ours = [g for g in groups if any("watch --tool" in h["command"] for h in g["hooks"])]
|
||||
self.assertEqual(len(ours), 1)
|
||||
self.assertFalse(ours[0].get("matcher"))
|
||||
|
||||
def test_sisi_update_brings_an_existing_installation_to_all_tool_hooks(self):
|
||||
self.put(".claude/settings.json", self.ORIGINAL)
|
||||
self.install_old_style()
|
||||
from sisi import lifecycle
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
lifecycle._rewire_existing()
|
||||
self.assertFalse(any(g.get("matcher") == "Bash" for g in self.groups("PreToolUse")))
|
||||
self.assertIn("PostToolUseFailure", json.load(open(self.settings()))["hooks"])
|
||||
wiring.uninstall()
|
||||
self.assertEqual(open(self.settings(), "rb").read(), self.ORIGINAL)
|
||||
|
||||
def test_update_without_an_installation_changes_nothing(self):
|
||||
self.put(".claude/settings.json", self.ORIGINAL)
|
||||
from sisi import lifecycle
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
lifecycle._rewire_existing()
|
||||
self.assertEqual(open(self.settings(), "rb").read(), self.ORIGINAL)
|
||||
|
||||
def test_codex_shell_only_hooks_are_widened_too(self):
|
||||
os.makedirs(self.path(".codex"))
|
||||
old = {"PreToolUse": {"cmd": "x"}}
|
||||
spec = adapters.BY_NAME["codex"].spec()
|
||||
spec_old = {k: dict(v, matcher="Bash") if k in ("PreToolUse", "PostToolUse") else v for k, v in spec.items()}
|
||||
with mock.patch.object(adapters.Codex, "spec", lambda self: spec_old):
|
||||
wiring.install()
|
||||
self.assertTrue(any(g.get("matcher") == "Bash" for g in json.load(open(self.path(".codex/hooks.json")))["hooks"]["PreToolUse"]))
|
||||
wiring.install()
|
||||
self.assertFalse(any(g.get("matcher") for g in json.load(open(self.path(".codex/hooks.json")))["hooks"]["PreToolUse"]))
|
||||
wiring.uninstall()
|
||||
self.assertFalse(os.path.exists(self.path(".codex/hooks.json")))
|
||||
|
||||
def test_doctor_says_what_the_meter_can_do_per_tool(self):
|
||||
from sisi import orchestration
|
||||
shutil.copy(os.path.join(REPO, "canon", "orchestration-tools.json"), os.path.join(self.repo, "canon"))
|
||||
orchestration._HOSTS.clear()
|
||||
self.addCleanup(orchestration._HOSTS.clear)
|
||||
os.makedirs(self.path(".codex"))
|
||||
os.makedirs(self.path(".qwen"))
|
||||
wiring.install()
|
||||
rows = {r["tool"]: r for r in wiring.doctor()}
|
||||
self.assertIn("can refuse", rows["claude-code"]["meter"])
|
||||
self.assertIn("observed live", rows["claude-code"]["meter"])
|
||||
self.assertIn("exit status 2", rows["codex"]["meter"])
|
||||
self.assertIn("not run live", rows["codex"]["meter"])
|
||||
self.assertIn("cannot run", rows["qwen"]["meter"])
|
||||
out = self.sisi("doctor").stdout
|
||||
self.assertIn("orchestration meter: cannot run", out)
|
||||
|
||||
|
||||
@@ -284,3 +284,201 @@ class DelegationGuardTests(MeterBase):
|
||||
for _ in range(10):
|
||||
self.assertFalse(self.deleg(model="alpha-small")[0])
|
||||
self.assertFalse(self.pre()[0])
|
||||
|
||||
|
||||
class DelegationRecordTests(MeterBase):
|
||||
"""Item 4: a host delegation writes itself to the ledger; the gate asks for the judgement once."""
|
||||
|
||||
def deleg_pre(self, tool_use_id="tu1", model="alpha-small"):
|
||||
return self.pre("Agent", {"description": "d", "prompt": "Outcome: x\nAcceptance: y\nFiles you may change: none",
|
||||
"model": model}, tool_use_id=tool_use_id)
|
||||
|
||||
def deleg_post(self, response, tool_use_id="tu1", event="PostToolUse"):
|
||||
return self.post("Agent", {"description": "d", "prompt": "p", "model": "alpha-small"}, response=response,
|
||||
event=event, tool_use_id=tool_use_id)
|
||||
|
||||
def stop(self):
|
||||
r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps(
|
||||
{"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False}))
|
||||
return json.loads(r.stdout) if r.stdout.strip() else {}
|
||||
|
||||
def runs(self):
|
||||
return workers.merged_runs()
|
||||
|
||||
def test_a_synchronous_delegation_is_written_pending_then_completed_with_tokens(self):
|
||||
self.prompt()
|
||||
_d, ctx, _ = self.deleg_pre()
|
||||
run = self.runs()[0]
|
||||
self.assertIn(run["id"], ctx) # the id is printed
|
||||
self.assertEqual((run["status"], run["worker"], run["session"]), ("pending", "alpha-small", self.sid))
|
||||
self.assertEqual(workers.unjudged_runs(), []) # in flight: nothing to judge yet
|
||||
self.deleg_post({"status": "completed", "totalTokens": 4321, "totalDurationMs": 90000})
|
||||
run = self.runs()[0]
|
||||
self.assertEqual((run["status"], run["tokens"], run["tokens_class"], run["minutes"]), ("waiting", 4321, "measured", 1.5))
|
||||
self.assertEqual([r["id"] for r in workers.unjudged_runs()], [run["id"]])
|
||||
r = self.sisi("delegate", "judge", run["id"], "--outcome", "accepted", "--check", "read",
|
||||
"--type", "research", "--difficulty", "1")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertEqual(workers.unjudged_runs(), [])
|
||||
att = [x for x in workers.read_records() if x.get("kind") == "attempt" and x.get("run_id") == run["id"]][0]
|
||||
self.assertEqual((att["type"], att["difficulty"], att["tokens"], att["minutes"]), ("research", 1, 4321, 1.5))
|
||||
|
||||
def test_an_async_launch_stays_pending_until_the_hosts_notice_arrives(self):
|
||||
"""The host answers an async launch at once; the run is finished only when its notice comes as a prompt."""
|
||||
self.prompt()
|
||||
self.deleg_pre(tool_use_id="toolu_A")
|
||||
self.read_n(3)
|
||||
self.deleg_post({"isAsync": True, "status": "async_launched", "agentId": "agent9", "resolvedModel": "alpha-small-2"},
|
||||
tool_use_id="toolu_A")
|
||||
self.assertEqual(self.runs()[0]["status"], "pending") # still running: nothing to judge or ask for
|
||||
self.assertEqual(workers.unjudged_runs(), [])
|
||||
note = ("<task-notification>\n<task-id>agent9</task-id>\n<tool-use-id>toolu_A</tool-use-id>\n"
|
||||
"<status>completed</status>\n<result>done</result>\n<usage><subagent_tokens>7302</subagent_tokens>"
|
||||
"<tool_uses>1</tool_uses><duration_ms>1612</duration_ms></usage>\n</task-notification>")
|
||||
self.prompt(note)
|
||||
run = self.runs()[0]
|
||||
self.assertEqual((run["status"], run["tokens"], run["tokens_class"]), ("waiting", 7302, "measured"))
|
||||
# a notice is the host reporting, not a new request: it gives no new budget
|
||||
self.assertEqual(self.read_n(5), [False] * 3 + [True] * 2)
|
||||
|
||||
def test_the_gate_asks_for_the_judgements_once_per_set_of_runs(self):
|
||||
self.prompt()
|
||||
self.deleg_pre("t1")
|
||||
self.deleg_post({"status": "completed"}, "t1")
|
||||
out = self.stop()
|
||||
self.assertEqual(out.get("decision"), "block")
|
||||
self.assertIn("not judged yet", out["reason"])
|
||||
rid = self.runs()[0]["id"]
|
||||
self.assertIn(rid, out["reason"])
|
||||
self.assertIn("sisi delegate judge", out["reason"])
|
||||
self.assertEqual(self.stop(), {}) # the same set is not asked again
|
||||
self.deleg_pre("t2")
|
||||
self.deleg_post({"status": "completed"}, "t2")
|
||||
out = self.stop() # a new set is
|
||||
self.assertEqual(out.get("decision"), "block")
|
||||
for r in self.runs():
|
||||
self.sisi("delegate", "judge", r["id"], "--outcome", "accepted", "--check", "read", "--type", "research", "--difficulty", "1")
|
||||
self.assertEqual(self.stop(), {})
|
||||
|
||||
def test_another_sessions_runs_are_not_asked_for(self):
|
||||
workers.append_record({"kind": "run", "id": "other1", "ts": 1, "worker": "alpha-small", "session": "someone-else",
|
||||
"status": "waiting"})
|
||||
self.assertEqual(self.stop(), {})
|
||||
|
||||
|
||||
class RepeatFailureTests(MeterBase):
|
||||
"""Item 5 (R-15-4): the fourth identical failing command with no file changed is refused once."""
|
||||
|
||||
def fail(self, cmd="make build"):
|
||||
denied, reason, _ = self.pre("Bash", {"command": cmd})
|
||||
if not denied:
|
||||
self.post("Bash", {"command": cmd}, response=None, event="PostToolUseFailure", error="Exit code 2")
|
||||
return denied, reason
|
||||
|
||||
def test_the_fourth_identical_attempt_is_refused_once(self):
|
||||
self.prompt()
|
||||
self.assertEqual([self.fail()[0] for _ in range(3)], [False] * 3)
|
||||
denied, reason = self.fail("make build") # whitespace-normalised
|
||||
self.assertTrue(denied)
|
||||
self.assertIn("will not produce new information", reason)
|
||||
self.assertIn("failed 3 times", reason)
|
||||
self.assertLessEqual(len(reason.splitlines()), 12)
|
||||
self.assertFalse(self.fail()[0]) # once: the next is let through
|
||||
self.assertEqual([e["why"] for e in self.events("refusal")], ["repeat"])
|
||||
|
||||
def test_a_changed_file_between_failures_resets_the_count(self):
|
||||
self.prompt()
|
||||
self.fail(); self.fail()
|
||||
open(os.path.join(self.proj, "fix.txt"), "w").write("a fix")
|
||||
self.fail() # first failure of the new state
|
||||
self.assertFalse(self.fail()[0])
|
||||
self.assertFalse(self.fail()[0])
|
||||
self.assertTrue(self.fail()[0])
|
||||
|
||||
def test_a_success_in_between_resets_it(self):
|
||||
self.prompt()
|
||||
self.fail(); self.fail()
|
||||
self.post("Bash", {"command": "make build"}, response={"stdout": "ok", "exit_code": 0})
|
||||
self.fail(); self.fail()
|
||||
self.assertFalse(self.fail()[0])
|
||||
|
||||
def test_another_command_is_not_affected(self):
|
||||
self.prompt()
|
||||
for _ in range(3):
|
||||
self.fail()
|
||||
self.assertFalse(self.fail("make test")[0])
|
||||
|
||||
def test_a_new_turn_starts_the_count_again(self):
|
||||
self.prompt()
|
||||
for _ in range(3):
|
||||
self.fail()
|
||||
self.prompt("the build is still broken, please look at it again now")
|
||||
self.assertFalse(self.fail()[0])
|
||||
|
||||
def test_workers_are_not_stopped(self):
|
||||
self.prompt()
|
||||
for _ in range(3):
|
||||
self.fail()
|
||||
self.assertFalse(self.pre("Bash", {"command": "make build"}, agent_id="a1")[0])
|
||||
|
||||
|
||||
class RecordTests(MeterBase):
|
||||
"""Item 6: the unit record and `sisi status` show orchestration, each value classed measured."""
|
||||
|
||||
def start_unit(self):
|
||||
from sisi import contract as C
|
||||
self.assertEqual(self.sisi("contract", "init", "--goal", "make the thing").returncode, 0)
|
||||
p = os.path.join(self.proj, ".sisi", "contract.json")
|
||||
c = C.load(p)
|
||||
c["checks"] = [check("works", "test -f done.txt")]
|
||||
C.save(p, c)
|
||||
|
||||
def finish_and_close(self):
|
||||
open(os.path.join(self.proj, "done.txt"), "w").write("x")
|
||||
self.assertEqual(self.sisi("verify").returncode, 0)
|
||||
r = self.sisi("unit", "close")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
return json.load(open(os.path.join(self.proj, ".sisi", "units", "proj.json")))
|
||||
|
||||
def test_the_closed_unit_carries_the_orchestration_part(self):
|
||||
self.start_unit()
|
||||
self.prompt()
|
||||
self.read_n(8) # 6 counted, 2 refused
|
||||
self.sisi("unit", "direct", "the two config files hold 40 lines each, a brief costs more")
|
||||
self.read_n(2)
|
||||
self.pre("Agent", {"description": "d", "prompt": "p", "model": "alpha-small"}, tool_use_id="x1")
|
||||
rec = self.finish_and_close()
|
||||
o = rec["orchestration"]
|
||||
self.assertEqual(o["direct_calls"], {"value": 8, "class": "measured"})
|
||||
self.assertEqual(o["refusals"], {"value": 2, "class": "measured"})
|
||||
self.assertEqual(o["extensions"], {"value": 1, "class": "measured"})
|
||||
self.assertIn("40 lines", o["extension_reasons"]["value"][0])
|
||||
self.assertEqual(o["delegations_started"]["value"], 1)
|
||||
self.assertEqual((o["delegations_judged"]["value"], o["delegations_unjudged"]["value"]), (0, 1))
|
||||
self.assertEqual(o["delegated_share"], {"value": 0.111, "class": "measured"}) # 1 of 9 tool calls
|
||||
self.assertEqual(rec["scorecard"]["parallelism"]["orch_direct_calls"]["class"], "measured")
|
||||
out = self.sisi("status").stdout
|
||||
self.assertIn("orch_direct_calls 8 (measured)", out)
|
||||
self.assertIn("orch_extension_reasons", out)
|
||||
|
||||
def test_status_shows_it_for_the_unit_in_progress(self):
|
||||
self.start_unit()
|
||||
self.prompt()
|
||||
self.read_n(7)
|
||||
out = self.sisi("status").stdout
|
||||
self.assertIn("orchestration (measured): 6 direct calls", out)
|
||||
self.assertIn("1 refusals", out)
|
||||
|
||||
def test_a_unit_with_nothing_metered_says_unavailable_not_zero(self):
|
||||
self.start_unit()
|
||||
rec = self.finish_and_close()
|
||||
self.assertEqual(rec["orchestration"]["direct_calls"]["class"], "unavailable")
|
||||
|
||||
def test_rule_six_is_listed_as_enforced_and_names_the_mechanisms(self):
|
||||
out = self.sisi("rule").stdout
|
||||
line = next(l for l in out.splitlines() if "orchestrate" in l)
|
||||
self.assertIn("enforced", line)
|
||||
self.assertNotIn("not enforced", line)
|
||||
detail = self.sisi("rule", "orchestrate").stdout
|
||||
for phrase in ("direct tool calls", "sisi unit direct", "names no model", "judg"):
|
||||
self.assertIn(phrase, detail)
|
||||
Reference in new issue
Block a user