"""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.assertRegex(brief.splitlines()[0], r"^sisi chore: models research [0-9a-f]{8}$") 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()