diff --git a/canon/core.md b/canon/core.md index 2f8cf7a..239d7a9 100644 --- a/canon/core.md +++ b/canon/core.md @@ -81,7 +81,9 @@ wrong work. You own the whole outcome; workers are specialists whose reports are evidence for you to judge. Give each task to the least expensive worker that is capable enough, counting rework as cost, -and keep your own context for judgement. Use the host's own delegation first. Run independent +and keep your own context for judgement. Always use the newest version of a given model +(same maker and class) when it is usable, never an older version of it; a newer release of a +different model or class is a different thing, so classify models before comparing them. Use the host's own delegation first. Run independent work in parallel when it shortens the critical path. Brief a worker with a contract (`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 diff --git a/canon/guard.json b/canon/guard.json index 8621342..c7b74c5 100644 --- a/canon/guard.json +++ b/canon/guard.json @@ -17,11 +17,6 @@ "apply", "insert" ], - "delegation_tools": [ - "Agent", - "Task", - "mcp__t3-code__delegate_task" - ], "build_kinds": [ "impl", "impl-multi", diff --git a/canon/orchestration-tools.json b/canon/orchestration-tools.json index d1874b9..3699ae5 100644 --- a/canon/orchestration-tools.json +++ b/canon/orchestration-tools.json @@ -1,5 +1,5 @@ { - "_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error, `none` means the meter only counts there. `evidence` says how sure this entry is. `capability` tools list what the host can reach (providers and models, as dotted paths into the tool's result), and a delegation entry that names a `provider` path says where the call carries the provider; both carry `reach`, the label under which what they learn is stored (sisi/discovery.py, read through orchestration.reach_specs). A tool name here may be an exact name or, when it starts with `^`, a pattern. This file is the one description of a host's tools: sisi/orchestration.py and sisi/discovery.py both read it.", + "_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error, `none` means the meter only counts there. `evidence` says how sure this entry is. A delegation entry's name may be a shell-style pattern (`*delegate_task`). `async` says how the tool's result marks a background launch: the dotted `path` into the result, the `running` values meaning \"still running\", and the `ids` paths whose values the later completion message will carry; `title` is the input path of the task's title, the other way that message names it. A listed tool with no `async` is a launch when its call returned in under five seconds with no report in the result. `capability` tools list what the host can reach (providers and models, as dotted paths into the tool's result); a delegation entry that names a `provider` path says where the call carries the provider; both carry `reach`, the label under which what discovery learns is stored (sisi/discovery.py, read through orchestration.reach_specs). This file is the one description of a host's tools: sisi/orchestration.py and sisi/discovery.py both read it.", "claude-code": { "refuse": "json-deny", "evidence": "observed live (tools/live_orchestration_check.py)", @@ -12,9 +12,21 @@ "model": "model", "brief": "prompt" }, - "mcp__t3-code__delegate_task": { + "*delegate_task": { "model": "target.model", "brief": "task", + "title": "title", + "async": { + "path": "status", + "running": [ + "starting", + "running" + ], + "ids": [ + "taskId", + "childThreadId" + ] + }, "provider": "target.providerInstanceId", "reach": "t3-code" } diff --git a/canon/orchestration.md b/canon/orchestration.md index 7a45853..0bb2f93 100644 --- a/canon/orchestration.md +++ b/canon/orchestration.md @@ -33,6 +33,11 @@ present; nothing here names one. Read on demand: `sisi delegate guide`. routine work measured proof outranks a benchmark: the cheapest worker with a judged record wins, and standing decides only when nobody has one. A thin record is a reason for care, not a verdict. +- Always use the newest version of a given model (same maker and class) when it is usable, never + an older version of it: neither a better old record nor a cheaper old plan brings it back, and a + newer release of a different model or class never wins for being newer. A new version starts from its + predecessor's record. Never guess maker, class or release date from a name: hand `sisi workers + classify` to a cheap worker and record its answer; `sisi workers classes` records a maker's classes. - Ask `sisi route --kind K --difficulty N` before delegating; `--explain` says why. Difficulty is 1 routine, 2 ordinary, 3 hard. Say the guess out loud; the record shows how good the guesses were. @@ -93,20 +98,14 @@ present; nothing here names one. Read on demand: `sisi delegate guide`. ## Keeping the picture current -- What exists, what it costs, and how good it is all change. Discovery is - `sisi workers`; prices and benchmark standing are worker facts, each with - a source and a date, recorded with `sisi workers fact`. -- When facts are missing or stale, hand the research itself to a fast, cheap - worker: find current prices and software-engineering benchmark standing, - then record them. Treat a newly appeared model as unproven: low-stakes - tasks first, checked one level more carefully, until its record is thick. -- Workers appear after sisi is installed: a new command-line tool is named once at session start - (`sisi workers learn NAME` prints the brief for the cheap worker that learns it), and the host's - own listing teaches the providers and models it reaches. A new worker is unproven: routine work - only, checked with at least the tests or a read of the diff, until its judged record decides. -- A tool can carry several providers, each with a plan, an allowance and failure phrases (`sisi - workers plan|allowance|signature`). The owner can vouch for a worker (`sisi workers vouch`). A - learned tool that switches off approvals, and an allowance probe, wait for the owner's `sisi approve`. +- What exists, what it costs and how good it is change. Discovery is `sisi workers`; prices and + benchmark standing are worker facts with a source and a date (`sisi workers fact`). When facts are + missing or stale, hand the research to a fast, cheap worker. A newly appeared model is unproven: + low-stakes tasks first, checked one level more carefully, until its record is thick. +- Workers appear after install: a new tool is named once (`sisi workers learn NAME` prints the brief + for the cheap worker that learns it) and the host's listing teaches its models; each is unproven + until judged. `sisi workers plan|allowance|signature|vouch` record a provider's facts and the + owner's word; a learned tool that switches off approvals, and an allowance probe, wait for `sisi approve`. - Orchestration legwork is delegable like any other legwork: discovery, price and benchmark research, routing lookups, first-pass review, and summarising the record can all go to a fast, cheap worker. The judgement diff --git a/canon/tool-name-words.json b/canon/tool-name-words.json new file mode 100644 index 0000000..fd5a96f --- /dev/null +++ b/canon/tool-name-words.json @@ -0,0 +1,5 @@ +{ + "_about": "What an UNLISTED host tool is, judged by its name (sisi/orchestration.py `classify`). A name is split into words at punctuation and case changes; a phrase matches when its words appear next to each other. `delegation`: the tool starts a worker, so it is never counted as direct work or refused by the meter. `control`: the tool only reads status, waits, cancels, lists, schedules or messages, so it is not counted. A tool named by neither still counts as direct work. Listed tools (canon/orchestration-tools.json) always win.", + "delegation": ["delegate", "delegation", "subagent", "sub_agent", "spawn", "thread_launch"], + "control": ["status", "wait", "cancel", "list", "read_thread", "schedule", "scheduled", "notify", "send", "ask"] +} diff --git a/canon/worker-openings.json b/canon/worker-openings.json new file mode 100644 index 0000000..3e926b6 --- /dev/null +++ b/canon/worker-openings.json @@ -0,0 +1,14 @@ +{ + "_about": "How a session's FIRST user message says it is a delegated worker (sisi/workerid.py). Each phrase is matched case-insensitively, with white space collapsed, inside the first `window` characters of that one message only; the brief template's own first line always counts too. A phrase later in a long message, or in a later message, never counts: a session a person started is a main thread.", + "window": 400, + "openings": [ + "you are a worker", + "you are a subagent", + "you are a sub-agent", + "you are a delegate", + "do this task yourself", + "do the task yourself", + "do not delegate" + ], + "head_bytes": 1048576 +} diff --git a/config.default.json b/config.default.json index b34cc38..ff608ea 100644 --- a/config.default.json +++ b/config.default.json @@ -18,7 +18,12 @@ "3": 85 }, "price_blend_input_parts": 3, - "explore_free_one_in": 3 + "explore_free_one_in": 3, + "class_span": { + "1": 100, + "2": 70, + "3": 35 + } }, "discovery": { "path_refresh_s": 21600, diff --git a/docs/workers.md b/docs/workers.md index dad47d0..dd230f3 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -20,6 +20,19 @@ or learned from judged results. The strategy is [canon/orchestration.md](../cano A fact without a source is refused. Ranking uses one blend of the two prices, by default three parts input to one part output (`route.price_blend_input_parts`); `sisi workers` shows both prices and the blend, and lists each benchmark standing apart from the accepted rates it prints. +- `sisi workers fact WORKER --maker M --class NAME [--released YYYY-MM-DD] --source S` — the maker, class and + release date researched for a model. `sisi workers` lists each routable worker's recorded maker, class and release date. +- `sisi workers classify [--record FILE [--by WORKER]]` — sisi reads nothing from a model's name. Without + arguments it prints a short instruction and the ids of routable workers that have no classification; hand + that to a fast, cheap worker (it takes seconds). The answer is one small JSON object: for each id its maker, + class and release date (`unknown` where it does not know), and for each maker its classes from most to least + capable. `--record FILE` validates it (an id that was not asked about refuses the whole answer; `unknown` is + stored as unknown and changes nothing in routing) and stores the facts with the classifying worker as the + source; a class order already recorded is never overwritten. Session start names unclassified workers in its + one facts line, and `sisi route` adds one line only when an unclassified worker is in the running. +- `sisi workers classes MAKER CLASS [CLASS...] --source S` — a maker's classes from most capable to least + (`--remove` forgets them). A class is the tier word of one line (a "flash" beside the standard model) or, + for a maker whose lines are the classes, the line's own name; `sisi workers` shows both as the class label. - `sisi workers avoid|prefer PATTERN --why TEXT` — the user's own routing constraints. - `sisi workers only PROVIDER PATTERN... --why TEXT` — only the matching models of that provider are routable; anything else from it (a newly discovered model, say) is passed over with the reason. @@ -82,6 +95,45 @@ instead, so cheaper options gather evidence. The choice is deterministic for one `--explain` prints one line for the evidence behind the choice (which of a to d, with the numbers), one per group of workers passed over as not capable enough, and names an exploration or a fallback. +## Newest version of a class, always + +Newer versions of a model are almost always better and almost always cheaper, so `sisi route` always uses +the newest version of a given model (the same maker and class) that is usable, and never an older version of +it. This is about versions of one model: a newer release of a different model or class never wins for being +newer. sisi reads +nothing from a model's name: a model's maker, class and release date are facts, researched by a cheap, +fast worker (session start and `sisi route` say when they are missing) and recorded with +`sisi workers fact WORKER --maker M --class C --released YYYY-MM-DD --source S`. A model's identity is its +maker and class; recency is its release date. For a maker whose lines are the classes the class is the +line's own name; for a maker with a "flash" beside its standard model it is `flash` or `standard`. A model +with no recorded maker and class is never compared with another. The same model through two providers is +one model: if its newest version is usable through any provider, older versions do not compete through any +provider, and the existing cost comparison picks the provider. There is no exception for a better old +record or a cheaper old plan. The older version competes again only while the newer is unusable (marked +down, allowance spent, avoided by the user, or limited away) or has no recorded class. A newer model with a +thick bad record is not replaced by its older version either: routing moves to another class or maker by the +usual rules. Different classes are different things and never supersede each other. A bare host alias with a +recorded class and no release date counts as the newest version of its class. + +The class order is a prior and nothing more. A worker with no judged proof and no benchmark standing, +whose class is in its maker's recorded order, is capable when the class sits high enough for the +difficulty: `route.class_span` (default routine work 100, ordinary 70, hard 35) is the share of the order, +counted from the most capable class down, that each difficulty reaches. With four classes routine work +reaches all four, ordinary work the top three, hard work the top two; the cheapest capable worker then +wins, so routine work goes to the lowest class and hard work to the upper ones. A judged record or a +benchmark standing always outranks the order; when nobody is proven, the strongest known worker is the +one in the highest class. Classes of different makers are never compared. Until a maker with two or +more classes among the usable workers has an order recorded, `sisi route` adds one line asking for it. + +A new version starts from its predecessor's judged record: a model with no thick record of its own +for a kind and difficulty inherits, as evidence, the thick record of the closest older version of +its maker and class (one version back at a time), named in `--explain`. It ranks below the model's +own record and above a benchmark, counts as a judged record for the rule that proof comes before +benchmark, stops once the model has a thick record of its own, and a predecessor's bad record is not +inherited. A discovered model with no data of its own is routable when its predecessor is. Where the +arithmetic falls back to a stable tie-break, the newer version of the same model goes first (never across makers +or classes). + ## Costs and failures Tokens and cost are captured where the worker's output reports them, and marked `unavailable` diff --git a/sisi/discovery.py b/sisi/discovery.py index a41bbd5..363f502 100644 --- a/sisi/discovery.py +++ b/sisi/discovery.py @@ -178,7 +178,7 @@ def new_line(models, tools): parts.append("command-line tool%s %s" % ("" if len(tools) == 1 else "s", _short_names(sorted(tools, key=lambda n: (not _hinted(n), n)), 2))) return ("sisi: new %s: unproven, so low-stakes work first, checked one level more carefully.%s" - % (" and ".join(parts), " An AI agent among the tools: `sisi workers learn NAME`." if tools else "")) + % (" and ".join(parts), " For an AI agent: `sisi workers learn NAME`." if tools else "")) def new_tools_line(new): diff --git a/sisi/gate.py b/sisi/gate.py index 9faf020..23e7861 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -251,15 +251,13 @@ def _decide(payload): cfg = store.config() if not cfg["gate"].get("enabled", True): return "allow", None - from . import workers - if workers.is_subagent_payload(payload): - return decide_subagent(payload) + from . import workerid cwd = _cwd(payload) sid = _session_key(payload, cwd) + if workerid.session_is_worker(payload, sid, cwd): + return decide_subagent(payload) # a worker's last message is its report to the agent that started it os.environ["SISI_SESSION_ID"] = sid sess = store.load_session(sid) - if sess.get("subagent"): - return "allow", None # a session another agent started: its last message is its report to that agent if not (sess.get("started") or sess.get("first_seen")): sess["first_seen"] = store.now() top = gitutil.root(cwd) @@ -525,12 +523,10 @@ def _orchestration_step(payload, action): """Rule 6 at the end of a turn, main thread only: ask once for the judgement of this session's finished delegations (a send-back like any other missing item); when the turn really ends, the meter starts over.""" try: - from . import orchestration, workers - if workers.is_subagent_payload(payload): - return None + from . import orchestration, workerid cwd = _cwd(payload) sid = _session_key(payload, cwd) - if store.load_session(sid).get("subagent"): + if workerid.session_is_worker(payload, sid, cwd): return None if action == "allow": text = (orchestration.fallback_sendback(payload, sid) or orchestration.judgement_sendback(payload, sid) diff --git a/sisi/helptext.py b/sisi/helptext.py index a507b07..59c9c19 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -31,7 +31,7 @@ LONG = { 'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score); --learning prints only the learning report', 'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library', '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 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', + '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', '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', diff --git a/sisi/learning.py b/sisi/learning.py index 4416139..de1cc31 100644 --- a/sisi/learning.py +++ b/sisi/learning.py @@ -801,7 +801,7 @@ def pending_notice(count=None): if not n: return "" return ("sisi: %d decision(s) wait for the owner. Ask through the host's question dialog, then give the owner the " - "command to run in a terminal (`sisi approve` lists each in full). Do not run it for the owner." % n) + "command to run in a terminal (`sisi approve` lists them). Do not run it for the owner." % n) # ---- owner statements (one path: learn writes, oracle prints) --------------------- diff --git a/sisi/orchestration.py b/sisi/orchestration.py index 845bfe6..0189833 100644 --- a/sisi/orchestration.py +++ b/sisi/orchestration.py @@ -17,9 +17,9 @@ canon/orchestration-tools.json. Per-session state is in /sessions/.me every counted event is also appended to /orchestration.jsonl for the unit record. Every entry point fails open (the caller wraps it): an error here must never hold up the user's tool. """ -import fcntl, json, os, re, shlex, time +import fcntl, fnmatch, json, os, re, shlex, time -from . import paths, store +from . import paths, store, workerid EVENTS = "orchestration.jsonl" _HOSTS = {} @@ -50,10 +50,14 @@ def hosts(): def _name_regex(name): - """A tool name from the data file as a case-insensitive regular expression: an exact name, or a pattern when - it starts with `^`.""" + """A tool name from the data file as a case-insensitive regular expression: an exact name, a shell-style pattern + (`*delegate_task`, as `_matches` reads it), or a regular expression when it starts with `^`.""" n = str(name) - return "(?i)" + (n if n.startswith("^") else "^" + re.escape(n) + "$") + if n.startswith("^"): + return "(?i)" + n + if any(c in n for c in "*?["): + return "(?i)" + fnmatch.translate(n) + return "(?i)^" + re.escape(n) + "$" def reach_specs(): @@ -71,7 +75,7 @@ def reach_specs(): if isinstance(spec, dict) and spec.get("reach") and spec.get("provider"): r = out.setdefault(spec["reach"], {"host": spec["reach"]}) r.update(delegation_tool=_name_regex(name), - delegation={"tool_name": str(name).rsplit("__", 1)[-1], "provider": spec["provider"], + delegation={"tool_name": str(name).rsplit("__", 1)[-1].lstrip("*"), "provider": spec["provider"], "model": spec.get("model")}) return list(out.values()) @@ -99,13 +103,6 @@ def meter_note(tool, wired): # ---------------------------------------------------------------- classifying a call -def _exempt_names(hd): - out = set() - for names in (hd.get("exempt") or {}).values(): - out.update(str(n).lower() for n in names or []) - return out - - def _dig(obj, dotted): for k in str(dotted or "").split("."): if not isinstance(obj, dict): @@ -114,13 +111,57 @@ def _dig(obj, dotted): return obj +def _matches(entry, tool): + """A data entry is an exact tool name or a shell-style pattern (`*delegate_task`), case-insensitive.""" + e, t = str(entry).lower(), str(tool or "").lower() + return e == t or (any(c in e for c in "*?[") and fnmatch.fnmatchcase(t, e)) + + def delegation_spec(hd, tool): - for name, spec in (hd.get("delegation") or {}).items(): - if str(name).lower() == str(tool or "").lower(): - return spec if isinstance(spec, dict) else {} + """The listed delegation entry for this tool (exact names first, then patterns), else None.""" + items = list((hd.get("delegation") or {}).items()) + for exact in (True, False): + for name, spec in items: + if (str(name).lower() == str(tool or "").lower()) == exact and _matches(name, tool): + return spec if isinstance(spec, dict) else {} return None +_WORDS = {} + + +def _name_words(): + if not _WORDS: # a failed read is not remembered + try: + with open(paths.canon("tool-name-words.json"), encoding="utf-8") as f: + d = json.load(f) + _WORDS.update({k: [str(w).lower() for w in v if isinstance(w, str)] for k, v in d.items() if isinstance(v, list)}) + except (OSError, ValueError): + return {} + return _WORDS + + +def name_kind(tool): + """"delegation" or "control" when an unlisted tool's NAME says what it is (canon/tool-name-words.json), else None.""" + t = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", str(tool or "")) + padded = "_" + "_".join(w for w in re.split(r"[^a-z0-9]+", t.lower()) if w) + "_" + words = _name_words() + for kind in ("delegation", "control"): + if any("_" + w.strip("_") + "_" in padded for w in words.get(kind, ())): + return kind + return None + + +def is_delegation(host, tool): + """Does this tool start a worker: listed in the host's data (name or pattern), or named like one.""" + return delegation_spec(host_data(host), tool) is not None or ( + not _listed_exempt(host_data(host), tool) and name_kind(tool) == "delegation") + + +def _listed_exempt(hd, tool): + return any(_matches(n, tool) for names in (hd.get("exempt") or {}).values() for n in names or []) + + def _segments(cmd): """The commands of a shell line, split at the operators outside quotes; None when it cannot be split.""" try: @@ -172,12 +213,13 @@ def classify(host, tool, inp, cmd): hd = host_data(host) if delegation_spec(hd, tool) is not None: return "delegation" - if str(tool or "").lower() in _exempt_names(hd): + if _listed_exempt(hd, tool): return "exempt" from . import watch - if watch.is_shell(tool, cmd) and runs_sisi(cmd): - return "exempt" - return "direct" + if watch.is_shell(tool, cmd): + return "exempt" if runs_sisi(cmd) else "direct" + kind = name_kind(tool) # an unlisted tool: its name says whether it starts a worker or only controls one + return "delegation" if kind == "delegation" else "exempt" if kind == "control" else "direct" # ---------------------------------------------------------------- the per-session meter @@ -248,11 +290,6 @@ def _peek(sid): return {} -def worker_flag(sid): - """Did this session's first prompt open with the brief template's line (it is a worker)?""" - return bool(_peek(sid).get("worker")) - - def routed_kind(sid): """The kind in the session's current routing decision (`sisi route` recorded it, here, in the meter), or None when there is none or it is older than orchestrate.route_window_min. The one place the decision is read.""" @@ -298,6 +335,26 @@ def _pending_for(m, text): return key, (m["pending"].get(key) if key else None) +_BRACKET = re.compile(r"\[(completed|failed|interrupted|cancelled|canceled)\]", re.I) + + +def bracket_status(text): + """The status a plain-text completion notice carries (`[completed]`, `[failed]`, `[interrupted]`) near its start.""" + m = _BRACKET.search((text or "").lstrip()[:300]) + return m.group(1).lower().replace("canceled", "cancelled") if m else None + + +def _pending_by_names(m, text): + """(key, entry) of the pending background delegation whose id or title this message names, else (None, None).""" + low = (text or "").lower() + for key, ent in m["pending"].items(): + ids = [str(i) for i in ent.get("ids") or [] if i] + title = str(ent.get("title") or "") + if any(i in text for i in ids) or (len(title) >= 8 and title.lower() in low): + return key, ent + return None, None + + def _task_done(m, key, ent, text, superseded=False): """A host's notice that a background worker finished: complete the run it started.""" from . import workers @@ -306,7 +363,7 @@ def _task_done(m, key, ent, text, superseded=False): tokens = _tag(text, "subagent_tokens") ms = _tag(text, "duration_ms") minutes = round(float(ms) / 60000.0, 2) if ms and ms.replace(".", "", 1).isdigit() else round((now - ent["t0"]) / 60.0, 2) - ok = (_tag(text, "status") or "completed") == "completed" + ok = (_tag(text, "status") or bracket_status(text) or "completed") == "completed" workers.append_record({"kind": "run-end", "run_id": ent["run"], "ts": round(now), "ended": round(now), "minutes": minutes, "tokens": int(tokens) if tokens and tokens.isdigit() else None, "tokens_class": "measured" if tokens and tokens.isdigit() else "unavailable", @@ -315,15 +372,6 @@ def _task_done(m, key, ent, text, superseded=False): _event(m, m.get("sid"), "delegation-done", run=ent["run"]) -def brief_line(): - from . import brief - return brief.template().splitlines()[0].strip().lower() - - -def _session_is_worker(m, sess): - return bool(m.get("worker") or sess.get("subagent") or os.environ.get("SISI_WORKER_RUN")) - - def new_turn(sid, cwd=None, prompt=None): """A prompt reached the session. A human request starts the meter's turn again (the first one that opens with the brief template's line makes the session a worker for good). A host notice about a background worker @@ -336,11 +384,16 @@ def new_turn(sid, cwd=None, prompt=None): _project(m, cwd) text = prompt if isinstance(prompt, str) else "" is_notice = text.lstrip().startswith(NOTIFICATION) + status = (_tag(text, "status") or "").lower() if is_notice else (bracket_status(text) if text else None) + named = _pending_by_names(m, text) if status and not is_notice else (None, None) failed = fallback.failure_notice(text) if text else None - if is_notice or failed: + if is_notice or failed or named[1] is not None: out = None - key, ent = _pending_for(m, text) if is_notice else (None, None) - if failed and not _session_is_worker(m, sess): + key, ent = _pending_for(m, text) if is_notice else named + if status in ("interrupted", "cancelled", "canceled") and ent is not None: + _task_done(m, key, ent, text, superseded=True) # stopped on purpose: nothing to judge + return None + if failed and not workerid.is_worker_session({}, sess, m): out = fallback.handle(m, sid, cwd or m.get("project") or os.getcwd(), failed["text"], own_model=_own_model({}, sess, m), worker=(ent or {}).get("worker"), run_id=(ent or {}).get("run")) @@ -350,8 +403,8 @@ def new_turn(sid, cwd=None, prompt=None): m["turn"] += 1 m.update(calls=0, chars=0, ext=0, refusals=0, fails={}, ext_log=[], same_model_ok=False, unavail=None) m["prompts"] += 1 - if m["prompts"] == 1 and text.lstrip()[:200].lower().startswith(brief_line()): - m["worker"] = True + if m["prompts"] == 1 and "worker" not in m: + m["worker"] = workerid.opens_as_brief(text) return None @@ -472,10 +525,6 @@ def _norm(cmd): return " ".join((cmd or "").split()) -def _is_worker(payload, sess, m): - return bool(m.get("worker") or sess.get("subagent") or store.is_subagent_payload(payload)) - - def _transcript_model(path): """The model the main thread last answered with, from the tail of the host's transcript (a session-start payload need not carry it). None when it cannot be read.""" @@ -539,7 +588,7 @@ def _before(payload, host=None): tool, cmd, _ev, cwd, sid = watch.extract(payload) host = host or store.tool() or "claude-code" hd = host_data(host) - if not hd or store.is_subagent_payload(payload): + if not hd: return {} sid = sid or "cwd-" + cwd inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {}) @@ -549,10 +598,10 @@ def _before(payload, host=None): return _dialog_guard(payload, host, sid, cwd) if kind == "exempt" and not shell: return {} + if workerid.session_is_worker(payload, sid, cwd): + return {} sess = store.load_session(sid) with Meter(sid) as m: - if _is_worker(payload, sess, m): - return {} project = _project(m, cwd) m["last_tool"] = tool if shell: @@ -599,10 +648,12 @@ def _dialog_guard(payload, host, sid, cwd): from . import fallback, workers if refuse_style(host) not in ("json-deny", "exit-2"): return {} + if workerid.session_is_worker(payload, sid, cwd): + return {} sess = store.load_session(sid) with Meter(sid) as m: info = m.get("unavail") - if not info or _is_worker(payload, sess, m): + if not info: return {} own = _own_model(payload, sess, m) project = _project(m, cwd) @@ -616,7 +667,10 @@ def _dialog_guard(payload, host, sid, cwd): def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd): - spec = delegation_spec(hd, tool) or {} + spec = delegation_spec(hd, tool) + if spec is None: + return {} # only named like a delegation tool: the data does not say where its model sits, so it is never + # counted, refused or recorded as a run here model = _dig(inp, spec.get("model", "model")) model = model.strip() if isinstance(model, str) else "" text = _dig(inp, spec.get("brief", "prompt")) @@ -662,7 +716,9 @@ def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd): except OSError as e: store.log_error("orchestration-run", e) key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last" - m["pending"][key] = {"run": run_id, "t0": now, "worker": worker} + title = _dig(inp, spec.get("title", "title")) + title = title.strip() if isinstance(title, str) else "" + m["pending"][key] = {"run": run_id, "t0": now, "worker": worker, "title": title or None} m["unavail"] = None # the agent is falling back (or delegating anew): nothing left to refuse a question for _event(m, sid, "delegation", run=run_id, worker=worker) known = bool(route and route.get("kind") and route.get("difficulty")) @@ -691,7 +747,7 @@ def after(payload, host=None): tool, cmd, ev, cwd, sid = watch.extract(payload) host = host or store.tool() or "claude-code" hd = host_data(host) - if not hd or store.is_subagent_payload(payload): + if not hd: return {} sid = sid or "cwd-" + cwd inp = next((payload[k] for k in ("tool_input", "toolInput", "input") if isinstance(payload.get(k), dict)), {}) @@ -699,14 +755,14 @@ def after(payload, host=None): shell = watch.is_shell(tool, cmd) if kind == "exempt" and not shell: return {} + if workerid.session_is_worker(payload, sid, cwd): + return {} sess = store.load_session(sid) out = {} with Meter(sid) as m: - if _is_worker(payload, sess, m): - return {} _project(m, cwd) if kind == "delegation": - return _after_delegation(payload, ev, sid, m, sess, cwd) + return _after_delegation(payload, ev, sid, m, sess, cwd, host, tool) if shell and re.search(r"\bsisi\b.*\bdelegate\b", cmd or "", re.S): # alone or inside a longer command line from . import fallback note = fallback.shell_notice(_flat(payload)) @@ -751,7 +807,61 @@ def _flat(payload): return "\n".join(parts) -def _after_delegation(payload, ev, sid, m, sess=None, cwd=None): +def _result_objects(resp): + """The JSON objects a tool result holds: the result itself, or the text blocks of a content list parsed.""" + out, stack = [], [resp] + while stack: + x = stack.pop(0) + if isinstance(x, str): + try: + x = json.loads(x) + except ValueError: + continue + if isinstance(x, str): + continue + if isinstance(x, dict): + out.append(x) + for k in ("content", "text", "structuredContent"): + if x.get(k) is not None: + stack.append(x[k]) + elif isinstance(x, list): + stack.extend(x) + return out + + +_TERMINAL = ("completed", "complete", "done", "finished", "success", "succeeded", "failed", "error", "cancelled", + "canceled", "interrupted") +_REPORT_KEYS = ("result", "report", "summary", "output", "text", "message", "totalDurationMs", "total_duration_ms", + "totalTokens", "total_tokens", "usage") +LAUNCH_SECONDS = 5 + + +def background_launch(spec, resp, elapsed): + """None when the delegation call returned its result; else the ids (possibly none) the later notice will carry. + The data says how a host's result marks a background launch (`async`: a dotted `path` and the `running` values, + and the `ids` paths); a tool with no such data counts as a launch when the call returned in under + LAUNCH_SECONDS with no report in the result (no report keys, no finished status, no long text).""" + objs = [o for o in _result_objects(resp)] + a = (spec or {}).get("async") + if isinstance(a, dict) and a.get("path"): + for o in objs: + v = _dig(o, a["path"]) + if isinstance(v, str) and v.lower() in [str(x).lower() for x in a.get("running") or []]: + ids = [_dig(o, q) for q in (a.get("ids") or ([a["id"]] if a.get("id") else []))] + return [str(i) for i in ids if isinstance(i, (str, int)) and str(i)] + return None + if elapsed >= LAUNCH_SECONDS or not objs: + return None + for o in objs: + status = str(o.get("status") or "").lower() + if status in _TERMINAL or any(k in o for k in _REPORT_KEYS) or any(isinstance(v, str) and len(v) >= 80 for v in o.values()): + return None + ids = [str(v) for k, v in objs[0].items() if isinstance(v, (str, int)) and not isinstance(v, bool) + and re.search(r"id$", k, re.I) and str(v)] + return ids + + +def _after_delegation(payload, ev, sid, m, sess=None, cwd=None, host=None, tool=None): from . import workers key = payload.get("tool_use_id") if isinstance(payload.get("tool_use_id"), str) else "last" ent = m["pending"].get(key) @@ -766,6 +876,11 @@ def _after_delegation(payload, ev, sid, m, sess=None, cwd=None): # the worker was only launched: it is finished when the host's notice arrives (new_turn), not now m["pending"][key] = dict(ent, agent=resp.get("agentId"), model=resp.get("resolvedModel")) return {} + launch = background_launch(delegation_spec(host_data(host), tool), resp, now - ent["t0"]) + if launch is not None: + # a launch call returns at once; the result arrives later as a message that names this id or title + m["pending"][key] = dict(ent, ids=launch, title=ent.get("title")) + return {} from . import fallback text = _flat(payload) if fallback.looks_failed(text, failure_event="failure" in str(ev or "").lower()): @@ -906,7 +1021,7 @@ def fallback_sendback(payload, sid): sess = store.load_session(sid) with Meter(sid) as m: info = m.get("unavail") - if not info or int(m.get("fallback_asked") or 0) >= FALLBACK_SENDBACKS or _session_is_worker(m, sess): + if not info or int(m.get("fallback_asked") or 0) >= FALLBACK_SENDBACKS or workerid.is_worker_session({}, sess, m): return None own = _own_model({}, sess, m) project = m.get("project") or os.getcwd() diff --git a/sisi/routing.py b/sisi/routing.py index 86a7d7f..95cd537 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -44,14 +44,21 @@ The rule, in order: 6. About one low-stakes task in ten (difficulty 1, every tenth judged attempt for that kind and difficulty) goes to a cheaper worker with a thin record instead, so cheaper options keep gathering evidence. The slot is a function of the record, so the choice stays deterministic. - 7. Load balancing: within the same price tier and price, the worker that has taken the least work + 7. The newest usable version of a maker's class always wins over its older versions (see + `superseded_by`): no better record and no cheaper plan on the older version brings it back. + The older one competes again only while the newer one is unusable. The class is read from the + recorded facts (see lineage_from_fact): maker, class and release date; a model with no recorded class + is never compared. + 8. Load balancing: within the same price tier and price, the worker that has taken the least work relative to its remaining allowance goes first (recorded uses divided by allowance left, an - unknown allowance counting as half). Ties break on the worker id. + unknown allowance counting as half). Ties break on the newer version of the same model (never across + makers or classes), then on the worker id. Candidates reach here already restricted to workers with a judged record, a known price or a benchmark standing (see workers.routable_candidates); on a cold start none qualifies and every usable worker is offered, with the explanation saying so. """ +import functools import re MIN_ATTEMPTS = 8 # below this, a worker's record for a kind and difficulty is thin @@ -62,9 +69,59 @@ STRONG_BAND = 10.0 # standing points from the best still counts as among EXPLORE_EVERY = 10 # about one low-stakes task in ten tries a cheaper thin-record worker EXPLORE_FREE_EVERY = 3 # an unproven worker that costs nothing extra gets one routine task in three DEFAULT_STANDING_FLOOR = {1: 0.0, 2: 60.0, 3: 85.0} # percent of the best usable standing needed +DEFAULT_CLASS_SPAN = {1: 100.0, 2: 70.0, 3: 35.0} # how far down a maker's class order still counts as capable DEFAULT_PRICE_BLEND = 3.0 # parts of input price to one part of output price in a blended price +# ---------------------------------------------------------------- a model's identity, from recorded facts only +# +# sisi reads nothing from a model's name. A model's maker, class and release date are facts, researched by a +# cheap, fast worker (`sisi workers classify`) and recorded with `sisi workers fact`. A model with no recorded +# maker and class has no identity and takes part in no comparison of versions. +# identity (maker, class). For a maker whose lines are the classes, the class is the line's own name; for a +# maker with a "flash" beside its standard model, the class is "flash" or "standard". Different +# classes are different things and never replace each other. +# recency the recorded release date (YYYY-MM-DD or YYYY-MM). A bare host alias with a recorded class and no +# release date counts as the newest version of its class. + +UNKNOWN = "unknown" + + +def lineage_from_fact(fact=None, host_native=False): + """{key, maker, class, label, released, alias, source} from a model's recorded facts. source is "fact" when + both a maker and a class are recorded, else "unknown" (key None: no comparison of versions).""" + fact = fact if isinstance(fact, dict) else {} + cls = str(fact.get("class") or "").strip().lower() + maker = str(fact.get("maker") or "").strip().lower() + cls, maker = ("" if cls == UNKNOWN else cls), ("" if maker == UNKNOWN else maker) # "unknown" is an answer, not a fact + released = str(fact["released"]) if fact.get("released") and fact["released"] != UNKNOWN else None + out = {"key": None, "maker": maker, "class": cls or UNKNOWN, "label": cls or UNKNOWN, "released": released, + "alias": False, "source": UNKNOWN} + if cls and maker: + out.update(key=(maker, cls), source="fact", alias=bool(host_native and not released)) + return out + + +def compare_release(a, b): + """1 when a is the more recently released model, -1 when b is, 0 when equal or unknowable. A bare alias is the + newest of its class; otherwise the recorded release dates decide.""" + if a.get("alias") or b.get("alias"): + return (1 if a.get("alias") else 0) - (1 if b.get("alias") else 0) + da, db = days(a.get("released")), days(b.get("released")) + if da and db and da != db: + return 1 if da > db else -1 + return 0 + + +def days(date): + """A YYYY-MM-DD or YYYY-MM date as a number that sorts correctly (months of 31 days: only the order matters); + 0 when there is no date.""" + d = str(date or "") + if len(d) >= 7 and d[:4].isdigit() and d[5:7].isdigit() and (len(d) == 7 or (len(d) >= 10 and d[8:10].isdigit())): + return int(d[0:4]) * 372 + int(d[5:7]) * 31 + (int(d[8:10]) if len(d) >= 10 else 0) + return 0 + + def maker_of(name): """A best-effort maker derived from a worker or model id: the first word of the model part. A stored `maker` fact wins wherever a candidate carries one; no table of names ships here.""" @@ -113,6 +170,32 @@ def _floor_pct(floors, difficulty): return table[max(table)] +def class_spans(configured=None): + """{difficulty: percent of a maker's class order, from the most capable class down, that is capable enough}. + With four classes: routine work (100) reaches all four, ordinary work (70) the top three, hard work (35) the + top two. The defaults are overridden by valid entries of the configured mapping (keys 1..3, values 0..100).""" + table = dict(DEFAULT_CLASS_SPAN) + if isinstance(configured, dict): + for k, v in configured.items(): + try: + d, pct = int(k), float(v) + except (TypeError, ValueError): + continue + if 1 <= d <= 3 and 0 <= pct <= 100: + table[d] = pct + return table + + +def class_rank(c, opts=None): + """(position, count) of the model's class in its maker's recorded order (0 is the most capable), or None when + the maker has no recorded order, the class could not be read, or the class is not in the order.""" + l = _lineage(c) + order = ((opts or {}).get("class_orders") or {}).get(l.get("maker")) if l and l.get("key") else None + if not order or l.get("label") not in order: + return None + return order.index(l["label"]), len(order) + + def _pattern_match(c, patterns): """The (pattern, why) a candidate matches, or None. A pattern matches as a substring of the worker, model or tool name, case aside; a pattern ending in `/` is a provider and matches only @@ -192,6 +275,62 @@ def candidate_stats(candidates, records): return stats +def _versions_newest_first(models): + """[[workers of one version], ...] from the newest version to the oldest (one model through several + providers is one version).""" + out = [] + ordered = sorted(models, key=lambda d: d["worker"]) + ordered.sort(key=functools.cmp_to_key(lambda a, b: compare_release(_lineage(b), _lineage(a)))) + for d in ordered: + if out and compare_release(_lineage(out[-1][0]), _lineage(d)) == 0: + out[-1].append(d) + else: + out.append([d]) + return out + + +def inherit_stats(candidates, stats, opts=None): + """Judged cells as evidence sees them: a model with no thick record of its own for a kind and difficulty + starts from the thick record of the closest older version of the same maker and class (walking back one + version at a time, the first thick record decides). Only a record that proves the work is inherited: a + predecessor's bad record starts the newer model from its benchmark or from nothing, and a thin record of the + model's own that already repeats rejections is not papered over. The model's own thick record always stands + alone. An inherited cell carries `from`, the worker whose record it is.""" + eff = {w: {"uses": st["uses"], "by_cell": dict(st["by_cell"])} for w, st in stats.items()} + groups = {} + for c in candidates: + l = _comparable(c, opts) + if l: + groups.setdefault(tuple(l["key"]), []).append(c) + for group in groups.values(): + for c in group: + older = [d for d in group if compare_release(_lineage(c), _lineage(d)) > 0] + if not older: + continue + levels = _versions_newest_first(older) + own = stats[c["worker"]]["by_cell"] + for ck in sorted({k for d in older for k in stats[d["worker"]]["by_cell"]}, key=str): + mine = own.get(ck, _NO_CELL) + if _thick(mine) or _contradicts(mine): + continue + for level in levels: + cells = [(d["worker"], stats[d["worker"]]["by_cell"].get(ck)) for d in level] + cells = [(w, x) for w, x in cells if x] + merged = {"n": sum(x["n"] for _w, x in cells), "good": sum(x["good"] for _w, x in cells)} + if _thick(merged): + if _proven(merged): + eff[c["worker"]]["by_cell"][ck] = dict(merged, **{"from": max(cells, key=lambda t: (t[1]["n"], t[0]))[0]}) + break + return eff + + +def has_predecessor(c, among, opts=None): + """Whether some worker in `among` is an older version of the same maker and class as `c`.""" + l = _comparable(c, opts) + return bool(l) and any(_comparable(d, opts) and tuple(_lineage(d)["key"]) == tuple(l["key"]) + and compare_release(l, _lineage(d)) > 0 for d in among) + + def _price_tier(c): if c.get("plan") == "flat": return 0 @@ -243,10 +382,12 @@ def _by_difficulty(stats, worker, kind): p = pooled.setdefault(d, {"n": 0, "good": 0}) p["n"] += cell["n"] p["good"] += cell["good"] + if cell.get("from"): + p["from"] = cell["from"] return own, pooled -def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=None, vouch=0): +def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=None, rank=None, spans=None, vouch=0): """What the evidence says about one worker for a kind and difficulty. Returns a dict: tier "a", "b-higher", "b-all", "standing", "unknown" or "none" capable whether the evidence says it is capable enough @@ -256,7 +397,12 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f level 3 judged proof, 2 benchmark, 1 weak, 0 nothing, -1 bad: never rises with difficulty n, good, at the judged cell behind a, b-higher, b-all and the weak tier (and its difficulty) share, needed, floor for the standing tier: percent of the best, the figure needed, the floor - Standing is compared only with the best standing; a rate only with the bar. + class_pos, class_n, class_share, class_allowed for the class tier (see below) + inherited_from the worker whose record this is, when it is a predecessor's (see inherit_stats) + The class tier is the last prior: a worker with no judged proof and no standing of its own, whose class has a + place in its maker's recorded order (`rank`, from class_rank), is capable when that place is within the span the + difficulty allows (`spans`, see class_spans). Standing is compared only with the best standing; a rate only with + the bar; neither is ever compared with a class. `vouch` is the difficulty up to which the owner vouched for the worker: a judged proof outranks it, a thick bad record or a thin one with repeated rejections cancels it, and it outranks a benchmark (tier "vouch").""" d = difficulty @@ -290,7 +436,8 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f proof = ("b-all", wide[0], pooled[wide[0]]) if proof is not None: tier, at, cell = proof - out.update(tier=tier, capable=True, level=3, at=at, n=cell["n"], good=cell["good"], measure=_rate(cell)) + out.update(tier=tier, capable=True, level=3, at=at, n=cell["n"], good=cell["good"], measure=_rate(cell), + inherited_from=cell.get("from")) return out if vouch and isinstance(d, int) and d <= vouch and not out["contradicted"]: out.update(tier="vouch", capable=True, level=3, at=vouch, measure=0.0) @@ -303,6 +450,14 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f if not out["contradicted"]: out.update(tier="standing", capable=capable, level=2 if capable else (1 if out["weak"] else 0)) return out + if standing is None and rank is not None and not out["contradicted"]: + pos, n = rank + share = 100.0 * pos / (n - 1) if n > 1 else 0.0 + allowed = class_spans(spans).get(d, 100.0 if d is None or d < 1 else class_spans(spans)[3]) + capable = share <= allowed + 1e-9 + out.update(tier="class", capable=capable, level=1 if capable else 0, class_pos=pos, class_n=n, + class_share=share, class_allowed=allowed) + return out if standing is None and d == 1 and not out["contradicted"]: out.update(tier="unknown", capable=True, level=0) return out @@ -318,9 +473,13 @@ def strength(a): if a["bad"]: return (-1, 0, 0.0) if a["tier"] in _TIER_RANK: + if a.get("inherited_from"): + return (3, 1, a["measure"]) # a predecessor's record: above a benchmark, below the model's own return (4, -_TIER_RANK[a["tier"]], a["measure"]) if a["standing"] is not None and not a["contradicted"]: return (3, 0, float(a["standing"])) + if a["tier"] == "class": + return (1, 1, 1.0 - a["class_share"] / 100.0) # the maker's own order: below a weak judged record if a["weak"]: return (2, 0, a["weak_rate"]) return (1, 0, 0.0) @@ -341,37 +500,70 @@ def vouch_level(c): return lvl if isinstance(lvl, int) and not isinstance(lvl, bool) and lvl > 0 else 0 -def _prepare(candidates, records, availability, now, exclude, avoid, review_of, difficulty=None): - """The workers that may be recommended at all: (eligible, passed, stats, author_maker). An unproven - worker (flagged by workers.build_candidates: new, with fewer than MIN_ATTEMPTS judged attempts) is - offered routine work only: above difficulty 1 it is passed over whatever benchmark it has.""" +def _unusable(c, availability, now): + """Why a candidate cannot be used right now (plain words), or None.""" + if "contributor" in str(c.get("model") or c["worker"]).lower(): + return "its id contains 'contributor', a tier that trains on prompts" + down = _down_entry(c, availability, now) + if down is not None: + return "unavailable (%s) until its retry time" % (down.get("reason") or "down") + if not c.get("usable", True): + return c.get("reason") or "not usable now" + if c.get("plan") == "flat" and c.get("allowance_pct_left") == 0: + return "its flat-rate allowance is spent" + return None + + +def _lineage(c): + l = c.get("lineage") + return l if isinstance(l, dict) else None + + +def _comparable(c, opts=None): + """The model's lineage when its maker and class are recorded; a model without them is never compared.""" + l = _lineage(c) + return l if l and l.get("key") else None + + +def superseded_by(pool, opts=None): + """{worker: the newest worker of its maker and class that replaces it}, over the usable `pool`. Workers + that share a recorded maker and class are versions of one model whichever provider carries them; the + older version is replaced by the newest one whatever its record or price. Pure.""" + groups = {} + for c in pool: + l = _comparable(c, opts) + if l: + groups.setdefault(tuple(l["key"]), []).append(c) + out = {} + for group in groups.values(): + for c in group: + newer = [d for d in group if compare_release(_lineage(d), _lineage(c)) > 0] + if newer: + out[c["worker"]] = _versions_newest_first(newer)[0][0]["worker"] + return out + + +def _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts=None, difficulty=None): + """The workers that may be recommended at all: (eligible, passed, stats, author_maker, superseded).""" exclude = {str(x) for x in exclude} stats = candidate_stats(candidates, records) passed = [] eligible = [] + tried = [] # usable workers already tried in this delegation: still the newest version, so older ones stay out for c in candidates: w = c["worker"] + why = _unusable(c, availability, now) if w in exclude: passed.append((w, "already tried in this delegation")) - continue - if "contributor" in str(c.get("model") or w).lower(): - passed.append((w, "its id contains 'contributor', a tier that trains on prompts")) - continue - if c.get("unproven") and isinstance(difficulty, int) and difficulty > max(1, vouch_level(c)): + if why is None: + tried.append(c) + elif why is not None: + passed.append((w, why)) + elif c.get("unproven") and isinstance(difficulty, int) and difficulty > max(1, vouch_level(c)): passed.append((w, "unproven: a new worker with no judged record is offered routine work (difficulty 1) only")) - continue - down = _down_entry(c, availability, now) - if down is not None: - passed.append((w, "unavailable (%s) until its retry time" % (down.get("reason") or "down"))) - continue - if not c.get("usable", True): - passed.append((w, c.get("reason") or "not usable now")) - continue - if c.get("plan") == "flat" and c.get("allowance_pct_left") == 0: - passed.append((w, "its flat-rate allowance is spent")) - continue - eligible.append(c) + else: + eligible.append(c) avoided = [(c, _pattern_match(c, avoid)) for c in eligible] kept = [c for c, m in avoided if m is None] @@ -382,6 +574,7 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of, passed.append((c["worker"], "avoided by the user's own pattern %r%s" % (pat, (" (%s)" % why) if why else ""))) eligible = kept + tried = [c for c in tried if _pattern_match(c, avoid) is None] author_maker = "" if review_of: @@ -399,18 +592,47 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of, else: rest.append(c) eligible = rest - return eligible, passed, stats, author_maker + tried = [c for c in tried if (c.get("maker") or maker_of(c.get("model") or c["worker"])) != author_maker] + + superseded = superseded_by(eligible + tried, opts) + if superseded: + for c in eligible: + if c["worker"] in superseded: + passed.append((c["worker"], "superseded by %s (a newer version of the same class)" % superseded[c["worker"]])) + eligible = [c for c in eligible if c["worker"] not in superseded] + return eligible, passed, stats, author_maker, superseded -def _assess_all(eligible, stats, kind, difficulty, floors): +def _assess_all(eligible, stats, kind, difficulty, floors, opts=None): """({worker: assessment}, best standing among the usable workers).""" standings = [s for s in (_standing_of(c) for c in eligible) if s is not None] best = max(standings) if standings else None - return ({c["worker"]: assess(stats, c["worker"], kind, difficulty, _standing_of(c), best, floors, vouch_level(c)) + spans = (opts or {}).get("class_span") + return ({c["worker"]: assess(stats, c["worker"], kind, difficulty, _standing_of(c), best, floors, + rank=class_rank(c, opts), spans=spans, vouch=vouch_level(c)) for c in eligible}, best) -def _make_key(stats, kind, difficulty, prefer): +def recency_order(candidates): + """{worker: position among the versions of its own model, newest first (0)}. Only versions of the same model + (the same recorded maker and class) are ever compared; models of different makers or classes are different + things, however recently each was released, and stay at 0 so the old tie-break decides between them.""" + out = {c["worker"]: 0 for c in candidates} + groups = {} + for c in candidates: + l = _comparable(c) + if l: + groups.setdefault(tuple(l["key"]), []).append(c) + for group in groups.values(): + for i, level in enumerate(_versions_newest_first(group)): + for d in level: + out[d["worker"]] = i + return out + + +def _make_key(stats, kind, difficulty, prefer, recency=None): + recency = recency or {} + def rate(c): cell = _cell(stats, c["worker"], kind, difficulty) return (cell["good"] / cell["n"]) if cell["n"] else None @@ -434,9 +656,10 @@ def _make_key(stats, kind, difficulty, prefer): standing_key(c), load_ratio(c), -(r if r is not None else -1.0), + recency.get(c["worker"], 0), c["worker"]) - return key, rate, load_ratio + return key, rate, load_ratio, recency def _prefer_judged(capable, assessments, difficulty): @@ -450,6 +673,9 @@ def _prefer_judged(capable, assessments, difficulty): own = [c for c in capable if assessments[c["worker"]]["tier"] in tiers] if own: return own, True + benchmarked = [c for c in capable if assessments[c["worker"]]["tier"] == "standing"] + if benchmarked and len(benchmarked) < len(capable): + return benchmarked, False # a benchmark standing outranks a class's place in its maker's order return list(capable), False @@ -469,7 +695,7 @@ def _select(eligible, assessments, difficulty): return weak, "weak" top = max(strength(assessments[c["worker"]]) for c in live) pool = [c for c in live if strength(assessments[c["worker"]]) == top] - return pool, ("nothing" if top[0] <= 1 else "strongest") + return pool, ("nothing" if top[:2] <= (1, 0) else "strongest") def _free_slot(choice, ranked, candidates, stats, kind, difficulty, basis, prefer, every): @@ -488,15 +714,15 @@ def _free_slot(choice, ranked, candidates, stats, kind, difficulty, basis, prefe def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(), - avoid=None, prefer=None, floors=None, explore_free_every=EXPLORE_FREE_EVERY): + avoid=None, prefer=None, floors=None, opts=None, explore_free_every=EXPLORE_FREE_EVERY): """Pick one candidate, or none. Returns {"choice", "passed_over", "stats", "author_maker", ...}. `passed_over` is [(worker, plain reason)] covering every candidate not chosen. `avoid` and `prefer` are the user's own [{"pattern", "why"}] constraints; `floors` the standing floors.""" now = float(now or 0) - eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of, - difficulty) - assessments, best = _assess_all(eligible, stats, kind, difficulty, floors) - key, rate, load_ratio = _make_key(stats, kind, difficulty, prefer) + eligible, passed, stats, author_maker, superseded = _prepare(candidates, records, availability, now, exclude, + avoid, review_of, opts, difficulty) + assessments, best = _assess_all(eligible, inherit_stats(candidates, stats, opts), kind, difficulty, floors, opts) + key, rate, load_ratio, recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible)) pool, basis = _select(eligible, assessments, difficulty) if eligible else ([], "none") detail = {} @@ -558,6 +784,8 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, r, cr = rate(c), rate(choice) reason = ("lower measured accepted rate for this kind and difficulty" if r is not None and cr is not None and r < cr else + "equal on price and load; the choice is the more recently released" + if recency.get(choice["worker"], 0) < recency.get(c["worker"], 0) else "equal on price and load; the choice came first in worker-id order") passed.append((w, reason)) judged_first = basis == "capable" and _prefer_judged(pool, assessments, difficulty)[1] @@ -567,9 +795,27 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, "load_ratios": {c["worker"]: load_ratio(c) for c in candidates}, "assessments": assessments, "basis": basis, "capable_count": capable_n, "judged_first": judged_first, "best_standing": best, "passed_detail": detail, "floors": floors, + "superseded": superseded, "class_ask": class_ask(eligible, pool, opts), "kind": kind, "difficulty": difficulty} +def class_ask(eligible, pool, opts=None): + """What the lead agent should be asked to have recorded, because the answer could depend on it: + {"classify": [workers], "order": [(maker, [classes])]}. + classify: a worker with no classification (none stored, not even "unknown") that is in the pool competing for the + request while another usable worker exists; a worker kept out for lack of capability could not change the answer. + order: a maker with two or more recorded classes among the usable workers and no recorded class order.""" + labels = {} + for c in eligible: + l = _comparable(c) + if l: + labels.setdefault(l["maker"], set()).add(l["label"]) + recorded = (opts or {}).get("class_orders") or {} + return {"classify": sorted(c["worker"] for c in pool if not _comparable(c) and not c.get("classified")) + if len(eligible) > 1 else [], + "order": [(m, sorted(ls)) for m, ls in sorted(labels.items()) if len(ls) > 1 and m not in recorded]} + + def _why_not(a, difficulty, basis, cheaper): """(plain reason, short per-worker detail) for a worker kept out of the pool by what is known about its capability. The reason text is the same for every worker it applies to, so reasons group.""" @@ -585,9 +831,14 @@ def _why_not(a, difficulty, basis, cheaper): "for this kind is usable", None) if a["tier"] == "vouch": return (lead + "capable by the owner's word, and a worker with a judged record for this kind is usable", None) - return (lead + "capable only by benchmark standing or as an exploration; above difficulty 1 a worker " - "with a judged record is preferred to a benchmark", + return (lead + "capable only by benchmark standing, its class's place in its maker's order, or as an " + "exploration; above difficulty 1 a worker with a judged record is preferred to a benchmark, and a " + "benchmark to a class order", ("standing %g" % a["standing"]) if a["standing"] is not None else None) + if a["tier"] == "class": + return (lead + "not capable enough for difficulty %d: its class is place %d of %d in its maker's recorded order, " + "and difficulty %d reaches only the top %g%% of it" % (difficulty, a["class_pos"] + 1, a["class_n"], + difficulty, a["class_allowed"]), None) if a.get("below"): return (lead + "not capable enough for difficulty %d: benchmark standing under the %g needed " "(%g%% of the best usable standing, %g)" % (difficulty, a["needed"], a["floor"], a["best"]), @@ -611,7 +862,7 @@ def _why_not(a, difficulty, basis, cheaper): def retry_choice(candidates, records, availability, kind, difficulty, rejected, rejections, - now=0.0, exclude=(), avoid=None, prefer=None, floors=None, review_of=None): + now=0.0, exclude=(), avoid=None, prefer=None, floors=None, review_of=None, opts=None): """Who gets a task again after `rejected` (a worker id) was rejected `rejections` times in this chain. The first retry goes back to the same worker while it is still usable and has no poor record. After that: the cheapest capable worker whose evidence is strictly better than the rejected one's, or, when there is none, @@ -619,10 +870,11 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, else is usable). Returns {"choice", "step", "assessments", ...}; step is "same", "better", "strongest" or "only", and choice is None when nobody is usable. Pure; the caller supplies facts.""" now = float(now or 0) - eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of, - difficulty) - assessments, best = _assess_all(eligible, stats, kind, difficulty, floors) - key, _rate, _load = _make_key(stats, kind, difficulty, prefer) + eligible, passed, stats, author_maker, _superseded = _prepare(candidates, records, availability, now, exclude, + avoid, review_of, opts, difficulty) + eff = inherit_stats(candidates, stats, opts) + assessments, best = _assess_all(eligible, eff, kind, difficulty, floors, opts) + key, _rate, _load, _recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible)) out = {"choice": None, "step": None, "passed_over": passed, "stats": stats, "author_maker": author_maker, "assessments": assessments, "best_standing": best, "kind": kind, "difficulty": difficulty, "rejected": rejected, "rejections": rejections} @@ -637,7 +889,8 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, return out gone = next((c for c in candidates if c["worker"] == rejected), None) floor = (strength(assessments[rejected]) if mine is not None else - strength(assess(stats, rejected, kind, difficulty, _standing_of(gone) if gone else None, best, floors))) + strength(assess(eff, rejected, kind, difficulty, _standing_of(gone) if gone else None, best, floors, + rank=class_rank(gone, opts) if gone else None, spans=(opts or {}).get("class_span")))) better = [c for c in others if assessments[c["worker"]]["capable"] and strength(assessments[c["worker"]]) > floor] better = _prefer_judged(better, assessments, difficulty)[0] if better: @@ -672,6 +925,13 @@ def evidence_line(a, kind, difficulty, choice, basis): if a["bad"]: return ("evidence: none favourable; every usable worker has a poor record, so this one has the best " "accepted rate (%d of %d for %s)" % (a["good"], a["n"], kind)) + line = _evidence_line(a, kind, difficulty, choice, basis) + if a.get("inherited_from"): + line += " (the record of its predecessor %s; it has none of its own yet)" % a["inherited_from"] + return line + + +def _evidence_line(a, kind, difficulty, choice, basis): tier = a["tier"] if tier == "a": return ("evidence (a), judged record: %d of %d accepted for %s at difficulty %d (%s, bar %s)" @@ -699,6 +959,10 @@ def evidence_line(a, kind, difficulty, choice, basis): return ("evidence (the owner's word): vouched for up to difficulty %d%s (%s, %s); it ranks with judged proof " "until its own record is thick" % (a["at"], " (relayed by an agent: counted up to difficulty 2 only)" if v.get("relayed") else "", _short(v.get("why")), v.get("date") or "no date stated")) + if tier == "class": + return ("evidence (class order): place %d of %d in its maker's recorded class order, which reaches the top %g%% " + "for difficulty %d; no judged record or benchmark decides" % (a["class_pos"] + 1, a["class_n"], + a["class_allowed"], difficulty)) if tier == "unknown": return "evidence (d): nothing is known about this worker yet; it is an exploration on low-stakes work" if a.get("weak"): diff --git a/sisi/tick.py b/sisi/tick.py index 1474619..3d7e02d 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -103,13 +103,13 @@ def main(args=()): store.log_error("tick-workers", e) try: # ONE line for new worker models and new command-line tools (each kind is announced once) sess3 = rec or store.load_session(sid) - from . import discovery, workers as _W3 - if not sess3.get("subagent") and not _W3.is_subagent_payload(payload): + from . import discovery, workers as _W3, workerid as _WI + if not _WI.is_worker_session(payload, sess3, {}): models = [] try: models = _W3.new_worker_names() - except Exception as e: - store.log_error("tick-new-workers", e) + except Exception as ex: + store.log_error("tick-new-workers", ex) tools = discovery.new_tools() # the first run only stores the list line = discovery.new_line(models, tools) if line: diff --git a/sisi/unitguard.py b/sisi/unitguard.py index e5c53c0..9ea87c9 100644 --- a/sisi/unitguard.py +++ b/sisi/unitguard.py @@ -683,7 +683,8 @@ def classify(tool, payload, cmd): t = tool or "" if t in _list("edit_tools") or any(w in t.lower() for w in _list("edit_name_words")): return "edit" - if t in _list("delegation_tools"): + from . import orchestration + if orchestration.is_delegation(store.tool() or "claude-code", t): return "delegate" if watch.is_shell(t, cmd): return "shell" @@ -805,22 +806,22 @@ def before(payload): def _before(payload): - from . import attribution, watch, workers + from . import attribution, watch, workerid tool, cmd, _ev, cwd, sid = watch.extract(payload) kind = classify(tool, payload, cmd) if kind is None: return None - if not store.config()["gate"].get("enabled", True) or workers.is_subagent_payload(payload): + if not store.config()["gate"].get("enabled", True): return None sid = sid or "cwd-" + cwd + if workerid.session_is_worker(payload, sid, cwd): + return None if kind == "shell": if CLAIM_RE.search(cmd or ""): note_claim(sid, cwd) if watch._may_write(cmd) is False or _is_sisi_command(cmd): return None sess = store.load_session(sid) - if sess.get("subagent"): - return None top = git_top(cwd) if top is None: return None # nothing to measure outside a repository @@ -918,12 +919,12 @@ def after(payload): def _after(payload): - from . import watch + from . import watch, workerid tool, cmd, _ev, cwd, sid = watch.extract(payload) sid = sid or "cwd-" + cwd sess = store.load_session(sid) - if not sess: - return + if not sess or workerid.session_is_worker(payload, sid, cwd): + return # a worker's changes are its parent's to answer for, never bookkept as this session's dirty = False top = git_top(cwd) if sess.get("ug_will_bind"): @@ -933,7 +934,7 @@ def _after(payload): if c is not None: bind(sid, proj, c, "wrote") sess = store.load_session(sid) - if top and classify(tool, payload, cmd) == "shell" and not sess.get("subagent"): + if top and classify(tool, payload, cmd) == "shell": dirty = _absorb(sess, top) or dirty # a change the before-hook could not see: the next counted call answers for it if dirty: store.save_session(sid, sess) diff --git a/sisi/watch.py b/sisi/watch.py index 4eedf25..a62863c 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -317,7 +317,8 @@ def run(payload, args=(), host=None): _tool, _cmd, ev, _cwd, sid = extract(payload) out = {} if "--before" in args or ev in BEFORE_EVENTS: - if not worker_session(payload, sid, _cwd): + from . import workerid + if not workerid.session_is_worker(payload, sid, _cwd): text = contract_guard(payload) if text: return {"deny": text} @@ -353,21 +354,6 @@ def run(payload, args=(), host=None): return out -def worker_session(payload, sid, cwd): - """Is this call from a worker or subagent (the host marks it, `sisi delegate` started it, or its first - prompt opened with the brief template's line)? Workers are exempt from the contract guard and the meter. - False when it cannot be told.""" - try: - if store.is_subagent_payload(payload): - return True - from . import orchestration - sid = sid or "cwd-" + cwd - return bool(store.load_session(sid).get("subagent") or orchestration.worker_flag(sid)) - except Exception as e: - store.log_error("watch-worker", e) - return False - - def render_claude(out, event): """The Claude Code hook output for a run() result, or None.""" if out.get("deny"): diff --git a/sisi/workerid.py b/sisi/workerid.py new file mode 100644 index 0000000..4dc4997 --- /dev/null +++ b/sisi/workerid.py @@ -0,0 +1,117 @@ +"""Who is a worker: the one decision, used by the contract guard, the meter, the delegation guard, the fallback +logic and the gate (R-7.1-1, R-7.2-2, R-16-1). A session is a worker when the host marks it as a subagent, +`sisi delegate` started it, or its FIRST user message opens like a brief (canon/worker-openings.json). A session +a person started is a main thread. Fails open: an error is "main thread" (the safe default), never stored.""" +import json, os + +from . import paths, store + +_DATA = {} + + +def _data(): + if not _DATA: + try: + with open(paths.canon("worker-openings.json"), encoding="utf-8") as f: + _DATA.update(json.load(f)) + except (OSError, ValueError): + return {} + return _DATA + + +def _squash(text): + return " ".join(str(text or "").split()).lower() + + +def opens_as_brief(text): + """Does this first user message open like a brief: a listed phrase (or the template's first line) within the + first `window` characters?""" + d = _data() + try: + window = int(d.get("window") or 400) + except (TypeError, ValueError): + window = 400 + head = _squash(str(text or "")[:window * 3])[:window] + phrases = [_squash(p) for p in d.get("openings") or [] if isinstance(p, str) and p.strip()] + try: + from . import brief + phrases.append(_squash(brief.template().splitlines()[0])) + except Exception: + pass + return any(p and p in head for p in phrases) + + +def _read_head(path, nbytes): + """(bytes, whole) from the start of the file: `whole` says the file ended inside the bound.""" + with open(os.path.expanduser(path), "rb") as f: + raw = f.read(nbytes + 1) + return raw[:nbytes], len(raw) <= nbytes + + +def first_user_text(path): + """(found, text): the first message the person typed, from only the head of the transcript. `found` is False + when the transcript cannot be read or holds no such message yet.""" + from . import harvest + try: + nbytes = int(_data().get("head_bytes") or 1048576) + raw, whole = _read_head(path, nbytes) + except (OSError, TypeError, ValueError): + return False, "" + lines = raw.split(b"\n") + if not whole: + lines = lines[:-1] # the last line is cut by the bound + for line in lines: + if b'"user"' not in line or b"toolUseResult" in line: + continue + try: + d = json.loads(line) + except ValueError: + continue + if isinstance(d, dict) and d.get("type") == "user": + text = harvest.typed_text(d)[0] + if text is not None: + return True, text + return False, "" + + +def is_worker_session(payload, session_record, meter_record): + """True for a worker or subagent session. A decision made from the transcript is written into + `meter_record` (key "worker"); the caller saves it. Without a readable first message nothing is stored.""" + payload = payload if isinstance(payload, dict) else {} + sess = session_record if isinstance(session_record, dict) else {} + if store.is_subagent_payload(payload) or sess.get("subagent"): + return True + if not isinstance(meter_record, dict): + return False + if "worker" in meter_record: + return bool(meter_record["worker"]) + tp = payload.get("transcript_path") or sess.get("transcript_path") + if not isinstance(tp, str) or not tp: + return False + found, text = first_user_text(tp) + if not found: + return False + meter_record["worker"] = opens_as_brief(text) + meter_record["worker_from"] = "transcript" + return bool(meter_record["worker"]) + + +def session_is_worker(payload, sid, cwd=None): + """The same decision for a caller holding no records: reads them, and keeps a new decision in the session's + meter record so the transcript is read once.""" + try: + from . import orchestration + sid = sid or "cwd-" + (cwd or os.getcwd()) + sess = store.load_session(sid) + m = orchestration._peek(sid) + had = "worker" in m + found = is_worker_session(payload, sess, m) + if not had and "worker" in m: + with orchestration.Meter(sid) as real: + real.setdefault("worker", m["worker"]) + real.setdefault("worker_from", m.get("worker_from")) + found = bool(real["worker"]) + return found + except Exception as e: + store.log_error("workerid", e) + return False diff --git a/sisi/workers.py b/sisi/workers.py index 0d9c0ec..d9b6d18 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -21,6 +21,12 @@ Personal files (all in the personal data folder): model-strength.json worker facts (benchmark standing, a published figure; never the measured accepted rate): {"models": {"": {"standing": 0..100, "source": text, "date": "YYYY-MM-DD"}}} + worker-models.json what the lead agent decided about each model: {"models": {"": + {"class": name, "maker": name, "released": "YYYY-MM-DD", + "source": text, "date": "YYYY-MM-DD"}}, "classes": {"": {"order": [class, + most capable first], "source": text, "date": "YYYY-MM-DD"}}}, written by + `sisi workers fact --class ...` and `sisi workers classes`. sisi reads + nothing from a model's name: these facts are researched by a cheap worker. worker-prefs.json the user's own routing constraints: {"avoid": [{"pattern", "why"}], "prefer": [...], "only": [{"provider", "patterns", "why"}]}, written by `sisi workers avoid|prefer|only` @@ -761,6 +767,26 @@ def entry_cost(entry): return float(single) if isinstance(single, (int, float)) and not isinstance(single, bool) else None +def models_path(): + return _data_file("worker-models.json") + + +def load_model_facts(): + """({worker or model: class fact}, {maker: class order}) from worker-models.json.""" + d = read_json(models_path()) + models = d.get("models") if isinstance(d.get("models"), dict) else {} + classes = d.get("classes") if isinstance(d.get("classes"), dict) else {} + return models, classes + + +def route_opts(): + """Routing options: the maker class orders the lead agent recorded (`sisi workers classes`) and + `route.class_span`, how far down an order each difficulty reaches.""" + orders = {m: [str(x) for x in e["order"]] for m, e in load_model_facts()[1].items() + if isinstance(e, dict) and isinstance(e.get("order"), list)} + return {"class_orders": orders, "class_span": route_cfg().get("class_span")} + + def route_floors(): """{difficulty: percent of the best usable standing needed} from `route.standing_floor`.""" return routing.standing_floors(route_cfg().get("standing_floor")) @@ -814,10 +840,11 @@ def build_candidates(disc=None, records=None): records = read_records() if records is None else records prices = load_prices() prior = load_strength_prior() + model_facts = load_model_facts()[0] disc_tools = _D.merge_tools(disc.get("tools") or []) cands, seen = [], set() - def add(tool, model, usable=True, reason=None, allowance=None, tool_plan=None): + def add(tool, model, usable=True, reason=None, allowance=None, tool_plan=None, host_native=False): worker = _canonical(tool, model) if tool else str(model) if worker.lower() in seen: return None @@ -827,7 +854,10 @@ def build_candidates(disc=None, records=None): prior_entry = next((prior[k] for k in (worker, model) if k and isinstance(prior.get(k), dict)), {}) standing = standing_of(prior_entry) - c = {"worker": worker, "tool": tool, "model": model, + fact = next((model_facts[k] for k in (worker, model) if k and isinstance(model_facts.get(k), dict)), {}) + maker_fact = price.get("maker") or prior_entry.get("maker") or fact.get("maker") + lineage = routing.lineage_from_fact(dict(fact, maker=maker_fact) if maker_fact else fact, host_native=host_native) + c = {"worker": worker, "lineage": lineage, "classified": bool(fact), "tool": tool, "model": model, "maker": price.get("maker") or prior_entry.get("maker") or routing.maker_of(model or worker), "plan": price.get("plan") or tool_plan, "cost": cost, @@ -865,7 +895,7 @@ def build_candidates(disc=None, records=None): if "/" not in str(w): # No provider prefix: the host tool's own subagent model. It needs no discovered # command-line tool and is usable unless marked down (routing checks that). - c = add(None, str(w), usable=True) + c = add(None, str(w), usable=True, host_native=True) if c is not None: c["host_native"] = True alias_set.add(str(w).lower()) @@ -979,7 +1009,7 @@ def notes_for(candidates_by_worker, chosen, passed, notes=None, limit=5): DATA_FILES = ("delegations.jsonl", "worker-availability.json", "worker-prices.json", - "model-strength.json", "worker-prefs.json", "worker-notes.json", "worker-drivers.json", + "model-strength.json", "worker-prefs.json", "worker-notes.json", "worker-models.json", "worker-drivers.json", "worker-providers.json", "worker-vouches.json") @@ -1058,20 +1088,23 @@ def facts_status(now=None): return {"state": "ok", "newest": newest, "max_age_days": max_age} -def facts_line(now=None): - """One session-start line asking for worker facts to be researched, or "" when they are fresh.""" +def facts_line(now=None, unclassified=0): + """One session-start line asking for worker facts to be researched, or "" when they are fresh and every routable + worker is classified. `unclassified` is how many routable workers have no recorded maker, class and release date.""" status = facts_status(now) targets = _D.facts_targets(_cached_candidates()[0]) + ask = ("%d routable worker%s no recorded maker, class and release date, so never compared with another version " + "(`sisi workers classify`)." % (unclassified, " has" if unclassified == 1 else "s have")) if status["state"] == "ok" and not targets: - return "" + return ("sisi: " + ask) if unclassified else "" if targets: what = "worker facts are missing for %s" % _D.facts_phrase(targets) elif status["state"] == "missing": what = "worker facts are missing (no prices or benchmark standing recorded yet)" else: what = "worker facts are stale (newest from %s)" % (status["newest"] or "an unstated date") - return ("sisi: %s: a cheap worker can research them (`sisi workers fact WORKER --price N|--standing N " - "--source S`); until then routing uses the judged record alone." % what) + return ("sisi: %s: have a cheap worker research them (`sisi workers fact W --price N|--standing N " + "--source S`).%s" % (what, (" " + ask) if unclassified else "")) def estimate_cost(tokens, price_entry): @@ -1098,6 +1131,9 @@ def routable_candidates(candidates, records): keep.append(c) if not keep: return list(candidates), True, 0 + # a new version of a model that has a record, price or standing starts from its predecessor's record + opts = route_opts() + keep = keep + [c for c in candidates if c not in keep and routing.has_predecessor(c, keep, opts)] return keep, False, len(candidates) - len(keep) @@ -1169,7 +1205,7 @@ def recommend(kind, difficulty, cwd=None, own_model=None): candidates, _limited = apply_limits(candidates, prefs) result = routing.choose(candidates, records, read_availability(), kind, difficulty, now=time.time(), exclude=_own_workers(candidates, own_model), avoid=prefs["avoid"], prefer=prefs["prefer"], - floors=route_floors(), explore_free_every=explore_free_every()) + floors=route_floors(), opts=route_opts(), explore_free_every=explore_free_every()) choice = result["choice"] if choice is None: return None, None, 0 @@ -1441,12 +1477,12 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty, review_of=review_of, now=time.time(), exclude=tried, avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(), - explore_free_every=explore_free_every()) + opts=route_opts(), explore_free_every=explore_free_every()) cand = result["choice"] if cand is None: 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"] + avoid=prefs["avoid"], prefer=prefs["prefer"], opts=route_opts())["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: " @@ -1554,8 +1590,8 @@ def is_subagent_payload(payload): return store.is_subagent_payload(payload) -def _with_facts(lines): - line = facts_line() +def _with_facts(lines, unclassified=0): + line = facts_line(unclassified=unclassified) return lines + [line] if line else lines @@ -1565,7 +1601,8 @@ def session_lines(model, payload=None): a missing number never argues against orchestrating. At most one extra line asks for worker facts to be researched when they are missing or stale (the caller shows these lines once per session). Uses only cached discovery and the record.""" - if not model or is_subagent_payload(payload or {}): + from . import workerid + if not model or workerid.is_worker_session(payload or {}, {}, None): return [] records = read_records() candidates, _tools = _cached_candidates(records) @@ -1600,7 +1637,7 @@ def session_lines(model, payload=None): suffix)) elif suffix: lines.append("sisi:" + suffix) - return _with_facts(lines) + return _with_facts(lines, len(unclassified_workers(candidates, records))) # ---------------------------------------------------------------- commands @@ -1658,6 +1695,22 @@ def _price_lines(tool_name, models, prices, shown_keys=None): return lines +def model_lines(cands, limit=40): + """One line per routable worker: its recorded maker, class and release date, or that none is recorded.""" + out = [] + for c in sorted(cands, key=lambda c: c["worker"]): + l = c.get("lineage") or {} + if l.get("source") != "fact": + out.append(" %s: no maker and class recorded" % c["worker"]) + continue + when = ("released %s" % l["released"]) if l.get("released") else ( + "newest of its class (a bare host alias)" if l.get("alias") else "no release date recorded") + out.append(" %s: maker %s, class %s; %s" % (c["worker"], l["maker"], l["label"], when)) + if len(out) > limit: + out = out[:limit] + [" ... and %d more" % (len(out) - limit)] + return out + + def cmd_workers(args=()): args = list(args) if args[:1] == ["fact"]: @@ -1668,6 +1721,10 @@ def cmd_workers(args=()): return _cmd_only(args[1:]) if args[:1] == ["note"]: return _cmd_note(args[1:]) + if args[:1] == ["classes"]: + return _cmd_classes(args[1:]) + if args[:1] == ["classify"]: + return _cmd_classify(args[1:]) if args[:1] == ["down"]: return _cmd_down(args[1:]) if args[:1] == ["up"]: @@ -1736,6 +1793,15 @@ def cmd_workers(args=()): for standing, worker, entry in standings: print(" benchmark standing %g - %s: %s (%s)" % (standing, worker, entry.get("source") or "no source stated", entry.get("date") or "no date stated")) + for maker, e in sorted(load_model_facts()[1].items()): + if isinstance(e, dict): + print(_classes_line(maker, e)) + routable, cold, _excluded = routable_candidates(build_candidates(disc, records), records) + if routable and not cold: + print("Model lines (the recorded maker, class and release date of each routable worker; sisi reads nothing " + "from a name: `sisi workers classify` asks a cheap worker):") + for line in model_lines(routable): + print(line) down_now = [(k, v) for k, v in sorted(avail.items()) if isinstance(v, dict)] for k, v in down_now: if k in {t["name"] for t in disc.get("tools") or []}: @@ -1840,7 +1906,8 @@ def _route_retry(args, ctx, kind, difficulty, candidates, records, prefs): strongest known.""" rejected = ctx["rejected"] res = routing.retry_choice(candidates, records, read_availability(), kind, difficulty, rejected[0], len(rejected), - now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors()) + now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(), + opts=route_opts()) pick = res["choice"] if pick is None: print("no usable worker for kind %s at difficulty %d after a rejection by %s" @@ -1869,6 +1936,22 @@ def route_decision(kind, difficulty, worker, retry_of=None): store.log_error("route-decision", e) +def class_line(result): + """The one line asking the lead agent to have the maker, class and release date recorded for the workers that + lack them (a cheap, fast worker does the research), or None.""" + ask = result.get("class_ask") or {} + names = ask.get("classify") or [] + if not names and ask.get("order"): + maker, labels = ask["order"][0] + return ("sisi: classify %s's models and record the order, most capable first: `sisi workers classes %s %s --source S` " + "(classes seen: %s)" % (maker, maker, " ".join(labels), ", ".join(labels))) + if not names: + return None + return ("sisi: no maker, class and release date are recorded for %s%s, so it is never compared with a newer or older " + "version: run `sisi workers classify`, hand its output to a fast, cheap worker, then `sisi workers classify --record FILE`" + % (names[0], (" and %d more" % (len(names) - 1)) if len(names) > 1 else "")) + + def cmd_route(args=()): retry_id = _opt(args, "--retry-of") ctx = None @@ -1897,7 +1980,7 @@ def cmd_route(args=()): result = routing.choose(candidates, records, read_availability(), kind, difficulty, review_of=_opt(args, "--review-of"), now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(), - explore_free_every=explore_free_every()) + opts=route_opts(), explore_free_every=explore_free_every()) result["passed_over"] = list(result["passed_over"]) + limited by_worker = {c["worker"]: c for c in everyone} down = _down_now(read_availability(), time.time()) @@ -1927,6 +2010,9 @@ def cmd_route(args=()): for line in notes_for(by_worker, result["choice"], result["passed_over"] if explain else [], limit=5 if explain else max(1, 5 - head)): print(line) + ask = class_line(result) + if ask: + print(ask) if explain: for line in routing.explain_choice(result, kind, difficulty): print(line) @@ -2279,7 +2365,9 @@ def _cmd_import(args): def _cmd_fact(args): usage = ("usage: sisi workers fact WORKER --price-in N --price-out N [--plan flat|per-use] [--maker M] --source S [--date YYYY-MM-DD]\n" " sisi workers fact WORKER --price N (one blended figure) [--plan ...] [--maker M] --source S\n" - " sisi workers fact WORKER --standing 0..100 --source S [--date YYYY-MM-DD] (--score is the old name)") + " sisi workers fact WORKER --standing 0..100 --source S [--date YYYY-MM-DD] (--score is the old name)\n" + " sisi workers fact WORKER --maker M --class NAME [--released YYYY-MM-DD] --source S\n" + " (the maker, class and release date of a model, as researched; sisi reads nothing from a name)") if not args: print(usage) return 1 @@ -2296,10 +2384,13 @@ def _cmd_fact(args): if not (price_ok and in_ok and out_ok and standing_ok and old_ok): print(usage) return 1 + model_fact = _model_fact_args(args) + if model_fact is False: + return 1 if (price_in is None) != (price_out is None) or (price is not None and price_in is not None): print("sisi: record either --price-in with --price-out, or one blended --price, not a mix", file=sys.stderr) return 1 - if price is None and price_in is None and standing is None: + if price is None and price_in is None and standing is None and not model_fact: print(usage) return 1 if min([v for v in (price, price_in, price_out) if v is not None] or [0]) < 0: @@ -2311,6 +2402,16 @@ def _cmd_fact(args): if standing is not None and not (0 <= standing <= 100): print("sisi: --standing wants a number from 0 to 100", file=sys.stderr) return 1 + if model_fact: + data = read_json(models_path()) + models = data.get("models") if isinstance(data.get("models"), dict) else {} + entry = dict(models.get(worker) or {}) + entry.update(model_fact, source=source, date=date) + models[worker] = entry + data["models"] = models + write_json(models_path(), data) + print("recorded for %s: %s (from %s, %s)" % (worker, ", ".join("%s %s" % kv for kv in sorted(model_fact.items())), + source, date)) if price is not None or price_in is not None: plan = _opt(args, "--plan") if plan is not None and plan not in ("flat", "per-use"): @@ -2357,6 +2458,183 @@ def _cmd_fact(args): return 0 +_NAME = re.compile(r"[a-z0-9][a-z0-9.+-]*") + + +def _model_fact_args(args): + """{class, maker, released} from the command line, {} when none is given, False (after saying why) when one is + malformed. The maker alone belongs to a price or standing fact, so it is read here only beside a class or a + release date.""" + out = {} + for opt, field in (("--class", "class"), ("--released", "released")): + v = _opt(args, opt) + if v is None: + continue + v = v.strip().lower() + if field == "released": + if not _valid_date(v): + print("sisi: --released wants a date as YYYY-MM-DD (or YYYY-MM)", file=sys.stderr) + return False + elif not _NAME.fullmatch(v): + print("sisi: %s wants a short name (letters, digits, hyphens)" % opt, file=sys.stderr) + return False + out[field] = v + if out and _opt(args, "--maker"): + out["maker"] = _opt(args, "--maker").strip().lower() + return out + + +CLASSIFY_BATCH = 40 +CLASSIFY_INSTRUCTION = """Classify these AI models. For each id below give: its maker; its class (the line or tier of that maker it +belongs to: a "flash" or "mini" beside a standard model, or a separately named line; one short lowercase word, +"standard" for a plain flagship); and its release date (YYYY-MM-DD, or YYYY-MM when the day is unknown). +For each maker also give its classes in order from most to least capable. Say "unknown" wherever you do not +know; do not guess. Answer with one JSON object and nothing else, in this shape: +{"workers": {"": {"maker": "...", "class": "...", "released": "..."}}, + "classes": {"": ["most capable class", "...", "least capable class"]}} +Ids to classify:""" + + +def unclassified_workers(candidates, records): + """Ids of routable workers with no classification stored (an answer of "unknown" counts as stored).""" + routable, cold, _ = routable_candidates(candidates, records) + return [] if cold else sorted(c["worker"] for c in routable if not c.get("classified")) + + +def _classify_answer(text): + """The JSON object in a worker's answer (it may be wrapped in prose or a code fence), or None.""" + for chunk in (text, text[text.find("{"):text.rfind("}") + 1] if "{" in text and "}" in text else ""): + try: + d = json.loads(chunk) + except ValueError: + continue + if isinstance(d, dict): + return d + return None + + +def _valid_date(v): + """A release date as YYYY-MM-DD or YYYY-MM.""" + try: + datetime.date.fromisoformat(v if len(v) == 10 else v + "-01") + except (ValueError, TypeError): + return False + return len(v) in (7, 10) + + +def _valid_name(v): + return isinstance(v, str) and (v.strip().lower() == "unknown" or bool(_NAME.fullmatch(v.strip().lower()))) + + +def _cmd_classify(args): + """`sisi workers classify` prints the question for a cheap, fast worker: the routable workers with no + classification and the instruction. `--record FILE [--by WORKER]` validates the answer and stores it.""" + records = read_records() + asked = unclassified_workers(build_candidates(records=records), records) + path = _opt(args, "--record") + if path is None: + if not asked: + print("every routable worker is classified.") + return 0 + print(CLASSIFY_INSTRUCTION) + for w in asked[:CLASSIFY_BATCH]: + print(w) + if len(asked) > CLASSIFY_BATCH: + print("(%d more: ask again after recording these)" % (len(asked) - CLASSIFY_BATCH)) + return 0 + try: + with open(path, encoding="utf-8") as f: + text = f.read() + except OSError as e: + print("sisi: cannot read %s: %s" % (path, e), file=sys.stderr) + return 1 + answer = _classify_answer(text) + given = answer.get("workers") if isinstance(answer, dict) else None + if not isinstance(given, dict): + print('sisi: the answer is not a JSON object with a "workers" object; nothing recorded', file=sys.stderr) + return 1 + strangers = sorted(w for w in given if w not in set(asked)) + if strangers: + print("sisi: not asked about (or already classified): %s; nothing recorded" % ", ".join(strangers[:5]), file=sys.stderr) + return 1 + clean = {} + for w, e in given.items(): + released = e.get("released", "unknown") if isinstance(e, dict) else None + ok = isinstance(e, dict) and _valid_name(e.get("maker")) and _valid_name(e.get("class")) + if ok and str(released).lower() != "unknown": + ok = isinstance(released, str) and _valid_date(released) + if not ok: + print("sisi: the entry for %s is not {maker, class, released} with short names and a YYYY-MM[-DD] date " + "(or unknown); nothing recorded" % w, file=sys.stderr) + return 1 + clean[w] = {"maker": e["maker"].strip().lower(), "class": e["class"].strip().lower(), + "released": str(released).strip().lower() if str(released).lower() != "unknown" else "unknown"} + orders = answer.get("classes") if isinstance(answer.get("classes"), dict) else {} + source = "classified by %s" % (_opt(args, "--by") or "a cheap worker") + date = time.strftime("%Y-%m-%d", time.localtime()) + data = read_json(models_path()) + models = data.get("models") if isinstance(data.get("models"), dict) else {} + classes = data.get("classes") if isinstance(data.get("classes"), dict) else {} + for w, e in clean.items(): + entry = {k: v for k, v in e.items() if not (k == "released" and v == "unknown")} + models[w] = dict(entry, source=source, date=date) + stored_orders = 0 + for maker, order in orders.items(): + names = [str(x).strip().lower() for x in order] if isinstance(order, list) else [] + maker = str(maker).strip().lower() + if (maker and maker != "unknown" and maker not in classes and len(names) > 1 and len(set(names)) == len(names) + and all(_NAME.fullmatch(x) for x in names)): + classes[maker] = {"order": names, "source": source, "date": date} + stored_orders += 1 + data["models"], data["classes"] = models, classes + write_json(models_path(), data) + unknown = sum(1 for e in clean.values() if "unknown" in (e["maker"], e["class"])) + print("recorded %d classification(s) (%d unknown) and %d class order(s), from %s" % (len(clean), unknown, stored_orders, source)) + return 0 + + +def _cmd_classes(args): + """`sisi workers classes MAKER CLASS [CLASS...] --source S` records a maker's classes, most capable first; + `sisi workers classes MAKER --remove` forgets them; no arguments lists them.""" + usage = ("usage: sisi workers classes MAKER CLASS [CLASS...] --source S [--date YYYY-MM-DD] (most capable class first)\n" + " sisi workers classes MAKER --remove") + data = read_json(models_path()) + classes = data.get("classes") if isinstance(data.get("classes"), dict) else {} + pos = _positional(args, ("--source", "--date")) + if not pos: + for maker, e in sorted(classes.items()): + print(_classes_line(maker, e)) + return 0 if classes else (print("no class order recorded yet.\n" + usage) or 0) + maker, names = pos[0].strip().lower(), [x.strip().lower() for x in pos[1:]] + if "--remove" in args: + if names or maker not in classes: + print(usage if names else "sisi: no class order is recorded for %s" % maker, file=sys.stderr) + return 1 + del classes[maker] + data["classes"] = classes + write_json(models_path(), data) + print("removed the class order of %s" % maker) + return 0 + source = _opt(args, "--source") + if not names or not source: + print(usage, file=sys.stderr) + return 1 + if any(not _NAME.fullmatch(x) for x in [maker] + names) or len(set(names)) != len(names): + print("sisi: a maker and each class is one short name (letters, digits, hyphens), none repeated", file=sys.stderr) + return 1 + entry = {"order": names, "source": source, "date": _opt(args, "--date") or time.strftime("%Y-%m-%d", time.localtime())} + classes[maker] = entry + data["classes"] = classes + write_json(models_path(), data) + print(_classes_line(maker, entry).strip().replace("Classes of", "recorded the classes of", 1)) + return 0 + + +def _classes_line(maker, e): + return "Classes of %s, most capable first: %s (%s, %s)" % (maker, ", ".join(e.get("order") or []), + e.get("source") or "no source stated", e.get("date") or "no date stated") + + def _cmd_pref(kind, args): prefs = load_prefs() if not args: diff --git a/tests/test_background_delegation.py b/tests/test_background_delegation.py new file mode 100644 index 0000000..857c045 --- /dev/null +++ b/tests/test_background_delegation.py @@ -0,0 +1,107 @@ +"""A background delegation is not finished when its launch call returns (R-7.1-1 the main agent owns and judges the +outcome, so it is asked to judge a result only once there is one; R-7.2-3 the routing record must not hold a +run's time as 0.01 minutes). The launch result and the later completion message are what the host's delegation tool +really sends: `{"taskId", "childThreadId", "status": "starting"|"running", "workState"}` and a message naming the task +with `[completed]`, `[failed]` or `[interrupted]`.""" +import json, unittest +from support import * +import test_meter as TM +from sisi import orchestration, workers + +TOOL = "mcp__t3-code__delegate_task" +INP = {"title": "Fix greeting parser", "task": "Outcome: x\nAcceptance: y\nFiles you may change: none", + "target": {"model": "alpha-small"}} +LAUNCH = {"taskId": "tk-77", "childThreadId": "th-88", "status": "running", "workState": "working"} + + +class Background(TM.MeterBase): + def launch(self, result=LAUNCH, use_id="u1", wrap=False): + self.prompt() + denied, text, _ = self.pre(TOOL, INP, tool_use_id=use_id) + self.assertFalse(denied, text) + resp = [{"type": "text", "text": json.dumps(result)}] if wrap else result + self.post(TOOL, INP, response=resp, tool_use_id=use_id) + return self.runs()[0] + + def runs(self): + return workers.merged_runs() + + def stop(self): + r = self.sisi("gate", "--tool", "claude-code", stdin=json.dumps( + {"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", "stop_hook_active": False})) + return json.loads(r.stdout) if r.stdout.strip() else {} + + def age(self, seconds): + with orchestration.Meter(self.sid) as m: + for e in m["pending"].values(): + e["t0"] -= seconds + + def notice(self, text): + return self.prompt(text, route=False) + + def test_a_running_launch_stays_pending_and_the_gate_says_nothing(self): + for wrap in (False, True): + with self.subTest(wrapped=wrap): + self.setUp() + run = self.launch(wrap=wrap) + self.assertEqual(run["status"], "pending") + self.assertEqual(workers.unjudged_runs(), []) + self.assertNotIn("not judged", self.stop().get("reason", "")) + + def test_the_completion_message_finishes_it_with_the_real_duration_and_the_gate_asks_once(self): + run = self.launch() + self.age(120) + self.notice("[completed] Task tk-77 (Fix greeting parser) finished: the parser now greets.") + run = self.runs()[0] + self.assertEqual(run["status"], "waiting") + self.assertAlmostEqual(run["minutes"], 2.0, delta=0.1) + first = self.stop() + self.assertEqual(first.get("decision"), "block") + self.assertIn("not judged yet", first["reason"]) + self.assertIn(run["id"], first["reason"]) + self.assertNotEqual(self.stop().get("decision"), "block") # once + + def test_the_message_may_name_the_task_by_its_title_instead_of_an_id(self): + self.launch() + self.notice("[completed] \"Fix greeting parser\" is done.") + self.assertEqual(self.runs()[0]["status"], "waiting") + + def test_a_failed_message_with_a_quota_error_marks_the_provider_down_and_hands_over_the_fallback(self): + self.launch() + r = self.notice("[failed] Task tk-77: 429 rate limit exceeded, quota exhausted for alpha-small") + self.assertIn("unavailable", r.stdout) + self.assertEqual(self.runs()[0]["status"], "superseded") + self.assertEqual(workers.unjudged_runs(), []) + self.assertIn("alpha-small", workers.read_availability()) + + def test_a_failed_message_that_is_not_unavailability_awaits_judgement(self): + self.launch() + self.notice("[failed] Task tk-77: the tests it was asked to make pass still fail") + self.assertEqual(self.runs()[0]["status"], "failed") + self.assertEqual([r["id"] for r in workers.unjudged_runs()], [self.runs()[0]["id"]]) + + def test_an_interrupted_message_supersedes_it_and_it_is_never_asked_for(self): + self.launch() + self.notice("[interrupted] Task tk-77 was stopped.") + self.assertEqual(self.runs()[0]["status"], "superseded") + self.assertNotIn("not judged", self.stop().get("reason", "")) + + def test_a_synchronous_delegation_carrying_the_report_is_finished_at_once(self): + run = self.launch(result={"status": "completed", "taskId": "tk-1", "result": "the parser now greets by name"}) + self.assertEqual(run["status"], "waiting") + self.assertEqual(self.stop().get("decision"), "block") + + def test_a_listed_tool_with_no_launch_data_and_a_bare_fast_result_is_a_launch(self): + self.prompt() + self.pre("Agent", {"description": "d", "prompt": "Outcome: x\nAcceptance: y", "model": "alpha-small"}, tool_use_id="a1") + self.post("Agent", {"description": "d"}, response={"agentRef": "z9", "status": "queued"}, tool_use_id="a1") + self.assertEqual(self.runs()[0]["status"], "pending") + + def test_an_unrelated_prompt_is_not_taken_for_a_notice(self): + self.launch() + self.prompt("please also fix the [failed] tests in other_module") + self.assertEqual(self.runs()[0]["status"], "pending") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_discovery.py b/tests/test_discovery.py index c6c0003..4975e0e 100644 --- a/tests/test_discovery.py +++ b/tests/test_discovery.py @@ -693,7 +693,7 @@ class FactsNameTheNewWorkers(DiscoveryCase): self.assertIn("worker facts are missing for the new workers p0/m", line) self.assertIn("and 4 more", line) self.assertEqual(sum(1 for i in range(7) if "p%d/m" % i in line), 3) - self.assertIn("sisi workers fact WORKER --price N", line) + self.assertIn("sisi workers fact W --price N", line) for i in range(7): self.write_data("model-strength.json", {"models": {"p%d/m" % j: {"standing": 40, "source": "s", "date": "2026-11-01"} for j in range(7)}}) diff --git a/tests/test_integration.py b/tests/test_integration.py index a97da6f..3659d09 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -11,7 +11,7 @@ from support import * import test_meter as TM import test_unitguard as TG from sisi import contract as C, gate, lifecycle, orchestration, prompt, routing, rulecmd, store, unit as U, unitguard as G -from sisi import watch, workers +from sisi import brief, watch, workers SRC = TG.SRC CONTRACT_LINES = 12 @@ -119,7 +119,7 @@ class OneRefusalAtATime(Both): self.assertIsNone(self.edit(agent_id="w1")) self.assertIsNone(self.agent(BUILD_BRIEF, agent_id="w1")) # a session whose first prompt opens with the brief template's line is a worker too - orchestration.new_turn("wk", self.proj, orchestration.brief_line() + "\nOutcome: x") + orchestration.new_turn("wk", self.proj, brief.template().splitlines()[0] + "\nOutcome: x") d = {"session_id": "wk", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Edit", "tool_input": {"file_path": os.path.join(self.proj, SRC), "old_string": "a", "new_string": "b"}} r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps(d)) @@ -346,7 +346,7 @@ class ConfigDefault(SisiCase): for section in ("gate", "verify", "retro", "route", "unit", "orchestrate"): self.assertIn(section, cfg) self.assertEqual(sorted(cfg["orchestrate"]), ["direct_calls", "direct_chars", "enabled", "extension", "route_window_min"]) - self.assertEqual(sorted(cfg["route"]), ["explore_free_one_in", "price_blend_input_parts", "standing_floor"]) + self.assertEqual(sorted(cfg["route"]), ["class_span", "explore_free_one_in", "price_blend_input_parts", "standing_floor"]) self.assertEqual(cfg["unit"], {"stale_hours": 12}) self.assertEqual(store.config()["orchestrate"]["direct_calls"], 6) diff --git a/tests/test_merge.py b/tests/test_merge.py index f7923ed..263c5e7 100644 --- a/tests/test_merge.py +++ b/tests/test_merge.py @@ -360,6 +360,27 @@ class LearnedWorkersEverywhere(HookCase): self.assertIsNotNone(out, "the learned driver's phrase counts") self.assertEqual(workers.read_availability()["fakeagent/fa-1"]["reason"], "limit") + def test_a_learned_worker_and_a_host_worker_are_classified_and_take_part_in_the_newest_version_rule(self): + self.learn() + self.listing() + asked = self.sisi("workers", "classify").stdout + for w in ("fakeagent/fa-1", "fakeagent/fa-2", "fakeagent/default", "alpha/m-1"): + self.assertIn(w, asked.splitlines(), w) + answer = os.path.join(self.tmp, "answer.json") + with open(answer, "w") as f: + json.dump({"workers": {"fakeagent/fa-1": {"maker": "fa", "class": "standard", "released": "2026-01-01"}, + "fakeagent/fa-2": {"maker": "fa", "class": "standard", "released": "2026-06-01"}, + "fakeagent/default": {"maker": "unknown", "class": "unknown", "released": "unknown"}, + "alpha/m-1": {"maker": "al", "class": "standard", "released": "2026-03-01"}, + "alpha/m-2": {"maker": "al", "class": "standard", "released": "2026-04-01"}}}, f) + r = self.sisi("workers", "classify", "--record", answer, "--by", "a test") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertNotIn("fakeagent/fa-1", self.sisi("workers", "classify").stdout.splitlines()) + explained = self.route("read", "1", "--explain").stdout + self.assertNotEqual(explained.splitlines()[0], "fakeagent/fa-1") + self.assertIn("superseded by fakeagent/fa-2", explained, "the older version of a learned worker is replaced by the newer") + self.assertIn("superseded by alpha/m-2", explained, "and so is a host worker's") + def test_route_retry_of_names_a_learned_worker_with_its_check_line(self): self.learn() self.sisi("workers", "vouch", "fakeagent/fa-1", "--up-to", "2", "--why", "words") diff --git a/tests/test_meter.py b/tests/test_meter.py index ace6c2f..381fd0a 100644 --- a/tests/test_meter.py +++ b/tests/test_meter.py @@ -245,7 +245,7 @@ class WhoIsMeteredTests(MeterBase): def test_a_main_prompt_that_only_mentions_worker_later_is_still_metered(self): from sisi import brief line = brief.template().splitlines()[0] - self.prompt("fix the parser, and remember this: " + line + " you are a worker of mine") + self.prompt("fix the parser and explain each module in the project. " * 8 + "remember this: " + line + " you are a worker of mine") self.assertEqual(self.read_n(8), [False] * 6 + [True] * 2) # nor does a brief line in the second prompt change a session that began as a main thread self.prompt(line + " again please do this") diff --git a/tests/test_model_classes.py b/tests/test_model_classes.py new file mode 100644 index 0000000..b284dba --- /dev/null +++ b/tests/test_model_classes.py @@ -0,0 +1,139 @@ +"""A maker's classes, most capable first: a prior between classes of that maker where nothing better exists, never +above a judged record or a benchmark standing. Invented ids: for this maker each class is a named line. +Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3.""" +import json, os, random, unittest +from support import * +from sisi import routing +from test_model_supersession import cand, attempts, pick, NOW, R1, R2 +from test_worker_models import ModelCase + +ORDER = {"abc": ["fable", "opus", "sonnet", "haiku"]} +COST = {"fable": 9.0, "opus": 6.0, "sonnet": 3.0, "haiku": 1.0} + + +def fleet(**extra): + return [cand("prov/abc-%s-5" % c, **dict({"cost": COST[c], "cls": c}, **extra.get(c, {}))) for c in ("fable", "opus", "sonnet", "haiku")] + + +def best(cands, difficulty, records=(), **kw): + opts = {"class_orders": ORDER} + opts.update(kw.pop("opts", {})) + return pick(cands, records, difficulty, opts=opts, **kw) + + +class ClassOrderTests(unittest.TestCase): + def test_routine_work_goes_to_the_lowest_class_and_hard_work_to_the_upper_ones(self): + """Nothing judged, no benchmark: the order is the prior and the cheapest capable class wins.""" + cands = fleet() + self.assertEqual(best(cands, 1)[0], "prov/abc-haiku-5") + self.assertEqual(best(cands, 2)[0], "prov/abc-sonnet-5") + who, r = best(cands, 3) + self.assertEqual(who, "prov/abc-opus-5") + self.assertEqual(r["assessments"]["prov/abc-opus-5"]["tier"], "class") + self.assertFalse(r["assessments"]["prov/abc-sonnet-5"]["capable"]) + + def test_the_mapping_is_configurable(self): + cands = fleet() + self.assertEqual(best(cands, 3, opts={"class_span": {"3": 0}})[0], "prov/abc-fable-5") + self.assertEqual(best(cands, 3, opts={"class_span": {"3": 100}})[0], "prov/abc-haiku-5") + self.assertEqual(routing.class_spans({"2": "x", "9": 50, "1": 101})[1], 100.0) + + def test_without_a_recorded_order_a_class_is_no_evidence(self): + who, r = pick(fleet(), (), 3) + self.assertEqual(r["basis"], "nothing") + self.assertFalse(any(a["tier"] == "class" for a in r["assessments"].values())) + + def test_a_judged_record_outranks_the_order(self): + records = attempts("prov/abc-haiku-5", 12, 12, difficulty=3) + who, r = best(fleet(), 3, records) + self.assertEqual(who, "prov/abc-haiku-5") + self.assertEqual(r["assessments"]["prov/abc-haiku-5"]["tier"], "a") + + def test_a_benchmark_standing_outranks_the_order(self): + cands = fleet(haiku={"standing": 80.0, "cost": 5.0}) + who, r = best(cands, 2) + self.assertEqual(who, "prov/abc-haiku-5") # sonnet is capable by class and cheaper than none, but the standing is preferred + self.assertEqual(r["assessments"]["prov/abc-haiku-5"]["tier"], "standing") + self.assertTrue(any("benchmark" in why for w, why in r["passed_over"] if w == "prov/abc-sonnet-5")) + + def test_when_nobody_is_proven_the_strongest_known_means_the_highest_class(self): + cands = [c for c in fleet() if c["worker"] in ("prov/abc-sonnet-5", "prov/abc-haiku-5")] + who, r = best(cands, 3) + self.assertEqual((who, r["basis"]), ("prov/abc-sonnet-5", "strongest")) + + def test_another_makers_models_are_not_placed_by_this_order(self): + other = cand("prov/xyz-opus-5", cls="opus", cost=0.1, maker="xyz") + who, r = best(fleet() + [other], 3) + self.assertEqual(who, "prov/abc-opus-5") + self.assertNotEqual(r["assessments"]["prov/xyz-opus-5"]["tier"], "class") + + def test_a_class_missing_from_the_order_is_not_placed(self): + extra = cand("prov/abc-ember-1", cls="ember", cost=0.1) + who, r = best(fleet() + [extra], 3) + self.assertNotEqual(r["assessments"]["prov/abc-ember-1"]["tier"], "class") + + def test_the_asking_line_wants_the_order_of_a_maker_with_several_classes(self): + r = pick(fleet(), (), 3)[1] + self.assertEqual(r["class_ask"]["order"], [("abc", ["fable", "haiku", "opus", "sonnet"])]) + r = best(fleet(), 3)[1] + self.assertEqual(r["class_ask"]["order"], []) + one = pick([cand("prov/abc-opus-5", cls="opus", rel=R1), cand("prov/abc-opus-6", cls="opus", rel=R2)], (), 3)[1] + self.assertEqual(one["class_ask"]["order"], []) # one class only: nothing to order + + def test_property_the_order_never_outranks_a_record_or_a_standing(self): + rng = random.Random(9) + for _ in range(300 * ITERS): + cands = [cand("prov/abc-%s-5" % c, cls=c, cost=rng.choice([1.0, 2.0, 5.0]), + standing=rng.choice([None, None, 40.0, 90.0])) for c in rng.sample(list(COST), rng.randint(2, 4))] + records = [] + for c in cands: + for d in (1, 2, 3): + if rng.random() < 0.4: + n = rng.choice([3, 10, 12]) + records += attempts(c["worker"], n, rng.randint(0, n), difficulty=d) + d = rng.choice([2, 3]) + who, r = best(cands, d, records) + if who is None or r["basis"] != "capable": + continue + tiers = {w: a["tier"] for w, a in r["assessments"].items() if a["capable"]} + if any(t in ("a", "b-higher", "b-all") for t in tiers.values()): + self.assertIn(tiers[who], ("a", "b-higher", "b-all")) + elif any(t == "standing" for t in tiers.values()): + self.assertEqual(tiers[who], "standing") + + +class ClassesCommandTests(ModelCase): + def test_a_makers_classes_are_recorded_shown_and_removed(self): + self.seed([("prov/abc-5.3", 9, 9)]) + r = self.sisi("workers", "classes", "abc", "fable", "opus", "sonnet", "haiku", "--source", "owner, in his words", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + stored = json.load(open(os.path.join(self.data, "worker-models.json")))["classes"]["abc"] + self.assertEqual((stored["order"], stored["source"]), (["fable", "opus", "sonnet", "haiku"], "owner, in his words")) + self.assertIn("Classes of abc, most capable first: fable, opus, sonnet, haiku (owner, in his words", self.listing()) + self.assertEqual(self.sisi("workers", "classes", "abc", "--remove", env=self.env()).returncode, 0) + self.assertNotIn("Classes of abc", self.listing()) + + def test_bad_input_is_refused(self): + for args in (("abc", "opus"), ("abc", "--source", "x"), ("abc", "o pus", "--source", "x"), ("abc", "opus", "opus", "--source", "x")): + r = self.sisi("workers", "classes", *args, env=self.env()) + self.assertEqual(r.returncode, 1, args) + self.assertFalse(os.path.exists(os.path.join(self.data, "worker-models.json"))) + + def test_route_uses_the_recorded_order_and_asks_for_it_until_then(self): + models = ("abc-fable-5", "abc-opus-5", "abc-sonnet-5", "abc-haiku-5") + for m in models: + self.sisi("workers", "fact", "muse/" + m, "--price", str(COST[m.split("-")[1]]), "--source", "fixture", env=self.env(models)) + self.record("muse/" + m, m.split("-")[1], models=models) + first = self.route(3, models=models) + self.assertIn("record the order", first.stdout) + self.assertLessEqual(len(first.stdout.splitlines()), 7, first.stdout) + self.sisi("workers", "classes", "abc", "fable", "opus", "sonnet", "haiku", "--source", "owner", env=self.env(models)) + after = self.route(3, "--explain", models=models) + self.assertEqual(after.stdout.splitlines()[0], "muse/abc-opus-5", after.stdout) + self.assertNotIn("record the order", after.stdout) + self.assertIn("class order", after.stdout) + self.assertEqual(self.route(1, models=models).stdout.splitlines()[0], "muse/abc-haiku-5") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_model_inheritance.py b/tests/test_model_inheritance.py new file mode 100644 index 0000000..8294d20 --- /dev/null +++ b/tests/test_model_inheritance.py @@ -0,0 +1,133 @@ +"""A new version of a model starts from its predecessor's judged record: inherited evidence ranks below the model's +own record and above a benchmark, counts as judged proof, stops once the model has a thick record of its own, and a +predecessor's bad record does not block it. Invented ids. Requirement ids: R-7.2-1, R-7.2-3.""" +import random, unittest +from support import * +from sisi import routing +from test_model_supersession import cand, attempts, pick, NOW, R1, R2, R3, R4 + + +def assessed(cands, records, worker, difficulty=2, kind="impl", **kw): + r = routing.choose(cands, list(records), {}, kind, difficulty, now=NOW, **kw) + return r["assessments"].get(worker), r + + +m_ = {'5.1': '2026-01-01', '5.2': '2026-03-01', '5.3': '2026-06-01', '5.4': '2026-09-01', '5.10': '2026-10-01'} + + +class InheritanceTests(unittest.TestCase): + def test_a_new_version_inherits_the_record_of_its_predecessor_and_says_so(self): + old, new = cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=2.0) + records = attempts("prov/abc-5.3", 12, 11, difficulty=2) + a, r = assessed([old, new], records, "prov/abc-5.4") + self.assertEqual((a["tier"], a["capable"], a["inherited_from"]), ("a", True, "prov/abc-5.3")) + self.assertEqual(r["choice"]["worker"], "prov/abc-5.4") + line = routing.evidence_line(a, "impl", 2, r["choice"], r["basis"]) + self.assertIn("the record of its predecessor prov/abc-5.3", line) + self.assertIn("11 of 12", line) + + def test_it_walks_back_one_predecessor_at_a_time(self): + cands = [cand("prov/abc-5.2", rel="2026-03-01", cost=1.0), cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0)] + records = attempts("prov/abc-5.2", 12, 12, difficulty=2) + attempts("prov/abc-5.3", 3, 3, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertEqual(a["inherited_from"], "prov/abc-5.2") # 5.3 has only a thin record + records += attempts("prov/abc-5.3", 9, 9, difficulty=2, start=50) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertEqual(a["inherited_from"], "prov/abc-5.3") # now the closest thick one + + def test_a_predecessors_bad_record_does_not_block_the_newer_model(self): + cands = [cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0, standing=70.0)] + records = attempts("prov/abc-5.3", 12, 2, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertFalse(a["bad"]) + self.assertEqual(a["tier"], "standing") # it starts from its benchmark, not from the old verdict + bare = assessed([cands[0], cand("prov/abc-5.4", rel="2026-09-01", cost=1.0)], records, "prov/abc-5.4")[0] + self.assertFalse(bare["bad"]) + self.assertFalse(bare["capable"]) + + def test_the_models_own_thick_record_replaces_the_inherited_one(self): + cands = [cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0)] + records = attempts("prov/abc-5.3", 12, 12, difficulty=2) + attempts("prov/abc-5.4", 9, 1, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertTrue(a["bad"]) + self.assertIsNone(a.get("inherited_from")) + records = attempts("prov/abc-5.3", 12, 2, difficulty=2) + attempts("prov/abc-5.4", 9, 9, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertEqual((a["tier"], a.get("inherited_from")), ("a", None)) + + def test_a_thin_record_that_already_contradicts_is_not_papered_over(self): + cands = [cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0)] + records = attempts("prov/abc-5.3", 12, 12, difficulty=2) + attempts("prov/abc-5.4", 3, 0, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertIsNone(a.get("inherited_from")) + self.assertFalse(a["capable"]) + + def test_nothing_is_inherited_across_classes_or_makers(self): + flash, new = cand("prov/abc-5.3-flash", cls="flash", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0) + records = attempts("prov/abc-5.3-flash", 12, 12, difficulty=2) + self.assertFalse(assessed([flash, new], records, "prov/abc-5.4")[0]["capable"]) + other = cand("prov/xyz-5.4", rel="2026-09-01", cost=1.0, maker="xyz") + self.assertFalse(assessed([cand("prov/abc-5.3", rel="2026-06-01"), other], attempts("prov/abc-5.3", 12, 12, difficulty=2), "prov/xyz-5.4")[0]["capable"]) + + def test_nothing_is_inherited_by_an_unreadable_class(self): + cands = [cand("prov/abc-6.2-sol", known=False), cand("prov/abc-6.3-sol", known=False)] + records = attempts("prov/abc-6.2-sol", 12, 12, difficulty=2) + self.assertFalse(assessed(cands, records, "prov/abc-6.3-sol")[0]["capable"]) + + def test_inherited_evidence_counts_as_a_judged_record_before_a_benchmark(self): + """Difficulty 2 and 3: proof comes before benchmark, and an inherited record is proof.""" + new = cand("prov/abc-5.4", rel="2026-09-01", cost=5.0) + rival = cand("prov/xyz-2.0", cost=0.1, maker="xyz", standing=90.0) + records = attempts("prov/abc-5.3", 12, 12, difficulty=3) + who, r = pick([cand("prov/abc-5.3", rel="2026-06-01", cost=5.0), new, rival], records, 3) + self.assertEqual(who, "prov/abc-5.4") + self.assertTrue(r["judged_first"]) + + def test_inherited_ranks_below_the_models_own_record_in_strength(self): + own = routing.assess({"w": {"uses": 0, "by_cell": {("impl", 2): {"n": 10, "good": 10}}}}, "w", "impl", 2) + inherited = routing.assess({"w": {"uses": 0, "by_cell": {("impl", 2): {"n": 10, "good": 10, "from": "old"}}}}, "w", "impl", 2) + bench = routing.assess({"w": {"uses": 0, "by_cell": {}}}, "w", "impl", 2, standing=80.0, best_standing=80.0) + self.assertGreater(routing.strength(own), routing.strength(inherited)) + self.assertGreater(routing.strength(inherited), routing.strength(bench)) + self.assertEqual(inherited["inherited_from"], "old") + + def test_a_model_with_no_data_of_its_own_is_routable_through_its_predecessor(self): + from sisi import workers + old, new, lone = cand("prov/abc-5.3", rel="2026-06-01"), cand("prov/abc-5.4", rel="2026-09-01"), cand("prov/xyz-9.9", rel="2026-09-01", maker="xyz") + for c in (old, new, lone): + c["price_source"] = None + old["price_source"] = "fixture" + keep, cold, excluded = workers.routable_candidates([old, new, lone], []) + self.assertEqual(sorted(c["worker"] for c in keep), ["prov/abc-5.3", "prov/abc-5.4"]) + self.assertEqual(excluded, 1) + + def test_property_inherited_evidence_never_outranks_a_thick_record_of_the_models_own(self): + rng = random.Random(41) + seen = 0 + for _ in range(300 * ITERS): + versions = rng.sample(["5.1", "5.2", "5.3", "5.4", "5.10"], rng.randint(2, 4)) + cands = [cand("prov/abc-%s" % v, rel=m_[v], cost=rng.choice([None, 1.0, 2.0])) for v in versions] + records = [] + for c in cands: + for d in (1, 2, 3): + if rng.random() < 0.6: + n = rng.choice([2, 8, 12]) + records += attempts(c["worker"], n, rng.randint(0, n), difficulty=d, start=d * 100) + stats = routing.candidate_stats(cands, records) + eff = routing.inherit_stats(cands, stats) + for c in cands: + for ck, cell in stats[c["worker"]]["by_cell"].items(): + if cell["n"] >= routing.MIN_ATTEMPTS: + self.assertEqual(eff[c["worker"]]["by_cell"][ck], cell) + seen += 1 + for ck, cell in eff[c["worker"]]["by_cell"].items(): + if cell.get("from"): + own = stats[c["worker"]]["by_cell"].get(ck, {"n": 0}) + self.assertLess(own["n"], routing.MIN_ATTEMPTS) + self.assertGreaterEqual(cell["n"], routing.MIN_ATTEMPTS) + self.assertGreaterEqual(cell["good"] / cell["n"], routing.MIN_ACCEPTED_RATE) # a bad record is never inherited + self.assertGreater(seen, 100) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_model_recency.py b/tests/test_model_recency.py new file mode 100644 index 0000000..6474277 --- /dev/null +++ b/tests/test_model_recency.py @@ -0,0 +1,68 @@ +"""Recency breaks ties: where the arithmetic falls back to a stable order, the more recently released model wins +first (a newer version of the same model, never across makers or classes), and the +rule is in the text agents and people read. Requirement ids: R-7.2-1, R-7.2-2.""" +import os, unittest +from support import * +from sisi import routing +from test_model_supersession import cand, pick + + +class RecencyTieBreakTests(unittest.TestCase): + def test_a_newer_release_never_beats_a_different_model_just_for_being_newer(self): + """The owner: newer means a newer version of the SAME model, not the newest release across models.""" + a = cand("prov/aaa-1.0", cost=1.0, rel="2026-01-10", maker="aaa") + b = cand("prov/bbb-2.0", cost=1.0, rel="2026-08-01", maker="bbb") + who, r = pick([a, b]) + self.assertEqual(who, "prov/aaa-1.0") # the old tie-break (worker id), whatever the release dates + self.assertEqual(pick([b, a])[0], "prov/aaa-1.0") + flash = cand("prov/abc-flash", cls="flash", cost=1.0, rel="2026-01-10") + std = cand("prov/abc-std", cls="standard", cost=1.0, rel="2026-08-01") + self.assertEqual(pick([flash, std])[0], "prov/abc-flash") + self.assertEqual(routing.recency_order([a, b, flash, std]), {w: 0 for w in ("prov/aaa-1.0", "prov/bbb-2.0", "prov/abc-flash", "prov/abc-std")}) + + def test_within_one_model_the_newer_version_goes_first(self): + old, new = cand("prov/abc-old", rel="2026-01-10"), cand("prov/abc-new", rel="2026-08-01") + self.assertEqual(routing.recency_order([old, new]), {"prov/abc-new": 0, "prov/abc-old": 1}) + + def test_price_and_load_still_come_before_the_tie_break(self): + cheap = cand("prov/aaa-1.0", cost=0.5, maker="aaa") + dear = cand("prov/bbb-2.0", cost=1.0, maker="bbb", rel="2026-08-01") + self.assertEqual(pick([cheap, dear])[0], "prov/aaa-1.0") + + +class TextTests(unittest.TestCase): + def read(self, *parts): + with open(os.path.join(REPO, *parts), encoding="utf-8") as f: + return f.read() + + def test_the_rule_is_in_the_always_loaded_rulebook_the_playbook_and_the_docs(self): + core = self.read("canon", "core.md") + rule6 = core[core.index("## 6. Orchestrate"):core.index("## 7.")] + self.assertIn("newest version of a given model", rule6) + self.assertIn("never an older version", rule6) + self.assertIn("different model or class", rule6) + for path in (("canon", "orchestration.md"), ("docs", "workers.md")): + text = self.read(*path).lower() + self.assertIn("newest version of a given model", text.replace("\n", " ").replace(" ", " "), path) + self.assertIn("different model or class", text.replace("\n", " ").replace(" ", " "), path) + self.assertIn("cheaper", text, path) # the reason: newer models are better and cheaper + + def test_the_rulebook_is_inside_its_budget(self): + from sisi import overlay + lines, chars = overlay.size(self.read("canon", "core.md")) + self.assertLessEqual(lines, overlay.MAX_LINES) + self.assertLessEqual(chars, overlay.MAX_CHARS) + + +class SessionLineTests(SisiCase): + def test_session_start_names_unclassified_workers_in_the_one_facts_line(self): + from sisi import workers + line = workers.facts_line(unclassified=2) + self.assertEqual(len(line.splitlines()), 1) + self.assertIn("2 routable workers have no recorded maker, class and release date", line) + self.assertIn("sisi workers classify", line) + self.assertNotIn("classify", workers.facts_line(unclassified=0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_model_supersession.py b/tests/test_model_supersession.py new file mode 100644 index 0000000..1cffd72 --- /dev/null +++ b/tests/test_model_supersession.py @@ -0,0 +1,243 @@ +"""The newest usable version of a maker's class always wins over its older versions (hard rule), however good the +older record or cheap its plan. Identity and recency come from recorded facts. Pure routing tests over invented ids. +Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3.""" +import random, unittest +from support import * +from sisi import routing + +NOW = 1000000.0 +R1, R2, R3, R4 = "2026-03-01", "2026-06-01", "2026-09-01", "2026-11-01" + + +def cand(worker, cls="standard", rel=None, maker="abc", plan="per-use", cost=1.0, host_native=False, standing=None, + known=True, **kw): + """A candidate whose maker, class and release date were recorded (known=False: nothing recorded).""" + model = worker.rsplit("/", 1)[-1] + fact = {"class": cls, "maker": maker, "released": rel} if known else {} + c = {"worker": worker, "tool": worker.split("/")[0] if "/" in worker else None, "model": model, "maker": maker, + "plan": plan, "cost": cost, "allowance_pct_left": None, "usable": True, "standing": standing, + "aliases": [worker, model], "lineage": routing.lineage_from_fact(fact, host_native=host_native)} + c.update(kw) + return c + + +def attempts(worker, n, good, kind="impl", difficulty=1, start=0): + return [{"kind": "attempt", "id": "%s-%d-%d" % (worker, difficulty, start + i), "type": kind, "difficulty": difficulty, + "worker": worker, "outcome": "accepted" if i < good else "rejected", "check": "tests", "ts": NOW - 10} + for i in range(n)] + + +def pick(cands, records=(), difficulty=1, availability=None, **kw): + r = routing.choose(cands, list(records), availability or {}, "impl", difficulty, now=NOW, **kw) + return (r["choice"] or {}).get("worker"), r + + +class IdentityTests(unittest.TestCase): + def test_no_recorded_class_and_maker_means_no_identity(self): + for fact in (None, {}, {"class": "flash"}, {"maker": "abc"}, {"released": "2026-01-01"}): + got = routing.lineage_from_fact(fact) + self.assertIsNone(got["key"], fact) + self.assertEqual(got["source"], "unknown") + + def test_a_recorded_maker_and_class_are_the_identity_whatever_the_name(self): + a = routing.lineage_from_fact({"class": "Flash", "maker": "ABC", "released": "2026-03-01"}) + self.assertEqual((a["key"], a["source"], a["released"]), (("abc", "flash"), "fact", "2026-03-01")) + self.assertNotEqual(routing.lineage_from_fact({"class": "standard", "maker": "abc"})["key"], a["key"]) + + def test_the_more_recent_release_date_is_newer_and_dates_compare_as_dates(self): + old = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-09-30"}) + new = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-10-02"}) + self.assertGreater(routing.compare_release(new, old), 0) + self.assertLess(routing.compare_release(old, new), 0) + self.assertEqual(routing.compare_release(old, old), 0) + self.assertEqual(routing.compare_release(old, routing.lineage_from_fact({"class": "x", "maker": "m"})), 0) # unknowable + self.assertGreater(routing.days("2026-10-02"), routing.days("2026-09-30")) + self.assertEqual(routing.days("soon"), 0) + + def test_a_bare_host_alias_without_a_release_date_is_the_newest_of_its_class(self): + alias = routing.lineage_from_fact({"class": "x", "maker": "m"}, host_native=True) + dated = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2030-01-01"}) + self.assertTrue(alias["alias"]) + self.assertGreater(routing.compare_release(alias, dated), 0) + self.assertFalse(routing.lineage_from_fact({"class": "x", "maker": "m"})["alias"]) + self.assertFalse(routing.lineage_from_fact({}, host_native=True)["alias"]) # no class recorded: no comparison + self.assertFalse(routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-01-01"}, host_native=True)["alias"]) + + def test_unknown_answers_and_partial_dates(self): + self.assertIsNone(routing.lineage_from_fact({"class": "unknown", "maker": "abc"})["key"]) + self.assertIsNone(routing.lineage_from_fact({"class": "x", "maker": "unknown"})["key"]) + self.assertIsNone(routing.lineage_from_fact({"class": "x", "maker": "abc", "released": "unknown"})["released"]) + a = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-09"}) + b = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-10-15"}) + self.assertGreater(routing.compare_release(b, a), 0) + self.assertGreater(routing.days("2026-10"), routing.days("2026-09-30")) + + def test_no_code_reads_a_model_name(self): + import os, re as _re + self.assertFalse(os.path.exists(os.path.join(REPO, "sisi", "modelid.py"))) + self.assertFalse(os.path.exists(os.path.join(REPO, "canon", "model-words.json"))) + text = open(os.path.join(REPO, "sisi", "routing.py")).read() + self.assertEqual(_re.findall(r"modelid|tier word|parse_model", text), []) + + +class SupersessionTests(unittest.TestCase): + def test_the_newer_version_wins_over_an_older_one_with_a_better_record_and_a_cheaper_plan(self): + """The owner's rule: no evidence exception, no price exception.""" + old = cand("prov/abc-old", rel=R1, plan="flat", cost=0.0) + new = cand("prov/abc-new", rel=R2, plan="per-use", cost=9.0) + records = attempts("prov/abc-old", 30, 30, difficulty=1) + who, r = pick([old, new], records) + self.assertEqual(who, "prov/abc-new") + self.assertIn(("prov/abc-old", "superseded by prov/abc-new (a newer version of the same class)"), r["passed_over"]) + + def test_the_release_date_decides_not_the_name(self): + """A name that looks newer but was released earlier is the older model.""" + a = cand("prov/abc-9.9", rel=R1) + b = cand("prov/abc-1.0", rel=R3) + self.assertEqual(pick([a, b])[0], "prov/abc-1.0") + + def test_different_classes_never_supersede_each_other(self): + flash, std = cand("prov/abc-a", cls="flash", rel=R1, cost=0.1), cand("prov/abc-b", rel=R2, cost=5.0) + who, r = pick([flash, std]) + self.assertEqual(who, "prov/abc-a") # the cheaper class still competes + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + + def test_two_named_lines_of_one_maker_are_different_classes(self): + a, b = cand("prov/abc-w", cls="wonder", rel=R1, cost=1.0), cand("prov/abc-e", cls="ember", rel=R2, cost=2.0) + who, r = pick([a, b]) + self.assertEqual(who, "prov/abc-w") + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + + def test_different_makers_never_supersede_each_other(self): + a, b = cand("prov/abc-a", rel=R1, cost=1.0), cand("prov/xyz-b", rel=R3, cost=2.0, maker="xyz") + self.assertEqual(pick([a, b])[0], "prov/abc-a") + + def test_a_model_with_nothing_recorded_is_never_compared(self): + a, b = cand("prov/abc-a", known=False, cost=1.0), cand("prov/abc-b", rel=R3, cost=2.0) + who, r = pick([a, b]) + self.assertEqual(who, "prov/abc-a") + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + no_date = cand("prov/abc-c", cost=1.0) # class recorded, no date: not comparable with a dated one + self.assertFalse([w for w, why in pick([no_date, cand("prov/abc-d", rel=R3)])[1]["passed_over"] if why.startswith("superseded")]) + + def test_the_newer_one_unusable_lets_the_older_compete_again(self): + old, new = cand("prov/abc-old", rel=R1, cost=1.0), cand("prov/abc-new", rel=R2, cost=2.0) + self.assertEqual(pick([old, new], availability={"prov/abc-new": {"reason": "limit", "retry_at": NOW + 99}})[0], "prov/abc-old") + self.assertEqual(pick([old, dict(new, usable=False, reason="not logged in")])[0], "prov/abc-old") + self.assertEqual(pick([old, new], avoid=[{"pattern": "abc-new"}])[0], "prov/abc-old") + self.assertEqual(pick([old, dict(new, plan="flat", allowance_pct_left=0)])[0], "prov/abc-old") + + def test_a_tried_newer_version_does_not_send_a_retry_back_to_the_older(self): + old, new = cand("prov/abc-old", rel=R1, cost=1.0), cand("prov/abc-new", rel=R2, cost=2.0) + self.assertIsNone(pick([old, new], exclude=["prov/abc-new"])[0]) + + def test_a_newer_version_with_a_thick_bad_record_never_sends_work_back_to_the_older(self): + old, new = cand("prov/abc-old", rel=R1, cost=1.0), cand("prov/abc-new", rel=R2, cost=2.0) + other = cand("prov/xyz-2", cost=3.0, maker="xyz") + records = attempts("prov/abc-new", 10, 1, difficulty=1) + attempts("prov/xyz-2", 10, 10, difficulty=1) + self.assertEqual(pick([old, new, other], records)[0], "prov/xyz-2") + self.assertEqual(pick([old, new], records)[0], "prov/abc-new") # nobody else: still not the older version + + def test_the_same_model_through_two_providers_is_one_model(self): + old_a = cand("prova/abc-old", rel=R1, plan="flat", cost=0.0) + new_a, new_b = cand("prova/abc-new", rel=R2, cost=5.0), cand("provb/abc-new", rel=R2, cost=2.0) + who, r = pick([old_a, new_a, new_b]) + self.assertEqual(who, "provb/abc-new") # the existing cost comparison picks the provider + self.assertEqual(sorted(w for w, why in r["passed_over"] if why.startswith("superseded")), ["prova/abc-old"]) + self.assertEqual(pick([old_a, new_a, new_b], availability={"provb": {"reason": "limit", "retry_at": NOW + 9}})[0], "prova/abc-new") + + def test_a_bare_host_alias_is_the_newest_of_its_class(self): + alias = cand("abc", host_native=True, cost=9.0) + versioned = cand("prov/abc-9", rel=R4, cost=0.1) + self.assertEqual(pick([alias, versioned])[0], "abc") + self.assertEqual(pick([cand("abc", host_native=True, known=False, cost=9.0), versioned])[0], "prov/abc-9") + + def test_the_asking_line_names_workers_with_nothing_recorded_when_a_choice_is_made_among_several(self): + a, b = cand("prov/abc-a", known=False), cand("prov/abc-b", rel=R2) + self.assertEqual(pick([a, b])[1]["class_ask"]["classify"], ["prov/abc-a"]) + self.assertEqual(pick([a])[1]["class_ask"]["classify"], []) + self.assertEqual(pick([cand("prov/abc-a", rel=R1), cand("prov/abc-b", rel=R2)])[1]["class_ask"]["classify"], []) + + +class SupersessionPropertyTests(unittest.TestCase): + def fleet(self, rng): + cands, records, down = [], [], {} + for maker in rng.sample(["abc", "xyz", "qrs"], rng.randint(1, 3)): + for cls in rng.sample(["standard", "flash", "mini", "wonder"], rng.randint(1, 3)): + for rel in rng.sample(["2026-01-05", "2026-03-01", "2026-06-01", "2026-09-30", "2026-10-02", None], rng.randint(1, 4)): + for prov in rng.sample(["pa", "pb"], rng.randint(1, 2)): + w = "%s/%s-%s-%s" % (prov, maker, cls, rel) + c = cand(w, cls=cls, rel=rel, maker=maker, plan=rng.choice(["flat", "per-use", None]), + cost=rng.choice([None, 0.1, 1.0, 5.0]), allowance_pct_left=rng.choice([None, 0, 50]), + known=rng.random() < 0.9) + cands.append(c) + if rng.random() < 0.15: + down[w] = {"reason": "limit", "retry_at": NOW + 99} + for d in (1, 2, 3): + if rng.random() < 0.5: + n = rng.choice([3, 10, 12]) + records += attempts(w, n, rng.randint(0, n), difficulty=d) + return cands, records, down + + def usable(self, c, down): + return c["worker"] not in down and not (c["plan"] == "flat" and c["allowance_pct_left"] == 0) + + def test_the_chosen_worker_is_never_an_older_version_of_a_class_with_a_newer_usable_version(self): + """Property: whatever the fleet, ledger, plans and availability.""" + rng = random.Random(20261123) + checked = 0 + for _ in range(300 * ITERS): + cands, records, down = self.fleet(rng) + who, r = pick(cands, records, rng.choice([1, 2, 3]), availability=down) + if who is None: + continue + chosen = next(c for c in cands if c["worker"] == who) + lc = chosen["lineage"] + for c in cands: + if c is chosen or not self.usable(c, down) or not lc["key"]: + continue + if c["lineage"]["key"] == lc["key"]: + self.assertLessEqual(routing.compare_release(c["lineage"], lc), 0, (who, c["worker"])) + checked += 1 + for w, why in r["passed_over"]: + if why.startswith("superseded by "): + newer = why[len("superseded by "):].split(" ")[0] + a = next(c for c in cands if c["worker"] == w)["lineage"] + b = next(c for c in cands if c["worker"] == newer)["lineage"] + self.assertEqual(a["key"], b["key"], "a model never supersedes one of another maker or class") + self.assertIsNotNone(a["key"]) + self.assertGreater(routing.compare_release(b, a), 0) + self.assertGreater(checked, 100) + + def test_adding_a_newer_version_of_the_chosen_model_never_makes_the_choice_an_older_model_of_that_class(self): + rng = random.Random(77) + done = 0 + for _ in range(200 * ITERS): + cands, records, down = self.fleet(rng) + d = rng.choice([1, 2, 3]) + who, _r = pick(cands, records, d, availability=down) + if who is None: + continue + lc = next(c for c in cands if c["worker"] == who)["lineage"] + if not lc["key"] or not lc["released"]: + continue + new = cand("pc/newest", cls=lc["class"], maker=lc["maker"], rel="2027-01-01", cost=rng.choice([None, 0.1, 5.0])) + after, _ = pick(cands + [new], records, d, availability=down) + if after is None: + continue + got = next(c for c in cands + [new] if c["worker"] == after)["lineage"] + if got["key"] == lc["key"]: + self.assertGreaterEqual(routing.compare_release(got, lc), 0, (who, after)) + done += 1 + self.assertGreater(done, 30) + + def test_a_model_with_nothing_recorded_never_triggers_supersession(self): + rng = random.Random(5) + for _ in range(100 * ITERS): + cands = [cand("prov/m-%d" % i, known=False, cost=rng.choice([None, 1.0, 2.0])) for i in range(rng.randint(2, 5))] + who, r = pick(cands) + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_orchestration.py b/tests/test_orchestration.py index dc31833..3ce4c49 100644 --- a/tests/test_orchestration.py +++ b/tests/test_orchestration.py @@ -263,7 +263,9 @@ class RouteTests(OrchCase): self.assertIn("mechanism:", r.stdout) def _big_catalogue(self, n=2000): - names = ["m-%d" % i for i in range(n)] + ["contributor-%d" % i for i in range(40)] + # letters only: a number in an id is a version, and the newest version of a class replaces the older ones + names = ["mdl-%s" % "".join(chr(97 + (i // 26 ** k) % 26) for k in range(3)) for i in range(n)] \ + + ["contributor-%d" % i for i in range(40)] script = FAKE_TOOL.replace('echo "beta-1"; echo "beta-2";', " ".join('echo "%s";' % x for x in names)) with open(os.path.join(self.bindir, "muse"), "w") as f: f.write(script) @@ -272,7 +274,7 @@ class RouteTests(OrchCase): """R-7.2-1: --explain prints at most 20 lines and 3 example names per reason group, and still shows every reason group, however many catalogue models were passed over.""" self._big_catalogue() - self.sisi("workers", "avoid", "m-7", "--why", "fixture avoid", env=self.env()) + self.sisi("workers", "avoid", "mdl-ab", "--why", "fixture avoid", env=self.env()) r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env()) self.assertEqual(r.returncode, 0, r.stderr) lines = r.stdout.splitlines() diff --git a/tests/test_worker_classify.py b/tests/test_worker_classify.py new file mode 100644 index 0000000..a01e564 --- /dev/null +++ b/tests/test_worker_classify.py @@ -0,0 +1,128 @@ +"""`sisi workers classify`: the question for a cheap, fast worker and the validated recording of its answer. +Invented ids. Requirement ids: R-7.2-1, R-7.2-3.""" +import json, os, unittest +from support import * +from test_worker_models import ModelCase + +MODELS = ("abc-old", "abc-new", "xyz-one") +ANSWER = {"workers": {"muse/abc-old": {"maker": "abc", "class": "standard", "released": "2026-03"}, + "muse/abc-new": {"maker": "abc", "class": "standard", "released": "2026-09-01"}, + "muse/xyz-one": {"maker": "xyz", "class": "unknown", "released": "unknown"}}, + "classes": {"abc": ["standard", "flash"]}} + + +class ClassifyCase(ModelCase): + def setUp(self): + super().setUp() + self.seed([("muse/abc-old", 12, 12), ("muse/abc-new", 3, 3), ("muse/xyz-one", 12, 12)], difficulty=2) + self.file = os.path.join(self.tmp, "answer.json") + + def classify(self, *args): + return self.sisi("workers", "classify", *args, env=self.env(MODELS)) + + def answer(self, obj, wrap=lambda t: t): + open(self.file, "w").write(wrap(obj if isinstance(obj, str) else json.dumps(obj))) + return self.classify("--record", self.file, "--by", "cheap-worker-x") + + def stored(self): + p = os.path.join(self.data, "worker-models.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +class QuestionTests(ClassifyCase): + def test_it_prints_a_short_instruction_and_the_ids_that_have_no_classification(self): + out = self.classify().stdout.splitlines() + ids = [l for l in out if l.startswith("muse/")] + self.assertEqual(sorted(ids), ["muse/abc-new", "muse/abc-old", "muse/xyz-one"]) + self.assertLessEqual(len(out) - len(ids), 15, out) + text = "\n".join(out) + for must in ("maker", "class", "release date", "unknown", "JSON"): + self.assertIn(must, text) + + def test_classified_workers_are_not_asked_again_and_nothing_is_left_to_ask_at_the_end(self): + self.record("muse/abc-old", "standard", "2026-03-01", models=MODELS) + ids = [l for l in self.classify().stdout.splitlines() if l.startswith("muse/")] + self.assertEqual(sorted(ids), ["muse/abc-new", "muse/xyz-one"]) + self.assertEqual(self.answer({"workers": {w: ANSWER["workers"][w] for w in ids}}).returncode, 0) + self.assertIn("every routable worker is classified", self.classify().stdout) + + +class RecordTests(ClassifyCase): + def test_a_valid_answer_is_stored_with_the_classifying_worker_as_the_source(self): + r = self.answer(ANSWER) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("3 classification(s) (1 unknown) and 1 class order(s)", r.stdout) + data = self.stored() + self.assertEqual(data["models"]["muse/abc-new"]["source"], "classified by cheap-worker-x") + self.assertEqual((data["models"]["muse/abc-old"]["class"], data["models"]["muse/abc-old"]["released"]), ("standard", "2026-03")) + self.assertEqual(data["classes"]["abc"]["order"], ["standard", "flash"]) + self.assertEqual(data["models"]["muse/xyz-one"]["class"], "unknown") + self.assertNotIn("released", data["models"]["muse/xyz-one"]) + + def test_an_answer_wrapped_in_prose_or_a_code_fence_is_read(self): + r = self.answer(ANSWER, wrap=lambda t: "Here you go:\n```json\n%s\n```\nDone." % t) + self.assertEqual(r.returncode, 0, r.stderr) + + def test_an_id_that_was_not_asked_about_is_refused_and_nothing_is_recorded(self): + bad = json.loads(json.dumps(ANSWER)) + bad["workers"]["muse/never-heard-of-it"] = {"maker": "abc", "class": "standard", "released": "2026-01"} + r = self.answer(bad) + self.assertEqual(r.returncode, 1) + self.assertIn("muse/never-heard-of-it", r.stderr) + self.assertEqual(self.stored(), {}) + self.record("muse/abc-old", "standard", models=MODELS) # an id that is already classified is not asked about either + r = self.answer({"workers": {"muse/abc-old": ANSWER["workers"]["muse/abc-old"]}}) + self.assertEqual(r.returncode, 1) + + def test_malformed_answers_are_refused_and_nothing_is_recorded(self): + for bad in ("not json at all", "[1, 2]", json.dumps({"workers": []}), + json.dumps({"workers": {"muse/abc-old": {"maker": "abc", "class": "so l", "released": "2026-01"}}}), + json.dumps({"workers": {"muse/abc-old": {"maker": "abc", "class": "x", "released": "last year"}}}), + json.dumps({"workers": {"muse/abc-old": "standard"}})): + self.assertEqual(self.answer(bad).returncode, 1, bad) + self.assertEqual(self.stored(), {}) + self.assertEqual(self.classify("--record", os.path.join(self.tmp, "missing.json")).returncode, 1) + + def test_a_recorded_class_order_is_never_overwritten_by_an_answer(self): + self.sisi("workers", "classes", "abc", "flash", "standard", "--source", "owner", env=self.env(MODELS)) + self.answer(ANSWER) + self.assertEqual(self.stored()["classes"]["abc"]["order"], ["flash", "standard"]) + + def test_an_unknown_answer_changes_nothing_in_routing_and_is_not_asked_again(self): + def route(): + return self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env(MODELS)).stdout + before = route() + self.answer({"workers": {w: {"maker": "unknown", "class": "unknown", "released": "unknown"} for w in ANSWER["workers"]}}) + after = route() + strip = lambda t: [l for l in t.splitlines() if not l.startswith("sisi:")] + self.assertEqual(strip(before), strip(after)) + self.assertIn("every routable worker is classified", self.classify().stdout) + self.assertNotIn("sisi: no maker", after) + + def test_after_recording_the_newest_version_wins(self): + self.answer(ANSWER) + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env(MODELS)) + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-new", r.stdout) + self.assertIn("superseded by muse/abc-new", r.stdout) + self.assertIn("the record of its predecessor muse/abc-old", r.stdout) + + +class AskingLineTests(ClassifyCase): + def test_route_asks_only_when_an_unclassified_worker_is_in_the_running(self): + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env(MODELS)) + self.assertEqual(len([l for l in r.stdout.splitlines() if "sisi workers classify" in l]), 1, r.stdout) + self.assertLessEqual(len(r.stdout.splitlines()), 7) + self.answer(ANSWER) + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env(MODELS)) + self.assertNotIn("sisi workers classify", r.stdout) + + def test_session_start_names_the_unclassified_workers_in_its_one_facts_line(self): + from sisi import workers + r = self.sisi("tick", stdin=json.dumps({"session_id": "s-cls", "cwd": self.proj, "source": "startup", "model": "mystery-9"}), + env=self.env(MODELS)) + lines = [l for l in r.stdout.splitlines() if "worker facts" in l or "sisi workers classify" in l] + self.assertEqual(len(lines), 1, r.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_worker_models.py b/tests/test_worker_models.py new file mode 100644 index 0000000..aebe79f --- /dev/null +++ b/tests/test_worker_models.py @@ -0,0 +1,162 @@ +"""The worker commands and the model facts: the maker, class and release date a cheap worker researched are +recorded with `sisi workers fact`, shown by `sisi workers`, and drive `sisi route`. sisi reads nothing from a name. +Invented ids. Requirement ids: R-7.2-1, R-7.2-3.""" +import json, os, stat, subprocess, unittest +from support import * + +FAKE_MUSE = """#!/bin/sh +case "$1" in + exec) + if [ "$2" = "--list-models" ]; then for m in $MUSE_MODELS; do echo "$m"; done; exit 0; fi + echo done ;; + *) echo help ;; +esac +exit 0 +""" + + +class ModelCase(SisiCase): + def seed(self, spec, type="impl", difficulty=2): + """spec: [(worker, attempts, accepted)]""" + os.makedirs(self.data, exist_ok=True) + n = len(self.rows()) + with open(os.path.join(self.data, "delegations.jsonl"), "a") as f: + for worker, attempts, accepted in spec: + for i in range(attempts): + n += 1 + f.write(json.dumps({"kind": "attempt", "id": "m%d" % n, "ts": 1760000000 + n, "project": "p", + "type": type, "difficulty": difficulty, "worker": worker, + "outcome": "accepted" if i < accepted else "rejected", + "check": "tests", "minutes": 5}) + "\n") + + def rows(self): + p = os.path.join(self.data, "delegations.jsonl") + return open(p).read().splitlines() if os.path.exists(p) else [] + + def env(self, models=None): + """No tool at all, or a fake `muse` tool that lists `models`.""" + if models is None: + return dict(PATH="") + bindir = os.path.join(self.tmp, "bin") + os.makedirs(bindir, exist_ok=True) + path = os.path.join(bindir, "muse") + open(path, "w").write(FAKE_MUSE) + os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR) + return dict(PATH=bindir, MUSE_MODELS=" ".join(models)) + + def record(self, worker, cls, released=None, maker="abc", models=None): + args = ["workers", "fact", worker, "--maker", maker, "--class", cls, "--source", "fixture research"] + if released: + args += ["--released", released] + r = self.sisi(*args, env=self.env(models)) + self.assertEqual(r.returncode, 0, r.stderr) + + def route(self, difficulty=1, *extra, models=("abc-old", "abc-new")): + return self.sisi("route", "--kind", "impl", "--difficulty", str(difficulty), *extra, env=self.env(models)) + + def listing(self): + r = self.sisi("workers", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + return r.stdout + + +class FactTests(ModelCase): + def test_a_maker_class_and_release_date_are_recorded_with_their_source_and_shown(self): + """R-7.2-3: what a cheap worker researched about a model is stored, with its source, and shown.""" + self.seed([("prov/abc-x", 9, 9)]) + self.assertIn("prov/abc-x: no maker and class recorded", self.listing()) + self.record("prov/abc-x", "flash", "2026-11-01") + stored = json.load(open(os.path.join(self.data, "worker-models.json")))["models"]["prov/abc-x"] + self.assertEqual((stored["class"], stored["maker"], stored["released"], stored["source"]), + ("flash", "abc", "2026-11-01", "fixture research")) + self.assertIn("prov/abc-x: maker abc, class flash; released 2026-11-01", self.listing()) + + def test_bad_input_is_refused_and_nothing_is_recorded(self): + self.seed([("prov/abc-x", 9, 9)]) + for args in (("--class", "sol"), ("--class", "so l", "--source", "x"), ("--released", "next week", "--source", "x"), + ("--released", "2026-13-40", "--source", "x")): + self.assertEqual(self.sisi("workers", "fact", "prov/abc-x", *args, env=self.env()).returncode, 1, args) + self.assertFalse(os.path.exists(os.path.join(self.data, "worker-models.json"))) + + def test_the_fact_file_is_committed_with_the_other_worker_data(self): + self.seed([("prov/abc-x", 9, 9)]) + self.record("prov/abc-x", "flash") + out = subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True).stdout + self.assertNotIn("worker-models.json", out) + + +class RouteSupersessionTests(ModelCase): + def setUp(self): + super().setUp() + self.ready = False + + def route(self, difficulty=1, *extra, models=("abc-old", "abc-new")): + if not self.ready: # a model is routable once it has a record, a price or a standing + self.ready = True + for w, price, rel in (("muse/abc-old", "0.5", "2026-03-01"), ("muse/abc-new", "1", "2026-09-01")): # the older is the cheaper + self.sisi("workers", "fact", w, "--price", price, "--source", "fixture", env=self.env(models)) + self.record(w, "standard", rel, models=models) + return super().route(difficulty, *extra, models=models) + + def test_route_uses_the_newest_version_though_the_older_has_the_record(self): + """R-7.2-1: the newest usable version of a class is always taken; --explain says what it replaced.""" + self.seed([("muse/abc-old", 30, 30)], difficulty=1) + r = self.route(1, "--explain") + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-new", r.stdout) + self.assertIn("superseded by muse/abc-new", r.stdout) + + def test_the_older_version_is_back_while_the_newer_is_marked_down(self): + self.seed([("muse/abc-old", 30, 30)], difficulty=1) + self.route(1) + env = self.env(("abc-old", "abc-new")) + self.sisi("workers", "down", "muse/abc-new", "--reason", "limit", "--until", "2099-01-02", env=env) + self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-old") + self.sisi("workers", "up", "muse/abc-new", env=env) + self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-new") + + def test_the_lead_agent_is_asked_once_for_workers_with_nothing_recorded_and_then_not(self): + models = ("abc-old", "abc-new") + self.seed([("muse/abc-old", 12, 12), ("muse/abc-new", 12, 12)], difficulty=1) + r = self.route(1, models=models) # route() records facts first + self.assertNotIn("no maker, class", r.stdout) + self.seed([("muse/abc-zzz", 12, 12)], difficulty=1) + r = self.sisi("route", "--kind", "impl", "--difficulty", "1", env=self.env(models + ("abc-zzz",))) + asks = [l for l in r.stdout.splitlines() if "no maker, class and release date are recorded" in l] + self.assertEqual(len(asks), 1, r.stdout) + self.assertIn("muse/abc-zzz", asks[0]) + self.assertLessEqual(len(r.stdout.splitlines()), 7, r.stdout) + self.record("muse/abc-zzz", "flash", "2026-01-01", models=models + ("abc-zzz",)) + self.assertNotIn("no maker, class", self.sisi("route", "--kind", "impl", "--difficulty", "1", + env=self.env(models + ("abc-zzz",))).stdout) + + +class RouteInheritanceTests(ModelCase): + def setUp(self): + super().setUp() + self.ready = False + + def route(self, difficulty=1, *extra, models=("abc-old", "abc-new")): + if not self.ready: + self.ready = True + self.record("muse/abc-old", "standard", "2026-03-01", models=models) + self.record("muse/abc-new", "standard", "2026-09-01", models=models) + return super().route(difficulty, *extra, models=models) + + def test_a_new_release_with_no_data_of_its_own_gets_ordinary_work_at_once(self): + """R-7.2-1: discovered, unpriced, unjudged, yet routable and capable through its predecessor's record.""" + self.seed([("muse/abc-old", 12, 12)], difficulty=2) + r = self.route(2, "--explain") + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-new", r.stdout) + self.assertIn("the record of its predecessor muse/abc-old", r.stdout) + self.assertLessEqual(len(r.stdout.splitlines()), 20, r.stdout) + self.assertLessEqual(len(self.route(2).stdout.splitlines()), 6) + + def test_once_it_has_a_thick_record_of_its_own_the_inherited_one_stops_applying(self): + self.seed([("muse/abc-old", 12, 12), ("muse/abc-new", 9, 9)], difficulty=2) + r = self.route(2, "--explain") + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-new", r.stdout) + self.assertNotIn("predecessor", r.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_worker_session.py b/tests/test_worker_session.py new file mode 100644 index 0000000..5662c13 --- /dev/null +++ b/tests/test_worker_session.py @@ -0,0 +1,198 @@ +"""Who is a worker, decided once, everywhere (R-7.1-1 the main agent owns the outcome and a worker is not metered +as one; R-7.2-2 legwork goes to a less expensive worker, so the meter must tell the two apart; R-16-1 a session a +person started is never exempted by words later in a message). Every test drives the real hook entry points with +hook-shaped JSON; the sessions here never had a prompt hook, as a session begun before sisi was upgraded.""" +import json, os, subprocess, time, unittest +from unittest import mock +from support import * +import test_meter as TM +import test_unitguard as TG +from sisi import brief, orchestration, store, workerid + +BRIEF = brief.template().splitlines()[0] +OPENINGS = [BRIEF, "You are a worker on this repository.", "You are a subagent for the lead.", "You are a sub-agent.", + "YOU ARE A DELEGATE of the main thread.", "Do this task yourself: fix the parser.", + "Please do the task yourself and report.", "Fix the parser. Do not delegate."] +ORDINARY = "Fix the parser and explain each module in the project." + + +class Base(TG.GuardCase): + sid = "wk" + + def setUp(self): + super().setUp() + os.makedirs(self.data, exist_ok=True) + TM.seed_workers(self) + self.tp = os.path.join(self.tmp, "t.jsonl") + + def transcript(self, first, path=None): + recs = [{"type": "file-history-snapshot", "snapshot": {}}, + {"type": "user", "message": {"role": "user", "content": first}, "timestamp": "2026-01-01T00:00:00Z"}, + {"type": "assistant", "message": {"role": "assistant", "content": "ok", "model": "m"}}] + with open(path or self.tp, "w") as f: + f.write("".join(json.dumps(r) + "\n" for r in recs)) + return path or self.tp + + def hook(self, tool, inp, after=False, sid=None, **extra): + """The real watch hook; (denied, text).""" + d = {"session_id": sid or self.sid, "cwd": self.proj, "tool_name": tool, "tool_input": inp, + "transcript_path": self.tp, "hook_event_name": "PostToolUse" if after else "PreToolUse"} + d.update(extra) + r = self.sisi("watch", "--after" if after else "--before", "--tool", "claude-code", stdin=json.dumps(d)) + self.assertEqual(r.returncode, 0, r.stderr) + out = json.loads(r.stdout) if r.stdout.strip() else {} + hs = out.get("hookSpecificOutput") or {} + return hs.get("permissionDecision") == "deny", hs.get("permissionDecisionReason") or "" + + def edit(self): + return self.hook("Edit", {"file_path": os.path.join(self.proj, SRC_FILE), "old_string": "hi", "new_string": "yo"}) + + def reads(self, n, tool="Read"): + return [self.hook(tool, {"file_path": "/x"})[0] for _ in range(n)] + + def stop(self): + r = self.sisi("gate", stdin=json.dumps({"session_id": self.sid, "cwd": self.proj, "hook_event_name": "Stop", + "transcript_path": self.tp})) + self.assertEqual(r.returncode, 0, r.stderr) + d = json.loads(r.stdout) if r.stdout.strip() else {} + return "block" if d.get("decision") == "block" else "allow" + + def stored(self): + return orchestration._peek(self.sid).get("worker") + + +SRC_FILE = TG.SRC + + +class RecognitionTests(Base): + def test_a_brief_in_the_transcript_makes_a_worker_for_the_guard_the_meter_and_the_gate(self): + """R-7.1-1: no meter record, no tick, no prompt: the transcript's first message decides, in all three.""" + self.transcript(BRIEF + "\n\n## Outcome and scope\nfix the greeting") + self.assertFalse(self.edit()[0]) # the contract guard + self.assertEqual(self.reads(9), [False] * 9) # the meter (limit 6) + with open(os.path.join(self.proj, SRC_FILE), "a") as f: + f.write("# changed\n") + self.assertEqual(self.stop(), "allow") # the gate + self.assertIs(self.stored(), True) + + def test_every_alternative_opening_makes_a_worker(self): + for i, text in enumerate(OPENINGS): + with self.subTest(opening=text): + self.sid = "wk%d" % i + self.transcript(text + "\nfix the greeting") + self.assertFalse(self.edit()[0]) + self.assertEqual(self.reads(8), [False] * 8) + self.assertIs(self.stored(), True) + + def test_an_ordinary_first_message_is_a_main_thread(self): + self.transcript(ORDINARY) + denied, text = self.edit() + self.assertTrue(denied, text) + self.assertEqual(self.reads(8), [False] * 6 + [True] * 2) + self.assertIs(self.stored(), False) + + def test_words_after_the_first_400_characters_do_not_count(self): + self.transcript(ORDINARY + " " * 5 + ("Context. " * 50) + "You are a worker. Do this task yourself. Do not delegate.") + self.assertTrue(self.edit()[0]) + self.assertEqual(self.reads(8), [False] * 6 + [True] * 2) + + def test_the_second_message_never_counts(self): + recs = [{"type": "user", "message": {"role": "user", "content": ORDINARY}, "timestamp": "2026-01-01T00:00:00Z"}, + {"type": "user", "message": {"role": "user", "content": BRIEF}, "timestamp": "2026-01-01T00:00:01Z"}] + with open(self.tp, "w") as f: + f.write("".join(json.dumps(r) + "\n" for r in recs)) + self.assertTrue(self.edit()[0]) + + def test_an_unreadable_transcript_is_a_main_thread_and_nothing_is_stored(self): + self.tp = os.path.join(self.tmp, "missing.jsonl") + self.assertTrue(self.edit()[0]) + self.assertEqual(self.reads(8), [False] * 6 + [True] * 2) + self.assertIsNone(self.stored()) + self.transcript(BRIEF) # a later call can still find it + self.assertFalse(self.edit()[0]) + self.assertIs(self.stored(), True) + + def test_the_decision_is_stored_and_the_transcript_is_read_once(self): + self.transcript(BRIEF) + reads = [] + real = workerid._read_head + with mock.patch.object(workerid, "_read_head", side_effect=lambda *a: reads.append(a) or real(*a)): + self.edit() + self.reads(5) + self.hook("Read", {"file_path": "/x"}, after=True) + self.stop() + self.assertEqual(len(reads), 1) + os.unlink(self.tp) # and it no longer needs the file + self.assertFalse(self.edit()[0]) + + def test_a_session_started_by_a_person_with_no_transcript_path_is_a_main_thread(self): + r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=json.dumps( + {"session_id": "nopath", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Edit", + "tool_input": {"file_path": os.path.join(self.proj, SRC_FILE)}})) + self.assertIn("deny", r.stdout) + + +class ShellChangeTests(Base): + """The lead's case: a worker known only by its first prompt changes files with a shell command (a merge); its + next call, a read-only one, was refused as an unowned change.""" + + def sequence(self): + self.hook("Bash", {"command": "git merge --no-commit other"}) + with open(os.path.join(self.proj, "canon_discovery.json"), "w") as f: + f.write("{}\n") # what the merge did to the tree + self.hook("Bash", {"command": "git merge --no-commit other"}, after=True) + return self.hook("Bash", {"command": "sed -n 1,5p README.md"}) + + def test_a_worker_whose_shell_command_changed_files_is_not_refused_on_its_next_call(self): + self.transcript(BRIEF + "\nmerge the branch") + denied, text = self.sequence() + self.assertFalse(denied, text) + self.assertEqual(self.stop(), "allow") + + def test_a_main_thread_in_the_same_sequence_is_still_refused(self): + self.transcript(ORDINARY) + denied, text = self.sequence() + self.assertTrue(denied) + self.assertIn("already changed", text) + + +class UnlistedToolTests(Base): + def counts(self): + return orchestration._peek(self.sid).get("calls") + + def test_an_unlisted_spawn_named_tool_at_the_limit_is_neither_refused_nor_counted(self): + self.transcript(ORDINARY) + self.assertEqual(self.reads(6), [False] * 6) + n = self.counts() + denied, text = self.hook("mcp__somehost__spawn_helper", {"task": "do x"}) + self.assertFalse(denied, text) + self.assertEqual(self.counts(), n) + self.assertTrue(self.reads(1)[0]) # the meter still bites for legwork + + def test_an_unlisted_status_tool_is_not_counted(self): + self.transcript(ORDINARY) + self.reads(6) + n = self.counts() + for tool in ("mcp__somehost__task_status", "mcp__somehost__t3_thread_wait", "mcp__somehost__ListThings"): + self.assertFalse(self.hook(tool, {})[0], tool) + self.assertEqual(self.counts(), n) + + def test_an_unlisted_read_tool_is_counted_and_refused_at_the_limit(self): + self.transcript(ORDINARY) + self.assertEqual([self.hook("mcp__somehost__read_file", {"p": "x"})[0] for _ in range(7)], [False] * 6 + [True]) + + def test_a_pattern_in_the_data_covers_a_prefixed_tool(self): + hd = {"delegation": {"*launch_it": {"model": "m", "brief": "b"}}} + self.assertIsNotNone(orchestration.delegation_spec(hd, "mcp__a__Launch_It")) + self.assertIsNone(orchestration.delegation_spec(hd, "mcp__a__launch_that")) + + def test_there_is_one_list_of_delegation_tools(self): + with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "canon", "guard.json")) as f: + self.assertNotIn("delegation_tools", json.load(f)) + from sisi import unitguard + self.assertEqual(unitguard.classify("Agent", {}, ""), "delegate") + self.assertEqual(unitguard.classify("mcp__x__spawn_helper", {}, ""), "delegate") + + +if __name__ == "__main__": + unittest.main()