From 7bcb6d0325957400cccdab17286490a5046fbf38 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 17:43:32 -0700 Subject: [PATCH] A worker's failure is read from the end of its output only: a run that did its work is no longer marked unavailable for what it read workers.failure_text returns the last 1,500 characters of each stream and nothing for an exit-0 run that printed more than 4,000. Runs, model listings, the learned-tool smoke run, provider and learned-driver phrases, and the after-tool hooks all read that text; the shell hook acts only on a real sisi delegate command and the last note line. sisi delegate --timeout-min N (1 to 120) sets one run's time limit. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 10 + docs/workers.md | 13 +- sisi/discovery.py | 2 +- sisi/fallback.py | 20 +- sisi/helptext.py | 2 +- sisi/orchestration.py | 11 +- sisi/workers.py | 48 ++++- tests/fixtures/exit0_head.txt | 9 + tests/fixtures/exit0_middle.txt | 28 +++ tests/fixtures/exit0_tail.txt | 6 + tests/fixtures/exit1_econnreset.txt | 4 + tests/test_failure_text.py | 299 ++++++++++++++++++++++++++++ 12 files changed, 430 insertions(+), 22 deletions(-) create mode 100644 tests/fixtures/exit0_head.txt create mode 100644 tests/fixtures/exit0_middle.txt create mode 100644 tests/fixtures/exit0_tail.txt create mode 100644 tests/fixtures/exit1_econnreset.txt create mode 100644 tests/test_failure_text.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8dad929..366e887 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,18 @@ All notable changes to this project are recorded here. The format follows ## Unreleased +### Fixed + +- A worker that finished its work is no longer recorded as unavailable because the files it read contain a + failure phrase: a failure is read only from the last 1,500 characters of each output stream, and a run that + exited 0 with more than 4,000 characters printed is not classified (`workers.failure_text`, used by + `sisi delegate`, model listings, learned-tool smoke runs, provider phrases and the after-tool hooks). The shell + hook acts only on a real `sisi delegate` command and on a line that begins with a worker id and + ` is unavailable (`. + ### Added +- `sisi delegate --timeout-min N` (1 to 120) sets the time limit of one run in place of `workers.timeout_s`. - Workers that appear after install become routable: the host's own listing and delegation calls, new command-line tools (`sisi workers learn`), per-provider plans, allowance probes, failure phrases and the owner's vouch (`sisi workers plan|allowance|signature|vouch`). Learned tools that switch off approvals and allowance probes are diff --git a/docs/workers.md b/docs/workers.md index dd230f3..695fa3b 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -53,9 +53,10 @@ or learned from judged results. The strategy is [canon/orchestration.md](../cano or `sisi delegate`). `--explain` says why, briefly, and why the rest were passed over. - `sisi delegate brief` prints the delegation-contract template (eight parts); `sisi delegate check FILE` lists the parts a brief lacks. -- `sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]` +- `sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR] [--timeout-min N]` runs a brief through the worker's own CLI when the host has no delegation of its own. A brief - lacking outcome, acceptance or the files it may change is refused. + lacking outcome, acceptance or the files it may change is refused. `--timeout-min N` (1 to 120) + sets the time limit of this run in place of `workers.timeout_s` (default 15 minutes). - `sisi delegate judge` is the only way a result enters the ledger: by run id for `sisi delegate` runs, or directly (`--worker --type --difficulty`) for work run any other way. It carries outcome, the strongest check applied, minutes, tokens, cost, retry-of, and project, @@ -161,7 +162,13 @@ When a worker fails for a reason that is not about its work (a quota, limit, log arriving as a delegation result or as a host notice), the hooks record it down until the reset time in the message, mark its pending run `superseded` and hand the agent the router's next worker. The agent is told to fall back at once with the same brief and neither ask the person nor report it. `sisi delegate` itself says -the same when only host-native workers remain. Models discovery finds that it had not seen are named once at +the same when only host-native workers remain. A failure is read from the end of what a worker printed, never +from everything it read: `workers.failure_text` returns the last 1,500 characters of each stream, and nothing +when the run exited 0 and printed more than 4,000 (it did its work; a short exit-0 message such as a limit +notice is still read). Every classifier (a run, a model listing, a smoke run of a learned tool, a provider's +own phrases, a learned tool's phrases, the hooks on a host delegation result) reads that text. The shell hook +acts only on a command that really runs `sisi delegate` and only on a line that begins with a worker id and +` is unavailable (`, the last one. Models discovery finds that it had not seen are named once at session start as unproven. Settings under `orchestrate`: `direct_calls`, `direct_chars`, `extension`, `route_window_min`. Mechanics: [design.md](design.md) section 9. diff --git a/sisi/discovery.py b/sisi/discovery.py index 363f502..8ad132e 100644 --- a/sisi/discovery.py +++ b/sisi/discovery.py @@ -659,7 +659,7 @@ def smoke(driver, timeout=None): shutil.rmtree(tmp, ignore_errors=True) text = out + "\n" + err res = {"output": " ".join(text.split())[:600], "seconds": round(time.time() - started, 1)} - fail = workers.classify_failure(text, rc, extra_signatures(driver)) + fail = workers.classify_failure(workers.failure_text(out, err, rc), rc, extra_signatures(driver)) if fail is not None: kind = {"auth": "login", "limit": "quota"}.get(fail[0], "error") return dict(res, ok=False, kind=kind, note=fail[1]) diff --git a/sisi/fallback.py b/sisi/fallback.py index c84e470..b51f8a6 100644 --- a/sisi/fallback.py +++ b/sisi/fallback.py @@ -3,7 +3,8 @@ A worker's unavailability reaches a main session as the result of a delegation tool call (the after-tool hook) or as a later notice that a background or delegated task failed (the prompt hook). Both run the same failure classifier (workers.classify_failure). Unavailability is never a quality judgement: nothing here -reads a rejected result, and a result that merely mentions a limit in a long report is not a failure. +reads a rejected result, and a result that merely mentions a limit in a long report is not a failure: only the last +workers.FAILURE_TAIL_CHARS characters of a message are classified, the same reading `sisi delegate` gives a run's output. 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 @@ -51,10 +52,18 @@ def failure_notice(prompt): return None +_NOTE_LINE = re.compile(r"^([\w.:@+/-]+) is unavailable \(.*$", re.M) + + def shell_notice(output): - """A `sisi delegate` run that already recorded a worker as unavailable: (worker, text) from its output.""" - m = re.search(r"(\S+) is unavailable \(([^)]*)\)", output or "") - return (m.group(1), output) if m else None + """A `sisi delegate` run that already recorded a worker as unavailable: (worker, its note line) from the output. + Only a line that begins with a worker id and ` is unavailable (` is a note (source text or a report that merely + prints the words is not), and the last such line is the one that decides: the run's final state.""" + notes = _NOTE_LINE.findall(output or "") + if not notes: + return None + last = [m for m in _NOTE_LINE.finditer(output)][-1] + return last.group(1), last.group(0) def fmt_time(ts): @@ -89,8 +98,9 @@ def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=T 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.""" from . import orchestration - worker = worker or workers.identify_worker(text) + worker = worker or workers.identify_worker(text) # the whole message may name the worker cand = workers.resolve_worker(worker, workers._cached_candidates()[0]) if worker else None + text = (text or "")[-workers.FAILURE_TAIL_CHARS:] # a failure message is the last thing a tool says; the rest is what it read failure = workers.failure_for(text, cand) # with the worker's provider's phrases and its learned driver's if failure is None: return None diff --git a/sisi/helptext.py b/sisi/helptext.py index 59c9c19..8c0b864 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -33,7 +33,7 @@ LONG = { 'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "" best-matching recipe', 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers fact W --maker M --class C [--released DATE] --source S the maker, class and release date researched for a model\n sisi workers classify [--record FILE [--by WORKER]] the question for a cheap worker (maker, class, release date of routable models), or store its answer\n sisi workers classes MAKER CLASS... --source S | MAKER --remove the classes of a maker, most capable first (a prior between them)\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)\n sisi workers learn NAME [--check FILE | --record FILE | --verify] a new command-line tool: print the brief a cheap worker follows to write its driver (JSON); --record validates it, stores it and runs ONE smoke task, and only a passing driver is used (one that switches off approvals waits for `sisi approve drv-NAME`)\n sisi workers forget NAME remove a learned driver or a provider the host listed\n sisi workers plan PROVIDER flat|free|per-use --source S [--note T] the plan of a provider (one tool can carry several providers, each with its own); a flat or free plan with allowance left costs nothing extra per task, a price fact on its models is their relative cost inside the plan\n sisi workers vouch WORKER --up-to 1|2|3 --why \"OWNER WORDS\" | --remove the word of the owner that a new worker handles up to that difficulty (counted to 2 only when the words were not typed by the owner)\n sisi workers allowance PROVIDER --url URL --header \"Name={secret}\" --secret-from-command CMD --secret-path P --remaining-path P --reset-path P | --command CMD read a provider allowance (the key is fetched at probe time, never stored; waits for `sisi approve probe-PROVIDER`)\n sisi workers signature PROVIDER --match \"TEXT|re:REGEX\" --class auth|limit|missing|error [--until-path P] a provider own failure phrase, consulted before the built-in ones', 'route': ' sisi route --kind K --difficulty N [--review-of W] [--explain]\n the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why', - 'delegate': ' sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook\n sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]\n run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused\n sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]\n record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID\n sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id', + 'delegate': ' sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook\n sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR] [--timeout-min N]\n run one brief on the chosen worker unattended; --timeout-min N (1 to 120) sets the time limit of this run in place of workers.timeout_s; a failure is read from the end of the output only; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused\n sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]\n record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID\n sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id', 'eval': ' sisi eval list|add|run|compare|shadow|judge|status|import\n the evaluation harness: benchmark cases from real work, isolated\n replay, policy comparison and independent judging (see docs/evaluation.md);\n `sisi eval` alone prints status; run without --tasks replays check cases only', 'version': ' sisi version | --version print the product version (the VERSION file in the product folder)', 'help': ' sisi help this text', diff --git a/sisi/orchestration.py b/sisi/orchestration.py index 0189833..17aa1e0 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -763,7 +763,7 @@ def after(payload, host=None): _project(m, cwd) if kind == "delegation": 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 + if shell and runs_sisi_delegate(cmd): # 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 @@ -794,6 +794,15 @@ def after(payload, host=None): return out +_DELEGATE_RUN = re.compile(r"^(?:\w+=\S*\s+)*(?:\S*/)?sisi\s+delegate(?!\S)(?!\s+(?:judge|brief|check|guide|amend|recent)\b)") + + +def runs_sisi_delegate(cmd): + """Does this shell command really run `sisi delegate` (as the first word of one of its commands), as opposed to + only naming it in a path, an argument or text? The subcommands that run no worker do not count.""" + return any(_DELEGATE_RUN.match(seg.strip()) for seg in re.split(r"\n|;|&&|\|\||\||&", cmd or "")) + + def _flat(payload): parts, stack = [], [payload.get(k) for k in _RESP_KEYS if payload.get(k) is not None][:1] while stack: diff --git a/sisi/workers.py b/sisi/workers.py index d9b6d18..984cbee 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -135,6 +135,24 @@ ERROR_SIGNATURES = ( ) +# A worker's output holds everything it read, so a phrase anywhere in it says nothing about the worker. A tool's own +# failure message is the last thing it prints, and a tool that failed to start prints little. So a failure is read only +# from the last FAILURE_TAIL_CHARS of each stream, and a run that exited 0 and printed more than QUIET_SUCCESS_CHARS +# did its work: nothing of it is read for failure (a short exit-0 message such as a limit notice still is). +FAILURE_TAIL_CHARS = 1500 +QUIET_SUCCESS_CHARS = 4000 + + +def failure_text(out, err, returncode=0): + """The only text any failure classifier may read for a command sisi ran itself: the last FAILURE_TAIL_CHARS of + standard output plus the last FAILURE_TAIL_CHARS of standard error; "" when the run exited 0 and printed more than + QUIET_SUCCESS_CHARS in total.""" + out, err = out or "", err or "" + if returncode == 0 and len(out) + len(err) > QUIET_SUCCESS_CHARS: + return "" + return out[-FAILURE_TAIL_CHARS:] + "\n" + err[-FAILURE_TAIL_CHARS:] + + def classify_failure(text, returncode=0, extra=None): """(reason, note, retry_after_s) for a run or listing that never got to do the work, else None. reason is one of auth, limit, missing, error. Text decides even when the exit status is 0. @@ -272,9 +290,9 @@ def _parse_models(driver, out): return models -def _parse_usage(driver, out, err): +def _parse_usage(driver, out, err, rc=0): """(allowance_pct_left, allowance_text, failure) from a tool's own usage command where it has one.""" - failure = classify_failure((out or "") + "\n" + (err or "")) + failure = classify_failure(failure_text(out, err, rc)) if failure and failure[0] == "auth": return None, None, failure if driver.get("usage_kind") == "muse-json": @@ -313,7 +331,7 @@ def _discover_tool(driver): if rc is None: entry.update(usable=False, reason="could not run its model list command") return entry - failure = classify_failure(out + "\n" + err, rc) + failure = classify_failure(failure_text(out, err, rc), rc) models = _parse_models(driver, out) if failure and failure[0] == "auth": entry.update(usable=False, reason=failure[1], failure_reason="auth", models=models) @@ -326,13 +344,13 @@ def _discover_tool(driver): if driver.get("auth_probe") and entry["usable"]: rc, out, err = _run_quiet(driver["auth_probe"]) if rc is not None: - failure = classify_failure(out + "\n" + err, rc) + failure = classify_failure(failure_text(out, err, rc), rc) if failure and failure[0] == "auth": entry.update(usable=False, reason=failure[1], failure_reason="auth") if driver.get("usage") and entry["usable"]: rc, out, err = _run_quiet(driver["usage"]) if rc is not None: - left, text, failure = _parse_usage(driver, out, err) + left, text, failure = _parse_usage(driver, out, err, rc) if failure: entry.update(usable=False, reason=failure[1], failure_reason=failure[0]) else: @@ -1450,7 +1468,7 @@ def _down_keys(cand, reason): return keys -def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, review_of=None, brief_path=None): +def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, review_of=None, brief_path=None, timeout_s=None): """Run the brief on the chosen worker, falling through to the next choice on unavailability. Returns (run_record, final_text, notes) or (None, None, notes).""" notes = [] @@ -1458,7 +1476,7 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev transcript = _transcript_path(run_id) cfg = workers_cfg() try: - timeout = float(cfg.get("timeout_s", DEFAULT_RUN_TIMEOUT_S)) + timeout = float(timeout_s if timeout_s is not None else cfg.get("timeout_s", DEFAULT_RUN_TIMEOUT_S)) except (TypeError, ValueError): timeout = DEFAULT_RUN_TIMEOUT_S tried = [] @@ -1525,10 +1543,11 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev % (cand["worker"], timeout, transcript)) return None, None, notes _append_transcript(transcript, cand["worker"], cmd, out, err, rc) - failure = failure_for(out + "\n" + err, cand, rc) + tail = failure_text(out, err, rc) # a failure is read from the end of the output, never from what the worker read + failure = failure_for(tail, cand, rc) if failure is not None: reason, note, retry = failure - until = parse_reset(out + "\n" + err) # the time the message itself names, when it names one + until = parse_reset(tail) # the time the message itself names, when it names one if until is None and reason == "limit": until = _D.limit_until(cand) # else the provider's allowance probe, when one is defined record_down(_down_keys(cand, reason), reason, note, retry_after_s=None if until else retry, until_ts=until, @@ -2058,7 +2077,7 @@ def cmd_delegate(args=()): setup = _route_setup(args) brief = _opt(args, "--brief") if setup is None or not brief: - print("usage: sisi delegate --kind K --difficulty 1|2|3 --brief FILE [--worker W] [--review-of W] [--cwd DIR]") + print("usage: sisi delegate --kind K --difficulty 1|2|3 --brief FILE [--worker W] [--review-of W] [--cwd DIR] [--timeout-min N]") return 1 kind, difficulty = setup try: @@ -2077,6 +2096,13 @@ def cmd_delegate(args=()): if not os.path.isdir(cwd): print("sisi delegate: not a folder: %s" % cwd, file=sys.stderr) return 1 + timeout_s = None + if any(a == "--timeout-min" or a.startswith("--timeout-min=") for a in args): + minutes = _opt(args, "--timeout-min", "") + if not re.fullmatch(r"\d{1,3}", minutes or "") or not 1 <= int(minutes) <= 120: + print("sisi delegate: --timeout-min wants a whole number of minutes from 1 to 120", file=sys.stderr) + return 1 + timeout_s = int(minutes) * 60 candidates = build_candidates() spent = _D.apply_allowances(candidates) explicit = None @@ -2093,7 +2119,7 @@ def cmd_delegate(args=()): candidates, _cold, _excluded = routable_candidates(candidates, read_records()) rec, final, notes = run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=explicit, review_of=_opt(args, "--review-of"), - brief_path=os.path.abspath(brief)) + brief_path=os.path.abspath(brief), timeout_s=timeout_s) for n in notes: print(n) if rec is None: diff --git a/tests/fixtures/exit0_head.txt b/tests/fixtures/exit0_head.txt new file mode 100644 index 0000000..223ad99 --- /dev/null +++ b/tests/fixtures/exit0_head.txt @@ -0,0 +1,9 @@ +## Outcome and scope +Grade how well this repository (the product `sisi`) meets one part of its specification. The 42 requirements -m zai-coding-plan/glm-5.4 +exit: 0 +--- stdout --- +`.agent-work/grade/A.json` is written and `python3 .agent-work/grade/check_chunk.py A` prints `ok 42` (exit 0). + +**Counts (42):** met 3, partial 31, missing 0, not-applicable 8. + +- **Met:** R-3.2-9, R-3.3-1, R-3.3-2 (the gate's send-back and unverified release; the scorecard with no aggregate). diff --git a/tests/fixtures/exit0_middle.txt b/tests/fixtures/exit0_middle.txt new file mode 100644 index 0000000..728aa19 --- /dev/null +++ b/tests/fixtures/exit0_middle.txt @@ -0,0 +1,28 @@ + 881 sisi/overlay.py + 940 sisi/unitguard.py + 1003 sisi/unit.py + 1044 sisi/routing.py + 1113 sisi/orchestration.py + 1285 SPEC.md + 1414 sisi/cycle.py + 1556 sisi/evaluate.py + 1622 sisi/adapters.py +--- stderr --- + +> build · glm-5.4 +! retrying (attempt 2): Rate limit reached for requests +→ Read .agent-work/grade/check_chunk.py +→ Read .agent-work/grade/req-D.json +$ ls -la && ls .agent-work/grade/ && wc -c .agent-work/grade/req-D.json SPEC.md docs/design.md + 881 sisi/overlay.py + 940 sisi/unitguard.py + 1003 sisi/unit.py + 1044 sisi/routing.py + 1113 sisi/orchestration.py + 1414 sisi/cycle.py + 1556 sisi/evaluate.py + "cwd_flag": "the flag that sets the working folder (for {cwd_flag}), or null", + "plan": "\"free\", \"flat\" (a subscription with an allowance) or \"per-use\"; null when unknown", + "auth_signatures": "lowercase phrases its output contains when it is not logged in (6 to 80 characters each)", + "limit_signatures": "lowercase phrases its output contains when a quota or rate limit is hit", + "tokens_regex": "a regular expression with ONE group that captures the total token count from its output, or null", diff --git a/tests/fixtures/exit0_tail.txt b/tests/fixtures/exit0_tail.txt new file mode 100644 index 0000000..4a112b5 --- /dev/null +++ b/tests/fixtures/exit0_tail.txt @@ -0,0 +1,6 @@ +exit=0 +39 {'partial': 34, 'missing': 4, 'met': 1} +evidence paths and test names resolve +B.json is git-ignored (untracked output) +> build · glm-5.4 + diff --git a/tests/fixtures/exit1_econnreset.txt b/tests/fixtures/exit1_econnreset.txt new file mode 100644 index 0000000..2ae1d73 --- /dev/null +++ b/tests/fixtures/exit1_econnreset.txt @@ -0,0 +1,4 @@ +=== zai-coding-plan/glm-5.3-flash +$ opencode run You are a worker. Do this task yourself; do not delegate it further. +--- stderr --- +Error: Transport: ECONNRESET: The socket connection was closed unexpectedly. For more information, pass `verbose: true` in the second argument to fetch() diff --git a/tests/test_failure_text.py b/tests/test_failure_text.py new file mode 100644 index 0000000..20eea7f --- /dev/null +++ b/tests/test_failure_text.py @@ -0,0 +1,299 @@ +"""A worker's failure is read from the END of what it printed, never from everything it read. + +A worker's output holds every file it read, so a run that did its work was thrown away as "not logged in" or a +limit because the words were in a file it had opened, and its provider was marked down for days. A tool's own failure +message is the last thing it prints and a tool that failed to start prints little: `workers.failure_text` returns the +only text any classifier may read (the last 1,500 characters of each stream; nothing when the run exited 0 and printed +more than 4,000). The fixtures are trimmed parts of three real runs that exited 0 (each recorded as an auth failure +on 2026-11-23) and one that ended in a connection error. + +Requirements: R-6-1 and R-9.7 (worker availability is recorded only when the worker was unavailable), R-4-4 (a result +that did not fail is not reported as failed).""" +import contextlib, io, json, os, time, unittest +from unittest import mock + +import test_meter as TM +import test_providers as TP +from support import * +from sisi import fallback, orchestration, workers + +FIX = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures") +SOURCE_LINE = ' notes.append("%s is unavailable (%s: %s); trying the next choice" % (cand["worker"], reason, note))' + + +def fixture(name): + with open(os.path.join(FIX, name), encoding="utf-8") as f: + return f.read() + + +def big_exit0_output(size=60000, final="Done. The monthly usage limit was never an issue for this run."): + """About `size` characters: a real run's opening, its middle (files it read: they hold the words 'rate limit' + and the number 1113) repeated with the other failure phrases added, and a closing line.""" + middle = fixture("exit0_middle.txt") + sprinkle = "not logged in\n401 unauthorized\nbilling\nrate limit\n1113\n" + parts = [fixture("exit0_head.txt")] + while sum(len(p) for p in parts) < size - 400: + parts.append(middle + sprinkle) + parts.append(fixture("exit0_tail.txt").replace("--- stderr ---", "")) + parts.append(final + "\n") + return "".join(parts) + + +def phrases_only_in_the_middle(): + """A large output whose last 1,500 characters are plain: what a failed run printed before its error.""" + return big_exit0_output() + "a plain line of the report\n" * 100 + + +class FailureTextUnit(unittest.TestCase): + def test_a_run_that_exited_zero_and_printed_a_lot_is_never_classified(self): + out = big_exit0_output() + self.assertGreater(len(out), 50000) + self.assertEqual(workers.failure_text(out, "", 0), "") + self.assertIsNone(workers.classify_failure(workers.failure_text(out, "", 0), 0)) + + def test_a_short_exit_zero_run_is_read_whole(self): + msg = "OpenCode Go monthly usage limit reached. Resets in 3 days." + self.assertIn(msg, workers.failure_text(msg, "", 0)) + self.assertEqual(workers.classify_failure(workers.failure_text(msg, "", 0), 0)[0], "limit") + + def test_a_failed_run_is_read_from_the_end_of_each_stream(self): + out = "usage limit reached\n" + "x" * 20000 + "\nthe end of stdout" + err = "not logged in\n" + "y" * 20000 + "\nError: Transport: ECONNRESET" + text = workers.failure_text(out, err, 1) + self.assertIn("the end of stdout", text) + self.assertIn("ECONNRESET", text) + self.assertNotIn("usage limit", text) + self.assertNotIn("not logged in", text) + self.assertLessEqual(len(text), 2 * workers.FAILURE_TAIL_CHARS + 1) + self.assertIsNone(workers.classify_failure(text, 1)) + + def test_the_two_numbers_are_named_constants(self): + self.assertEqual((workers.FAILURE_TAIL_CHARS, workers.QUIET_SUCCESS_CHARS), (1500, 4000)) + + def test_missing_output_is_not_a_crash(self): + self.assertEqual(workers.failure_text(None, None, None).strip(), "") + + +class Delegations(TP.ProviderCase): + """`sisi delegate --worker zai/b` against a tool whose output and exit status the test sets.""" + TOOL = """#!/bin/sh +if [ "$1" = "models" ]; then echo "zai/a"; echo "zai/b"; echo "other/c"; exit 0; fi +model=""; prev="" +for a in "$@"; do if [ "$prev" = "--model" ]; then model="$a"; fi; prev="$a"; done +case "$model" in + zai/*) + printf '%s' "$FAKE_OUT" + printf '%s' "$FAKE_ERR" >&2 + exit ${FAKE_RC:-0} ;; +esac +echo "other worker report" +exit 0 +""" + + def setUp(self): + super().setUp() + self.sisi("workers", "plan", "zai", "flat", "--source", "owner") + self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "words") + self.fact("zai/a", 3) + self.fact("zai/b", 1) + self.fact("other/c", 2) + self.exe("multi", self.TOOL) + + def go(self, out="", err="", rc=0, worker="zai/b"): + with mock.patch.dict(os.environ, {"FAKE_OUT": out, "FAKE_ERR": err, "FAKE_RC": str(rc)}): + return self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", worker) + + def runs(self): + return [r for r in workers.read_records() if r.get("kind") == "run"] + + def test_a_run_that_finished_its_work_is_not_down_because_of_what_it_read(self): + out = big_exit0_output() + r = self.go(out=out, rc=0) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertNotIn("is unavailable", r.stdout) + self.assertIn("worker: zai/b", r.stdout) + run = self.runs()[-1] + self.assertEqual((run["worker"], run["status"], run["exit"]), ("zai/b", "waiting", 0)) + self.assertEqual(workers.read_availability(), {}) + + def test_a_short_exit_zero_limit_message_is_still_a_limit(self): + msg = ("OpenCode Go monthly usage limit reached. Your plan renews on the first of the month; " + "until then no request is served. " * 3)[:300] + r = self.go(out=msg, rc=0) + self.assertIn("zai/b is unavailable (limit", r.stdout) + self.assertEqual(workers.read_availability()["zai"]["reason"], "limit") + self.assertIn("worker: other/c", r.stdout) + + def test_a_failed_run_that_ended_in_a_connection_error_is_a_failed_run_not_an_unavailable_worker(self): + err = fixture("exit1_econnreset.txt").split("--- stderr ---", 1)[1] + r = self.go(out=phrases_only_in_the_middle(), err="rate limit seen while reading\n" + "z" * 5000 + err, rc=1) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertNotIn("is unavailable", r.stdout) + self.assertEqual(workers.read_availability(), {}) + run = self.runs()[-1] + self.assertEqual((run["worker"], run["status"], run["exit"]), ("zai/b", "failed", 1)) + + def test_a_failed_run_whose_stderr_ends_in_a_limit_message_is_a_limit_and_the_next_choice_runs(self): + err = "\n" + "z" * 5000 + "\nError: monthly usage limit reached for this plan\n" + r = self.go(out=phrases_only_in_the_middle(), err=err, rc=1) + self.assertIn("zai/b is unavailable (limit", r.stdout) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("other worker report", r.stdout) + self.assertIn("zai", workers.read_availability()) + + def test_a_provider_phrase_in_the_middle_of_a_large_successful_output_is_not_a_failure(self): + self.assertEqual(self.sisi("workers", "signature", "zai", "--match", "re:\\b1113\\b", "--class", "auth").returncode, 0) + out = "x" * 3000 + "\nsisi/orchestration.py has 1113 lines\n" + "y" * 3000 + "\nall done\n" + r = self.go(out=out, rc=0) + self.assertNotIn("is unavailable", r.stdout) + self.assertEqual(self.runs()[-1]["status"], "waiting") + self.assertEqual(workers.read_availability(), {}) + + def test_the_same_provider_phrase_at_the_end_of_a_failed_run_is_still_read(self): + self.sisi("workers", "signature", "zai", "--match", "re:\\b1113\\b", "--class", "auth") + r = self.go(out="x" * 5000, err='{"error":{"code":"1113","message":"no package"}}', rc=1) + self.assertIn("zai/b is unavailable (auth", r.stdout) + self.assertEqual(workers.read_availability()["zai"]["reason"], "auth") + + +class Timeout(TP.ProviderCase): + def setUp(self): + super().setUp() + self.fact("zai/b", 1) + + def delegate(self, *extra, cfg=None): + if cfg: + self.write_cfg(dict({"discovery": {"allowance_timeout_s": 1}}, **cfg)) + seen = [] + + def fake_run(cmd, **kw): + seen.append(kw.get("timeout")) + import subprocess + return subprocess.CompletedProcess(cmd, 0, "report\n", "") + out = io.StringIO() + with mock.patch.object(workers.subprocess, "run", side_effect=fake_run), contextlib.redirect_stdout(out), \ + contextlib.redirect_stderr(io.StringIO()): + rc = workers.cmd_delegate(["--kind", "read", "--difficulty", "1", "--brief", self.brief(), + "--worker", "zai/b", *extra]) + return rc, seen + + def test_timeout_min_overrides_the_configured_limit_for_that_run(self): + rc, seen = self.delegate("--timeout-min", "45", cfg={"workers": {"timeout_s": 100}}) + self.assertEqual(rc, 0) + self.assertEqual(seen[-1], 45 * 60) + + def test_without_it_the_default_and_the_configured_limit_are_unchanged(self): + self.assertEqual(self.delegate()[1][-1], workers.DEFAULT_RUN_TIMEOUT_S) + self.assertEqual(self.delegate(cfg={"workers": {"timeout_s": 100}})[1][-1], 100) + + def test_a_value_outside_one_to_one_hundred_twenty_is_refused_and_nothing_runs(self): + for bad in ("0", "121", "-3", "abc", "1.5", ""): + with self.subTest(value=bad): + rc, seen = self.delegate("--timeout-min", bad) + self.assertEqual(rc, 1) + self.assertEqual(seen, []) + self.assertEqual(self.delegate("--timeout-min", "1")[1][-1], 60) + self.assertEqual(self.delegate("--timeout-min", "120")[1][-1], 7200) + + def test_the_help_says_so(self): + text = self.sisi("help", "delegate").stdout + self.assertIn("--timeout-min N", text) + + +class HookPaths(TM.MeterBase): + FUTURE = "2036-11-30T05:00:00Z" + + def setUp(self): + super().setUp() + # one prefixed provider (a command-line tool's model) besides the two host-native workers + with open(os.path.join(self.data, "workers.json"), "w") as f: + json.dump({"checked": time.time(), "tools": [{"name": "opencode", "installed": True, "usable": True, + "models": ["provx/model-1"]}]}, f) + with open(os.path.join(self.data, "worker-prices.json"), "w") as f: + json.dump({"models": {"provx/model-1": {"cost_per_million_tokens": 0.1}, + "alpha-small": {"cost_per_million_tokens": 1}, + "beta-large": {"cost_per_million_tokens": 9}}}, f) + + def shell(self, command, output, event="PostToolUse"): + key = "error" if event == "PostToolUseFailure" else "tool_response" + r = self.sisi("watch", "--after", "--tool", "claude-code", + stdin=self.payload(event, "Bash", {"command": command}, **{key: output})) + self.assertEqual(r.returncode, 0, r.stderr) + return r.stdout.strip() + + def test_a_command_that_only_prints_sisis_source_is_not_a_delegation_result(self): + self.prompt() + src = "\n".join([" \"403 forbidden\", \"not logged in\", \"login required\", \"please log in\", \"invalid api key\",", + " driver = DRIVER_BY_NAME.get(cand.get('tool') or '')", SOURCE_LINE, + " cand = None", " continue"]) + cmd = "ls ~/.local/state/sisi/delegate/*.log; sed -n 1516,1560p sisi/workers.py" + out = self.shell(cmd, "state/sisi/delegate/e7260961.log\n" + src) + self.assertEqual(out, "") + self.assertEqual(workers.read_availability(), {}) + self.assertEqual(self.events("unavailable"), []) + + def test_commands_that_mention_delegate_but_do_not_run_it_are_not_delegations(self): + self.prompt() + line = "fakeprov/model-1 is unavailable (limit: API error 429: quota exhausted); trying the next choice" + for cmd in ("echo sisi delegate", "cat docs/sisi-delegate.md", "grep -n 'sisi delegate' README.md", + "sisi delegate judge abc123 --outcome accepted --check read", "sisi delegate recent", + "sisi delegate guide", "sisi delegate brief", "sisi delegate check b.md", "sisi delegate amend x"): + with self.subTest(cmd=cmd): + self.assertEqual(self.shell(cmd, line), "") + self.assertEqual(workers.read_availability(), {}) + + def test_real_delegate_command_shapes_are_recognised(self): + for cmd in ("sisi delegate --kind research --difficulty 1 --brief b.md", + "bin/sisi delegate --kind research --difficulty 1 --brief b.md", + "/opt/tools/bin/sisi delegate --kind research --difficulty 1 --brief b.md", + "cd proj && sisi delegate --kind research --difficulty 1 --brief b.md", + "cat > b.md <<'EOF'\nx\nEOF\nsisi delegate --kind research --difficulty 1 --brief b.md", + "SISI_X=1 sisi delegate --kind research --difficulty 1 --brief b.md"): + with self.subTest(cmd=cmd): + self.assertTrue(orchestration.runs_sisi_delegate(cmd)) + for cmd in ("echo sisi delegate", "ls state/sisi/delegate/*.log", "sisi delegate judge x", "sisi route --kind x", + "sisi-helper delegate", "notsisi delegate"): + with self.subTest(cmd=cmd): + self.assertFalse(orchestration.runs_sisi_delegate(cmd)) + + def test_the_last_unavailable_line_of_a_real_delegate_result_decides_the_fallback(self): + self.prompt() + out = ("other/x is unavailable (auth: not logged in (you are not authenticated)); trying the next choice\n" + "fakeprov/model-1 is unavailable (limit: API error 429: Subscription quota exhausted. Your usage window resets at " + + self.FUTURE + "); trying the next choice\nsisi: no usable worker remains for kind research at difficulty 1") + ctx = self.shell("sisi delegate --kind research --difficulty 1 --brief b.md", out, event="PostToolUseFailure") + text = json.loads(ctx)["hookSpecificOutput"]["additionalContext"] + self.assertIn("fakeprov/model-1 is unavailable", text) + self.assertNotIn("other/x", text) + self.assertIn("Fall back now", text) + self.assertEqual(workers.read_availability(), {}) # `sisi delegate` recorded it itself + + def test_a_note_counts_only_at_the_start_of_a_line(self): + self.assertIsNone(fallback.shell_notice('notes.append("%s is unavailable (%s: %s)" % (a, b, c))')) + self.assertIsNone(fallback.shell_notice(" see: x/y is unavailable (auth: no)")) + got = fallback.shell_notice("a/b is unavailable (auth: no); trying the next choice\n" + "c/d is unavailable (limit: rate limit); trying the next choice\nmore") + self.assertEqual(got[0], "c/d") + self.assertTrue(got[1].startswith("c/d is unavailable (limit")) + + def test_a_long_delegation_result_that_only_mentions_a_limit_in_its_middle_is_not_a_failure(self): + self.prompt() + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="t9") + body = ("Error: two tests were red when I started, and I fixed them.\n" + "line of the report\n" * 400 + + "the file said: usage limit reached, not logged in, quota exhausted\n" + "line of the report\n" * 400) + r = self.post("Agent", {"description": "d", "prompt": "p", "model": "provx/model-1"}, response=body, tool_use_id="t9") + self.assertNotIn("is unavailable", r.stdout) + self.assertEqual(workers.read_availability(), {}) + + def test_a_long_delegation_result_that_ends_in_its_failure_is_one(self): + self.prompt() + self.pre("Agent", {"description": "d", "prompt": "Outcome: x", "model": "provx/model-1"}, tool_use_id="t9") + body = "API error: the run stopped\n" + "line of the report\n" * 800 + \ + "API error 429: Subscription quota exhausted. Your usage window resets at %s\n" % self.FUTURE + r = self.post("Agent", {"description": "d", "prompt": "p", "model": "provx/model-1"}, response=body, tool_use_id="t9") + self.assertIn("provx/model-1 is unavailable", r.stdout) + self.assertIn("provx", workers.read_availability()) + + +if __name__ == "__main__": + unittest.main()