From 858401d58e7b2d8514821679fdd669e5247f3778 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:25:19 -0700 Subject: [PATCH 1/5] workerid: one decision of who is a worker, lazy transcript recognition, opening patterns as data. done: module / next: wire callers --- canon/tool-name-words.json | 5 ++ canon/worker-openings.json | 14 +++++ sisi/workerid.py | 117 +++++++++++++++++++++++++++++++++++++ 3 files changed, 136 insertions(+) create mode 100644 canon/tool-name-words.json create mode 100644 canon/worker-openings.json create mode 100644 sisi/workerid.py diff --git a/canon/tool-name-words.json b/canon/tool-name-words.json new file mode 100644 index 0000000..fd5a96f --- /dev/null +++ b/canon/tool-name-words.json @@ -0,0 +1,5 @@ +{ + "_about": "What an UNLISTED host tool is, judged by its name (sisi/orchestration.py `classify`). A name is split into words at punctuation and case changes; a phrase matches when its words appear next to each other. `delegation`: the tool starts a worker, so it is never counted as direct work or refused by the meter. `control`: the tool only reads status, waits, cancels, lists, schedules or messages, so it is not counted. A tool named by neither still counts as direct work. Listed tools (canon/orchestration-tools.json) always win.", + "delegation": ["delegate", "delegation", "subagent", "sub_agent", "spawn", "thread_launch"], + "control": ["status", "wait", "cancel", "list", "read_thread", "schedule", "scheduled", "notify", "send", "ask"] +} diff --git a/canon/worker-openings.json b/canon/worker-openings.json new file mode 100644 index 0000000..3e926b6 --- /dev/null +++ b/canon/worker-openings.json @@ -0,0 +1,14 @@ +{ + "_about": "How a session's FIRST user message says it is a delegated worker (sisi/workerid.py). Each phrase is matched case-insensitively, with white space collapsed, inside the first `window` characters of that one message only; the brief template's own first line always counts too. A phrase later in a long message, or in a later message, never counts: a session a person started is a main thread.", + "window": 400, + "openings": [ + "you are a worker", + "you are a subagent", + "you are a sub-agent", + "you are a delegate", + "do this task yourself", + "do the task yourself", + "do not delegate" + ], + "head_bytes": 1048576 +} diff --git a/sisi/workerid.py b/sisi/workerid.py new file mode 100644 index 0000000..4dc4997 --- /dev/null +++ b/sisi/workerid.py @@ -0,0 +1,117 @@ +"""Who is a worker: the one decision, used by the contract guard, the meter, the delegation guard, the fallback +logic and the gate (R-7.1-1, R-7.2-2, R-16-1). A session is a worker when the host marks it as a subagent, +`sisi delegate` started it, or its FIRST user message opens like a brief (canon/worker-openings.json). A session +a person started is a main thread. Fails open: an error is "main thread" (the safe default), never stored.""" +import json, os + +from . import paths, store + +_DATA = {} + + +def _data(): + if not _DATA: + try: + with open(paths.canon("worker-openings.json"), encoding="utf-8") as f: + _DATA.update(json.load(f)) + except (OSError, ValueError): + return {} + return _DATA + + +def _squash(text): + return " ".join(str(text or "").split()).lower() + + +def opens_as_brief(text): + """Does this first user message open like a brief: a listed phrase (or the template's first line) within the + first `window` characters?""" + d = _data() + try: + window = int(d.get("window") or 400) + except (TypeError, ValueError): + window = 400 + head = _squash(str(text or "")[:window * 3])[:window] + phrases = [_squash(p) for p in d.get("openings") or [] if isinstance(p, str) and p.strip()] + try: + from . import brief + phrases.append(_squash(brief.template().splitlines()[0])) + except Exception: + pass + return any(p and p in head for p in phrases) + + +def _read_head(path, nbytes): + """(bytes, whole) from the start of the file: `whole` says the file ended inside the bound.""" + with open(os.path.expanduser(path), "rb") as f: + raw = f.read(nbytes + 1) + return raw[:nbytes], len(raw) <= nbytes + + +def first_user_text(path): + """(found, text): the first message the person typed, from only the head of the transcript. `found` is False + when the transcript cannot be read or holds no such message yet.""" + from . import harvest + try: + nbytes = int(_data().get("head_bytes") or 1048576) + raw, whole = _read_head(path, nbytes) + except (OSError, TypeError, ValueError): + return False, "" + lines = raw.split(b"\n") + if not whole: + lines = lines[:-1] # the last line is cut by the bound + for line in lines: + if b'"user"' not in line or b"toolUseResult" in line: + continue + try: + d = json.loads(line) + except ValueError: + continue + if isinstance(d, dict) and d.get("type") == "user": + text = harvest.typed_text(d)[0] + if text is not None: + return True, text + return False, "" + + +def is_worker_session(payload, session_record, meter_record): + """True for a worker or subagent session. A decision made from the transcript is written into + `meter_record` (key "worker"); the caller saves it. Without a readable first message nothing is stored.""" + payload = payload if isinstance(payload, dict) else {} + sess = session_record if isinstance(session_record, dict) else {} + if store.is_subagent_payload(payload) or sess.get("subagent"): + return True + if not isinstance(meter_record, dict): + return False + if "worker" in meter_record: + return bool(meter_record["worker"]) + tp = payload.get("transcript_path") or sess.get("transcript_path") + if not isinstance(tp, str) or not tp: + return False + found, text = first_user_text(tp) + if not found: + return False + meter_record["worker"] = opens_as_brief(text) + meter_record["worker_from"] = "transcript" + return bool(meter_record["worker"]) + + +def session_is_worker(payload, sid, cwd=None): + """The same decision for a caller holding no records: reads them, and keeps a new decision in the session's + meter record so the transcript is read once.""" + try: + from . import orchestration + sid = sid or "cwd-" + (cwd or os.getcwd()) + sess = store.load_session(sid) + m = orchestration._peek(sid) + had = "worker" in m + found = is_worker_session(payload, sess, m) + if not had and "worker" in m: + with orchestration.Meter(sid) as real: + real.setdefault("worker", m["worker"]) + real.setdefault("worker_from", m.get("worker_from")) + found = bool(real["worker"]) + return found + except Exception as e: + store.log_error("workerid", e) + return False From 1899f1ae4a0c578ea55aec0bb0c96ce571b7b3d4 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:29:15 -0700 Subject: [PATCH 2/5] One worker decision used by the contract guard, meter, delegation guard, fallback logic, gate; lazy transcript recognition; opening patterns as data. done: items 1-3 / next: tool list and name words --- sisi/gate.py | 14 +++++-------- sisi/orchestration.py | 44 +++++++++++++-------------------------- sisi/tick.py | 4 ++-- sisi/unitguard.py | 10 ++++----- sisi/watch.py | 18 ++-------------- sisi/workers.py | 3 ++- tests/test_integration.py | 4 ++-- tests/test_meter.py | 2 +- 8 files changed, 33 insertions(+), 66 deletions(-) diff --git a/sisi/gate.py b/sisi/gate.py index 9faf020..23e7861 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -251,15 +251,13 @@ def _decide(payload): cfg = store.config() if not cfg["gate"].get("enabled", True): return "allow", None - from . import workers - if workers.is_subagent_payload(payload): - return decide_subagent(payload) + from . import workerid cwd = _cwd(payload) sid = _session_key(payload, cwd) + if workerid.session_is_worker(payload, sid, cwd): + return decide_subagent(payload) # a worker's last message is its report to the agent that started it os.environ["SISI_SESSION_ID"] = sid sess = store.load_session(sid) - if sess.get("subagent"): - return "allow", None # a session another agent started: its last message is its report to that agent if not (sess.get("started") or sess.get("first_seen")): sess["first_seen"] = store.now() top = gitutil.root(cwd) @@ -525,12 +523,10 @@ 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 + from . import orchestration, workerid cwd = _cwd(payload) sid = _session_key(payload, cwd) - if store.load_session(sid).get("subagent"): + if workerid.session_is_worker(payload, sid, cwd): return None if action == "allow": text = (orchestration.fallback_sendback(payload, sid) or orchestration.judgement_sendback(payload, sid) diff --git a/sisi/orchestration.py b/sisi/orchestration.py index f8d51d1..7924d13 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -19,7 +19,7 @@ fails open (the caller wraps it): an error here must never hold up the user's to """ import fcntl, json, os, re, shlex, time -from . import paths, store +from . import paths, store, workerid EVENTS = "orchestration.jsonl" _HOSTS = {} @@ -221,11 +221,6 @@ def _peek(sid): return {} -def worker_flag(sid): - """Did this session's first prompt open with the brief template's line (it is a worker)?""" - return bool(_peek(sid).get("worker")) - - def routed_kind(sid): """The kind in the session's current routing decision (`sisi route` recorded it, here, in the meter), or None when there is none or it is older than orchestrate.route_window_min. The one place the decision is read.""" @@ -288,15 +283,6 @@ def _task_done(m, key, ent, text, superseded=False): _event(m, m.get("sid"), "delegation-done", run=ent["run"]) -def brief_line(): - from . import brief - return brief.template().splitlines()[0].strip().lower() - - -def _session_is_worker(m, sess): - return bool(m.get("worker") or sess.get("subagent") or os.environ.get("SISI_WORKER_RUN")) - - def new_turn(sid, cwd=None, prompt=None): """A prompt reached the session. A human request starts the meter's turn again (the first one that opens with the brief template's line makes the session a worker for good). A host notice about a background worker @@ -313,7 +299,7 @@ def new_turn(sid, cwd=None, prompt=None): if is_notice or failed: out = None key, ent = _pending_for(m, text) if is_notice else (None, None) - if failed and not _session_is_worker(m, sess): + if failed and not workerid.is_worker_session({}, sess, m): out = fallback.handle(m, sid, cwd or m.get("project") or os.getcwd(), failed["text"], own_model=_own_model({}, sess, m), worker=(ent or {}).get("worker"), run_id=(ent or {}).get("run")) @@ -323,8 +309,8 @@ def new_turn(sid, cwd=None, prompt=None): m["turn"] += 1 m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None) m["prompts"] += 1 - if m["prompts"] == 1 and text.lstrip()[:200].lower().startswith(brief_line()): - m["worker"] = True + if m["prompts"] == 1 and "worker" not in m: + m["worker"] = workerid.opens_as_brief(text) return None @@ -445,10 +431,6 @@ def _norm(cmd): return " ".join((cmd or "").split()) -def _is_worker(payload, sess, m): - return bool(m.get("worker") or sess.get("subagent") or store.is_subagent_payload(payload)) - - def _transcript_model(path): """The model the main thread last answered with, from the tail of the host's transcript (a session-start payload need not carry it). None when it cannot be read.""" @@ -512,7 +494,7 @@ def _before(payload, host=None): tool, cmd, _ev, cwd, sid = watch.extract(payload) host = host or store.tool() or "claude-code" hd = host_data(host) - if not hd or store.is_subagent_payload(payload): + if not hd: return {} sid = sid or "cwd-" + cwd inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {}) @@ -522,10 +504,10 @@ def _before(payload, host=None): return _dialog_guard(payload, host, sid, cwd) if kind == "exempt" and not shell: return {} + if workerid.session_is_worker(payload, sid, cwd): + 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: @@ -572,10 +554,12 @@ def _dialog_guard(payload, host, sid, cwd): from . import fallback, workers if refuse_style(host) not in ("json-deny", "exit-2"): return {} + if workerid.session_is_worker(payload, sid, cwd): + return {} sess = store.load_session(sid) with Meter(sid) as m: info = m.get("unavail") - if not info or _is_worker(payload, sess, m): + if not info: return {} own = _own_model(payload, sess, m) project = _project(m, cwd) @@ -661,7 +645,7 @@ def after(payload, host=None): tool, cmd, ev, cwd, sid = watch.extract(payload) host = host or store.tool() or "claude-code" hd = host_data(host) - if not hd or store.is_subagent_payload(payload): + if not hd: return {} sid = sid or "cwd-" + cwd inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {}) @@ -669,11 +653,11 @@ def after(payload, host=None): shell = watch.is_shell(tool, cmd) if kind == "exempt" and not shell: return {} + if workerid.session_is_worker(payload, sid, cwd): + 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, sess, cwd) @@ -876,7 +860,7 @@ def fallback_sendback(payload, sid): sess = store.load_session(sid) with Meter(sid) as m: info = m.get("unavail") - if not info or int(m.get("fallback_asked") or 0) >= FALLBACK_SENDBACKS or _session_is_worker(m, sess): + if not info or int(m.get("fallback_asked") or 0) >= FALLBACK_SENDBACKS or workerid.is_worker_session({}, sess, m): return None own = _own_model({}, sess, m) project = m.get("project") or os.getcwd() diff --git a/sisi/tick.py b/sisi/tick.py index b10587b..23ac176 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -103,8 +103,8 @@ def main(args=()): store.log_error("tick-workers", e) try: sess3 = rec or store.load_session(sid) - from . import workers as _W3 - if not sess3.get("subagent") and not _W3.is_subagent_payload(payload): + from . import workers as _W3, workerid as _WI + if not _WI.is_worker_session(payload, sess3, {}): line = _W3.new_worker_line() if line: sys.stdout.write(line + "\n") diff --git a/sisi/unitguard.py b/sisi/unitguard.py index e5c53c0..063368d 100644 --- a/sisi/unitguard.py +++ b/sisi/unitguard.py @@ -805,22 +805,22 @@ def before(payload): def _before(payload): - from . import attribution, watch, workers + from . import attribution, watch, workerid tool, cmd, _ev, cwd, sid = watch.extract(payload) kind = classify(tool, payload, cmd) if kind is None: return None - if not store.config()["gate"].get("enabled", True) or workers.is_subagent_payload(payload): + if not store.config()["gate"].get("enabled", True): return None sid = sid or "cwd-" + cwd + if workerid.session_is_worker(payload, sid, cwd): + return None if kind == "shell": if CLAIM_RE.search(cmd or ""): note_claim(sid, cwd) if watch._may_write(cmd) is False or _is_sisi_command(cmd): return None sess = store.load_session(sid) - if sess.get("subagent"): - return None top = git_top(cwd) if top is None: return None # nothing to measure outside a repository @@ -933,7 +933,7 @@ def _after(payload): if c is not None: bind(sid, proj, c, "wrote") sess = store.load_session(sid) - if top and classify(tool, payload, cmd) == "shell" and not sess.get("subagent"): + if top and classify(tool, payload, cmd) == "shell": dirty = _absorb(sess, top) or dirty # a change the before-hook could not see: the next counted call answers for it if dirty: store.save_session(sid, sess) diff --git a/sisi/watch.py b/sisi/watch.py index 802b2dd..b3306aa 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -305,7 +305,8 @@ def run(payload, args=(), host=None): _tool, _cmd, ev, _cwd, sid = extract(payload) out = {} if "--before" in args or ev in BEFORE_EVENTS: - if not worker_session(payload, sid, _cwd): + from . import workerid + if not workerid.session_is_worker(payload, sid, _cwd): text = contract_guard(payload) if text: return {"deny": text} @@ -336,21 +337,6 @@ def run(payload, args=(), host=None): return out -def worker_session(payload, sid, cwd): - """Is this call from a worker or subagent (the host marks it, `sisi delegate` started it, or its first - prompt opened with the brief template's line)? Workers are exempt from the contract guard and the meter. - False when it cannot be told.""" - try: - if store.is_subagent_payload(payload): - return True - from . import orchestration - sid = sid or "cwd-" + cwd - return bool(store.load_session(sid).get("subagent") or orchestration.worker_flag(sid)) - except Exception as e: - store.log_error("watch-worker", e) - return False - - def render_claude(out, event): """The Claude Code hook output for a run() result, or None.""" if out.get("deny"): diff --git a/sisi/workers.py b/sisi/workers.py index 8a3ff3b..8eadcfe 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -1488,7 +1488,8 @@ def session_lines(model, payload=None): a missing number never argues against orchestrating. At most one extra line asks for worker facts to be researched when they are missing or stale (the caller shows these lines once per session). Uses only cached discovery and the record.""" - if not model or is_subagent_payload(payload or {}): + from . import workerid + if not model or workerid.is_worker_session(payload or {}, {}, None): return [] records = read_records() candidates, _tools = _cached_candidates(records) diff --git a/tests/test_integration.py b/tests/test_integration.py index 206eb48..9d57a29 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -11,7 +11,7 @@ from support import * import test_meter as TM import test_unitguard as TG from sisi import contract as C, gate, lifecycle, orchestration, prompt, routing, rulecmd, store, unit as U, unitguard as G -from sisi import watch, workers +from sisi import brief, watch, workers SRC = TG.SRC CONTRACT_LINES = 12 @@ -119,7 +119,7 @@ class OneRefusalAtATime(Both): self.assertIsNone(self.edit(agent_id="w1")) self.assertIsNone(self.agent(BUILD_BRIEF, agent_id="w1")) # a session whose first prompt opens with the brief template's line is a worker too - orchestration.new_turn("wk", self.proj, orchestration.brief_line() + "\nOutcome: x") + orchestration.new_turn("wk", self.proj, brief.template().splitlines()[0] + "\nOutcome: x") d = {"session_id": "wk", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Edit", "tool_input": {"file_path": os.path.join(self.proj, SRC), "old_string": "a", "new_string": "b"}} r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps(d)) diff --git a/tests/test_meter.py b/tests/test_meter.py index ace6c2f..381fd0a 100644 --- a/tests/test_meter.py +++ b/tests/test_meter.py @@ -245,7 +245,7 @@ class WhoIsMeteredTests(MeterBase): 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.prompt("fix the parser and explain each module in the project. " * 8 + "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") From fd97cf88f41b8c80f4898e92d207e6f2cc28b7d2 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:31:01 -0700 Subject: [PATCH 3/5] One tool list with patterns and name words; worker exemption on every unitguard path; tests. done: items 1-5 / next: item 6 background delegation pending --- canon/guard.json | 5 - sisi/orchestration.py | 66 ++++++++++-- sisi/unitguard.py | 9 +- tests/test_worker_session.py | 198 +++++++++++++++++++++++++++++++++++ 4 files changed, 260 insertions(+), 18 deletions(-) create mode 100644 tests/test_worker_session.py diff --git a/canon/guard.json b/canon/guard.json index 8621342..c7b74c5 100644 --- a/canon/guard.json +++ b/canon/guard.json @@ -17,11 +17,6 @@ "apply", "insert" ], - "delegation_tools": [ - "Agent", - "Task", - "mcp__t3-code__delegate_task" - ], "build_kinds": [ "impl", "impl-multi", diff --git a/sisi/orchestration.py b/sisi/orchestration.py index 7924d13..d3e56c2 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -17,7 +17,7 @@ canon/orchestration-tools.json. Per-session state is in /sessions/.me 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 +import fcntl, fnmatch, json, os, re, shlex, time from . import paths, store, workerid @@ -87,13 +87,57 @@ def _dig(obj, dotted): return obj +def _matches(entry, tool): + """A data entry is an exact tool name or a shell-style pattern (`*delegate_task`), case-insensitive.""" + e, t = str(entry).lower(), str(tool or "").lower() + return e == t or (any(c in e for c in "*?[") and fnmatch.fnmatchcase(t, e)) + + 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 {} + """The listed delegation entry for this tool (exact names first, then patterns), else None.""" + items = list((hd.get("delegation") or {}).items()) + for exact in (True, False): + for name, spec in items: + if (str(name).lower() == str(tool or "").lower()) == exact and _matches(name, tool): + return spec if isinstance(spec, dict) else {} return None +_WORDS = {} + + +def _name_words(): + if not _WORDS: # a failed read is not remembered + try: + with open(paths.canon("tool-name-words.json"), encoding="utf-8") as f: + d = json.load(f) + _WORDS.update({k: [str(w).lower() for w in v if isinstance(w, str)] for k, v in d.items() if isinstance(v, list)}) + except (OSError, ValueError): + return {} + return _WORDS + + +def name_kind(tool): + """"delegation" or "control" when an unlisted tool's NAME says what it is (canon/tool-name-words.json), else None.""" + t = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", str(tool or "")) + padded = "_" + "_".join(w for w in re.split(r"[^a-z0-9]+", t.lower()) if w) + "_" + words = _name_words() + for kind in ("delegation", "control"): + if any("_" + w.strip("_") + "_" in padded for w in words.get(kind, ())): + return kind + return None + + +def is_delegation(host, tool): + """Does this tool start a worker: listed in the host's data (name or pattern), or named like one.""" + return delegation_spec(host_data(host), tool) is not None or ( + not _listed_exempt(host_data(host), tool) and name_kind(tool) == "delegation") + + +def _listed_exempt(hd, tool): + return any(_matches(n, tool) for names in (hd.get("exempt") or {}).values() for n in names or []) + + def _segments(cmd): """The commands of a shell line, split at the operators outside quotes; None when it cannot be split.""" try: @@ -145,12 +189,13 @@ def classify(host, tool, inp, cmd): hd = host_data(host) if delegation_spec(hd, tool) is not None: return "delegation" - if str(tool or "").lower() in _exempt_names(hd): + if _listed_exempt(hd, tool): return "exempt" from . import watch - if watch.is_shell(tool, cmd) and runs_sisi(cmd): - return "exempt" - return "direct" + if watch.is_shell(tool, cmd): + return "exempt" if runs_sisi(cmd) else "direct" + kind = name_kind(tool) # an unlisted tool: its name says whether it starts a worker or only controls one + return "delegation" if kind == "delegation" else "exempt" if kind == "control" else "direct" # ---------------------------------------------------------------- the per-session meter @@ -573,7 +618,10 @@ def _dialog_guard(payload, host, sid, cwd): def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd): - spec = delegation_spec(hd, tool) or {} + spec = delegation_spec(hd, tool) + if spec is None: + return {} # only named like a delegation tool: the data does not say where its model sits, so it is never + # counted, refused or recorded as a run here model = _dig(inp, spec.get("model", "model")) model = model.strip() if isinstance(model, str) else "" text = _dig(inp, spec.get("brief", "prompt")) diff --git a/sisi/unitguard.py b/sisi/unitguard.py index 063368d..9ea87c9 100644 --- a/sisi/unitguard.py +++ b/sisi/unitguard.py @@ -683,7 +683,8 @@ def classify(tool, payload, cmd): t = tool or "" if t in _list("edit_tools") or any(w in t.lower() for w in _list("edit_name_words")): return "edit" - if t in _list("delegation_tools"): + from . import orchestration + if orchestration.is_delegation(store.tool() or "claude-code", t): return "delegate" if watch.is_shell(t, cmd): return "shell" @@ -918,12 +919,12 @@ def after(payload): def _after(payload): - from . import watch + from . import watch, workerid tool, cmd, _ev, cwd, sid = watch.extract(payload) sid = sid or "cwd-" + cwd sess = store.load_session(sid) - if not sess: - return + if not sess or workerid.session_is_worker(payload, sid, cwd): + return # a worker's changes are its parent's to answer for, never bookkept as this session's dirty = False top = git_top(cwd) if sess.get("ug_will_bind"): diff --git a/tests/test_worker_session.py b/tests/test_worker_session.py new file mode 100644 index 0000000..27fa0af --- /dev/null +++ b/tests/test_worker_session.py @@ -0,0 +1,198 @@ +"""Who is a worker, decided once, everywhere (R-7.1-1 the main agent owns the outcome and a worker is not metered +as one; R-7.2-2 legwork goes to a less expensive worker, so the meter must tell the two apart; R-16-1 a session a +person started is never exempted by words later in a message). Every test drives the real hook entry points with +hook-shaped JSON; the sessions here never had a prompt hook, as a session begun before sisi was upgraded.""" +import json, os, subprocess, time, unittest +from unittest import mock +from support import * +import test_meter as TM +import test_unitguard as TG +from sisi import brief, orchestration, store, workerid + +BRIEF = brief.template().splitlines()[0] +OPENINGS = [BRIEF, "You are a worker on this repository.", "You are a subagent for the lead.", "You are a sub-agent.", + "YOU ARE A DELEGATE of the main thread.", "Do this task yourself: fix the parser.", + "Please do the task yourself and report.", "Fix the parser. Do not delegate."] +ORDINARY = "Fix the parser and explain each module in the project." + + +class Base(TG.GuardCase): + sid = "wk" + + def setUp(self): + super().setUp() + os.makedirs(self.data, exist_ok=True) + TM.seed_workers(self) + self.tp = os.path.join(self.tmp, "t.jsonl") + + def transcript(self, first, path=None): + recs = [{"type": "file-history-snapshot", "snapshot": {}}, + {"type": "user", "message": {"role": "user", "content": first}, "timestamp": "2026-01-01T00:00:00Z"}, + {"type": "assistant", "message": {"role": "assistant", "content": "ok", "model": "m"}}] + with open(path or self.tp, "w") as f: + f.write("".join(json.dumps(r) + "\n" for r in recs)) + return path or self.tp + + def hook(self, tool, inp, after=False, sid=None, **extra): + """The real watch hook; (denied, text).""" + d = {"session_id": sid or self.sid, "cwd": self.proj, "tool_name": tool, "tool_input": inp, + "transcript_path": self.tp, "hook_event_name": "PostToolUse" if after else "PreToolUse"} + d.update(extra) + r = self.sisi("watch", "--after" if after else "--before", "--tool", "claude-code", stdin=json.dumps(d)) + self.assertEqual(r.returncode, 0, r.stderr) + out = json.loads(r.stdout) if r.stdout.strip() else {} + hs = out.get("hookSpecificOutput") or {} + return hs.get("permissionDecision") == "deny", hs.get("permissionDecisionReason") or "" + + def edit(self): + return self.hook("Edit", {"file_path": os.path.join(self.proj, SRC_FILE), "old_string": "hi", "new_string": "yo"}) + + def reads(self, n, tool="Read"): + return [self.hook(tool, {"file_path": "/x"})[0] for _ in range(n)] + + def stop(self): + r = self.sisi("gate", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", + "transcript_path": self.tp})) + self.assertEqual(r.returncode, 0, r.stderr) + d = json.loads(r.stdout) if r.stdout.strip() else {} + return "block" if d.get("decision") == "block" else "allow" + + def stored(self): + return orchestration._peek(self.sid).get("worker") + + +SRC_FILE = TG.SRC + + +class RecognitionTests(Base): + def test_a_brief_in_the_transcript_makes_a_worker_for_the_guard_the_meter_and_the_gate(self): + """R-7.1-1: no meter record, no tick, no prompt: the transcript's first message decides, in all three.""" + self.transcript(BRIEF + "\n\n## Outcome and scope\nfix the greeting") + self.assertFalse(self.edit()[0]) # the contract guard + self.assertEqual(self.reads(9), [False] * 9) # the meter (limit 6) + with open(os.path.join(self.proj, SRC_FILE), "a") as f: + f.write("# changed\n") + self.assertEqual(self.stop(), "allow") # the gate + self.assertIs(self.stored(), True) + + def test_every_alternative_opening_makes_a_worker(self): + for i, text in enumerate(OPENINGS): + with self.subTest(opening=text): + self.sid = "wk%d" % i + self.transcript(text + "\nfix the greeting") + self.assertFalse(self.edit()[0]) + self.assertEqual(self.reads(8), [False] * 8) + self.assertIs(self.stored(), True) + + def test_an_ordinary_first_message_is_a_main_thread(self): + self.transcript(ORDINARY) + denied, text = self.edit() + self.assertTrue(denied, text) + self.assertEqual(self.reads(8), [False] * 6 + [True] * 2) + self.assertIs(self.stored(), False) + + def test_words_after_the_first_400_characters_do_not_count(self): + self.transcript(ORDINARY + " " * 5 + ("Context. " * 50) + "You are a worker. Do this task yourself. Do not delegate.") + self.assertTrue(self.edit()[0]) + self.assertEqual(self.reads(8), [False] * 6 + [True] * 2) + + def test_the_second_message_never_counts(self): + recs = [{"type": "user", "message": {"role": "user", "content": ORDINARY}, "timestamp": "2026-01-01T00:00:00Z"}, + {"type": "user", "message": {"role": "user", "content": BRIEF}, "timestamp": "2026-01-01T00:00:01Z"}] + with open(self.tp, "w") as f: + f.write("".join(json.dumps(r) + "\n" for r in recs)) + self.assertTrue(self.edit()[0]) + + def test_an_unreadable_transcript_is_a_main_thread_and_nothing_is_stored(self): + self.tp = os.path.join(self.tmp, "missing.jsonl") + self.assertTrue(self.edit()[0]) + self.assertEqual(self.reads(8), [False] * 6 + [True] * 2) + self.assertIsNone(self.stored()) + self.transcript(BRIEF) # a later call can still find it + self.assertFalse(self.edit()[0]) + self.assertIs(self.stored(), True) + + def test_the_decision_is_stored_and_the_transcript_is_read_once(self): + self.transcript(BRIEF) + reads = [] + real = workerid._read_head + with mock.patch.object(workerid, "_read_head", side_effect=lambda *a: reads.append(a) or real(*a)): + self.edit() + self.reads(5) + self.hook("Read", {"file_path": "/x"}, after=True) + self.stop() + self.assertEqual(len(reads), 1) + os.unlink(self.tp) # and it no longer needs the file + self.assertFalse(self.edit()[0]) + + def test_a_session_started_by_a_person_with_no_transcript_path_is_a_main_thread(self): + r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps( + {"session_id": "nopath", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Edit", + "tool_input": {"file_path": os.path.join(self.proj, SRC_FILE)}})) + self.assertIn("deny", r.stdout) + + +class ShellChangeTests(Base): + """The lead's case: a worker known only by its first prompt changes files with a shell command (a merge); its + next call, a read-only one, was refused as an unowned change.""" + + def sequence(self): + self.hook("Bash", {"command": "git merge --no-commit other"}) + with open(os.path.join(self.proj, "canon_discovery.json"), "w") as f: + f.write("{}\n") # what the merge did to the tree + self.hook("Bash", {"command": "git merge --no-commit other"}, after=True) + return self.hook("Bash", {"command": "sed -n 1,5p README.md"}) + + def test_a_worker_whose_shell_command_changed_files_is_not_refused_on_its_next_call(self): + self.transcript(BRIEF + "\nmerge the branch") + denied, text = self.sequence() + self.assertFalse(denied, text) + self.assertEqual(self.stop(), "allow") + + def test_a_main_thread_in_the_same_sequence_is_still_refused(self): + self.transcript(ORDINARY) + denied, text = self.sequence() + self.assertTrue(denied) + self.assertIn("already changed", text) + + +class UnlistedToolTests(Base): + def counts(self): + return orchestration._peek(self.sid).get("calls") + + def test_an_unlisted_delegation_named_tool_at_the_limit_is_neither_refused_nor_counted(self): + self.transcript(ORDINARY) + self.assertEqual(self.reads(6), [False] * 6) + n = self.counts() + denied, text = self.hook("mcp__somehost__delegate_task", {"task": "do x", "target": {"model": "alpha-small"}}) + self.assertFalse(denied, text) + self.assertEqual(self.counts(), n) + self.assertTrue(self.reads(1)[0]) # the meter still bites for legwork + + def test_an_unlisted_status_tool_is_not_counted(self): + self.transcript(ORDINARY) + self.reads(6) + n = self.counts() + for tool in ("mcp__somehost__task_status", "mcp__somehost__t3_thread_wait", "mcp__somehost__ListThings"): + self.assertFalse(self.hook(tool, {})[0], tool) + self.assertEqual(self.counts(), n) + + def test_an_unlisted_read_tool_is_counted_and_refused_at_the_limit(self): + self.transcript(ORDINARY) + self.assertEqual([self.hook("mcp__somehost__read_file", {"p": "x"})[0] for _ in range(7)], [False] * 6 + [True]) + + def test_a_pattern_in_the_data_covers_a_prefixed_tool(self): + hd = {"delegation": {"*launch_it": {"model": "m", "brief": "b"}}} + self.assertIsNotNone(orchestration.delegation_spec(hd, "mcp__a__Launch_It")) + self.assertIsNone(orchestration.delegation_spec(hd, "mcp__a__launch_that")) + + def test_there_is_one_list_of_delegation_tools(self): + with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "canon", "guard.json")) as f: + self.assertNotIn("delegation_tools", json.load(f)) + from sisi import unitguard + self.assertEqual(unitguard.classify("Agent", {}, ""), "delegate") + self.assertEqual(unitguard.classify("mcp__x__spawn_helper", {}, ""), "delegate") + + +if __name__ == "__main__": + unittest.main() From 1cd7ab14465c75ba6fe14796ac31c67e6cb741e9 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:33:24 -0700 Subject: [PATCH 4/5] A background delegation stays pending until its completion message; data entry for *delegate_task; tests. done: item 6 / next: full suite, repeats, timing --- canon/orchestration-tools.json | 18 ++++- sisi/orchestration.py | 98 +++++++++++++++++++++++-- tests/test_background_delegation.py | 107 ++++++++++++++++++++++++++++ tests/test_worker_session.py | 4 +- 4 files changed, 216 insertions(+), 11 deletions(-) create mode 100644 tests/test_background_delegation.py diff --git a/canon/orchestration-tools.json b/canon/orchestration-tools.json index a0a172d..fa4f2e3 100644 --- a/canon/orchestration-tools.json +++ b/canon/orchestration-tools.json @@ -1,5 +1,5 @@ { - "_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.", + "_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. A delegation entry's name may be a shell-style pattern (`*delegate_task`). `async` says how the tool's result marks a background launch: the dotted `path` into the result, the `running` values meaning \"still running\", and the `ids` paths whose values the later completion message will carry; `title` is the input path of the task's title, the other way that message names it. A listed tool with no `async` is a launch when its call returned in under five seconds with no report in the result.", "claude-code": { "refuse": "json-deny", "evidence": "observed live (tools/live_orchestration_check.py)", @@ -12,9 +12,21 @@ "model": "model", "brief": "prompt" }, - "mcp__t3-code__delegate_task": { + "*delegate_task": { "model": "target.model", - "brief": "task" + "brief": "task", + "title": "title", + "async": { + "path": "status", + "running": [ + "starting", + "running" + ], + "ids": [ + "taskId", + "childThreadId" + ] + } } }, "exempt": { diff --git a/sisi/orchestration.py b/sisi/orchestration.py index d3e56c2..bacafa0 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -311,6 +311,26 @@ def _pending_for(m, text): return key, (m["pending"].get(key) if key else None) +_BRACKET = re.compile(r"\[(completed|failed|interrupted|cancelled|canceled)\]", re.I) + + +def bracket_status(text): + """The status a plain-text completion notice carries (`[completed]`, `[failed]`, `[interrupted]`) near its start.""" + m = _BRACKET.search((text or "").lstrip()[:300]) + return m.group(1).lower().replace("canceled", "cancelled") if m else None + + +def _pending_by_names(m, text): + """(key, entry) of the pending background delegation whose id or title this message names, else (None, None).""" + low = (text or "").lower() + for key, ent in m["pending"].items(): + ids = [str(i) for i in ent.get("ids") or [] if i] + title = str(ent.get("title") or "") + if any(i in text for i in ids) or (len(title) >= 8 and title.lower() in low): + return key, ent + return None, None + + def _task_done(m, key, ent, text, superseded=False): """A host's notice that a background worker finished: complete the run it started.""" from . import workers @@ -319,7 +339,7 @@ def _task_done(m, key, ent, text, superseded=False): tokens = _tag(text, "subagent_tokens") ms = _tag(text, "duration_ms") minutes = round(float(ms) / 60000.0, 2) if ms and ms.replace(".", "", 1).isdigit() else round((now - ent["t0"]) / 60.0, 2) - ok = (_tag(text, "status") or "completed") == "completed" + ok = (_tag(text, "status") or bracket_status(text) or "completed") == "completed" workers.append_record({"kind": "run-end", "run_id": ent["run"], "ts": round(now), "ended": round(now), "minutes": minutes, "tokens": int(tokens) if tokens and tokens.isdigit() else None, "tokens_class": "measured" if tokens and tokens.isdigit() else "unavailable", @@ -340,10 +360,15 @@ def new_turn(sid, cwd=None, prompt=None): _project(m, cwd) text = prompt if isinstance(prompt, str) else "" is_notice = text.lstrip().startswith(NOTIFICATION) + status = (_tag(text, "status") or "").lower() if is_notice else (bracket_status(text) if text else None) + named = _pending_by_names(m, text) if status and not is_notice else (None, None) failed = fallback.failure_notice(text) if text else None - if is_notice or failed: + if is_notice or failed or named[1] is not None: out = None - key, ent = _pending_for(m, text) if is_notice else (None, None) + key, ent = _pending_for(m, text) if is_notice else named + if status in ("interrupted", "cancelled", "canceled") and ent is not None: + _task_done(m, key, ent, text, superseded=True) # stopped on purpose: nothing to judge + return None if failed and not workerid.is_worker_session({}, sess, m): out = fallback.handle(m, sid, cwd or m.get("project") or os.getcwd(), failed["text"], own_model=_own_model({}, sess, m), worker=(ent or {}).get("worker"), @@ -664,7 +689,9 @@ def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd): 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, "worker": worker} + title = _dig(inp, spec.get("title", "title")) + title = title.strip() if isinstance(title, str) else "" + m["pending"][key] = {"run": run_id, "t0": now, "worker": worker, "title": title or None} m["unavail"] = None # the agent is falling back (or delegating anew): nothing left to refuse a question for _event(m, sid, "delegation", run=run_id, worker=worker) known = bool(route and route.get("kind") and route.get("difficulty")) @@ -708,7 +735,7 @@ def after(payload, host=None): with Meter(sid) as m: _project(m, cwd) if kind == "delegation": - return _after_delegation(payload, ev, sid, m, sess, cwd) + return _after_delegation(payload, ev, sid, m, sess, cwd, host, tool) if shell and re.search(r"\bsisi\b.*\bdelegate\b", cmd or "", re.S): # alone or inside a longer command line from . import fallback note = fallback.shell_notice(_flat(payload)) @@ -753,7 +780,61 @@ def _flat(payload): return "\n".join(parts) -def _after_delegation(payload, ev, sid, m, sess=None, cwd=None): +def _result_objects(resp): + """The JSON objects a tool result holds: the result itself, or the text blocks of a content list parsed.""" + out, stack = [], [resp] + while stack: + x = stack.pop(0) + if isinstance(x, str): + try: + x = json.loads(x) + except ValueError: + continue + if isinstance(x, str): + continue + if isinstance(x, dict): + out.append(x) + for k in ("content", "text", "structuredContent"): + if x.get(k) is not None: + stack.append(x[k]) + elif isinstance(x, list): + stack.extend(x) + return out + + +_TERMINAL = ("completed", "complete", "done", "finished", "success", "succeeded", "failed", "error", "cancelled", + "canceled", "interrupted") +_REPORT_KEYS = ("result", "report", "summary", "output", "text", "message", "totalDurationMs", "total_duration_ms", + "totalTokens", "total_tokens", "usage") +LAUNCH_SECONDS = 5 + + +def background_launch(spec, resp, elapsed): + """None when the delegation call returned its result; else the ids (possibly none) the later notice will carry. + The data says how a host's result marks a background launch (`async`: a dotted `path` and the `running` values, + and the `ids` paths); a tool with no such data counts as a launch when the call returned in under + LAUNCH_SECONDS with no report in the result (no report keys, no finished status, no long text).""" + objs = [o for o in _result_objects(resp)] + a = (spec or {}).get("async") + if isinstance(a, dict) and a.get("path"): + for o in objs: + v = _dig(o, a["path"]) + if isinstance(v, str) and v.lower() in [str(x).lower() for x in a.get("running") or []]: + ids = [_dig(o, q) for q in (a.get("ids") or ([a["id"]] if a.get("id") else []))] + return [str(i) for i in ids if isinstance(i, (str, int)) and str(i)] + return None + if elapsed >= LAUNCH_SECONDS or not objs: + return None + for o in objs: + status = str(o.get("status") or "").lower() + if status in _TERMINAL or any(k in o for k in _REPORT_KEYS) or any(isinstance(v, str) and len(v) >= 80 for v in o.values()): + return None + ids = [str(v) for k, v in objs[0].items() if isinstance(v, (str, int)) and not isinstance(v, bool) + and re.search(r"id$", k, re.I) and str(v)] + return ids + + +def _after_delegation(payload, ev, sid, m, sess=None, cwd=None, host=None, tool=None): from . import workers key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last" ent = m["pending"].get(key) @@ -768,6 +849,11 @@ def _after_delegation(payload, ev, sid, m, sess=None, cwd=None): # the worker was only launched: it is finished when the host's notice arrives (new_turn), not now m["pending"][key] = dict(ent, agent=resp.get("agentId"), model=resp.get("resolvedModel")) return {} + launch = background_launch(delegation_spec(host_data(host), tool), resp, now - ent["t0"]) + if launch is not None: + # a launch call returns at once; the result arrives later as a message that names this id or title + m["pending"][key] = dict(ent, ids=launch, title=ent.get("title")) + return {} from . import fallback text = _flat(payload) if fallback.looks_failed(text, failure_event="failure" in str(ev or "").lower()): diff --git a/tests/test_background_delegation.py b/tests/test_background_delegation.py new file mode 100644 index 0000000..857c045 --- /dev/null +++ b/tests/test_background_delegation.py @@ -0,0 +1,107 @@ +"""A background delegation is not finished when its launch call returns (R-7.1-1 the main agent owns and judges the +outcome, so it is asked to judge a result only once there is one; R-7.2-3 the routing record must not hold a +run's time as 0.01 minutes). The launch result and the later completion message are what the host's delegation tool +really sends: `{"taskId", "childThreadId", "status": "starting"|"running", "workState"}` and a message naming the task +with `[completed]`, `[failed]` or `[interrupted]`.""" +import json, unittest +from support import * +import test_meter as TM +from sisi import orchestration, workers + +TOOL = "mcp__t3-code__delegate_task" +INP = {"title": "Fix greeting parser", "task": "Outcome: x\nAcceptance: y\nFiles you may change: none", + "target": {"model": "alpha-small"}} +LAUNCH = {"taskId": "tk-77", "childThreadId": "th-88", "status": "running", "workState": "working"} + + +class Background(TM.MeterBase): + def launch(self, result=LAUNCH, use_id="u1", wrap=False): + self.prompt() + denied, text, _ = self.pre(TOOL, INP, tool_use_id=use_id) + self.assertFalse(denied, text) + resp = [{"type": "text", "text": json.dumps(result)}] if wrap else result + self.post(TOOL, INP, response=resp, tool_use_id=use_id) + return self.runs()[0] + + def runs(self): + return workers.merged_runs() + + 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 age(self, seconds): + with orchestration.Meter(self.sid) as m: + for e in m["pending"].values(): + e["t0"] -= seconds + + def notice(self, text): + return self.prompt(text, route=False) + + def test_a_running_launch_stays_pending_and_the_gate_says_nothing(self): + for wrap in (False, True): + with self.subTest(wrapped=wrap): + self.setUp() + run = self.launch(wrap=wrap) + self.assertEqual(run["status"], "pending") + self.assertEqual(workers.unjudged_runs(), []) + self.assertNotIn("not judged", self.stop().get("reason", "")) + + def test_the_completion_message_finishes_it_with_the_real_duration_and_the_gate_asks_once(self): + run = self.launch() + self.age(120) + self.notice("[completed] Task tk-77 (Fix greeting parser) finished: the parser now greets.") + run = self.runs()[0] + self.assertEqual(run["status"], "waiting") + self.assertAlmostEqual(run["minutes"], 2.0, delta=0.1) + first = self.stop() + self.assertEqual(first.get("decision"), "block") + self.assertIn("not judged yet", first["reason"]) + self.assertIn(run["id"], first["reason"]) + self.assertNotEqual(self.stop().get("decision"), "block") # once + + def test_the_message_may_name_the_task_by_its_title_instead_of_an_id(self): + self.launch() + self.notice("[completed] \"Fix greeting parser\" is done.") + self.assertEqual(self.runs()[0]["status"], "waiting") + + def test_a_failed_message_with_a_quota_error_marks_the_provider_down_and_hands_over_the_fallback(self): + self.launch() + r = self.notice("[failed] Task tk-77: 429 rate limit exceeded, quota exhausted for alpha-small") + self.assertIn("unavailable", r.stdout) + self.assertEqual(self.runs()[0]["status"], "superseded") + self.assertEqual(workers.unjudged_runs(), []) + self.assertIn("alpha-small", workers.read_availability()) + + def test_a_failed_message_that_is_not_unavailability_awaits_judgement(self): + self.launch() + self.notice("[failed] Task tk-77: the tests it was asked to make pass still fail") + self.assertEqual(self.runs()[0]["status"], "failed") + self.assertEqual([r["id"] for r in workers.unjudged_runs()], [self.runs()[0]["id"]]) + + def test_an_interrupted_message_supersedes_it_and_it_is_never_asked_for(self): + self.launch() + self.notice("[interrupted] Task tk-77 was stopped.") + self.assertEqual(self.runs()[0]["status"], "superseded") + self.assertNotIn("not judged", self.stop().get("reason", "")) + + def test_a_synchronous_delegation_carrying_the_report_is_finished_at_once(self): + run = self.launch(result={"status": "completed", "taskId": "tk-1", "result": "the parser now greets by name"}) + self.assertEqual(run["status"], "waiting") + self.assertEqual(self.stop().get("decision"), "block") + + def test_a_listed_tool_with_no_launch_data_and_a_bare_fast_result_is_a_launch(self): + self.prompt() + self.pre("Agent", {"description": "d", "prompt": "Outcome: x\nAcceptance: y", "model": "alpha-small"}, tool_use_id="a1") + self.post("Agent", {"description": "d"}, response={"agentRef": "z9", "status": "queued"}, tool_use_id="a1") + self.assertEqual(self.runs()[0]["status"], "pending") + + def test_an_unrelated_prompt_is_not_taken_for_a_notice(self): + self.launch() + self.prompt("please also fix the [failed] tests in other_module") + self.assertEqual(self.runs()[0]["status"], "pending") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_worker_session.py b/tests/test_worker_session.py index 27fa0af..5662c13 100644 --- a/tests/test_worker_session.py +++ b/tests/test_worker_session.py @@ -160,11 +160,11 @@ class UnlistedToolTests(Base): def counts(self): return orchestration._peek(self.sid).get("calls") - def test_an_unlisted_delegation_named_tool_at_the_limit_is_neither_refused_nor_counted(self): + def test_an_unlisted_spawn_named_tool_at_the_limit_is_neither_refused_nor_counted(self): self.transcript(ORDINARY) self.assertEqual(self.reads(6), [False] * 6) n = self.counts() - denied, text = self.hook("mcp__somehost__delegate_task", {"task": "do x", "target": {"model": "alpha-small"}}) + denied, text = self.hook("mcp__somehost__spawn_helper", {"task": "do x"}) self.assertFalse(denied, text) self.assertEqual(self.counts(), n) self.assertTrue(self.reads(1)[0]) # the meter still bites for legwork From 9dc829d04664344afc376d25f8bd69c0e8f6c9c4 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:36:17 -0700 Subject: [PATCH 5/5] Remove the unused exempt-name helper. done: suite green / next: report --- sisi/orchestration.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/sisi/orchestration.py b/sisi/orchestration.py index bacafa0..3cf5b07 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -72,13 +72,6 @@ def meter_note(tool, wired): # ---------------------------------------------------------------- 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):