diff --git a/canon/orchestration-tools.json b/canon/orchestration-tools.json new file mode 100644 index 0000000..72f1a9f --- /dev/null +++ b/canon/orchestration-tools.json @@ -0,0 +1,56 @@ +{ + "_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.", + "claude-code": { + "refuse": "json-deny", + "evidence": "observed live (tools/live_orchestration_check.py)", + "delegation": { + "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"] + } + }, + "codex": { + "refuse": "exit-2", + "evidence": "from the host's hook documentation; not run live here", + "delegation": {}, + "exempt": { + "dialog": ["request_user_input"], + "planning": ["update_plan"], + "messaging": [] + } + }, + "gemini": { + "refuse": "exit-2", + "evidence": "from the host's hook documentation; not run live here", + "delegation": {}, + "exempt": { + "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"}}, + "exempt": { + "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"}}, + "exempt": { + "dialog": ["AskQuestion"], + "planning": ["TodoWrite"], + "messaging": [] + } + } +} diff --git a/config.default.json b/config.default.json index 784dd43..c62bd34 100644 --- a/config.default.json +++ b/config.default.json @@ -10,5 +10,11 @@ }, "retro": { "required": true + }, + "orchestrate": { + "enabled": true, + "direct_calls": 6, + "direct_chars": 30000, + "extension": 10 } } diff --git a/sisi/adapters.py b/sisi/adapters.py index 71d952b..048727f 100644 --- a/sisi/adapters.py +++ b/sisi/adapters.py @@ -532,8 +532,8 @@ class Codex(Adapter): "UserPromptSubmit": {"cmd": _cmd("prompt", "codex"), "timeout": 10, "sub": "prompt"}, "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"}, + "PreToolUse": {"cmd": _cmd("watch", "codex"), "timeout": 60, "sub": "watch"}, + "PostToolUse": {"cmd": _cmd("watch", "codex"), "timeout": 60, "sub": "watch"}, } def detect(self): diff --git a/sisi/brief.py b/sisi/brief.py index 6503e67..489d01a 100644 --- a/sisi/brief.py +++ b/sisi/brief.py @@ -171,3 +171,16 @@ def advice(text): out.append("It has numbered items but no commit per item: ask for a commit after each, with a " "\"done / next\" note, so an interruption loses at most one.") return out + + +def check(text): + """Plain lines about a brief that arrives by a host's own delegation tool: what it lacks of the + three required parts (outcome, acceptance, the files the worker may change), then the usual + advice. Always advice for the main agent; a brief is never refused here.""" + lines = [] + missing = missing_required(text) + if missing: + lines.append("the brief has no %s; a worker starts cold, so say %s (`sisi delegate brief` prints the template)" + % (" and no ".join(m.lower() for m in missing), "each of them")) + lines += advice(text) + return lines diff --git a/sisi/gate.py b/sisi/gate.py index f5dc46e..21d5684 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -487,12 +487,36 @@ def _send_back(stop, cwd, c, path, project, profile, info, reasons, miss, failin return stop.block(assure.fit(lines), uid, project) +def _orchestration_step(payload, action): + """Rule 6 at the end of a turn, main thread only: ask once for the judgement of this session's finished + delegations (a send-back like any other missing item); when the turn really ends, the meter starts over.""" + try: + from . import orchestration, workers + if workers.is_subagent_payload(payload): + return None + cwd = _cwd(payload) + sid = _session_key(payload, cwd) + if store.load_session(sid).get("subagent"): + return None + if action == "allow": + text = orchestration.judgement_sendback(payload, sid) + if text: + return "block", text + orchestration.end_turn(sid) + except Exception as e: # the meter must never break the gate + store.log_error("gate-orchestration", e) + return None + + def decide(payload): """The gate's answer: the contract decision, then — only on an otherwise-clean stop — the rule-5 question check, which sends the agent back at most once per final message.""" action, msg = _decide(payload) if action != "allow": return action, msg + j = _orchestration_step(payload, action) + if j: + return j try: from . import questions q = questions.sendback(payload) diff --git a/sisi/helptext.py b/sisi/helptext.py index 58568b2..8524dcb 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -6,7 +6,7 @@ command is printed by `sisi help COMMAND` and `sisi COMMAND --help`. LONG = { 'contract': ' sisi contract init [--goal TEXT] start a work unit: create .sisi/contract.json here (refuses while one is open)\n sisi contract check validate the contract (vacuous checks are refused)\n sisi contract waive [--check ID] ""\n record a deviation: a waived check does not pass; the unit closes as a deviation and the report must say so\n sisi contract trust | untrust allow / stop allowing this project\'s contract to run commands', - 'unit': ' sisi unit close [--abandon ""]\n archive the unit to .sisi/units/.json with its scorecard; --abandon records why it stopped\n sisi unit pause ""\n record a wait; the turn may end with no demands\n sisi unit show [ID] | list print the open unit or an archived record; list this project\'s units', + 'unit': ' sisi unit close [--abandon ""]\n archive the unit to .sisi/units/.json with its scorecard; --abandon records why it stopped\n sisi unit pause ""\n record a wait; the turn may end with no demands\n sisi unit direct ""\n say why doing this work yourself is cheaper than delegating it; a specific reason allows more direct calls this turn and is kept with the unit record\n sisi unit show [ID] | list print the open unit or an archived record; list this project\'s units', 'verify': ' sisi verify [--json] run the selected fast checks (five statuses; nothing unrun passes); exit 0 ok, 1 failure, 2 no contract, 3 untrusted\n sisi verify --deep [--background] run the deep (long) checks; --background detaches and returns at once\n sisi verify --all | --state run every check in both tiers; print only the deep-check state (with --json)', 'gate': " sisi gate [--tool NAME] end-of-turn hook (reads hook JSON on stdin; NAME selects the tool's hook shape)", 'tick': ' sisi tick [--tool NAME] session-start hook', @@ -58,7 +58,7 @@ GROUPS = ( )), ("For the agent at work", ( (("contract",), "contract init|check|waive|trust|untrust", "start, validate and bend the unit's contract"), - (("unit",), "unit close|pause|show|list", "close a unit with its scorecard, record a wait, look back"), + (("unit",), "unit close|pause|direct|show|list", "close a unit with its scorecard, record a wait, look back"), (("risk",), "risk [--json]", "the risk floor of the working-tree change; what it requires"), (("verify",), "verify [--deep|--all|--state] [--json]", "run the contract's checks; nothing unrun passes"), (("retro",), "retro [--finding F ...|--adopt ID]", "the unit's record; record a finding, with its cause and fix"), diff --git a/sisi/hookio.py b/sisi/hookio.py index 496243e..aae4cce 100644 --- a/sisi/hookio.py +++ b/sisi/hookio.py @@ -150,17 +150,18 @@ def gate_main(tool, args=()): def watch_main(tool, args=()): - """Before/after tool measurement for the other tools. Always exits 0 (fail open).""" + """Before/after tool measurement and the orchestration meter for the other tools. Fail open: any + error exits 0. A refusal is exit status 2 with the reason on standard error, where the tool's + before-tool event documents that contract (canon/orchestration-tools.json `refuse`).""" try: d = _payload(store.read_stdin()) if d is not None: - from . import watch + from . import orchestration, 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) + out = watch.run(norm, args, host=tool) + if out.get("deny") and orchestration.refuse_style(tool) == "exit-2": + sys.stderr.write(out["deny"] + "\n") + return 2 except Exception as e: store.log_error("watch-%s" % tool, e) return 0 @@ -218,6 +219,7 @@ def prompt_main(tool, args=()): if cwd and _os.path.isdir(cwd): _os.chdir(cwd) query = P.extract_prompt(norm) + P.meter_new_turn(norm.get("session_id"), _os.getcwd(), query) text = P.build_context(query, session=norm.get("session_id")) if query else "" out = _prompt_out(tool, text) except Exception as e: # fail open: a prompt hook must never fail a turn diff --git a/sisi/hookjson.py b/sisi/hookjson.py index 013bc2b..4ce01eb 100644 --- a/sisi/hookjson.py +++ b/sisi/hookjson.py @@ -409,11 +409,39 @@ def _add_nested_event(text, event, s): ours = _nested_ours(text, event, s["sub"]) if ours: want = _nested_entry(s) + text = _fit_group_matcher(text, event, s, ours[0]) + ours = _nested_ours(text, event, s["sub"]) + if not ours: # the entry shared a group with another hook and was moved out: add it in a group of its own + return _add_nested_event(text, event, s) return _update_fields(text, lambda t: _nested_locate(t, event, _nested_ours(t, event, s["sub"])[0])[3], want) _r, hooks = _hooks_node(text) return append_element(text, member(hooks, event)[1], _dump(_nested_group(s))) +def _group_matcher(g): + """(matcher text or None, its value node or None) of a group node.""" + for k, _kn, v in g.members: + if k == "matcher": + return (v.value if v.kind == "str" else None), v + return None, None + + +def _fit_group_matcher(text, event, s, loc): + """Make the group that holds our entry match what the spec wants: no matcher (every tool) when the spec has none, + else exactly its matcher. A group of ours alone is edited in place; one shared with another hook is left as it + is and our entry is moved out of it (the caller adds it back in a group of its own).""" + want = s.get("matcher") or None + _arr, g, hm, _e = _nested_locate(text, event, loc) + have, node = _group_matcher(g) + if (node is None and want is None) or have == want or (want is None and have in ("", "*")): + return text + if len(hm.items) == 1: + if want is None: + return remove_member(text, g, "matcher") + return replace_node(text, node, json.dumps(want)) if node is not None else insert_member(text, g, "matcher", json.dumps(want)) + return _nested_remove_at(text, event, loc) + + def add_nested(text, spec, created_version=None): """Merge nested hook groups into JSON text. spec: {event: {cmd, timeout, sub, matcher?, name?}}.""" text = _seed_version(text, created_version) diff --git a/sisi/lifecycle.py b/sisi/lifecycle.py index f3b05fa..c985129 100644 --- a/sisi/lifecycle.py +++ b/sisi/lifecycle.py @@ -534,11 +534,27 @@ def post_update(): except pdata.DataError as e: print("sisi update: %s" % e) return 1 + _rewire_existing() from . import cli print("doctor:") return cli.cmd_wiring("doctor") +def _rewire_existing(): + """An installation that exists is brought up to what this version registers (the tool hooks now run for + every tool, not only the shell). Idempotent and span-preserving; nothing happens without an installation.""" + try: + from . import wiring + if not os.path.exists(wiring._mpath()): + return + rc, notes = wiring.install() + for n in notes: + if "hook" in n or rc: + print(n) + except Exception as e: + print("sisi update: re-registering the hooks failed (%r); run `sisi install`" % e) + + # ---- export / import ------------------------------------------------------------------------------ def _tar_filter(ti): parts = ti.name.split("/") diff --git a/sisi/orchestration.py b/sisi/orchestration.py new file mode 100644 index 0000000..166b76d --- /dev/null +++ b/sisi/orchestration.py @@ -0,0 +1,668 @@ +"""Rule 6 as a mechanism: the direct-work meter, the delegation guard and the delegation record. + +The before-tool and after-tool hooks (sisi/watch.py) call in here for every tool. On a main thread: + + * every tool call that is not a delegation, a question dialog, a planning or to-do tool, a message or a + `sisi` command counts as direct work, with the characters of its result; past the budget + (`orchestrate.direct_calls` / `orchestrate.direct_chars`) the next counted call is refused with the + router's recommendation and the two ways on (delegate with a brief, or `sisi unit direct ""`); + * a delegation that names no model, or the session's own model, is refused the same way; one that is + allowed is written to the ledger as a pending run, completed when it returns, and its brief is checked; + * the fourth identical failing shell command with no file changed in between is refused once. + +Only main threads are metered: a session the host marks as a subagent, one whose first prompt opens with the +brief template's line, one started by `sisi delegate` (SISI_WORKER_RUN) is a worker and never refused. Nothing +is refused when no usable worker other than the session's own model exists. Host tool names live in +canon/orchestration-tools.json. Per-session state is in /sessions/.meter.json under a file lock; +every counted event is also appended to /orchestration.jsonl for the unit record. Every entry point +fails open (the caller wraps it): an error here must never hold up the user's tool. +""" +import fcntl, json, os, re, shlex, time, uuid + +from . import paths, store + +EVENTS = "orchestration.jsonl" +_HOSTS = {} + + +def cfg(): + c = store.config().get("orchestrate") or {} + + def num(key, default): + try: + return max(0, int(c.get(key, default))) + except (TypeError, ValueError): + return default + return {"enabled": bool(c.get("enabled", True)), "direct_calls": max(1, num("direct_calls", 6)), + "direct_chars": max(1, num("direct_chars", 30000)), "extension": max(1, num("extension", 10))} + + +def hosts(): + if not _HOSTS: + 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 _HOSTS + + +def host_data(host): + return hosts().get(host or "claude-code") or {} + + +def refuse_style(host): + return host_data(host).get("refuse") + + +# ---------------------------------------------------------------- classifying a call + +def _exempt_names(hd): + out = set() + for names in (hd.get("exempt") or {}).values(): + out.update(str(n).lower() for n in names or []) + return out + + +def _dig(obj, dotted): + for k in str(dotted or "").split("."): + if not isinstance(obj, dict): + return None + obj = obj.get(k) + return obj + + +def delegation_spec(hd, tool): + for name, spec in (hd.get("delegation") or {}).items(): + if str(name).lower() == str(tool or "").lower(): + return spec if isinstance(spec, dict) else {} + return None + + +def _segments(cmd): + """The commands of a shell line, split at the operators outside quotes; None when it cannot be split.""" + try: + lex = shlex.shlex(cmd, posix=True, punctuation_chars=True) + lex.whitespace_split = True + toks = list(lex) + except ValueError: + return None + segs, cur = [], [] + for t in toks: + if t and all(ch in "();&|<>" for ch in t) and not t.startswith(("<", ">")): + if cur: + segs.append(cur) + cur = [] + else: + cur.append(t) + if cur: + segs.append(cur) + return segs + + +def runs_sisi(cmd): + """True when every command in the shell line is an invocation of `sisi` itself.""" + segs = _segments(cmd or "") + if not segs: + return False + for seg in segs: + toks = [t for t in seg if not re.match(r"^[A-Za-z_]\w*=", t)] + if not toks: + return False + first = toks[0] + if re.match(r"^python[\d.]*$", os.path.basename(first)) and len(toks) > 1: + first = toks[1] + if os.path.basename(first) != "sisi": + return False + return True + + +def classify(host, tool, inp, cmd): + """"delegation", "exempt" or "direct".""" + hd = host_data(host) + if delegation_spec(hd, tool) is not None: + return "delegation" + if str(tool or "").lower() in _exempt_names(hd): + return "exempt" + from . import watch + if watch.is_shell(tool, cmd) and runs_sisi(cmd): + return "exempt" + return "direct" + + +# ---------------------------------------------------------------- the per-session meter + +def meter_path(sid): + return os.path.join(paths.state(), "sessions", store.safe_id(sid) + ".meter.json") + + +class Meter: + """The session's meter under an exclusive lock; saved on a clean exit.""" + + def __init__(self, sid): + self.sid = sid + self.m = None + + def __enter__(self): + p = meter_path(self.sid) + os.makedirs(os.path.dirname(p), exist_ok=True) + self.f = open(p, "a+", encoding="utf-8") + end = time.time() + 2.0 + while True: + try: + fcntl.flock(self.f, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except OSError: + if time.time() > end: + self.f.close() + raise + time.sleep(0.005) + self.f.seek(0) + try: + m = json.loads(self.f.read() or "{}") + except ValueError: + m = {} + self.m = m if isinstance(m, dict) else {} + self.m.setdefault("sid", self.sid) + for k, v in (("turn", 0), ("calls", 0), ("chars", 0), ("ext", 0), ("refusals", 0), ("prompts", 0)): + self.m.setdefault(k, v) + for k in ("fails", "pending"): + self.m.setdefault(k, {}) + for k in ("ext_log", "judge_asked"): + self.m.setdefault(k, []) + return self.m + + def __exit__(self, et, ev, tb): + try: + if et is None: + self.m["last_ts"] = time.time() + self.f.seek(0) + self.f.truncate() + self.f.write(json.dumps(self.m)) + self.f.flush() + finally: + try: + fcntl.flock(self.f, fcntl.LOCK_UN) + finally: + self.f.close() + return False + + +def _event(m, sid, ev, **kw): + rec = {"ts": round(time.time(), 3), "session": sid, "project": m.get("project"), "ev": ev} + rec.update(kw) + store.append(EVENTS, rec) + + +def _project(m, cwd): + if m.get("cwd") != cwd or not m.get("project"): + from . import gitutil + m["cwd"] = cwd + m["project"] = gitutil.root(cwd) or cwd + return m["project"] + + +def brief_line(): + from . import brief + return brief.template().splitlines()[0].strip().lower() + + +def new_turn(sid, cwd=None, prompt=None): + """A prompt reached the session: the meter for the turn starts again. The first prompt of a session + that opens with the brief template's line makes it a worker for good.""" + with Meter(sid) as m: + m["turn"] += 1 + m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False) + m["prompts"] += 1 + if cwd: + _project(m, cwd) + if m["prompts"] == 1 and isinstance(prompt, str) \ + and prompt.lstrip()[:200].lower().startswith(brief_line()): + m["worker"] = True + return m + + +def end_turn(sid): + """The turn ended (the gate let the agent finish): counts start again at the next call.""" + with Meter(sid) as m: + m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False) + + +# ---------------------------------------------------------------- messages + +def _fmt_pick(kind, difficulty, cwd, own_model): + from . import workers + try: + worker, mech, _n = workers.recommend(kind, difficulty, cwd, own_model) + except Exception as e: + store.log_error("orchestration-route", e) + worker, mech = None, None + return worker, mech + + +def _picks(cwd, own_model): + return (_fmt_pick("research", 1, cwd, own_model), _fmt_pick("implementation", 2, cwd, own_model)) + + +def _pick_line(label, pick): + worker, mech = pick + return " %s: %s (%s)" % (label, worker, mech) if worker else " %s: no worker is usable now" % label + + +def refusal_text(m, c, picks, why="budget", detail=""): + """At most 12 lines.""" + limit = c["direct_calls"] + m["ext"] * c["extension"] + read, build = picks + if why == "budget": + head = ("sisi: %d direct tool calls this turn (limit %d, %d characters of results). Legwork belongs to a " + "less expensive worker (rule 6)." % (m["calls"], limit, m["chars"])) + else: + head = "sisi: %s. Legwork belongs to a less expensive worker (rule 6)." % detail + lines = [head, "Router for this project:", _pick_line("reading and searching", read), + _pick_line("building", build), "Two ways on:", + " 1. Delegate the rest: `sisi delegate brief` prints the brief to fill in; start the worker as above%s." + % (", naming its model" if why != "budget" else ""), + " 2. Record why doing it directly is cheaper: `sisi unit direct \"\"`%s." + % (" (allows %d more calls this turn)" % c["extension"] if why == "budget" + else " (also allows this same-model delegation)"), + "This call was not run."] + return "\n".join(lines) + + +def repeat_text(key, n): + return ("sisi: `%s` has failed %d times in a row and no file has changed since, so running it again will not " + "produce new information (rule 5). Diagnose why it fails, or change the approach; this one repeat is " + "refused once." % (key[:80], n)) + + +# ---------------------------------------------------------------- hook entry points + +_RESP_KEYS = ("tool_response", "toolResponse", "tool_result", "toolResult", "tool_output", "result", "output", "error") + + +def _chars(payload): + n = 0 + for k in _RESP_KEYS: + if k in payload and payload[k] is not None: + stack = [payload[k]] + while stack: + x = stack.pop() + if isinstance(x, str): + n += len(x) + elif isinstance(x, dict): + stack.extend(x.values()) + elif isinstance(x, list): + stack.extend(x) + break + return n + + +def _failed(payload, ev): + if "failure" in str(ev or "").lower(): + return True + resp = None + for k in _RESP_KEYS: + if isinstance(payload.get(k), dict): + resp = payload[k] + break + if resp: + for k in ("exit_code", "exitCode", "returncode", "returnCode", "code"): + v = resp.get(k) + if isinstance(v, int) and not isinstance(v, bool): + return v != 0 + return False + + +def _norm(cmd): + return " ".join((cmd or "").split()) + + +def _is_worker(payload, sess, m): + from . import workers + return bool(m.get("worker") or sess.get("subagent") or workers.is_subagent_payload(payload)) + + +def _own_model(payload, sess): + v = payload.get("model") + return v if isinstance(v, str) and v else sess.get("model") + + +def before(payload, host=None): + """{"deny": text} to refuse the call, {"context": text} for advice, {} otherwise.""" + c = cfg() + if not c["enabled"]: + return {} + from . import watch, workers + tool, cmd, _ev, cwd, sid = watch.extract(payload) + host = host or store.tool() or "claude-code" + hd = host_data(host) + if not hd or workers.is_subagent_payload(payload): + return {} + sid = sid or "cwd-" + cwd + inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {}) + kind = classify(host, tool, inp, cmd) + shell = watch.is_shell(tool, cmd) + if kind == "exempt" and not shell: + return {} + sess = store.load_session(sid) + with Meter(sid) as m: + if _is_worker(payload, sess, m): + return {} + project = _project(m, cwd) + m["last_tool"] = tool + if shell: + key = _norm(cmd) + e = m["fails"].get(key) + if e and e.get("n", 0) >= 3 and not e.get("refused"): + from . import gitutil + try: + fp = gitutil.fingerprint(cwd) + except Exception: + fp = None + if fp == e.get("fp"): + e["refused"] = True + m["refusals"] += 1 + _event(m, sid, "refusal", why="repeat", tool=tool) + return {"deny": repeat_text(key, e["n"])} + m["fails"].pop(key, None) + if kind == "exempt": + return {} + if kind == "delegation": + return _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd) + limit = c["direct_calls"] + m["ext"] * c["extension"] + chars_limit = c["direct_chars"] * limit / float(c["direct_calls"]) + if m["calls"] >= limit or m["chars"] >= chars_limit: + own = _own_model(payload, sess) + picks = _picks(project, own) + if not any(p[0] for p in picks): + m["calls"] += 1 + _event(m, sid, "unrefused", why="no usable worker", tool=tool) + _event(m, sid, "call", tool=tool) + return {} + m["refusals"] += 1 + _event(m, sid, "refusal", why="budget", tool=tool, calls=m["calls"], chars=m["chars"]) + return {"deny": refusal_text(m, c, picks)} + m["calls"] += 1 + _event(m, sid, "call", tool=tool) + return {} + + +def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd): + spec = delegation_spec(hd, tool) or {} + model = _dig(inp, spec.get("model", "model")) + model = model.strip() if isinstance(model, str) else "" + text = _dig(inp, spec.get("brief", "prompt")) + own = _own_model(payload, sess) + problem = None + if not model: + problem = "this delegation names no model, so the subagent would run on this session's own model%s" \ + % (" (%s)" % own if own else "") + elif own and workers_same(model, own): + problem = "this delegation names this session's own model (%s)" % own + if problem and not m.get("same_model_ok"): + picks = _picks(m.get("project") or cwd, own) + if any(p[0] for p in picks): + m["refusals"] += 1 + _event(m, sid, "refusal", why="delegation-model", tool=tool) + return {"deny": refusal_text(m, c, picks, why="delegation", detail=problem)} + from . import brief, workers + run_id = uuid.uuid4().hex[:8] + now = time.time() + worker = model or own or "(inherited)" + try: + workers.append_record({"kind": "run", "id": run_id, "ts": round(now), "type": None, "difficulty": None, + "worker": worker, "model": model or own, "tool": workers.host_tool(), "cwd": m.get("project") or cwd, + "session": sid, "started": round(now), "ended": None, "minutes": None, + "status": "pending", "origin": "hook", "tokens": None, "tokens_class": "unavailable"}) + except OSError as e: + store.log_error("orchestration-run", e) + key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last" + m["pending"][key] = {"run": run_id, "t0": now} + _event(m, sid, "delegation", run=run_id, worker=worker) + lines = ["sisi: delegation recorded as run %s. When it returns, judge it: `sisi delegate judge %s --outcome " + "accepted|rejected --check read|tests|diffstat|review|none --type KIND --difficulty 1|2|3`." + % (run_id, run_id)] + if isinstance(text, str): + lines += ["sisi brief advice: " + a for a in brief.check(text)] + return {"context": "\n".join(lines)} + + +def workers_same(a, b): + from . import workers + return workers.same_model(a, b) + + +def after(payload, host=None): + """Record what a call returned: result characters, a delegation's end, a failing shell command. + {"context": text} may carry a line for the agent.""" + c = cfg() + if not c["enabled"]: + return {} + from . import watch, workers + tool, cmd, ev, cwd, sid = watch.extract(payload) + host = host or store.tool() or "claude-code" + hd = host_data(host) + if not hd or workers.is_subagent_payload(payload): + return {} + sid = sid or "cwd-" + cwd + inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {}) + kind = classify(host, tool, inp, cmd) + shell = watch.is_shell(tool, cmd) + if kind == "exempt" and not shell: + return {} + sess = store.load_session(sid) + out = {} + with Meter(sid) as m: + if _is_worker(payload, sess, m): + return {} + _project(m, cwd) + if kind == "delegation": + return _after_delegation(payload, ev, sid, m) + if shell: + key = _norm(cmd) + if _failed(payload, ev): + from . import gitutil + try: + fp = gitutil.fingerprint(cwd) + except Exception: + fp = None + e = m["fails"].get(key) + if e and e.get("fp") == fp: + e["n"] = e.get("n", 0) + 1 + else: + m["fails"][key] = {"n": 1, "fp": fp, "refused": False} + else: + m["fails"].pop(key, None) + if kind == "direct": + n = _chars(payload) + m["chars"] += n + _event(m, sid, "chars", tool=tool, chars=n) + return out + + +def _after_delegation(payload, ev, sid, m): + from . import workers + key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last" + ent = m["pending"].pop(key, None) + if ent is None and m["pending"]: + ent = m["pending"].pop(sorted(m["pending"], key=lambda k: m["pending"][k]["t0"])[-1]) + if ent is None: + return {} + now = time.time() + resp = next((payload[k] for k in _RESP_KEYS if payload.get(k) is not None), None) + tokens, _cost = workers.extract_usage(json.dumps(resp) if resp is not None else "") + minutes = round((now - ent["t0"]) / 60.0, 2) + if isinstance(resp, dict): + ms = resp.get("totalDurationMs", resp.get("total_duration_ms")) + if isinstance(ms, (int, float)) and not isinstance(ms, bool): + minutes = round(ms / 60000.0, 2) + failed = "failure" in str(ev or "").lower() + try: + workers.append_record({"kind": "run-end", "run_id": ent["run"], "ts": round(now), "ended": round(now), + "minutes": minutes, "tokens": tokens, + "tokens_class": "measured" if tokens is not None else "unavailable", + "status": "failed" if failed else "waiting"}) + except OSError as e: + store.log_error("orchestration-run-end", e) + return {"context": "sisi: delegation run %s finished (%s min). Judge it: `sisi delegate judge %s --outcome " + "accepted|rejected --check read|tests|diffstat|review|none --type KIND --difficulty 1|2|3`." + % (ent["run"], minutes, ent["run"])} + + +# ---------------------------------------------------------------- `sisi unit direct` + +_FILLER = set("easier easy quick quicker quickly faster fast simpler simple convenient convenience myself directly " + "direct itself rather instead because just efficient efficiently less effort overhead trivial small " + "short like want prefer simply".split()) + + +def reason_is_generic(text): + """The existing generic-text check, plus the filler a lazy reason is made of: it must name something + specific (a number, a file, a particular fact), not only that direct work is easier or faster.""" + from . import learning as L + if L.is_generic(text): + return True + toks = re.findall(r"[a-z0-9_]+", (text or "").lower()) + if any(any(ch.isdigit() for ch in t) for t in toks): + return False + rest = [t for t in toks if len(t) >= 2 and t not in L.STOP and t not in L.GENERIC_WORDS and t not in _FILLER] + return len(rest) < 2 + + +def find_session(cwd): + """The session a `sisi unit direct` belongs to: SISI_SESSION_ID, else the most recently active meter + in this project, else the most recent one of all (within the last ten minutes).""" + sid = os.environ.get("SISI_SESSION_ID") + if sid: + return sid + d = os.path.join(paths.state(), "sessions") + best, any_best = None, None + from . import gitutil + project = gitutil.root(cwd) or cwd + try: + names = [n for n in os.listdir(d) if n.endswith(".meter.json")] + except OSError: + return None + for n in names: + try: + with open(os.path.join(d, n), encoding="utf-8") as f: + mm = json.load(f) + except (OSError, ValueError): + continue + ts = float(mm.get("last_ts") or 0) + sid = mm.get("sid") or n[:-len(".meter.json")] + if mm.get("project") == project and (best is None or ts > best[0]): + best = (ts, sid) + if time.time() - ts < 600 and (any_best is None or ts > any_best[0]): + any_best = (ts, sid) + return (best or any_best or (0, None))[1] + + +def cmd_direct(args, cwd=None): + """`sisi unit direct ""`: record why doing this directly is cheaper; grants an extension.""" + reason = " ".join(args).strip() + if not reason: + print('usage: sisi unit direct ""') + return 1 + if reason_is_generic(reason): + print("sisi: that reason is generic: say what makes direct work cheaper here (which file, how many lines, " + "what a brief would have to carry), not only that it is easier or faster.") + return 1 + cwd = cwd or os.getcwd() + sid = find_session(cwd) + if not sid: + print("sisi: no session is being metered here; nothing to extend (no limit applies).") + return 0 + c = cfg() + with Meter(sid) as m: + if any(e.get("reason") == reason for e in m["ext_log"]): + print("sisi: that same reason was already recorded this turn; say what is different now, or delegate.") + return 1 + m["ext"] += 1 + m["same_model_ok"] = True + m["ext_log"].append({"reason": reason, "ts": store.now(), "calls": c["extension"]}) + _event(m, sid, "extension", reason=reason[:300], calls=c["extension"]) + limit = c["direct_calls"] + m["ext"] * c["extension"] + print("recorded: %d more direct calls allowed this turn (limit now %d, extension %d); the reason is kept with " + "the unit record." % (c["extension"], limit, m["ext"])) + return 0 + + +# ---------------------------------------------------------------- the gate asks for judgements + +def judgement_sendback(payload, sid): + """Text asking for the judgements of this session's finished, unjudged delegations, once per set of + runs; None when there is nothing to ask.""" + from . import workers + runs = [r for r in workers.unjudged_runs() if r.get("session") == sid] + if not runs: + return None + ids = sorted(r["id"] for r in runs) + with Meter(sid) as m: + if m["judge_asked"] == ids: + return None + m["judge_asked"] = ids + lines = ["sisi: %d delegation(s) from this session finished and are not judged yet (rule 6: the record is the " + "routing policy):" % len(runs)] + for r in runs[:6]: + lines.append("- %s: %s%s" % (r["id"], r.get("worker"), (", %s min" % r["minutes"]) if r.get("minutes") is not None else "")) + lines.append("Judge each: `sisi delegate judge ID --outcome accepted|rejected --check read|tests|diffstat|review|none " + "--type KIND --difficulty 1|2|3`, then finish. (Asked once for this set.)") + return "\n".join(lines) + + +# ---------------------------------------------------------------- the unit record + +def _inside(project, root): + root = str(root or "").rstrip(os.sep) + return bool(project) and (project == root or str(project).startswith(root + os.sep)) + + +def summary(project, t0, t1): + """Facts about orchestration for one project between two epochs, or None when nothing was metered.""" + from . import workers + evs = [e for e in store.read(EVENTS) if isinstance(e, dict) and _inside(e.get("project"), project) + and isinstance(e.get("ts"), (int, float)) and (t0 is None or e["ts"] >= t0) and e["ts"] <= t1] + if not evs: + return None + calls = sum(1 for e in evs if e["ev"] == "call") + chars = sum(int(e.get("chars") or 0) for e in evs if e["ev"] == "chars") + refusals = [e for e in evs if e["ev"] == "refusal"] + exts = [e for e in evs if e["ev"] == "extension"] + runs = [e["run"] for e in evs if e["ev"] == "delegation"] + records = workers.read_records() + judged = {r.get("run_id") for r in records if r.get("kind") == "attempt"} + done = sum(1 for r in runs if r in judged) + total = calls + len(runs) + return {"direct_calls": calls, "direct_chars": chars, "refusals": len(refusals), + "extensions": len(exts), "extension_reasons": [e.get("reason") for e in exts], + "unrefused": sum(1 for e in evs if e["ev"] == "unrefused"), + "delegations_started": len(runs), "delegations_judged": done, + "delegations_unjudged": len(runs) - done, + "delegated_share": round(len(runs) / float(total), 3) if total else None} + + +def telemetry(project, t0, t1): + """The orchestration part of a unit's telemetry, each value with its class.""" + from .scorecard import val, unavailable + s = summary(project, t0, t1) + keys = ("direct_calls", "direct_chars", "refusals", "extensions", "extension_reasons", "delegations_started", + "delegations_judged", "delegations_unjudged", "delegated_share") + if s is None: + return {k: unavailable() for k in keys} + return {k: (val(s[k], "measured") if s[k] is not None else unavailable()) for k in keys} + + +def status_line(project, t0, t1): + s = summary(project, t0, t1) + if s is None: + return None + share = ("%d%%" % round(s["delegated_share"] * 100)) if s["delegated_share"] is not None else "n/a" + line = ("orchestration (measured): %d direct calls, %d characters read, %d refusals, %d extension(s), " + "%d delegation(s) started (%d judged, %d unjudged), %s of tool calls delegated" + % (s["direct_calls"], s["direct_chars"], s["refusals"], s["extensions"], s["delegations_started"], + s["delegations_judged"], s["delegations_unjudged"], share)) + if s["extension_reasons"]: + line += "; extension reasons: " + " | ".join(str(r) for r in s["extension_reasons"]) + return line diff --git a/sisi/prompt.py b/sisi/prompt.py index 89d9b19..ab97914 100644 --- a/sisi/prompt.py +++ b/sisi/prompt.py @@ -112,6 +112,17 @@ def build_context(query, session=None): return text +def meter_new_turn(session, cwd, query): + """Every prompt the session receives starts the orchestration meter's turn again (and the first one may + show the session is a worker). Never raises.""" + try: + if session and query: + from . import orchestration + orchestration.new_turn(session, cwd, query) + except Exception as e: + store.log_error("prompt-meter", e) + + def extract_prompt(payload): """The human's request text from a hook payload, across the tools' documented field names.""" if not isinstance(payload, dict): @@ -150,6 +161,7 @@ def main(args=()): os.chdir(cwd) if not query: return 0 + meter_new_turn(session, os.getcwd(), query) text = build_context(query, session=session) if not text: return 0 diff --git a/sisi/scorecard.py b/sisi/scorecard.py index 82a4bee..ac307e7 100644 --- a/sisi/scorecard.py +++ b/sisi/scorecard.py @@ -211,6 +211,8 @@ def build_scorecard(c, results, telemetry, delivery_status): "overlapped_delegations": T("overlapped_delegations"), "worker_minutes": T("worker_minutes"), "wall_time_s": T("time_to_validated_completion_s"), + # who did the work: the main thread's own calls against delegated ones (sisi/orchestration.py) + **{"orch_" + k: v for k, v in (tel.get("orchestration") or {}).items()}, }, "human_experience": { "human_messages": T("human_messages"), @@ -372,6 +374,12 @@ def open_units(cwd=None): started, basis = U.start_of(c, p) row = {"id": c["id"], "status": c.get("status", "open"), "age": _age(started), "goal": c.get("goal") or "", "age_basis": basis} + try: + from . import orchestration + t0 = harvest.epoch(started) if isinstance(started, str) else None + row["orchestration"] = orchestration.status_line(project, t0, time.time()) + except Exception as e: + store.log_error("status-orchestration", e) if row["status"] == "paused": pz = next((x for x in reversed(c.get("pauses") or []) if isinstance(x, dict) and not x.get("until")), {}) row["waiting_for"], row["paused_for"] = pz.get("what"), _age(pz.get("since")) @@ -407,6 +415,8 @@ def format_open(rows): lines.append("paused %-24s age %s%s waiting for: %s (for %s)" % (r["id"], r["age"], _basis_note(r), r.get("waiting_for") or "?", r.get("paused_for"))) else: lines.append("open %-24s age %s%s %s" % (r["id"], r["age"], _basis_note(r), r["goal"][:80])) + if r.get("orchestration"): + lines.append(" " + r["orchestration"]) if r.get("lowered"): lines.append(" lowered: " + r["lowered"]) if r.get("unverified"): diff --git a/sisi/store.py b/sisi/store.py index 21f7afe..72f5acb 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -157,6 +157,7 @@ def stamp(extra): DEFAULTS = {"gate": {"enabled": True, "budget_s": 120, "max_blocks": 3}, "verify": {"default_timeout_s": 60, "fast_limit_s": 60}, "retro": {"required": True}, + "orchestrate": {"enabled": True, "direct_calls": 6, "direct_chars": 30000, "extension": 10}, "scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000, "prune_budget_s": 0.25}} diff --git a/sisi/unit.py b/sisi/unit.py index affbe1e..d760c3b 100644 --- a/sisi/unit.py +++ b/sisi/unit.py @@ -319,6 +319,13 @@ def build_telemetry(c, project, results, t0, t1, t0_basis="measured"): tel["time_in_delegations_s"] = val(0, "measured") tel["overlapped_delegations"] = val(0, "measured") + try: + from . import orchestration + tel["orchestration"] = orchestration.telemetry(project, t0, t1) + except Exception as e: # the part is measurement; never lose the record for it + store.log_error("unit-orchestration", e) + tel["orchestration"] = {} + changed = _changed_artifacts(c, project) tel["files_changed"] = val(len(changed["files"]), "measured") if changed else unavailable() tel["lines_changed"] = val(changed["lines"], "measured") if changed else unavailable() @@ -503,6 +510,7 @@ def build_record(c, project, delivery_status, ended_epoch, abandon_reason=None, "approach": c.get("approach"), "plan": c.get("plan") or [], "workers": delegation_rows, + "orchestration": tel.get("orchestration") or {}, "models": models, "budgets": c.get("budgets"), "started": started, "started_basis": basis, "ended": ended, "closed_at": ended, "telemetry": tel, "start_commit": c.get("base_head"), @@ -781,6 +789,9 @@ def cmd_unit(args, cwd=None, out=print): C.save(p, c) out("unit %s paused: %s" % (c.get("id"), what)) return 0 + if sub == "direct": + from . import orchestration + return orchestration.cmd_direct(args[1:], cwd) if sub == "show": uid = args[1] if len(args) > 1 else None if uid is None: @@ -827,5 +838,5 @@ def cmd_unit(args, cwd=None, out=print): if c is None and not rows: out("no units in this project yet") return 0 - out("usage: sisi unit close [--abandon \"\"] | pause \"\" | show [ID] | list") + out("usage: sisi unit close [--abandon \"\"] | pause \"\" | direct \"\" | show [ID] | list") return 1 diff --git a/sisi/watch.py b/sisi/watch.py index 5634941..04cd89a 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -18,7 +18,7 @@ from . import gitutil, paths, store BEFORE_EVENTS = {"PreToolUse", "BeforeTool", "preToolUse", "beforeShellExecution", "tool_call"} AFTER_EVENTS = {"PostToolUse", "AfterTool", "postToolUse", "afterShellExecution", - "postToolUseFailure", "tool_result"} + "PostToolUseFailure", "postToolUseFailure", "tool_result"} SHELL_TOOLS = ("bash", "shell", "command", "terminal", "exec") @@ -213,23 +213,69 @@ def commit_notice(payload): "`sisi verify` first (a notice, not a block)." % c.get("id")) +def meter(payload, after_call, host=None): + """The orchestration meter's answer for one tool call ({"deny": text} / {"context": text} / {}); never + raises: an error inside the meter lets the call through.""" + try: + from . import orchestration + return (orchestration.after if after_call else orchestration.before)(payload, host) + except Exception as e: + store.log_error("watch-meter", e) + return {} + + +def run(payload, args=(), host=None): + """One before/after hook call for any tool: the meter first (a refusal skips the rest: the command will + not run), then the shell measurement. Returns {"deny": text} or {"context": text} or {}.""" + _tool, _cmd, ev, _cwd, _sid = extract(payload) + out = {} + if "--before" in args or ev in BEFORE_EVENTS: + out = meter(payload, False, host) + if out.get("deny"): + return out + try: + before(payload) + except Exception as e: + store.log_error("watch", e) + try: + line = commit_notice(payload) + if line: + out = dict(out, notice=line) + except Exception as e: + store.log_error("watch-commit-notice", e) + elif "--after" in args or ev in AFTER_EVENTS: + out = meter(payload, True, host) + try: + after(payload) + except Exception as e: + store.log_error("watch", e) + return out + + +def render_claude(out, event): + """The Claude Code hook output for a run() result, or None.""" + if out.get("deny"): + return json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", + "permissionDecisionReason": out["deny"]}}) + ctx = "\n".join(x for x in (out.get("context"), out.get("notice")) if x) + if not ctx: + return None + d = {"hookSpecificOutput": {"hookEventName": event, "additionalContext": ctx}} + if out.get("notice"): + d["systemMessage"] = out["notice"] + return json.dumps(d) + + 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) - try: - line = commit_notice(payload) - if line: - import sys - sys.stdout.write(json.dumps({"systemMessage": line, "hookSpecificOutput": { - "hookEventName": "PreToolUse", "additionalContext": line}}) + "\n") - except Exception as e: - store.log_error("watch-commit-notice", e) - elif "--after" in args or ev in AFTER_EVENTS: - after(payload) + out = run(payload, args) + text = render_claude(out, "PreToolUse" if ("--before" in args or ev in BEFORE_EVENTS) else "PostToolUse") + if text: + import sys + sys.stdout.write(text + "\n") 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 0436521..4d97bd7 100644 --- a/sisi/wiring.py +++ b/sisi/wiring.py @@ -229,7 +229,7 @@ def _claude_md_wired(data): # ---- settings.json --------------------------------------------------------- -HOOK_MATCHERS = {"PreToolUse": "Bash", "PostToolUse": "Bash"} +HOOK_MATCHERS = {} # no matcher: the tool hooks run for every tool (the orchestration meter counts all of them) def hook_cmds(): @@ -240,7 +240,8 @@ def hook_cmds(): "Stop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code"), gate_to), "SubagentStop": (hookjson.fail_open_command(paths.launcher(), "gate", "claude-code", True), 30), "PreToolUse": (watch, 60), - "PostToolUse": (watch, 60)} + "PostToolUse": (watch, 60), + "PostToolUseFailure": (watch, 60)} def _claude_spec(): @@ -326,11 +327,15 @@ def _hooks_wired(obj): out = {} for ev, sub, name in (("SessionStart", "tick", "tick"), ("UserPromptSubmit", "prompt", "prompt"), ("Stop", "gate", "gate"), ("SubagentStop", "gate", "subagent"), - ("PreToolUse", "watch", "pre"), ("PostToolUse", "watch", "post")): + ("PreToolUse", "watch", "pre"), ("PostToolUse", "watch", "post"), + ("PostToolUseFailure", "watch", "postfail")): groups = hooks.get(ev) if isinstance(hooks, dict) else None sub, key = sub, name out[key] = False for g in groups if isinstance(groups, list) else []: + if ev in ("PreToolUse", "PostToolUse", "PostToolUseFailure") and isinstance(g, dict) \ + and g.get("matcher") not in (None, "", "*"): + continue # a hook limited to some tools (the shell only, in an older install) does not meter the rest for h in g.get("hooks", []) if isinstance(g, dict) and isinstance(g.get("hooks"), list) else []: inv = hookjson.sisi_invocation(h.get("command")) if isinstance(h, dict) else None if _is_ours(h, sub) and inv and inv[0] == paths.launcher(): @@ -561,7 +566,7 @@ def uninstall(): try: text = data.decode("utf-8") subs = {"SessionStart": "tick", "UserPromptSubmit": "prompt", "Stop": "gate", "SubagentStop": "gate", - "PreToolUse": "watch", "PostToolUse": "watch"} + "PreToolUse": "watch", "PostToolUse": "watch", "PostToolUseFailure": "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) @@ -617,7 +622,8 @@ def doctor(): missing = [n for n, ok in (("import line", _claude_md_wired(cm)), ("tick hook", hw["tick"]), ("prompt hook", hw.get("prompt", False)), ("gate hook", hw["gate"]), ("subagent hook", hw["subagent"]), - ("watch-before hook", hw["pre"]), ("watch-after hook", hw["post"])) if not ok] + ("watch-before hook (all tools)", hw["pre"]), ("watch-after hook (all tools)", hw["post"]), + ("watch-failure hook", hw.get("postfail", False))) if not ok] 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", @@ -708,7 +714,8 @@ def doctor_claude(): missing = [n for n, ok in (("import line", _claude_md_wired(cm)), ("tick hook", hw["tick"]), ("prompt hook", hw.get("prompt", False)), ("gate hook", hw["gate"]), ("subagent hook", hw["subagent"]), - ("watch-before hook", hw["pre"]), ("watch-after hook", hw["post"])) if not ok] + ("watch-before hook (all tools)", hw["pre"]), ("watch-after hook (all tools)", hw["post"]), + ("watch-failure hook", hw.get("postfail", False))) if not ok] return ", ".join(missing) diff --git a/sisi/workers.py b/sisi/workers.py index 694d752..03df8b7 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -480,10 +480,31 @@ def import_ledger(src, now=None): return before, before + added, added +def merged_runs(records=None): + """The ledger's runs, each with the later `run-end` fact for its id applied (a delegation the + host started: written when it begins, completed when it returns). A run still in flight keeps + status "pending".""" + records = read_records() if records is None else records + ends = {} + for r in records: + if r.get("kind") == "run-end" and r.get("run_id"): + ends[r["run_id"]] = r + out = [] + for r in records: + if r.get("kind") != "run": + continue + end = ends.get(r.get("id")) + if end is not None: + r = dict(r, **{k: v for k, v in end.items() if k not in ("kind", "run_id", "ts") and v is not None}) + out.append(r) + return out + + def unjudged_runs(records=None): + """Finished runs with no judgement. A run still in flight (status "pending") is not waiting yet.""" records = read_records() if records is None else records judged = {r.get("run_id") for r in records if r.get("kind") == "attempt" and r.get("run_id")} - return [r for r in records if r.get("kind") == "run" and r.get("id") not in judged] + return [r for r in merged_runs(records) if r.get("id") not in judged and r.get("status") != "pending"] # ---------------------------------------------------------------- candidates @@ -857,6 +878,40 @@ def mechanism_for(cand, host=None): return "use `sisi delegate` (the host has no delegation of its own for this worker)" +def same_model(a, b): + """Do two spellings name one model? Equal, or one an alias contained in the other's full name + (a short name against a dated id). Neither side may be empty or shorter than three characters.""" + a, b = str(a or "").strip().lower(), str(b or "").strip().lower() + if len(a) < 3 or len(b) < 3: + return False + a, b = a.rsplit("/", 1)[-1], b.rsplit("/", 1)[-1] + return a == b or a in b or b in a + + +def _own_workers(candidates, own_model): + return [c["worker"] for c in candidates + if own_model and any(same_model(own_model, x) for x in + [c.get("worker"), c.get("model")] + list(c.get("aliases") or []))] + + +def recommend(kind, difficulty, cwd=None, own_model=None): + """The router's pick for a kind of task as (worker, mechanism line, usable_count), reading only + the cached discovery and the record, never printing. The session's own model is not offered: + delegating to the same model is what orchestration is meant to avoid. (None, None, 0) when no + other worker is usable.""" + records = read_records() + candidates, _tools = _cached_candidates(records) + candidates, _cold, _x = routable_candidates(candidates, records) + prefs = effective_prefs(kind, difficulty, cwd or os.getcwd()) + candidates, _limited = apply_limits(candidates, prefs) + result = routing.choose(candidates, records, read_availability(), kind, difficulty, now=time.time(), + exclude=_own_workers(candidates, own_model), avoid=prefs["avoid"], prefer=prefs["prefer"]) + choice = result["choice"] + if choice is None: + return None, None, 0 + return choice["worker"], mechanism_for(choice), 1 + + def _pct(ok, n): return ("%d%%" % round(100.0 * ok / n)) if n else "-" @@ -1615,7 +1670,7 @@ def _cmd_judge(args): records = read_records() run_id = args[0] if args and not args[0].startswith("--") else None if run_id is not None: - run = next((r for r in records if r.get("kind") == "run" and r.get("id") == run_id), None) + run = next((r for r in merged_runs(records) if r.get("id") == run_id), None) if run is None: print("sisi delegate: no delegation run with id %s" % run_id, file=sys.stderr) return 1 @@ -1626,10 +1681,14 @@ def _cmd_judge(args): "project": os.path.basename(str(run.get("cwd") or "").rstrip("/")) or None, "type": run.get("type"), "difficulty": run.get("difficulty"), "worker": run.get("worker"), "model": run.get("model"), "tool": run.get("tool"), "outcome": outcome, "check": check, - "minutes": None, "tokens": run.get("tokens"), "tokens_class": run.get("tokens_class"), + "minutes": run.get("minutes"), "tokens": run.get("tokens"), "tokens_class": run.get("tokens_class"), "cost": run.get("cost"), "cost_class": run.get("cost_class"), "started": run.get("started"), "ended": run.get("ended"), "retry_of": run.get("retry_of"), "note": None} + if _opt(args, "--type") or _opt(args, "--kind"): # a run the host started carries no kind until judged + rec["type"] = _opt(args, "--type") or _opt(args, "--kind") + if _opt(args, "--difficulty") in ("1", "2", "3"): + rec["difficulty"] = int(_opt(args, "--difficulty")) else: worker = _opt(args, "--worker") kind = _opt(args, "--type") or _opt(args, "--kind") diff --git a/tests/test_adapters.py b/tests/test_adapters.py index b3b810a..726003b 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -88,7 +88,7 @@ class HookToolTests(AdapterBase): 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.assertFalse(any(g.get("matcher") for g in obj["hooks"][ev]), "tool hooks cover every tool") self.assertEqual(self.rows()[name]["status"], "wired") wiring.uninstall() diff --git a/tests/test_meter.py b/tests/test_meter.py new file mode 100644 index 0000000..10e2461 --- /dev/null +++ b/tests/test_meter.py @@ -0,0 +1,286 @@ +"""The direct-work meter, the delegation guard and the repeat-failure stop (rule 6, SPEC section 7; R-7.1-1, +R-7.2-2, R-6.3-1, R-6.3-3, R-15-4). Every test is written from the side of an agent trying to keep working +directly; hook input is what Claude Code sends, the output is what the host reads.""" +import json, os, subprocess, unittest +from unittest import mock +from support import * + +from sisi import orchestration, store, workers + + +def seed_workers(case, names=("alpha-small", "beta-large")): + """A ledger with two usable workers (host-native, judged), the first the cheaper.""" + for i, w in enumerate(names): + for t in ("research", "implementation"): + workers.append_record({"kind": "attempt", "id": "%s%s" % (w[:3], t[:2]), "run_id": None, "ts": 1, + "project": "p", "type": t, "difficulty": 1, "worker": w, + "outcome": "accepted", "check": "read"}) + with open(os.path.join(case.data, "worker-prices.json"), "w") as f: + json.dump({"models": {names[0]: {"cost_per_million_tokens": 1}, names[1]: {"cost_per_million_tokens": 9}}}, f) + + +class MeterBase(SisiCase): + def setUp(self): + super().setUp() + self.git_init() + os.makedirs(self.data, exist_ok=True) + seed_workers(self) + self.sid = "sess-1" + self.own = "gamma-top" + self.tick() + + def payload(self, ev, tool, inp=None, **kw): + d = {"session_id": self.sid, "cwd": self.proj, "hook_event_name": ev, "tool_name": tool, + "tool_input": inp or {}} + d.update(kw) + return json.dumps(d) + + def tick(self, sid=None, **kw): + d = {"session_id": sid or self.sid, "cwd": self.proj, "hook_event_name": "SessionStart", + "source": "startup", "model": self.own} + d.update(kw) + self.sisi("tick", "--tool", "claude-code", stdin=json.dumps(d)) + + def prompt(self, text="fix the parser and explain each module in the project", sid=None): + return self.sisi("prompt", "--tool", "claude-code", stdin=json.dumps( + {"session_id": sid or self.sid, "cwd": self.proj, "hook_event_name": "UserPromptSubmit", "prompt": text})) + + def pre(self, tool="Read", inp=None, **kw): + """The decoded hook output of one before-tool call: (denied, reason, whole output).""" + r = self.sisi("watch", "--before", "--tool", "claude-code", + stdin=self.payload("PreToolUse", tool, inp or {"file_path": "/x"}, **kw)) + self.assertEqual(r.returncode, 0) + out = json.loads(r.stdout) if r.stdout.strip() else {} + hs = out.get("hookSpecificOutput") or {} + return hs.get("permissionDecision") == "deny", hs.get("permissionDecisionReason") or hs.get("additionalContext"), out + + def post(self, tool="Read", inp=None, response="x", event="PostToolUse", **kw): + return self.sisi("watch", "--after", "--tool", "claude-code", + stdin=self.payload(event, tool, inp or {"file_path": "/x"}, tool_response=response, **kw)) + + def events(self, ev=None): + rows = store.read(orchestration.EVENTS) + return [r for r in rows if ev is None or r["ev"] == ev] + + def read_n(self, n, tool="Read"): + return [self.pre(tool)[0] for _ in range(n)] + + +class BudgetTests(MeterBase): + def test_fifty_reads_in_one_turn(self): + """R-7.2-2: the seventh counted call is refused, and so is every one after it, with a message of at most + 12 lines that gives the count, rule 6, the router's workers and both ways on.""" + self.prompt() + denied = self.read_n(50) + self.assertEqual(denied[:6], [False] * 6) + self.assertEqual(denied[6:], [True] * 44) + _d, reason, _o = self.pre() + self.assertLessEqual(len(reason.splitlines()), 12) + self.assertIn("6 direct tool calls", reason) + self.assertIn("rule 6", reason) + self.assertIn("alpha-small", reason) # the router's pick, by calling the routing code + self.assertIn("host's own subagent tool", reason) # its mechanism line + self.assertIn("sisi delegate brief", reason) + self.assertIn('sisi unit direct ""', reason) + self.assertEqual(len(self.events("refusal")), 45) + + def test_one_shell_command_printing_twenty_files_trips_the_character_budget(self): + """A single call whose result is huge uses the character budget: the very next counted call is refused.""" + self.prompt() + self.assertFalse(self.pre("Bash", {"command": "cat src/*"})[0]) + self.post("Bash", {"command": "cat src/*"}, response={"stdout": "x" * 31000, "stderr": ""}) + denied, reason, _ = self.pre("Read") + self.assertTrue(denied) + self.assertIn("1 direct tool calls", reason.replace("1 direct tool call ", "1 direct tool calls ")) + self.assertIn("31000 characters", reason) + + def test_a_tool_sisi_has_never_heard_of_counts(self): + """Legwork through a tool named nowhere in the data still counts.""" + self.prompt() + denied = [self.pre("mcp__some__brandnew_tool", {"q": "x"})[0] for _ in range(8)] + self.assertEqual(denied, [False] * 6 + [True] * 2) + + def test_exempt_tools_and_sisi_commands_are_never_counted_or_refused(self): + self.prompt() + self.read_n(6) + for tool in ("AskUserQuestion", "TodoWrite", "EnterPlanMode", "SendMessage"): + self.assertFalse(self.pre(tool, {})[0], tool) + for cmd in ("sisi route --kind research --difficulty 1", 'sisi unit direct "a; b"', "FOO=1 sisi delegate brief", + "python3 /opt/x/bin/sisi status", "sisi status && sisi risk"): + self.assertFalse(self.pre("Bash", {"command": cmd})[0], cmd) + self.assertTrue(self.pre("Read")[0]) + + def test_a_command_that_only_starts_with_sisi_still_counts(self): + """`sisi x && cat everything` is legwork with a sisi command in front.""" + self.prompt() + self.read_n(6) + self.assertTrue(self.pre("Bash", {"command": "sisi status && cat src/*"})[0]) + self.assertTrue(self.pre("Bash", {"command": "echo sisi"})[0]) + + def test_the_turn_resets_at_each_prompt(self): + self.prompt() + self.read_n(7) + self.assertTrue(self.pre()[0]) + self.prompt("now fix the second bug in the parser as well please") + self.assertFalse(self.pre()[0]) + + def test_limits_come_from_config(self): + os.makedirs(self.data, exist_ok=True) + with open(os.path.join(self.data, "config.json"), "w") as f: + json.dump({"orchestrate": {"direct_calls": 2}}, f) + self.prompt() + self.assertEqual(self.read_n(4), [False, False, True, True]) + + def test_a_hook_that_raises_lets_the_call_through(self): + """Fail open: a crash inside the meter never blocks the user's tool.""" + self.prompt() + self.read_n(6) + with mock.patch.object(orchestration, "before", side_effect=RuntimeError("boom")): + denied, _r, out = self.pre() + self.assertFalse(denied) + self.assertEqual(out, {}) + with mock.patch.object(orchestration.Meter, "__enter__", side_effect=OSError("disk")): + self.assertFalse(self.pre()[0]) + + +class ExtensionTests(MeterBase): + def test_a_generic_reason_is_refused_a_specific_one_grants_the_extension(self): + """R-6.3-3: 'because it is easier' is not a reason; a specific one extends the turn by ten calls and is stored.""" + self.prompt() + self.read_n(7) + for generic in ("because it is easier", "faster", "it is simpler and quicker to just do it myself"): + r = self.sisi("unit", "direct", generic) + self.assertEqual(r.returncode, 1, generic) + self.assertIn("generic", r.stdout) + self.assertTrue(self.pre()[0]) + r = self.sisi("unit", "direct", "the fix is one line in parser.py and a brief would be longer than the change") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertEqual(self.read_n(10), [False] * 10) + self.assertTrue(self.pre()[0]) + ext = self.events("extension") + self.assertEqual(len(ext), 1) + self.assertIn("parser.py", ext[0]["reason"]) + + def test_many_extensions_are_each_recorded_and_visible_in_status(self): + """Splitting legwork across the allowed calls and many extensions: nothing hides, every extension and its + reason is stored and `sisi status` shows it for the open unit.""" + self.write_contract(contract([check("c", "true")])) + self.prompt() + for i in range(4): + self.read_n(7 if i == 0 else 11) + r = self.sisi("unit", "direct", "step %d of the parser migration reads src/part%d.py once" % (i, i)) + self.assertEqual(r.returncode, 0, r.stdout) + self.assertEqual(len(self.events("extension")), 4) + out = self.sisi("status").stdout + self.assertIn("4 extension(s)", out) + self.assertIn("src/part3.py", out) + self.assertIn("orchestration (measured)", out) + + def test_the_same_reason_twice_in_a_turn_is_refused(self): + self.prompt() + self.read_n(7) + why = "the fix is one line in parser.py and a brief would be longer" + self.assertEqual(self.sisi("unit", "direct", why).returncode, 0) + self.assertEqual(self.sisi("unit", "direct", why).returncode, 1) + + def test_the_character_budget_grows_with_an_extension(self): + self.prompt() + self.pre("Bash", {"command": "cat a"}) + self.post("Bash", {"command": "cat a"}, response="y" * 31000) + self.assertTrue(self.pre()[0]) + self.sisi("unit", "direct", "the two config files hold 40 lines each, a brief costs more") + self.assertFalse(self.pre()[0]) + + +class WhoIsMeteredTests(MeterBase): + def test_a_host_marked_subagent_call_is_never_counted_or_refused(self): + self.prompt() + self.read_n(7) + denied, _r, _o = self.pre("Read", agent_id="sub-1") + self.assertFalse(denied) + self.assertEqual(self.events("call")[-1]["ev"], "call") + self.assertEqual(len(self.events("call")), 6) # the subagent's call is not in the count + + def test_a_session_started_by_sisi_delegate_is_never_refused(self): + self.prompt() + with mock.patch.dict(os.environ, {"SISI_WORKER_RUN": "1"}): + self.assertEqual(self.read_n(20), [False] * 20) + + def test_a_session_the_host_started_as_a_subagent_is_never_refused(self): + self.tick("sub-sess", agent_id="a1") + self.sid = "sub-sess" + self.prompt() + self.assertEqual(self.read_n(20), [False] * 20) + + def test_a_first_prompt_that_opens_with_the_brief_line_makes_a_worker(self): + """Compared case-insensitively on the first 200 characters.""" + from sisi import brief + line = brief.template().splitlines()[0] + self.prompt(line.upper() + "\n\n## Outcome and scope\nfind the bug") + self.assertEqual(self.read_n(20), [False] * 20) + + def test_a_main_prompt_that_only_mentions_worker_later_is_still_metered(self): + from sisi import brief + line = brief.template().splitlines()[0] + self.prompt("fix the parser, and remember this: " + line + " you are a worker of mine") + self.assertEqual(self.read_n(8), [False] * 6 + [True] * 2) + # nor does a brief line in the second prompt change a session that began as a main thread + self.prompt(line + " again please do this") + self.assertEqual(self.read_n(8), [False] * 6 + [True] * 2) + + def test_no_refusal_when_no_other_worker_is_usable(self): + """Counts and records, never refuses: the ledger knows only the session's own model.""" + os.unlink(workers.ledger_path()) + workers.append_record({"kind": "attempt", "id": "x", "run_id": None, "ts": 1, "project": "p", "type": "research", + "difficulty": 1, "worker": self.own, "outcome": "accepted", "check": "read"}) + self.prompt() + self.assertEqual(self.read_n(10), [False] * 10) + self.assertEqual(len(self.events("call")), 10) + self.assertTrue(self.events("unrefused")) + self.assertEqual(self.events("refusal"), []) + + +class DelegationGuardTests(MeterBase): + def deleg(self, **kw): + inp = {"description": "read the code", "prompt": "Outcome: list what each file does.", "subagent_type": "general-purpose"} + inp.update(kw) + return self.pre("Agent", inp) + + def test_a_delegation_naming_no_model_is_refused_with_the_recommendation(self): + self.prompt() + denied, reason, _ = self.deleg() + self.assertTrue(denied) + self.assertIn("names no model", reason) + self.assertIn("alpha-small", reason) + self.assertIn('sisi unit direct ""', reason) + self.assertLessEqual(len(reason.splitlines()), 12) + + def test_the_same_expensive_model_named_explicitly_is_refused(self): + self.prompt() + denied, reason, _ = self.deleg(model="gamma") # an alias of the session's own model + self.assertTrue(denied) + self.assertIn("own model", reason) + denied, _r, _o = self.deleg(model="gamma-top") + self.assertTrue(denied) + + def test_a_recorded_reason_allows_the_same_model_delegation(self): + self.prompt() + self.assertTrue(self.deleg()[0]) + self.sisi("unit", "direct", "the review must see exactly what this session saw, 3 files") + self.assertFalse(self.deleg()[0]) + + def test_a_delegation_to_another_model_is_allowed_recorded_and_its_brief_advised(self): + self.prompt() + denied, ctx, _ = self.deleg(model="alpha-small", prompt="read the files and tell me what they do") + self.assertFalse(denied) + self.assertIn("recorded as run", ctx) + self.assertIn("no outcome and scope", ctx) # missing parts are advice, never a refusal + runs = [r for r in workers.read_records() if r.get("kind") == "run"] + self.assertEqual(len(runs), 1) + self.assertEqual((runs[0]["worker"], runs[0]["status"], runs[0]["session"]), ("alpha-small", "pending", self.sid)) + + def test_delegations_are_not_counted_as_direct_calls(self): + self.prompt() + for _ in range(10): + self.assertFalse(self.deleg(model="alpha-small")[0]) + self.assertFalse(self.pre()[0]) diff --git a/tests/test_unit.py b/tests/test_unit.py index f0337bb..2cf9bb5 100644 --- a/tests/test_unit.py +++ b/tests/test_unit.py @@ -549,7 +549,7 @@ class StatusTests(UnitCase): helptext = self.sisi("help").stdout for gone in ("sisi time", "sisi scoreboard", "sisi improve", "sisi backlog"): self.assertNotIn(gone, helptext) - for kept in ("sisi unit close|pause|show|list", "sisi status"): + for kept in ("sisi unit close|pause|direct|show|list", "sisi status"): self.assertIn(kept, helptext) self.assertIn("sisi unit pause", self.sisi("help", "unit").stdout) for cmd in ("time", "scoreboard"): diff --git a/tests/test_wiring.py b/tests/test_wiring.py index f186dca..5817cc8 100644 --- a/tests/test_wiring.py +++ b/tests/test_wiring.py @@ -26,7 +26,7 @@ def remove_hooks(obj): if not isinstance(hooks, dict): return False for ev, sub in (("SessionStart", "tick"), ("UserPromptSubmit", "prompt"), ("Stop", "gate"), ("SubagentStop", "gate"), - ("PreToolUse", "watch"), ("PostToolUse", "watch")): + ("PreToolUse", "watch"), ("PostToolUse", "watch"), ("PostToolUseFailure", "watch")): groups = hooks.get(ev) if not isinstance(groups, list): continue @@ -259,15 +259,16 @@ class WiringTests(WiringBase): class WatchHookTests(WiringBase): - def test_watch_hooks_registered_with_bash_matcher_and_removed(self): + def test_watch_hooks_registered_for_every_tool_and_removed(self): + """R-7.1-1: the tool hooks carry no matcher, so the meter sees every tool, not only the shell.""" before = snapshot(self.home) wiring.install() d = json.load(open(self.path(".claude/settings.json"))) - for ev in ("PreToolUse", "PostToolUse"): + for ev in ("PreToolUse", "PostToolUse", "PostToolUseFailure"): 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.assertFalse(any(g.get("matcher") for g in groups), (ev, groups)) self.assertEqual(wiring.doctor()[0]["status"], "wired") snap = snapshot(self.home) wiring.install()