From 64f87e19b67807027fddcbd998f9f26f1bf9a945 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 13:47:44 -0700 Subject: [PATCH] Worker availability is internal: the fallback and dialog refusal say do not ask and do not report; rule 6/7 and orchestration.md reworded; route decision, retry-of, judge hint. done: item 9 correction, 10a/10b code / next: 10d, tests for 10, live scenario 2 --- canon/core.md | 9 ++-- canon/orchestration.md | 14 +++--- config.default.json | 3 +- sisi/fallback.py | 16 +++--- sisi/orchestration.py | 69 ++++++++++++++++++++++--- sisi/store.py | 2 +- sisi/workers.py | 111 +++++++++++++++++++++++++++++++++++++++-- tests/test_meter.py | 23 +++++++-- 8 files changed, 211 insertions(+), 36 deletions(-) diff --git a/canon/core.md b/canon/core.md index fa55cda..2f8cf7a 100644 --- a/canon/core.md +++ b/canon/core.md @@ -86,8 +86,9 @@ work in parallel when it shortens the critical path. Brief a worker with a contr (`sisi delegate brief`), check what comes back in proportion to the risk, and record the judgement (`sisi delegate judge`). Before delegating, ask `sisi route`, which recommends a worker from that record and keeps your difficulty guess. When a worker is unavailable, give the same -brief to the next worker the router names without asking, and tell the person in one line what is -down and what was used. `sisi delegate guide` is the playbook. +brief to the next worker the router names, without asking the person and without reporting it: +worker availability is internal, and only a changed outcome or time is theirs to hear. `sisi delegate guide` +is the playbook. Why: verified value per unit of time, cost and attention is the objective, and the strongest model's attention is the scarcest resource. @@ -97,8 +98,8 @@ model's attention is the scarcest resource. When you finish, say what was delivered, the decisions that matter, what was verified and how, what was not verified, and any risk or follow-up, in proportion to the change. Leave out the story of how you got there. State assumptions and departures from what was asked. Never describe -unverified work as done. Say which worker did what, and what you verified yourself against what -you took on a worker's word. +unverified work as done. Say what you verified yourself and what you took on a worker's word. Leave +out which workers, tools or providers were used or unavailable, unless it changes the outcome. Why: the person acts on your report. A false or padded one costs them more than a late one. diff --git a/canon/orchestration.md b/canon/orchestration.md index 3b6db01..1d32a23 100644 --- a/canon/orchestration.md +++ b/canon/orchestration.md @@ -79,12 +79,14 @@ present; nothing here names one. Read on demand: `sisi delegate guide`. A rejected result never marks a worker down. - When a worker is unavailable (a quota, limit, login or connection failure that reaches you as a delegation result or as a later notice), do not ask - the person whether or when: give the same brief to the next worker the - router names, cancel the failed task so it cannot resume on a stale - branch, and tell the person in one line what is down, why, and what was - used instead. If every other provider is down, use the host's own - subagents and say so; if nothing at all is usable, do the work yourself - and say when the earliest worker is due. + the person whether or when, and do not report it: worker availability, + quotas, retries and routing are internal. Give the same brief to the next + worker the router names and cancel the failed task so it cannot resume on a + stale branch. If every other provider is down, use the host's own + subagents. If nothing at all is usable, do the work yourself. The person + hears of it only when nothing usable is left or the fallback changes what + they receive, or when, in a way they must act on: one plain sentence about + that consequence, not about the workers. ## Keeping the picture current diff --git a/config.default.json b/config.default.json index c62bd34..035b5cd 100644 --- a/config.default.json +++ b/config.default.json @@ -15,6 +15,7 @@ "enabled": true, "direct_calls": 6, "direct_chars": 30000, - "extension": 10 + "extension": 10, + "route_window_min": 15 } } diff --git a/sisi/fallback.py b/sisi/fallback.py index b6b0cf4..bfe8920 100644 --- a/sisi/fallback.py +++ b/sisi/fallback.py @@ -7,9 +7,10 @@ reads a rejected result, and a result that merely mentions a limit in a long rep What the agent is told, in at most six lines: which worker is out and until when, the router's next pick for the same kind of work with its mechanism line (a host-native worker when every other provider is down), to fall -back now with the same brief without asking the person, to say in one line what is down and what was used, and -to cancel the failed task so it cannot resume later on a stale branch. When nothing else is usable it says so -and when the earliest worker is due. +back now with the same brief, neither asking the person nor reporting it to them (worker availability is +internal, SPEC 9.7 and 17), and to cancel the failed task so it cannot resume later on a stale branch. When +nothing else is usable it says so and when the earliest worker is due; the person hears of it only if the +outcome or its timing changes for them, in one plain sentence about that consequence. """ import re, time @@ -70,13 +71,14 @@ def fallback_text(info, cwd, own_model): if worker: return "\n".join([head, "Next for the same kind of work (%s, difficulty %s): %s (%s)." % (kind, diff, worker, mech), - "Fall back now with the same brief. Do not ask the person whether or when; tell them in one " - "line what is down and what was used instead.", cancel]) + "Fall back now with the same brief. Do not ask the person, and do not report this to them: " + "which worker is out is internal.", cancel]) due = workers.earliest_due() return "\n".join([head, "No other worker is usable now%s." % ((" (earliest due: %s at %s)" % (due[0], fmt_time(due[1]))) if due else ""), - "Do the work yourself with this session's own tools meanwhile; do not ask the person whether or " - "when, and tell them in one line what is down and why.", cancel]) + "Do the work yourself with this session's own tools meanwhile; do not ask the person. Tell them " + "only if what they receive, or when, changes in a way they must act on: one plain sentence about " + "that consequence, not about the workers.", cancel]) def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=True): diff --git a/sisi/orchestration.py b/sisi/orchestration.py index 5c7b519..8ec863d 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -34,7 +34,8 @@ def cfg(): 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))} + "direct_chars": max(1, num("direct_chars", 30000)), "extension": max(1, num("extension", 10)), + "route_window_min": max(1, num("route_window_min", 15))} def hosts(): @@ -336,6 +337,27 @@ def refusal_text(m, c, picks, why="budget", detail=""): return "\n".join(lines) +KINDS = ("research", "implementation", "review", "test", "docs", "debug") + + +def route_text(): + return ("sisi: ask the router before delegating (rule 6; it also records your difficulty guess). Run " + "`sisi route --kind K --difficulty N` first: K is one of %s; N is 1 routine, 2 ordinary, 3 hard. " + "This delegation was not started; start it again after." % ", ".join(KINDS)) + + +def record_route(kind, difficulty, worker, cwd, retry_of=None): + """`sisi route` ran: the session's routing decision (kind, difficulty guess, recommended worker, time). Quiet + when no session can be named.""" + sid = find_session(cwd) + if not sid: + return + with Meter(sid) as m: + m["route"] = {"kind": kind, "difficulty": difficulty, "worker": worker, "ts": time.time(), "retry_of": retry_of} + m["route_asked"] = False + _event(m, sid, "route", kind=kind, difficulty=difficulty, worker=worker) + + 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 " @@ -429,7 +451,22 @@ def _own_model(payload, sess, m=None): def before(payload, host=None): - """{"deny": text} to refuse the call, {"context": text} for advice, {} otherwise.""" + """{"deny": text} to refuse the call, {"context": text} for advice, {} otherwise. On a host whose before-tool + hook cannot refuse (canon/orchestration-tools.json), a refusal is recorded as not made and the call goes on.""" + out = _before(payload, host) + if out.get("deny") and refuse_style(host or store.tool() or "claude-code") not in ("json-deny", "exit-2"): + try: + from . import watch + _t, _c, _e, cwd, sid = watch.extract(payload) + with Meter(sid or "cwd-" + cwd) as m: + _event(m, sid or "cwd-" + cwd, "unrefused", why="the host cannot refuse") + except Exception as e: + store.log_error("orchestration-unrefused", e) + return {} + return out + + +def _before(payload, host=None): c = cfg() if not c["enabled"]: return {} @@ -532,12 +569,25 @@ def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd): _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() + route = m.get("route") + if route and now - float(route.get("ts") or 0) > c["route_window_min"] * 60: + route = None # a decision from long ago is no decision + if route is None and not m.get("route_asked"): + m["route_asked"] = True # once: the next delegation goes through even without a decision + m["refusals"] += 1 + _event(m, sid, "refusal", why="route", tool=tool) + return {"deny": route_text()} + run_id = uuid.uuid4().hex[:8] worker = model or own or "(inherited)" + against = None + if route and route.get("worker"): + against = not workers.same_model(worker, route["worker"]) 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, + workers.append_record({"kind": "run", "id": run_id, "ts": round(now), + "type": (route or {}).get("kind"), "difficulty": (route or {}).get("difficulty"), + "route_worker": (route or {}).get("worker"), "chosen_against_route": against, + "retry_of": (route or {}).get("retry_of"), "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: @@ -546,9 +596,12 @@ def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd): m["pending"][key] = {"run": run_id, "t0": now, "worker": worker} 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) - 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)] + known = bool(route and route.get("kind") and route.get("difficulty")) + lines = ["sisi: delegation recorded as run %s%s. When it returns, judge it: `sisi delegate judge %s --outcome " + "accepted|rejected --check read|tests|diffstat|review|none%s`." + % (run_id, (" (%s, difficulty %s%s)" % (route["kind"], route["difficulty"], + "; you chose %s over the router's %s" % (worker, route["worker"]) if against else "")) + if known else "", run_id, "" if known else " --type KIND --difficulty 1|2|3")] if isinstance(text, str): lines += ["sisi brief advice: " + a for a in brief.check(text)] return {"context": "\n".join(lines)} diff --git a/sisi/store.py b/sisi/store.py index 72f5acb..2ede782 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -157,7 +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}, + "orchestrate": {"enabled": True, "direct_calls": 6, "direct_chars": 30000, "extension": 10, "route_window_min": 15}, "scratch": {"session_max_age_days": 30, "prune_every": 20, "prune_max_delete": 1000, "prune_budget_s": 0.25}} diff --git a/sisi/workers.py b/sisi/workers.py index 150a8de..d5f0e94 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -1556,9 +1556,11 @@ def _down_lines(down, limit=3): return ["down now: %s%s" % ("; ".join(shown), more)] -def _route_setup(args): - kind = _opt(args, "--kind") +def _route_setup(args, derived=None): + kind = _opt(args, "--kind") or (derived or {}).get("kind") difficulty = _opt(args, "--difficulty") + if difficulty is None and derived: + difficulty = derived.get("difficulty") if not kind or difficulty is None: return None try: @@ -1570,10 +1572,99 @@ def _route_setup(args): return kind, difficulty +def retry_context(retry_id, records=None): + """What `sisi route --retry-of ID` needs from the judged record: the attempt (ID is an attempt id, or the + id of a run that was judged), its kind and difficulty, and how many results in the retry chain behind it + were rejected in a row, newest first, with the workers that produced them. None when ID is unknown or + its run is not judged yet.""" + records = read_records() if records is None else records + attempts = {r["id"]: r for r in records if r.get("kind") == "attempt" and r.get("id")} + by_run = {r["run_id"]: r for r in attempts.values() if r.get("run_id")} + a = attempts.get(retry_id) or by_run.get(retry_id) + if a is None: + return None + rejected, seen, cur = [], set(), a + while cur is not None and cur["id"] not in seen: + seen.add(cur["id"]) + if cur.get("outcome") != "rejected": + break + rejected.append(cur.get("worker")) + cur = attempts.get(cur.get("retry_of")) + return {"attempt": a, "kind": a.get("type"), "difficulty": a.get("difficulty"), "rejected": rejected} + + +def stronger_choice(candidates, records, kind, difficulty, excluded, prefs, now=None): + """The next worker up after rejections: not one already rejected in the chain, usable and allowed as in any + route, then the strongest by the judged record or the stored benchmark standing; a host-native worker ahead + of the unknown when nothing is known. None when nobody else is usable.""" + now = time.time() if now is None else now + pool, ordered = [c for c in candidates if c["worker"] not in excluded], [] + while pool: + c = routing.choose(pool, records, read_availability(), kind, difficulty, now=now, + avoid=prefs["avoid"], prefer=prefs["prefer"])["choice"] + if c is None: + break + ordered.append(c) + pool = [x for x in pool if x is not c] + scores = strength_scores(candidates, records) + + def key(ic): + i, c = ic + known = scores.get(c["worker"]) + return (0, -known[0], i) if known else (1, 0 if c.get("host_native") else 1, i) + return min(enumerate(ordered), key=key)[1] if ordered else None + + +RETRY_BRIEF_LINE = ("retry: most failures are brief failures. Improve the brief (what was missing, what is known now, " + "the exact failure) and check it with `sisi delegate check`, then give it to this same worker once more.") + + +def _route_retry(args, ctx, kind, difficulty, candidates, records, prefs): + """Print the pick for a retry and return (worker or None). The first rejection keeps the worker and asks for + a better brief; a second rejection in the chain moves up.""" + rejected = ctx["rejected"] + same = next((c for c in candidates if c["worker"] == rejected[0]), None) if len(rejected) == 1 else None + if same is not None: + usable = routing.choose([same], records, read_availability(), kind, difficulty, now=time.time(), + avoid=prefs["avoid"], prefer=prefs["prefer"])["choice"] + if usable is not None: + print(usable["worker"]) + print("mechanism: %s" % mechanism_for(usable)) + print(RETRY_BRIEF_LINE) + return usable + pick = stronger_choice(candidates, records, kind, difficulty, set(rejected), prefs) + if pick is None: + print("no stronger usable worker for kind %s at difficulty %d after rejections by %s" + % (kind, difficulty, ", ".join(sorted(set(rejected))))) + return None + print(pick["worker"]) + print("mechanism: %s" % mechanism_for(pick)) + print("stronger: %s was rejected%s, so it is excluded; this is the next one up by the judged record or benchmark standing." + % (", ".join(sorted(set(rejected))), " twice in this chain" if len(rejected) > 1 else "")) + return pick + + +def route_decision(kind, difficulty, worker, retry_of=None): + """Write the routing decision for the session this command runs in (see orchestration.record_route).""" + try: + from . import orchestration + orchestration.record_route(kind, difficulty, worker, os.getcwd(), retry_of) + except Exception as e: + store.log_error("route-decision", e) + + def cmd_route(args=()): - setup = _route_setup(args) + retry_id = _opt(args, "--retry-of") + ctx = None + if retry_id: + ctx = retry_context(retry_id) + if ctx is None: + print("sisi route: no judged delegation with id %s (judge the run first: `sisi delegate judge`)" % retry_id, + file=sys.stderr) + return 1 + setup = _route_setup(args, ctx) if setup is None: - print("usage: sisi route --kind K --difficulty 1|2|3 [--review-of WORKER] [--explain]") + print("usage: sisi route --kind K --difficulty 1|2|3 [--review-of WORKER] [--explain] | --retry-of ID") return 1 kind, difficulty = setup records = read_records() @@ -1581,6 +1672,10 @@ def cmd_route(args=()): prefs = effective_prefs(kind, difficulty, os.getcwd()) everyone = candidates candidates, limited = apply_limits(candidates, prefs) + if ctx is not None and ctx["rejected"]: + pick = _route_retry(args, ctx, kind, difficulty, candidates, records, prefs) + route_decision(kind, difficulty, pick["worker"] if pick else None, ctx["attempt"]["id"]) + return 0 if pick else 1 result = routing.choose(candidates, records, read_availability(), kind, difficulty, review_of=_opt(args, "--review-of"), now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"]) @@ -1588,6 +1683,7 @@ def cmd_route(args=()): by_worker = {c["worker"]: c for c in everyone} down = _down_now(read_availability(), time.time()) if result["choice"] is None: + route_decision(kind, difficulty, None, ctx["attempt"]["id"] if ctx else None) print("no usable worker for kind %s at difficulty %d" % (kind, difficulty)) for line in _down_lines(down): print(line) @@ -1598,6 +1694,7 @@ def cmd_route(args=()): for line in routing.explain_choice(result, kind, difficulty)[1:]: print(line) return 1 + route_decision(kind, difficulty, result["choice"]["worker"], ctx["attempt"]["id"] if ctx else None) print(result["choice"]["worker"]) print("mechanism: %s" % mechanism_for(result["choice"])) for line in _down_lines(down): @@ -1778,7 +1875,8 @@ def _cmd_judge(args): "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} + "retry_of": run.get("retry_of"), "note": None, + "route_worker": run.get("route_worker"), "chosen_against_route": run.get("chosen_against_route")} 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"): @@ -1820,6 +1918,9 @@ def _cmd_judge(args): # it never marks the worker unavailable. clear_down(rec["worker"]) print(rec["id"]) + if rec["outcome"] == "rejected": + print("next: `sisi route --retry-of %s` names the worker for the retry (the same one with a better brief first, " + "a stronger one after a second rejection)" % rec["id"]) return 0 diff --git a/tests/test_meter.py b/tests/test_meter.py index ee6b915..1c82cf3 100644 --- a/tests/test_meter.py +++ b/tests/test_meter.py @@ -17,6 +17,9 @@ def seed_workers(case, names=("alpha-small", "beta-large")): "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) + # a fresh discovery cache (no command-line tool installed): no test ever runs a real tool's model listing + with open(os.path.join(case.data, "workers.json"), "w") as f: + json.dump({"checked": time.time(), "tools": [{"name": "opencode", "installed": False, "models": [], "usable": False}]}, f) class MeterBase(SisiCase): @@ -41,9 +44,18 @@ class MeterBase(SisiCase): 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( + def prompt(self, text="fix the parser and explain each module in the project", sid=None, route=True): + """A prompt reaches the session; by default the agent has also asked `sisi route` (a delegation needs that).""" + r = self.sisi("prompt", "--tool", "claude-code", stdin=json.dumps( {"session_id": sid or self.sid, "cwd": self.proj, "hook_event_name": "UserPromptSubmit", "prompt": text})) + if route and not text.startswith("") and not text.startswith("[failed]") \ + and not text.startswith("You are a worker"): + self.route(sid=sid) + return r + + def route(self, kind="research", difficulty="1", *extra, sid=None): + return self.sisi("route", "--kind", kind, "--difficulty", difficulty, *extra, + env={"SISI_SESSION_ID": sid or self.sid}) def pre(self, tool="Read", inp=None, **kw): """The decoded hook output of one before-tool call: (denied, reason, whole output).""" @@ -544,8 +556,8 @@ class FallbackTests(MeterBase): self.assertIn("2036-11-30 05:00 UTC", ctx) self.assertIn("alpha-small", ctx) # every prefixed provider is down: host-native self.assertIn("host's own subagent tool", ctx) - self.assertIn("do not ask the person", ctx.lower().replace("not ask", "not ask")) - self.assertIn("one line", ctx) + self.assertIn("Do not ask the person, and do not report this to them", ctx) + self.assertNotIn("tell them", ctx.lower()) # worker availability is internal (SPEC 9.7, 17) self.assertIn("Cancel or interrupt", ctx) def test_the_same_through_a_delegation_tool_result(self): @@ -593,6 +605,7 @@ class FallbackTests(MeterBase): self.assertTrue(denied) self.assertIn("alpha-small", reason) self.assertIn("do not ask the person", reason.lower()) + self.assertIn("do not report this to them", reason.lower()) self.assertFalse(self.pre("AskUserQuestion", {"questions": [{"question": "something else"}]})[0]) self.assertEqual([e["why"] for e in self.events("refusal")], ["question-after-unavailable"]) @@ -617,6 +630,8 @@ class FallbackTests(MeterBase): "Your usage window resets at " + FUTURE, use_id="zz"))) self.assertIn("No other worker is usable now", ctx) self.assertIn("earliest due: alpha-small at 2036-11-30 05:00 UTC", ctx) + self.assertIn("only if what they receive, or when, changes", ctx) # the one case the person hears of it + self.assertIn("not about the workers", ctx) self.assertLessEqual(len(ctx.splitlines()), 6) self.assertFalse(self.pre("AskUserQuestion", {"questions": []})[0])