From 2175b566a806f2d4961efab01bbd9a07ce65051d Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Wed, 2 Dec 2026 08:47:02 -0700 Subject: [PATCH] Models table: one most-efficient row per provider per class, spread load by plan windows Research brief asks for provider and efficiency columns (published allowance with URL and 5h/week/month request windows), at most one row per provider per class, most efficient first, and is marked as a sisi chore; ASK sends it to a hard-class worker with web search. research_record refuses missing provider/efficiency and duplicate provider+class rows. The wheel weights each worker by its plan's share left (sisi's own delegations against the table's request windows, floored at 0.05); sisi models prints estimated plan use. research_days 7 -> 3. Co-Authored-By: Claude Opus 5.5 --- sisi/models.py | 90 ++++++++++++---- sisi/store.py | 2 +- tests/test_core.py | 38 ++++--- tests/test_models_research.py | 197 ++++++++++++++++++++++++++++++++++ 4 files changed, 295 insertions(+), 32 deletions(-) create mode 100644 tests/test_models_research.py diff --git a/sisi/models.py b/sisi/models.py index 763ffad..34a603f 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -7,30 +7,38 @@ from . import rules, store ASK_FRESH = ("which providers and models from the shipped baseline table below are usable on this machine, how to call each, and what each costs here; map them to whatever providers this user has", "Reuse the shipped baseline table below for class (`use for`), baseline score, benchmarks, list price, and public good-at/bad-at — do not re-research them online. Combine them with our own judged record below, which outranks a benchmark.", - "Order rows within each class by baseline score descending (the picker's row weighting uses row order); break ties or unranked models by cheapest capable first.") + "Use the baseline score to decide which models truly perform at a class; then choose and order by efficiency (step 3).") ASK_STALE = ("which AI models this machine can delegate work to, what each is good at and what it costs", "What each is good at. Use current public software-engineering benchmarks and the maker's own description (search the web), then our own record below, which outranks a benchmark.", - "Only the newest version of each model belongs in the table. A smaller or faster variant is a different model.") + "Only the newest version of each model belongs in the table. A smaller or faster variant is a different model. Then choose and order by efficiency (step 3).") EXTRA_SHARED = ("\nThen a second, separately marked section starting on its own line with `=== Shared models ===`, followed by `researched YYYY-MM-DD` on its first line and a baseline ranking table " "(`| model | maker | class | score | released | list price | benchmarks | good at, bad at |`) with one row per model (keyed by model id, never provider route), sorted by class then score descending, " "holding only shared public facts (no plans, allowances, availability, judged records, or personal notes).\n") -RESEARCH = """You are a worker. Do this task yourself; do not delegate it further. +RESEARCH = """sisi chore: models research +You are a worker. Do this task yourself; do not delegate it further. Find out %(intro)s, and write the personal table an engineering lead will route by. -1. What is there. Look for AI coding command-line tools on PATH and run each one's own model listing. Add the - models the host offers its own subagents. Do not log in, change a setting or run a paid task. +1. What is there: every provider (the account or plan a call draws its allowance or bill from) the host's delegation + tool can start, and each one every AI coding tool on PATH routes to (run its auth/provider list and model list; a + second plan behind one tool is a separate provider). Do not log in, change a setting or run a paid task. 2. %(step2)s -3. What it costs here: free, a flat plan with an allowance, or paid per use, and anything that limits it. +3. Efficiency: how much work at its class one unit of this person's allowance or money buys. The `efficiency` cell + quotes the provider's own published allowance or price for that model with the plan/pricing page URL (or + "measured: ..." from our record), and its quota windows exactly as `5h: N req; week: N req; month: N req` (`req` + only when N counts requests; else name the unit). sisi spreads delegations by these so no plan runs dry early. + Among models that truly perform at a class, keep the one whose allowance goes furthest (flat plan: most requests + per window; per use: lowest cost per benchmark task): at most one row per provider per class; drop the rest. + Notes hold `usage: ` where one exists. 4. %(step4)s -5. What the person has said, below, stands exactly: their limits and preferences are not yours to change. +5. What the person has said, below, stands exactly and outranks all of this: it is not yours to change. List only workers the host's delegation tool can actually start: check the host's own list of enabled providers. -Answer with exactly this and nothing else. First a markdown table of at most 40 rows, the cheapest capable -worker first within each level (or ordered by baseline score descending when reusing the baseline), with these columns: -| worker | maker | how to call it | use for | cost | good at, bad at | notes | -"maker" is the company or lab that trained the model, lower case, one word. "use for" is exactly one of: routine, +Answer with exactly this and nothing else. First a markdown table of at most 40 rows, at most one row per provider +per class, ordered within each class most efficient first (the wheel weights by row order), with these columns: +| worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes | +"provider" names the account or plan as the person knows it. "maker" is the company or lab that trained the model, lower case, one word. "use for" is exactly one of: routine, ordinary, hard. It is the model's capability class, not a list of tasks it could do. Routine is the small, fast, cheap tier (the level of a maker's smallest current model); ordinary is the mid tier (a maker's main everyday model); hard is the top tier (a maker's strongest model). Place each model by comparing it with its peers from @@ -55,8 +63,8 @@ Then one line starting "Fallback order:" that says who takes over when a worker === How delegations went here, newest last === %(outcomes)s """ -ASK = ("In the background, give the output of `sisi models research` to a research worker and record its " - "answer with `sisi models research --record FILE`.") +ASK = ("In the background, give the output of `sisi models research` to a hard-class worker that can search the web " + "(`sisi pick hard`: choosing models well pays for itself) and record its answer with `sisi models research --record FILE`.") def table(): return store.data("models.md") @@ -104,7 +112,7 @@ def stale(mark=None): return ("sisi: a delegation named `%s`, which the models table does not list. " % who + ASK) if who and not known(store.read(table()), who) else "" -KEYS = ("worker", "how", "use", "cost", "good", "notes", "maker") # a column is known by its header's first word +KEYS = ("worker", "how", "use", "cost", "good", "notes", "maker", "provider", "efficiency") # a column is known by its header's first word LAUNCHERS = {"python", "python3", "bash", "sh", "zsh", "cd", "env", "npx", "npm", "node", "uv", "uvx", "make", "ssh", "git", "docker", "sudo"} @@ -255,10 +263,46 @@ def qualities(): return {w: (sum(v[-10:]) + 1) / (len(v[-10:]) + 1) for w, v in out.items()} -def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None, quality=None): +WINDOWS, FLOOR = {"5h": 5 * 3600, "week": 7 * 86400, "month": 30 * 86400}, 0.05 +pkey = lambda provider: " ".join(str(provider).lower().split()) + + +def budgets(cell): + """{window: N} from `5h: N req; week: N req; month: N req` in a cell; only counts of requests, which a delegation is counted as.""" + return {w: int(n.replace(",", "")) for w, n in re.findall( + r"\b(5h|week|month)\s*:\s*(\d[\d,]*)\s*(?:req|requests|prompts|messages|calls|delegations)\b", cell.lower()) if int(n.replace(",", ""))} + + +def plan_use(text, cwd=None, now=None): + """{provider: {window: share used}} by sisi's own delegations: each started in the window spends 1/N of its plan's + window, N the allowance its row gives (outcomes.jsonl, plus the current session's open jobs).""" + now, by, times, sid = now or time.time(), {short(r[0]): r for r in rows(text) if r[7]}, [], store.current_session(cwd) + try: starts = json.loads(store.read(store._session_path(sid)) or "{}").get("starts") if sid else None + except (ValueError, AttributeError): starts = None + for o in store.records("outcomes.jsonl"): + try: + w = o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"] + times.append((short(w), time.mktime(time.strptime(o.get("started") or o["ts"], "%Y-%m-%dT%H:%M:%S")))) + except (KeyError, TypeError, ValueError, AttributeError): pass # a damaged line spends nothing + for w, v in (starts.items() if isinstance(starts, dict) else ()): + times += [(short(w), t) for t in (v if isinstance(v, list) else ()) if type(t) in (int, float)] + out = {} + [out.setdefault(pkey(r[7]), {}).update(dict.fromkeys(budgets(r[3] + " " + r[8]), 0.0)) for r in by.values()] + for w, t in times: + if (r := by.get(w)) and t <= now: + for win, n in budgets(r[3] + " " + r[8]).items(): + if now - t < WINDOWS[win]: out[pkey(r[7])][win] += 1.0 / n + return {p: u for p, u in out.items() if u} + + +def shares(use): return {p: max(FLOOR, min(1 - x for x in u.values())) for p, u in use.items()} + + +def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None, quality=None, share=None): """One worker of this class, by a wheel weighted by table order (the first of n has weight n, the last 1) times its speed: the fastest candidate's median minutes over its own, cubed, at least 0.02 (1 with no timed jobs), - times its quality factor over its last 10 good/bad outcomes ((good+1)/(n+1), so no bad runs keeps weight 1). + times its quality factor over its last 10 good/bad outcomes ((good+1)/(n+1), so no bad runs keeps weight 1), + times its provider's share of plan left (`share`, from `shares`: at least FLOOR), so no plan runs dry early. A worker last said out less than OUT seconds ago (`gone`, from `outs`) is not on the wheel.""" table_rows, gone, now = rows(text), gone or {}, now or time.time() bad = next((maker(r) for r in table_rows if short(r[0]) == short(review)), None) if review else None @@ -270,7 +314,7 @@ def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, no med = {short(r[0]): median(speed[short(r[0])]) for r in left if (speed or {}).get(short(r[0]))} fast, qual = min(med.values(), default=1), quality or {} weights = [w * (max(0.02, (fast / med[short(r[0])]) ** 3) if short(r[0]) in med else 1) - * max(1 / 11, qual.get(short(r[0]), 1)) for w, r in zip(range(len(left), 0, -1), left)] + * max(1 / 11, qual.get(short(r[0]), 1)) * (share or {}).get(pkey(r[7]), 1) for w, r in zip(range(len(left), 0, -1), left)] x = rand() * sum(weights) for weight, r in zip(weights, left): if (x := x - weight) < 0: return r @@ -299,7 +343,7 @@ def pick(args, cwd=None, rand=None): print("sisi pick: %r is not a worker in the models table; --review-of names the worker whose work is reviewed." % review) return 1 speed, gone, qual, now = speeds(), away(), qualities(), time.time() - r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual) + r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual, share=shares(plan_use(text, cwd, now))) if not r: bad = next((maker(x) for x in rows(text) if short(x[0]) == short(review)), None) again = {"routine": " Choose again from ordinary.", "ordinary": " Choose again from hard."}.get(cls, "") @@ -353,7 +397,14 @@ def research_record(answer_file): lines = [l for l in text.splitlines() if l.startswith("|")] if "| worker" not in text.lower() or "fallback order:" not in text.lower() or len(lines) < 3: return "the answer needs the table (a `| worker |` header and at least one row) and a `Fallback order:` line" + seen = {} for r in rows(text): + if not r[7] or not r[8]: + return "each row needs its %s: | %s |" % ("provider (a `provider` column: the account or plan the call draws on)" if not r[7] else "efficiency (the published allowance or price, with its URL, or \"measured: ...\")", " | ".join(r[:6])) + key = (pkey(r[7]), r[2].strip().lower()) + if key in seen: + return "keep at most one row per provider per class, the most efficient: %s and %s are both %s at %s" % (seen[key], r[0], r[2].strip(), r[7]) + seen[key] = r[0] if len(re.findall(r"routine|ordinary|hard", r[2].lower())) != 1: return "each row's \"use for\" must name exactly one of routine, ordinary or hard: | %s |" % " | ".join(r[:6]) if re.search(r"\bout (?:until|till)\b", " ".join(r), re.I): # what the wheel would read as a legacy note @@ -445,6 +496,9 @@ def run(args, cwd=None): gone, now, listed = away(), time.time(), {short(r[0]) for r in rows(text)} if sitting := sorted((t, w) for w, (t, _) in gone.items() if w in listed and now - t < OUT): print("\nOff the wheel now:\n" + "\n".join("%s: %s" % (w, SINCE % (clock(t), clock(t + OUT))) for t, w in sitting)) + if use := plan_use(text, cwd, now): + print("\nPlan use by sisi's own delegations (an estimate; the plan's own usage page is exact):\n" + "\n".join( + "%s: %s" % (p, ", ".join("%s %d%%" % (w, round(100 * x)) for w, x in u.items())) for p, u in sorted(use.items()))) if recent := outcomes(15): print("\nHow recent delegations went:\n" + "\n".join(recent)) if stale(): print("\n" + stale()) return 0 diff --git a/sisi/store.py b/sisi/store.py index 0353b4b..d9386ea 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -24,7 +24,7 @@ GIT_ERROR = "" # why the last git call that failed did: the first line of its s # Every setting there is. The person overrides one under "core" in config.json in their store. DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8, - "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 7, "shell_workers": False, + "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 3, "shell_workers": False, "worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8} def config(): diff --git a/tests/test_core.py b/tests/test_core.py index 61e37df..cdd3357 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -34,6 +34,18 @@ TWO = ONE + "| beta | host subagent model `beta` | routine | free | quick | |\n" LIMIT = "You have hit your usage limit for this model" +def rec(text): + """A table as `sisi models research --record` takes it: each row with a provider of its own and an efficiency cell.""" + out, i = [], 0 + for line in text.splitlines(True): + body = line.rstrip("\n") + if line.startswith("| worker"): body += " provider | efficiency |" + elif line.startswith("|---"): body += "---|---|" + elif line.startswith("|"): i, body = i + 1, body + " plan %d | 5h: 100 req |" % (i + 1) + out.append(body + ("\n" if line.endswith("\n") else "")) + return "".join(out) + + def tree(): """A fingerprint of the product tree, so a test that writes into it is caught.""" out = hashlib.sha1() @@ -1616,9 +1628,9 @@ cli.main(["tick"]) self.assertIn("Only the cheapest models on the shared plan", brief) # the person's words bind the researcher answer = os.path.join(self.tmp, "table.md") self.assertEqual(self.sisi("models", "research", "--record", self.write(answer, "a few words of prose"))[0], 1) - self.write(answer, "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n" - "| small | host subagent `small` | routine | flat | fast; weak at design | |\n" - "Fallback order: routine: small, then the lead.\n") + self.write(answer, rec("| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n" + "| small | host subagent `small` | routine | flat | fast; weak at design | |\n" + "Fallback order: routine: small, then the lead.\n")) self.assertEqual(self.sisi("models", "research", "--record", answer)[0], 0) self.assertIn("| small |", self.sisi("models")[1]) self.assertNotIn("models table", self.hook("tick", sid="s2")[1]) @@ -1653,7 +1665,7 @@ cli.main(["tick"]) def test_research_record_writes_models_shared_and_rejects_bad_shared(self): answer = os.path.join(self.tmp, "answer.md") - personal = ("| worker | maker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|---|\n" + personal = rec("| worker | maker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|---|\n" "| small | x | host subagent `small` | routine | flat | fast | |\nFallback order: routine: small.\n") shared = ("researched 2026-11-25\n\n| model | maker | class | score | released | list price | benchmarks | good at, bad at |\n|---|---|---|---|---|---|---|---|\n" "| small | x | routine | 40.0 | | free | TB4 40% | fast |\n") @@ -1749,8 +1761,8 @@ cli.main(["tick"]) def test_a_model_is_in_exactly_one_class_and_the_wheel_never_mixes_classes(self): answer = os.path.join(self.tmp, "table.md") - mixed = HEADER + ("| opus | host subagent model `opus` | hard | per use | hardest | |\n" - "| sonnet | host subagent model `sonnet` | ordinary, hard | per use | everything | |\n") + mixed = rec(HEADER + ("| opus | host subagent model `opus` | hard | per use | hardest | |\n" + "| sonnet | host subagent model `sonnet` | ordinary, hard | per use | everything | |\n")) self.write(answer, mixed + "Fallback order: none.\n") rc, out, _ = self.sisi("models", "research", "--record", answer) # check a self.assertEqual((rc, "| sonnet | host subagent model `sonnet` | ordinary, hard |" in out), (1, True)) @@ -2176,7 +2188,7 @@ cli.main(["tick"]) self.assertIn("gemini-3.8-flash-medium", tick) self.assertIn("sisi models research --record FILE", tick) # recording a new table clears the marker - ans = self.write(os.path.join(self.tmp, "ans.md"), WORKERS + "Fallback order: sonnet\n") + ans = self.write(os.path.join(self.tmp, "ans.md"), rec(WORKERS) + "Fallback order: sonnet\n") self.assertEqual(self.sisi("models", "research", "--record", ans)[0], 0) self.assertNotIn("gemini-3.8-flash-medium", self.hook("tick", sid="s6")[1]) @@ -2788,7 +2800,7 @@ cli.main(["tick"]) def test_a_table_with_no_usable_row_is_refused_and_enforces_nothing(self): answer = os.path.join(self.tmp, "table.md") - self.write(answer, HEADER + "| small | host subagent `small` | quick jobs | flat | fast | |\nFallback order: none.\n") + self.write(answer, rec(HEADER + "| small | host subagent `small` | quick jobs | flat | fast | |\nFallback order: none.\n")) rc, out, _ = self.sisi("models", "research", "--record", answer) self.assertEqual((rc, "routine, ordinary or hard" in out), (1, True)) self.table(HEADER + "| small | host subagent `small` | quick jobs | flat | fast | |\n") @@ -2962,11 +2974,11 @@ cli.main(["tick"]) self.assertNotIn("out until", brief) self.assertIn("sisi judge WORKER out", brief) answer = os.path.join(self.tmp, "table.md") - clean = HEADER + "| small | host subagent `small` | routine | flat | fast | |\nFallback order: none.\n" + clean = rec(HEADER + "| small | host subagent `small` | routine | flat | fast | |\nFallback order: none.\n") self.write(answer, clean) self.assertEqual(self.sisi("models", "research", "--record", answer)[0], 0) for notes in ("out till 2999-01-01", "out until next week", "Out Until 2999-1-1", "out until 2999-01-01"): - self.write(answer, HEADER + "| small | host subagent `small` | routine | flat | fast | %s |\nFallback order: none.\n" % notes) + self.write(answer, rec(HEADER + "| small | host subagent `small` | routine | flat | fast | %s |\nFallback order: none.\n" % notes)) rc, out, _ = self.sisi("models", "research", "--record", answer) self.assertEqual((rc, "| small |" in out, "delete the" in out, "judge the worker instead" in out), (1, True, True, False), notes) # a table writer is told to delete it, not to invent a verdict self.assertEqual(self.read(self.data, "models.md").strip(), clean.strip()) @@ -3034,14 +3046,14 @@ cli.main(["tick"]) new = ("| worker | maker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|---|\n" "| sonnet | anthropic | host subagent `sonnet` | hard | paid | x | |\n| glm-5.4 | zhipu | opencode glm-5.4 | hard | flat | x | |\n" "| haiku | anthropic | host subagent `haiku` | hard | paid | x | |\n") - self.assertEqual(models.rows(new)[0], ["sonnet", "host subagent `sonnet`", "hard", "paid", "x", "", "anthropic"]) + self.assertEqual(models.rows(new)[0], ["sonnet", "host subagent `sonnet`", "hard", "paid", "x", "", "anthropic", "", ""]) for _ in range(50): self.assertEqual(models.choose(new, "hard", review="sonnet", rand=random.random)[0], "glm-5.4") answer = os.path.join(self.tmp, "table.md") for text in (new, WORKERS): - self.assertEqual(self.sisi("models", "research", "--record", self.write(answer, text + "Fallback order: none.\n"))[0], 0) + self.assertEqual(self.sisi("models", "research", "--record", self.write(answer, rec(text) + "Fallback order: none.\n"))[0], 0) brief = self.sisi("models", "research")[1] - self.assertIn("| worker | maker | how to call it |", brief) + self.assertIn("| worker | provider | maker | how to call it |", brief) self.assertIn("enabled providers", brief) def test_a_failed_check_alone_forces_the_retro_and_says_so(self): diff --git a/tests/test_models_research.py b/tests/test_models_research.py new file mode 100644 index 0000000..9d0a97c --- /dev/null +++ b/tests/test_models_research.py @@ -0,0 +1,197 @@ +"""Tests for the efficiency-first models table: one row per provider per class, each with its evidence.""" +import contextlib +import glob +import hashlib +import io +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +REAL_HOME = os.path.expanduser("~") +sys.path.insert(0, REPO) +from sisi import models, store + +HEAD = ("| worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |\n" + "|---|---|---|---|---|---|---|---|---|\n") +GO = "| go/qwen-flash | OpenCode Go | qwen | `opencode run -m go/qwen-flash \"\"` | routine | flat | 5,400 per 5h, 16,200 per week (https://example.test/go) | fast | |\n" +ZAI = "| zai/glm-5 | z.ai coding plan | zhipu | `opencode run -m zai/glm-5 \"\"` | hard | flat | 600 prompts per 5h (https://example.test/zai) | strong | |\n" +HOST = "| sonnet | Anthropic | anthropic | host subagent `sonnet` | ordinary | per use | measured: 12 good jobs at $0.40 each | broad | |\n" +FALL = "Fallback order: routine: go/qwen-flash; ordinary: sonnet; hard: zai/glm-5.\n" + + +def tree(): + out = hashlib.sha1() + for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))): + if os.path.isfile(p): + with open(p, "rb") as f: + out.update(p.encode() + f.read()) + return out.hexdigest() + + +class ModelsResearch(unittest.TestCase): + def setUp(self): + before = tree() + self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) + book = os.path.join(REAL_HOME, ".claude", "CLAUDE.md") + mine = self.read(book) if os.path.exists(book) else None + self.addCleanup(lambda: self.assertEqual(self.read(book) if os.path.exists(book) else None, mine, "a test wrote the person's own rules file")) + self.tmp = tempfile.mkdtemp(prefix="sisi-models-") + self.addCleanup(shutil.rmtree, self.tmp, True) + self.data = os.path.join(self.tmp, "data") + self.env = dict(os.environ, HOME=self.tmp, SISI_DATA=self.data, + SISI_STATE=os.path.join(self.tmp, "state"), SISI_LIB=os.path.join(self.tmp, "lib"), + CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude")) + for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"): + self.env.pop(name, None) + subprocess.run(["git", "init", "-q", self.data], check=True, capture_output=True, stdin=subprocess.DEVNULL) + + def in_process(self, fn, *args): + out, here = io.StringIO(), os.getcwd() + os.chdir(self.tmp) + try: + with mock.patch.object(store, "DATA", self.data), mock.patch.object(store, "STATE", os.path.join(self.tmp, "state")), \ + mock.patch.object(store, "LIB", os.path.join(self.tmp, "lib")), mock.patch.object(store, "HOME", self.tmp), \ + mock.patch.dict(os.environ, {k: self.env[k] for k in ("HOME", "CLAUDE_CONFIG_DIR")}), contextlib.redirect_stdout(out): + return fn(*args), out.getvalue() + finally: + os.chdir(here) + + def read(self, *parts): + with open(os.path.join(*parts), encoding="utf-8") as f: + return f.read() + + def record(self, text): + path = os.path.join(self.tmp, "answer.md") + with open(path, "w", encoding="utf-8") as f: + f.write(text) + return self.in_process(models.run, ["research", "--record", path]) + + def table(self): + p = os.path.join(self.data, "models.md") + return self.read(p) if os.path.exists(p) else None + + def test_rows_read_provider_and_efficiency_and_keep_old_indices(self): + r = models.rows(HEAD + GO)[0] + self.assertEqual(r[6], "qwen") # maker stays at index 6 + self.assertEqual(r[7], "OpenCode Go") + self.assertIn("5,400 per 5h", r[8]) + self.assertEqual(r[:3], ["go/qwen-flash", "`opencode run -m go/qwen-flash \"\"`", "routine"]) + old = "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n| a | x | hard | flat | y | z |\n" + self.assertEqual(models.rows(old)[0][7:], ["", ""]) # an older table still parses + + def test_two_plans_behind_one_cli_record_as_two_providers(self): + rc, out = self.record(HEAD + GO + ZAI + HOST + FALL) + self.assertEqual(rc, 0, out) + self.assertEqual({r[7] for r in models.rows(self.table())}, {"OpenCode Go", "z.ai coding plan", "Anthropic"}) + + def test_refuses_a_missing_provider_column(self): + old = ("| worker | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |\n|---|---|---|---|---|---|---|---|\n" + "| a | x | host subagent `a` | hard | flat | 100 per day (https://example.test) | y | |\n") + rc, out = self.record(old + FALL) + self.assertEqual(rc, 1) + self.assertIn("provider", out) + self.assertIn("Nothing was changed", out) + self.assertIsNone(self.table()) + + def test_refuses_an_empty_provider_or_efficiency_cell_naming_the_row(self): + for row in (GO.replace("| OpenCode Go |", "| |"), GO.replace("| 5,400 per 5h, 16,200 per week (https://example.test/go) |", "| |")): + rc, out = self.record(HEAD + row + ZAI + FALL) + self.assertEqual(rc, 1, row) + self.assertIn("go/qwen-flash", out) + self.assertIn("Nothing was changed", out) + self.assertIsNone(self.table()) + + def test_refuses_two_rows_of_one_provider_in_one_class(self): + twin = GO.replace("go/qwen-flash", "go/hy4-flash").replace("| OpenCode Go |", "| opencode GO |") + rc, out = self.record(HEAD + GO + twin + FALL) + self.assertEqual(rc, 1) + self.assertIn("go/qwen-flash", out) + self.assertIn("go/hy4-flash", out) + self.assertIsNone(self.table()) + other = twin.replace("| routine |", "| ordinary |") # the same provider in another class is fine + self.assertEqual(self.record(HEAD + GO + other + FALL)[0], 0) + + def test_brief_asks_for_provider_efficiency_and_one_row_per_provider_class(self): + rc, brief = self.in_process(models.run, ["research"]) + self.assertEqual(rc, 0) + self.assertEqual(brief.splitlines()[0], "sisi chore: models research") + self.assertIn("| worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |", brief) + self.assertIn("at most one row per provider per class", brief.lower()) + self.assertIn("most efficient first", brief.lower()) + self.assertIn("separate provider", brief.lower()) + with mock.patch.object(models, "_shared_date", return_value=("2000-01-01", 0.0)): # the stale variant too + stale = self.in_process(models.research_brief)[0] + with mock.patch.object(models, "_shared_date", return_value=("2999-01-01", 4e10)): + fresh = self.in_process(models.research_brief)[0] + self.assertNotEqual(stale, fresh) + for b in (stale, fresh): + self.assertTrue(b.startswith("sisi chore: models research\n")) + self.assertIn("| worker | provider | maker |", b) + self.assertIn("efficiency", b) + + def test_ask_sends_the_brief_to_a_hard_worker_and_research_is_kept_current(self): + self.assertIn("sisi pick hard", models.ASK) + self.assertIn("web", models.ASK) + self.assertEqual(store.DEFAULTS["research_days"], 3) + + def test_budget_parser_reads_request_windows_only(self): + self.assertEqual(models.budgets("5h: 60,700 req; week: 121,000 req (https://example.test/go)"), {"5h": 60700, "week": 121000}) + self.assertEqual(models.budgets("month: 300 prompts"), {"month": 300}) + self.assertEqual(models.budgets("5h: 2,000,000 tokens; week: 0 req"), {}) # tokens do not map to delegations + self.assertEqual(models.budgets("flat plan, no numbers"), {}) + + def use_log(self, worker, n, hours_ago=1): + import json, time + os.makedirs(self.data, exist_ok=True) + t = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(time.time() - hours_ago * 3600)) + with open(os.path.join(self.data, "outcomes.jsonl"), "a", encoding="utf-8") as f: + for _ in range(n): + f.write(json.dumps({"ts": t, "started": t, "worker": worker, "model": worker, "verdict": "good", "why": "did it well"}) + "\n") + + BUSY = HEAD + ("| a/one | Plan A | qwen | `a one \"\"` | routine | flat | 5h: 10 req; week: 40 req (https://example.test/a) | x | |\n" + "| b/two | Plan B | zhipu | `b two \"\"` | routine | flat | 5h: 10 req; week: 40 req (https://example.test/b) | x | |\n") + + def test_a_heavily_used_plan_is_picked_less_and_never_below_the_floor(self): + import random + self.use_log("a/one", 8) # plan A: 80% of its 5h window spent + use = self.in_process(models.plan_use, self.BUSY)[0] + self.assertAlmostEqual(use["plan a"]["5h"], 0.8) + self.assertAlmostEqual(use["plan a"]["week"], 0.2) + self.assertEqual(use["plan b"], {"5h": 0.0, "week": 0.0}) + share = models.shares(use) + self.assertAlmostEqual(share["plan a"], 0.2) + rng = random.Random(1) + picks = [models.choose(self.BUSY, "routine", rand=rng.random, share=share)[0] for _ in range(2000)] + self.assertLess(picks.count("a/one"), picks.count("b/two") / 2) # without share a/one, listed first, wins 2:1 + self.use_log("a/one", 50) # past the whole allowance: the floor holds + share = models.shares(self.in_process(models.plan_use, self.BUSY)[0]) + self.assertEqual(share["plan a"], models.FLOOR) + picks = [models.choose(self.BUSY, "routine", rand=rng.random, share=share)[0] for _ in range(4000)] + self.assertGreater(picks.count("a/one"), 0) + + def test_two_models_of_one_plan_spend_the_same_windows(self): + both = self.BUSY + "| a/big | Plan A | qwen | `a big \"\"` | hard | flat | 5h: 2 req; month: 4 req (https://example.test/a) | x | |\n" + self.use_log("a/one", 1) + self.use_log("a/big", 1) + use = self.in_process(models.plan_use, both)[0]["plan a"] + self.assertEqual({k: round(v, 3) for k, v in use.items()}, {"5h": 0.6, "week": 0.025, "month": 0.25}) + + def test_old_delegations_leave_the_window_and_models_prints_plan_use(self): + self.use_log("a/one", 5, hours_ago=6) # outside 5h, inside the week + os.makedirs(self.data, exist_ok=True) + with open(os.path.join(self.data, "models.md"), "w", encoding="utf-8") as f: + f.write(self.BUSY) + use = self.in_process(models.plan_use, self.BUSY)[0] + self.assertEqual((use["plan a"]["5h"], use["plan a"]["week"]), (0.0, 0.125)) + out = self.in_process(models.run, [])[1] + self.assertIn("Plan use by sisi's own delegations", out) + self.assertIn("plan a: 5h 0%, week 12%", out) + + +if __name__ == "__main__": + unittest.main()