From 8a884ced7d04290438071a27cbe150525f862086 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 14:02:00 -0700 Subject: [PATCH] Gate sends back an unfinished fallback (twice at most) and a final message that mentions the internal failure; live scenario 2 passes. done: item 9 live assertion / next: docs, timing, repeat runs --- sisi/fallback.py | 12 ++++- sisi/gate.py | 3 +- sisi/orchestration.py | 51 +++++++++++++++++- sisi/rulecmd.py | 3 +- tests/test_meter.py | 90 +++++++++++++++++++++++++++++++ tools/live_orchestration_check.py | 8 +-- 6 files changed, 158 insertions(+), 9 deletions(-) diff --git a/sisi/fallback.py b/sisi/fallback.py index 3a4e823..129540b 100644 --- a/sisi/fallback.py +++ b/sisi/fallback.py @@ -19,6 +19,9 @@ from . import store, workers NOTICE = "" _FAIL_MARKERS = ("[failed]", "api error", "error:", "failed:", "traceback", "exit code") _DEFAULT_KIND = ("implementation", 2) +# what a report of the failure would call it, by class: the final message must not say these after one (state-based) +_REASON_WORDS = {"limit": ("quota", "rate limit", "usage limit", "429"), "auth": ("logged in", "login", "credentials"), + "missing": ("not connected", "not installed"), "error": ("outage",)} def _tag(text, name): @@ -90,7 +93,7 @@ def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=T from . import orchestration worker = worker or workers.identify_worker(text) info = {"worker": worker, "ts": time.time(), "kind": kind, "difficulty": difficulty} - run = None + run, marked = None, None if run_id: run = next((r for r in workers.merged_runs() if r.get("id") == run_id), None) if run: @@ -109,5 +112,12 @@ def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=T workers.append_record({"kind": "run-end", "run_id": run_id, "ts": round(time.time()), "status": "superseded", "ended": round(time.time())}) m["unavail"] = {k: info.get(k) for k in ("worker", "kind", "difficulty", "until", "reason")} + names = set(m.get("unavail_names") or []) + for n in [worker] + list((marked or {}).get("keys") or []): + for part in re.split(r"[/\s]+", str(n or "").lower()): + if len(part) >= 4: + names.add(part) + names.update(("fallback", "fall back", "unavailable") + _REASON_WORDS.get(workers.classify_failure(text)[0], ())) + m["unavail_names"] = sorted(names) orchestration._event(m, sid, "unavailable", worker=worker, run=run_id) return fallback_text(info, cwd, own_model) diff --git a/sisi/gate.py b/sisi/gate.py index 21d5684..6160fe9 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -499,7 +499,8 @@ def _orchestration_step(payload, action): if store.load_session(sid).get("subagent"): return None if action == "allow": - text = orchestration.judgement_sendback(payload, sid) + text = (orchestration.fallback_sendback(payload, sid) or orchestration.judgement_sendback(payload, sid) + or orchestration.report_sendback(payload, sid)) if text: return "block", text orchestration.end_turn(sid) diff --git a/sisi/orchestration.py b/sisi/orchestration.py index 7a47118..4af3650 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -293,7 +293,8 @@ def new_turn(sid, cwd=None, prompt=None): 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, unavail=None) + m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None, + unavail_names=[], report_asked=False, fallback_asked=0) # ---------------------------------------------------------------- messages @@ -638,7 +639,7 @@ def after(payload, host=None): _project(m, cwd) if kind == "delegation": return _after_delegation(payload, ev, sid, m, sess, cwd) - if shell and kind == "exempt" and " delegate" in " " + (cmd or ""): + 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)) if note: # `sisi delegate` recorded the worker down itself; hand over the fallback in the same breath @@ -827,6 +828,52 @@ def judgement_sendback(payload, sid): return "\n".join(lines) +FALLBACK_SENDBACKS = 2 # bounded, like every send-back: a session is never trapped + + +def fallback_sendback(payload, sid): + """The turn is ending with an unavailability recorded and no fallback started: sent back (at most twice) with + the fallback instruction, when the router has a worker to name. State, not wording.""" + from . import fallback, workers + 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): + return None + own = _own_model({}, sess, m) + project = m.get("project") or os.getcwd() + worker, _mech, _n = workers.recommend(info.get("kind") or "implementation", info.get("difficulty") or 2, project, own) + if worker is None: + return None + m["fallback_asked"] = int(m.get("fallback_asked") or 0) + 1 + text = fallback.fallback_text(info, project, own) + return "sisi: not finished: the failed task has not been given to another worker yet.\n" + text + + +def report_sendback(payload, sid): + """The final message to the person names a worker or provider that was unavailable this turn: sent back once, + because which worker is out is internal (SPEC 9.7, 17). Judged on the names recorded, never on the wording.""" + from . import questions + with Meter(sid) as m: + names = m.get("unavail_names") or [] + if not names or m.get("report_asked"): + return None + sess = store.load_session(sid) + final = payload.get("last_assistant_message") # the host's own copy of the final message, when it sends one + if not isinstance(final, str) or not final: + tp = payload.get("transcript_path") if isinstance(payload.get("transcript_path"), str) else sess.get("transcript_path") + turn = questions._last_turn(tp) if isinstance(tp, str) and tp else None + final = turn[0] if turn else "" + low = final.lower() + hits = [n for n in names if n in low] + if not hits: + return None + m["report_asked"] = True + return ("sisi: your final message mentions a worker, provider or failure that was internal (%s). Do not " + "report it. Say only what the person receives and when, and only if that differs from what they expect; " + "then finish again." % ", ".join(hits[:3])) + + # ---------------------------------------------------------------- the unit record def _inside(project, root): diff --git a/sisi/rulecmd.py b/sisi/rulecmd.py index 77dd5b1..e64217b 100644 --- a/sisi/rulecmd.py +++ b/sisi/rulecmd.py @@ -134,7 +134,8 @@ def _orchestrate(): if meter else None, "an unavailable worker (a limit, quota, login or connection failure arriving as a delegation result or as " "a later notice) is recorded down with the reset time parsed from the message, the router's next worker " - "is handed over for the same brief, and a question-dialog call right after it is refused once" + "is handed over for the same brief; a question-dialog call right after it is refused once, ending the turn with no fallback " + "started is sent back once, and so is a final message that names the unavailable worker" if meter and _has("fallback", "handle", "fallback_text") else None, "a delegation with no `sisi route` decision in the last minutes (`orchestrate.route_window_min`) is refused once; " "the run keeps the kind and difficulty guess, and a worker other than the router's pick is recorded as an override" diff --git a/tests/test_meter.py b/tests/test_meter.py index d814b74..ee1bb87 100644 --- a/tests/test_meter.py +++ b/tests/test_meter.py @@ -585,6 +585,11 @@ class FallbackTests(MeterBase): 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 + # the same inside a longer command line (writing the brief and running it in one call) + r = self.sisi("watch", "--after", "--tool", "claude-code", stdin=self.payload( + "PostToolUseFailure", "Bash", {"command": "cat > b.md <<'EOF'\nx\nEOF\nsisi delegate --kind research --difficulty 1 --brief b.md"}, + error="Exit code 1\n" + out)) + self.assertIn("Fall back now", json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"]) 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 @@ -605,6 +610,91 @@ class FallbackTests(MeterBase): self.assertIn("host's own subagent tool", text) self.assertEqual(self.down()["provx"]["retry_at"], future_ts()) + def transcript(self, final): + path = os.path.join(self.tmp, "t.jsonl") + with open(path, "w") as f: + f.write(json.dumps({"type": "user", "message": {"role": "user", "content": "list the files"}}) + "\n") + f.write(json.dumps({"type": "assistant", "message": {"role": "assistant", "content": [{"type": "text", "text": final}]}}) + "\n") + return path + + def stop_with(self, final): + r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps( + {"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", "transcript_path": self.transcript(final)})) + return json.loads(r.stdout) if r.stdout.strip() else {} + + def test_a_final_message_that_names_the_unavailable_worker_is_sent_back_once(self): + """The person is not told which worker is out (SPEC 9.7, 17): judged on the recorded names, once.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb1") # fell back + out = self.stop_with("Done. The provx provider hit its quota so I did it myself.") + self.assertEqual(out.get("decision"), "block") + self.assertIn("internal", out["reason"]) + self.assertIn("provx", out["reason"]) + self.assertEqual(self.stop_with("Done. The provx provider was out."), {}) # once: never a trap + + def test_the_failure_words_are_covered_too(self): + """The provider's name need not appear: "quota" or "fallback" after an unavailability is the same leak.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb5") + out = self.stop_with("Here are the files, from a subagent after the first worker hit its quota.") + self.assertEqual(out.get("decision"), "block") + self.assertIn("quota", out["reason"]) + + def test_the_hosts_own_copy_of_the_final_message_is_used_when_it_is_sent(self): + """Found by the live check: the transcript may not hold the final message yet when the stop hook runs.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb3") + r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps( + {"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", + "last_assistant_message": "The provx provider hit its quota, so I did it myself."})) + self.assertEqual(json.loads(r.stdout).get("decision"), "block") + + def test_ending_the_turn_with_no_fallback_started_is_sent_back_twice_at_most(self): + """Found by the live check: a small model read the instruction and still stopped. State-based, once.""" + self.prompt() + self.launch() + self.prompt(self.notice()) + out = self.stop_with("Here are the 14 files.") + self.assertEqual(out.get("decision"), "block") + self.assertIn("has not been given to another worker", out["reason"]) + self.assertIn("alpha-small", out["reason"]) + self.assertLessEqual(len(out["reason"].splitlines()), 6) + self.assertEqual(self.stop_with("Here are the 14 files.").get("decision"), "block") # a model may ignore it once + self.assertEqual(self.stop_with("Here are the 14 files."), {}) # bounded: never a trap + + def test_no_send_back_when_the_fallback_was_started(self): + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb2") + self.assertEqual(self.stop_with("Here are the 14 files."), {}) + + def test_no_send_back_when_nothing_usable_is_left(self): + os.unlink(workers.ledger_path()) + os.unlink(os.path.join(self.data, "workers.json")) + workers.append_record({"kind": "attempt", "id": "only", "run_id": None, "ts": 1, "project": "p", "type": "research", + "difficulty": 1, "worker": "alpha-small", "outcome": "accepted", "check": "read"}) + self.prompt() + self.prompt(self.notice("[failed]: alpha-small: API error 429: Subscription quota exhausted. Your usage window resets at " + FUTURE)) + self.assertEqual(self.stop_with("Done myself."), {}) + + def test_a_final_message_that_does_not_name_it_is_left_alone(self): + self.prompt() + self.launch() + self.prompt(self.notice()) + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "alpha-small"}, tool_use_id="fb4") + self.assertEqual(self.stop_with("Here are the 14 files, one per line."), {}) + + def test_no_unavailability_no_report_check(self): + self.prompt() + self.assertEqual(self.stop_with("provx was great"), {}) + 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 b8e4df6..eb1ee45 100644 --- a/tools/live_orchestration_check.py +++ b/tools/live_orchestration_check.py @@ -35,10 +35,10 @@ MAIN_MODEL = "haiku" # the host's least expensive model, the 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 " +PROMPT2 = ("This project is in the current directory. Have a worker do one small task: list the python " + "files in src/, one per line. Ask `sisi route --kind research --difficulty 1` who the cheapest suitable worker 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.") + "`sisi delegate --kind research --difficulty 1 --brief brief.md`. The listing must come from a worker, not from your own commands. 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.") @@ -132,7 +132,7 @@ 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", "--include-hook-events", "--setting-sources", "project", "--settings", settings, - "--strict-mcp-config", "--disable-slash-commands", "--no-session-persistence", + "--strict-mcp-config", "--disable-slash-commands", "--permission-mode", "bypassPermissions", "--max-budget-usd", str(args.max_usd), "--tools", "Bash,Read,Edit,Write,Glob,Grep,Agent,AskUserQuestion"] t0 = time.time()