From e616fc968bdd1d9f194c30c02c28beadd4239cdf Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 13:54:28 -0700 Subject: [PATCH] Live check scenarios (route then delegate; automatic fallback with no question and a silent report); fix hook event name on tool failure; sisi delegate says fall back now. done: live scenarios / next: docs, timing, repeat runs --- sisi/fallback.py | 4 +- sisi/orchestration.py | 5 +- sisi/watch.py | 4 +- sisi/workers.py | 16 ++- tests/test_meter.py | 33 +++++ tools/live_orchestration_check.py | 213 +++++++++++++++++++++++------- 6 files changed, 220 insertions(+), 55 deletions(-) diff --git a/sisi/fallback.py b/sisi/fallback.py index bfe8920..3a4e823 100644 --- a/sisi/fallback.py +++ b/sisi/fallback.py @@ -81,7 +81,7 @@ def fallback_text(info, cwd, own_model): "that consequence, not about the workers.", cancel]) -def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=True): +def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=True, kind=None, difficulty=None): """A failure message arrived. Classify it; record the worker down (when it can be identified and `record`); mark its pending run superseded; remember it in the meter for the question-dialog check; return the fallback text, or None when the text is not an unavailability. Never raises past the caller's guard.""" @@ -89,7 +89,7 @@ def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=T return None from . import orchestration worker = worker or workers.identify_worker(text) - info = {"worker": worker, "ts": time.time()} + info = {"worker": worker, "ts": time.time(), "kind": kind, "difficulty": difficulty} run = None if run_id: run = next((r for r in workers.merged_runs() if r.get("id") == run_id), None) diff --git a/sisi/orchestration.py b/sisi/orchestration.py index 8ec863d..7a47118 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -642,7 +642,10 @@ def after(payload, host=None): from . import fallback note = fallback.shell_notice(_flat(payload)) if note: # `sisi delegate` recorded the worker down itself; hand over the fallback in the same breath - text = fallback.handle(m, sid, cwd, note[1], own_model=_own_model(payload, sess, m), worker=note[0], record=False) + km = re.search(r"--kind[ =](\S+)", cmd or "") + dm = re.search(r"--difficulty[ =]([123])\b", cmd or "") + text = fallback.handle(m, sid, cwd, note[1], own_model=_own_model(payload, sess, m), worker=note[0], record=False, + kind=km.group(1) if km else None, difficulty=int(dm.group(1)) if dm else None) return {"context": text} if text else {} if shell: key = _norm(cmd) diff --git a/sisi/watch.py b/sisi/watch.py index 04cd89a..045e748 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -272,7 +272,9 @@ def main(args=()): payload = gate._read_payload() _tool, _cmd, ev, _cwd, _sid = extract(payload) out = run(payload, args) - text = render_claude(out, "PreToolUse" if ("--before" in args or ev in BEFORE_EVENTS) else "PostToolUse") + before_call = "--before" in args or ev in BEFORE_EVENTS + # the host rejects output whose event name is not the event it is answering (found by the live check) + text = render_claude(out, "PreToolUse" if before_call else (ev if ev in AFTER_EVENTS else "PostToolUse")) if text: import sys sys.stdout.write(text + "\n") diff --git a/sisi/workers.py b/sisi/workers.py index d217eb7..859f9ef 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -1299,7 +1299,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev notes.append("sisi: %s is a host-native worker; start it with the host's own subagent tool " "(`sisi delegate` runs only command-line tools)" % cand["worker"]) return None, None, notes - candidates = [c for c in apply_limits(candidates, prefs)[0] if not c.get("host_native")] + limited = apply_limits(candidates, prefs)[0] + candidates = [c for c in limited if not c.get("host_native")] while True: if cand is None: prefs = effective_prefs(kind, difficulty, cwd) @@ -1308,7 +1309,15 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev avoid=prefs["avoid"], prefer=prefs["prefer"]) cand = result["choice"] if cand is None: - notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty)) + native = routing.choose([c for c in limited if c.get("host_native")], read_records(), read_availability(), + kind, difficulty, now=time.time(), exclude=tried, + avoid=prefs["avoid"], prefer=prefs["prefer"])["choice"] + if native is not None: # every command-line worker is out: the host's own subagents take it, at once + notes.append("sisi: no command-line worker remains for kind %s at difficulty %s. Fall back now with the " + "same brief: %s (model %s). Do not ask the person and do not report this to them: " + "which worker is out is internal." % (kind, difficulty, mechanism_for(native), native.get("model") or native["worker"])) + else: + notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty)) return None, None, notes tried.append(cand["worker"]) if "contributor" in str(cand.get("model") or cand["worker"]).lower(): @@ -1343,7 +1352,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev failure = classify_failure(out + "\n" + err, rc) if failure is not None: reason, note, retry = failure - record_down(_down_keys(cand, reason), reason, note, retry_after_s=retry) + until = parse_reset(out + "\n" + err) # the time the message itself names, when it names one + record_down(_down_keys(cand, reason), reason, note, retry_after_s=None if until else retry, until_ts=until) mark_discovery_stale() notes.append("%s is unavailable (%s: %s); trying the next choice" % (cand["worker"], reason, note)) cand = None diff --git a/tests/test_meter.py b/tests/test_meter.py index 80ffeaa..d814b74 100644 --- a/tests/test_meter.py +++ b/tests/test_meter.py @@ -572,6 +572,39 @@ class FallbackTests(MeterBase): self.assertEqual(run["status"], "superseded") # never asked to be judged self.assertEqual(workers.unjudged_runs(), []) + def test_a_failing_sisi_delegate_run_hands_over_the_fallback_under_the_event_name_the_host_expects(self): + """Found by the live check: the host rejects hook output whose event name is not the event it answers.""" + self.prompt() + out = ("fakeprov/model-1 is unavailable (limit: API error 429: Subscription quota exhausted. Your usage window resets at " + + FUTURE + "); trying the next choice\nsisi: no usable worker remains for kind research at difficulty 1") + r = self.sisi("watch", "--after", "--tool", "claude-code", stdin=self.payload( + "PostToolUseFailure", "Bash", {"command": "sisi delegate --kind research --difficulty 1 --brief b.md"}, + error="Exit code 1\n" + out)) + hs = json.loads(r.stdout)["hookSpecificOutput"] + self.assertEqual(hs["hookEventName"], "PostToolUseFailure") + self.assertIn("Next for the same kind of work (research, difficulty 1)", hs["additionalContext"]) + self.assertIn("Do not ask the person", hs["additionalContext"]) + self.assertEqual(self.down(), {}) # `sisi delegate` recorded it itself; the hook does not do it twice + + def test_sisi_delegate_itself_tells_the_agent_to_fall_back_when_only_host_workers_remain(self): + """Found by the live check: a small model stopped at "no usable worker remains"; the command's own output now + carries the instruction, and the reset time in the message is what is recorded.""" + fake = os.path.join(self.tmp, "fakebin") + os.makedirs(fake) + with open(os.path.join(fake, "opencode"), "w") as f: + f.write("#!/bin/sh\necho 'API error 429: Subscription quota exhausted. Your usage window resets at %s' >&2\nexit 1\n" % FUTURE) + os.chmod(os.path.join(fake, "opencode"), 0o755) + brief = os.path.join(self.proj, "brief.md") + with open(brief, "w") as f: + f.write("## Outcome and scope\nlist files\n## Acceptance\none per line\n## Files you may change\nnone\n") + r = self.sisi("delegate", "--kind", "research", "--difficulty", "1", "--brief", brief, + env={"PATH": fake + os.pathsep + os.environ["PATH"]}) + text = r.stdout + r.stderr + self.assertIn("Fall back now with the same brief", text) + self.assertIn("Do not ask the person and do not report this to them", text) + self.assertIn("host's own subagent tool", text) + self.assertEqual(self.down()["provx"]["retry_at"], future_ts()) + def test_a_tool_failure_event_for_the_delegation_counts_too(self): self.prompt() self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="t8") diff --git a/tools/live_orchestration_check.py b/tools/live_orchestration_check.py index e5627fe..b8e4df6 100644 --- a/tools/live_orchestration_check.py +++ b/tools/live_orchestration_check.py @@ -17,7 +17,14 @@ What it does: `sisi unit direct`, (c) the temporary ledger or unit telemetry holds the matching record, (d) nothing under the real sisi data folder changed. -Exit status 0 only when all four hold. Options: --keep (leave the temporary folder), --model NAME, --max-usd N. +A second short scenario proves the automatic fallback: the fixture has one prefixed provider whose fake +command-line tool always prints a quota error with a reset time, and another usable worker; the main thread is +asked to delegate a small task to the cheapest worker. It asserts that the provider was marked down until the +parsed time, that the session went on to use another worker, that it never called the question dialog, and that +its final message to the person says nothing about the provider, a quota, a limit or a fallback. + +Exit status 0 only when everything holds. Options: --keep (leave the temporary folder), --model NAME, --max-usd N, +--only 1|2 (run one scenario). """ import argparse, hashlib, json, os, shutil, subprocess, sys, tempfile, time @@ -26,6 +33,12 @@ sys.path.insert(0, REPO) MAIN_MODEL = "haiku" # the host's least expensive model, the main thread WORKERS = (("sonnet", 3), ("opus", 15)) # fixture workers (names the host's subagent tool accepts) and a price each +RESET = "2036-12-01T00:00:00Z" # the reset time the fake provider's error message names +QUOTA_TEXT = ("API error 429 [request_id=req_live]: Subscription quota exhausted. Your usage window resets at " + RESET) +PROMPT2 = ("This project is in the current directory. Delegate one small task to the cheapest worker: list the python " + "files in src/, one per line. Ask `sisi route --kind research --difficulty 1` who that is, write the brief " + "(`sisi delegate brief` prints the template; save it as brief.md), and run it with " + "`sisi delegate --kind research --difficulty 1 --brief brief.md`. The list is what I want back: reply with it.") PROMPT = ("This project is in the current directory. Find and fix the bug (a test in tests/ fails), then tell me " "what each file in src/ does, one line per file.") @@ -66,6 +79,30 @@ def fixture_ledger(data): json.dump({"models": {w: {"cost_per_million_tokens": p} for w, p in WORKERS}}, f) +def fixture_fallback(data, tmpbin): + """Scenario 2: the cheapest worker is a fake provider whose command-line tool always answers with a quota error.""" + os.makedirs(data, exist_ok=True) + rows = [] + for w in ("fakeprov/fake-model", "sonnet", "opus"): + rows.append({"kind": "attempt", "id": "x%s" % w[:3], "run_id": None, "ts": 1, "project": "fixture", + "type": "research", "difficulty": 1, "worker": w, "outcome": "accepted", "check": "read"}) + with open(os.path.join(data, "delegations.jsonl"), "w") as f: + f.write("".join(json.dumps(r) + "\n" for r in rows)) + with open(os.path.join(data, "worker-prices.json"), "w") as f: + json.dump({"models": {"fakeprov/fake-model": {"cost_per_million_tokens": 0.1}, "sonnet": {"cost_per_million_tokens": 3}, + "opus": {"cost_per_million_tokens": 15}}}, f) + with open(os.path.join(data, "workers.json"), "w") as f: # a fresh discovery, so no real tool is ever listed + json.dump({"checked": time.time(), "tools": [{"name": "opencode", "installed": True, "usable": True, + "models": ["fakeprov/fake-model"], "learned_by_use": False}]}, f) + with open(os.path.join(data, "config.json"), "w") as f: + json.dump({"workers": {"refresh_after_s": 1e12}}, f) + exe = os.path.join(tmpbin, "opencode") + with open(exe, "w") as f: + f.write("#!/bin/sh\nif [ \"$1\" = models ]; then echo fakeprov/fake-model; exit 0; fi\n" + "echo '%s' >&2\nexit 1\n" % QUOTA_TEXT) + os.chmod(exe, 0o755) + + def real_data_dir(): env = dict(os.environ) for k in ("SISI_DATA", "SISI_HOME"): @@ -91,13 +128,13 @@ def snapshot(d): return rows -def run_agent(args, tmp, proj, env, log): +def run_agent(args, tmp, proj, env, log, prompt=PROMPT): settings = os.path.join(tmp, "home", ".claude", "settings.json") - cmd = ["claude", "-p", PROMPT, "--model", args.model, "--output-format", "stream-json", "--verbose", + cmd = ["claude", "-p", prompt, "--model", args.model, "--output-format", "stream-json", "--verbose", "--include-hook-events", "--setting-sources", "project", "--settings", settings, "--strict-mcp-config", "--disable-slash-commands", "--no-session-persistence", "--permission-mode", "bypassPermissions", "--max-budget-usd", str(args.max_usd), - "--tools", "Bash,Read,Edit,Write,Glob,Grep,Agent"] + "--tools", "Bash,Read,Edit,Write,Glob,Grep,Agent,AskUserQuestion"] t0 = time.time() with open(log, "w") as f: p = subprocess.run(cmd, cwd=proj, env=env, stdout=f, stderr=subprocess.PIPE, text=True, stdin=subprocess.DEVNULL, @@ -134,22 +171,14 @@ def parse(log): return calls, results, events -def main(argv): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--keep", action="store_true") - ap.add_argument("--model", default=MAIN_MODEL) - ap.add_argument("--max-usd", type=float, default=1.0) - args = ap.parse_args(argv) - if shutil.which("claude") is None: - print("live check: the host's command-line tool (claude) is not installed here; nothing was run") - return 2 - tmp = tempfile.mkdtemp(prefix="sisi-live-") +def setup(prefix): + """A temporary world: project, temporary sisi data and state, hooks installed from this checkout's launcher, a + temporary `sisi` first on PATH. Returns a dict, or None when the install failed.""" + tmp = tempfile.mkdtemp(prefix=prefix) data, state, lib, home, proj = (os.path.join(tmp, n) for n in ("data", "state", "lib", "home", "proj")) os.makedirs(os.path.join(home, ".claude")) os.makedirs(lib) build_project(proj) - real = real_data_dir() - before_real = snapshot(real) base_env = dict(os.environ, SISI_DATA=data, SISI_STATE=state, SISI_LIB=lib) for k in ("SISI_HOME", "SISI_TOOL", "SISI_SESSION_ID", "SISI_WORKER_RUN"): base_env.pop(k, None) @@ -157,18 +186,39 @@ def main(argv): text=True, env=dict(base_env, SISI_HOME=home)) if inst.returncode != 0: print("live check: install into the temporary home failed:\n" + inst.stdout + inst.stderr) - return 1 - fixture_ledger(data) + return None tmpbin = os.path.join(tmp, "bin") os.makedirs(tmpbin) os.symlink(os.path.join(REPO, "bin", "sisi"), os.path.join(tmpbin, "sisi")) env = dict(base_env, PATH=tmpbin + os.pathsep + os.environ.get("PATH", "")) - log = os.path.join(tmp, "stream.jsonl") - rc, err, secs = run_agent(args, tmp, proj, env, log) - calls, results, events = parse(log) - failures, report = [], [] + return {"tmp": tmp, "data": data, "state": state, "proj": proj, "bin": tmpbin, "env": env, + "log": os.path.join(tmp, "stream.jsonl")} - # (a) a refusal from sisi's hook, as the agent received it + +def jsonl(path): + return [json.loads(l) for l in open(path) if l.strip()] if os.path.exists(path) else [] + + +def bash_cmd(call): + return str((call[2] or {}).get("command") or "") if call[1] == "Bash" else "" + + +def final_message(events): + for ev in reversed(events): + if ev.get("type") == "result": + return str(ev.get("result") or "") + return "" + + +def scenario_orchestration(args): + """The meter, the delegation guard and the record, in a real session. Returns (failures, report lines, ctx).""" + w = setup("sisi-live-1-") + if w is None: + return ["install failed"], [], None + fixture_ledger(w["data"]) + rc, err, secs = run_agent(args, w["tmp"], w["proj"], w["env"], w["log"]) + calls, results, events = parse(w["log"]) + failures, report = [], [] refused = [(i, c) for i, c in enumerate(calls) if results.get(c[0], ("", False))[1] and "sisi: " in results[c[0]][0] and "direct tool calls" in results[c[0]][0]] if not refused: @@ -176,47 +226,114 @@ def main(argv): else: first_i, first = refused[0] report.append("refusal text the agent received (call #%d, %s):\n%s" % (first_i + 1, first[1], results[first[0]][0])) - after = calls[first_i + 1:first_i + 3] report.append("the next two tool calls after it:\n" + "\n".join( - " %s %s" % (c[1], json.dumps(c[2])[:300]) for c in after)) - # (b) a delegation naming a model, or a recorded reason + " %s %s" % (c[1], json.dumps(c[2])[:300]) for c in calls[first_i + 1:first_i + 3])) later = calls[first_i + 1:] - deleg = [c for c in later if c[1] in ("Agent", "Task") and str((c[2] or {}).get("model") or "").strip()] - direct = [c for c in later if c[1] == "Bash" and "unit direct" in str((c[2] or {}).get("command") or "")] - if not deleg and not direct: - failures.append("(b) after the refusal the session neither delegated with a model nor ran `sisi unit direct`") - # (c) the matching record in the temporary data - ledger = [json.loads(l) for l in open(os.path.join(data, "delegations.jsonl")) if l.strip()] \ - if os.path.exists(os.path.join(data, "delegations.jsonl")) else [] + routes = [i for i, c in enumerate(later) if "sisi route" in bash_cmd(c)] + deleg = [i for i, c in enumerate(later) if c[1] in ("Agent", "Task") and str((c[2] or {}).get("model") or "").strip()] + direct = [c for c in later if "unit direct" in bash_cmd(c)] + routed_then_delegated = any(d > r for r in routes for d in deleg) + if not routed_then_delegated and not direct: + failures.append("(b) after the refusal the session neither ran `sisi route` and then delegated with a model " + "nor ran `sisi unit direct`") + ledger = jsonl(os.path.join(w["data"], "delegations.jsonl")) runs = [r for r in ledger if r.get("kind") in ("run", "run-end")] - evfile = os.path.join(state, "orchestration.jsonl") - evs = [json.loads(l) for l in open(evfile) if l.strip()] if os.path.exists(evfile) else [] + evs = jsonl(os.path.join(w["state"], "orchestration.jsonl")) exts = [e for e in evs if e.get("ev") == "extension"] - if deleg and not [r for r in runs if r.get("kind") == "run"]: + if routed_then_delegated and not [r for r in runs if r.get("kind") == "run"]: failures.append("(c) the session delegated but the ledger holds no run record") - if direct and not deleg and not exts: + if routed_then_delegated and not [e for e in evs if e.get("ev") == "route"]: + failures.append("(c) the session ran `sisi route` but no routing decision was recorded") + if direct and not routed_then_delegated and not exts: failures.append("(c) the session ran `sisi unit direct` but no extension was recorded " "(its reasons may have been refused as generic)") report.append("ledger lines after the run:\n" + "\n".join(" " + json.dumps(r) for r in runs[-4:] or [" (none)"])) report.append("orchestration events (state):\n" + "\n".join( " " + json.dumps(e) for e in [e for e in evs if e.get("ev") != "chars"][-8:] or [" (none)"])) - # (d) the real sisi data is untouched + report.append("scenario 1: tool calls made by the main thread: %d; refused: %d; host exit status %s; %.0fs" + % (len(calls), len(refused), rc, secs)) + return failures, report, w + + +def scenario_fallback(args): + """The automatic fallback in a real session (item 9g).""" + w = setup("sisi-live-2-") + if w is None: + return ["install failed"], [], None + fixture_fallback(w["data"], w["bin"]) + rc, err, secs = run_agent(args, w["tmp"], w["proj"], w["env"], w["log"], prompt=PROMPT2) + calls, results, events = parse(w["log"]) + failures, report = [], [] + avail = {} + try: + with open(os.path.join(w["data"], "worker-availability.json")) as f: + avail = json.load(f) + except (OSError, ValueError): + pass + sys.path.insert(0, REPO) + from sisi import workers + want = workers._parse_time(RESET) + down = avail.get("fakeprov") or {} + if down.get("retry_at") != want: + failures.append("(g1) the provider was not marked down until the parsed reset time (availability: %s)" + % json.dumps(avail)[:300]) + delegate_i = next((i for i, c in enumerate(calls) if "sisi delegate" in bash_cmd(c) and "brief" not in bash_cmd(c).split("delegate")[1][:8]), None) + after = calls[delegate_i + 1:] if delegate_i is not None else [] + other = [c for c in after if c[1] in ("Agent", "Task") and str((c[2] or {}).get("model") or "").strip() + and "fake" not in str((c[2] or {}).get("model")).lower()] + ledger_runs = [r for r in jsonl(os.path.join(w["data"], "delegations.jsonl")) if r.get("kind") == "run"] + if delegate_i is None: + failures.append("(g2) the session never ran `sisi delegate`") + elif not other: + failures.append("(g2) after the failed worker the session did not go on to use another worker (the host's own subagent tool)") + dialog = [c for c in calls if c[1] == "AskUserQuestion"] + if dialog: + failures.append("(g3) the session called the question dialog %d time(s): %s" % (len(dialog), json.dumps(dialog[0][2])[:200])) + final = final_message(events) + leaked = [t for t in ("fakeprov", "fake-model", "opencode", "quota", "limit", "fallback", "unavailable", "429") + if t in final.lower()] + if leaked: + failures.append("(g4) the final message to the person mentions %s: %s" % (leaked, final[:300])) + report.append("scenario 2: availability file: %s" % json.dumps(avail)) + report.append("calls after the failed worker: " + "; ".join("%s %s" % (c[1], json.dumps(c[2])[:120]) for c in after[:4])) + report.append("ledger runs: " + ("; ".join(json.dumps(r)[:200] for r in ledger_runs[-2:]) or "(none)")) + report.append("question dialog calls: %d; final message to the person: %r" % (len(dialog), final[:300])) + report.append("scenario 2: %d tool calls; host exit status %s; %.0fs" % (len(calls), rc, secs)) + return failures, report, w + + +def main(argv): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--keep", action="store_true") + ap.add_argument("--model", default=MAIN_MODEL) + ap.add_argument("--max-usd", type=float, default=1.0) + ap.add_argument("--only", choices=("1", "2")) + args = ap.parse_args(argv) + if shutil.which("claude") is None: + print("live check: the host's command-line tool (claude) is not installed here; nothing was run") + return 2 + real = real_data_dir() + before_real = snapshot(real) + failures, report, worlds = [], [], [] + for n, fn in (("1", scenario_orchestration), ("2", scenario_fallback)): + if args.only in (None, n): + f, r, w = fn(args) + failures += f + report += r + worlds.append(w) if snapshot(real) != before_real: failures.append("(d) files under the real sisi data folder (%s) changed" % real) - report.append("tool calls made by the main thread: %d; refused: %d; host exit status %s; %.0fs" - % (len(calls), len(refused), rc, secs)) print("\n\n".join(report)) - if rc not in (0, None) and not calls: - print("\nhost stderr:\n" + (err or "")[-1500:]) if failures: print("\nLIVE CHECK FAILED:\n " + "\n ".join(failures)) - print("temporary folder kept: %s" % tmp) + print("temporary folders kept: %s" % ", ".join(w["tmp"] for w in worlds if w)) return 1 - print("\nLIVE CHECK PASSED (a, b, c, d)") - if args.keep: - print("temporary folder kept: %s" % tmp) - else: - shutil.rmtree(tmp, ignore_errors=True) + print("\nLIVE CHECK PASSED (a, b, c, d, g)") + for w in worlds: + if w and args.keep: + print("temporary folder kept: %s" % w["tmp"]) + elif w: + shutil.rmtree(w["tmp"], ignore_errors=True) return 0