Merge branch 't3/fix-judge-retro-agent-faults' into spec-reconciliation

This commit is contained in:
swaits committed 2026-11-23 23:15:08 -07:00
commit 7821c268fa
7 files changed
+126 -37

No files matched your search

+6 -2
View File
@@ -12,7 +12,9 @@ It routes by a models table: which workers you have, what each is good at, what
rebuilds that table when it gets old, and every judged delegation feeds the next research. The lead does not
choose the worker: `sisi pick CLASS` spins a wheel over the workers of that class (a capability tier: each model is
in exactly one class, so the wheel never mixes tiers; weighted by table order and by speed),
and a delegation to a worker the wheel did not give is refused. One pick, one delegation.
and a delegation to a worker the wheel did not give is refused. One pick, one delegation. A host that names its models
shortly (Claude Code's `Agent` tool says `sonnet`) may give one whole segment of the picked model id, so name a worker
by its full model id (`claude-sonnet-5-5`); anywhere else the name must match whole.
**Done.** Nothing starts before `sisi done` has recorded the goal, the checks that decide success and what the
person will need next: delegating or editing is refused until then. Every check needs a verdict
@@ -33,6 +35,8 @@ sisi doctor # how each tool stands
Python 3 standard library only. `sisi rollback` goes back to the release before. `sisi uninstall` takes out exactly
what `install` put in. `sisi update` fetches the newest sisi from the repository the release in use was made from
(`sisi release` records that remote: `github`, else `origin`) and releases it, so a checkout is only needed once.
`sisi release` run through the installed command never copies that release onto itself: it releases the checkout the
release records it came from when that is a local checkout, and otherwise says to run it from a checkout.
## Which agent tools
@@ -76,7 +80,7 @@ its limits are.
| `sisi learn [--project] "…"` | The person's own words become a rule at once |
| `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them; undo the last change |
| `sisi models` / `sisi models research [--record FILE]` | The workers table; have a worker rebuild it |
| `sisi judge WORKER good\|bad "…"` | How a delegation went; the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers |
| `sisi judge WORKER good\|bad "…" [--minutes N] [--newest]` | How a delegation went; the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first, `--newest` the newest |
| `sisi direct "…"` | Allow more direct tool calls this turn, with the reason |
## Where things live
+6 -17
View File
@@ -56,24 +56,13 @@ def main(argv):
except Exception as e: # a hook must never break the agent's session
store.append(os.path.join(store.STATE, "core-errors.log"), "%s %s: %r" % (time.strftime("%Y-%m-%dT%H:%M:%S"), cmd, e))
return 0
if cmd == "retro":
if cmd in ("retro", "done"):
from . import retro
return retro.run(args)
if cmd == "rules":
return rules.run(args)
if cmd == "done":
from . import retro
return retro.done(args)
if cmd == "pick":
return models.pick(args)
if cmd == "learn":
return rules.learn(args)
if cmd == "models":
return models.run(args)
if cmd == "judge":
return models.judge(args)
if cmd == "direct":
return hooks.direct(args)
return (retro.run if cmd == "retro" else retro.done)(args)
one = {"rules": rules.run, "pick": models.pick, "learn": rules.learn, "models": models.run, "judge": models.judge,
"direct": hooks.direct}
if cmd in one:
return one[cmd](args)
if cmd in ("install", "uninstall", "release", "update", "rollback", "doctor"):
from . import install
return getattr(install, cmd)()
+2 -2
View File
@@ -155,8 +155,8 @@ def watch(p):
if kind == "delegate" or shell:
target = ti.get("target") if isinstance(ti.get("target"), dict) else {}
names = (ti.get("model"),) if tool == "agent" else (ti.get("model"), target.get("model"), ti.get("agent"))
text = command if shell else str(next((n for n in names if n), ""))
if tool != "workflow" and models.usable(store.read(models.table())) and not models.claim(s, text):
text = command if shell else str(next((n for n in names if n), "")) # tool_input.model may be a short name: a segment
if tool != "workflow" and models.usable(store.read(models.table())) and not models.claim(s, text, not shell and bool(names[0])):
sys.stderr.write(say(NOPICK))
return 2
s["delegations_since"] = s.get("delegations_since", 0) + 1
+9 -2
View File
@@ -225,11 +225,18 @@ def _switch(dest):
def release():
"""Run the tests, then make this copy the one the hooks run. The four newest releases are kept."""
"""Run the tests, then make this copy the one the hooks run. The four newest releases are kept. Run through the
installed command (a copy in the releases folder) it releases the checkout that copy came from, if there is one."""
folder, src = os.path.join(store.LIB, "releases"), store.read(os.path.join(store.ROOT, "SOURCE")).strip()
if store.ROOT.startswith(os.path.realpath(folder) + os.sep): # the installed command: a copy of it ships nothing new
if src and os.path.isfile(os.path.join(src, "bin", "sisi")): # the checkout this copy records it came from
print("sisi release: this is the installed copy; releasing from %s instead." % src)
return subprocess.run([sys.executable, os.path.join(src, "bin", "sisi"), "release"]).returncode
print("sisi release: run it from the source checkout.")
return 1
if subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", "tests", "-q"], cwd=store.ROOT).returncode:
print("sisi release: the tests fail. Nothing was released.")
return 1
folder = os.path.join(store.LIB, "releases")
name = time.strftime("%Y%m%dT%H%M%S", time.gmtime()) + "%03dZ" % (time.time() % 1 * 1000) # two in one second differ
dest = os.path.join(folder, name)
shutil.copytree(store.ROOT, dest, ignore=shutil.ignore_patterns(".git", ".agent-work", ".sisi", "__pycache__"))
+13 -10
View File
@@ -118,10 +118,12 @@ def is_call(command_line):
return False
def claim(s, text):
"""Spend the pick that this delegation's model text names; False when none of the picks fits."""
def claim(s, text, segment=False):
"""Spend the pick that this delegation's model text names; False when none of the picks fits. With `segment` (the
host names its models shortly: `fast` for `maker-fast-2`) one whole segment of a picked id that has a letter fits."""
for name in s.get("picked") or []:
if any(re.search(r"(?<![a-z0-9.-])%s(?![a-z0-9.-])" % re.escape(n), text.lower()) for n in (name, name.rsplit("/", 1)[-1])):
if any(re.search(r"(?<![a-z0-9.-])%s(?![a-z0-9.-])" % re.escape(n), text.lower()) for n in (name, name.rsplit("/", 1)[-1])) or (
segment and re.search("[a-z]", text) and text.lower() in re.split("[-/]", name)):
s["picked"].remove(name)
starts = s["starts"] if isinstance(s.get("starts"), dict) else {}
starts[name] = (starts[name] if isinstance(starts.get(name), list) else []) + [time.time()]
@@ -252,31 +254,32 @@ def research_record(answer_file):
def judge(args, cwd=None):
"""`sisi judge WORKER good|bad "<why>" [--minutes N]`: how a delegation went, and how long it took (from the
pick's start in this session unless --minutes says)."""
"""`sisi judge WORKER good|bad "<why>" [--minutes N] [--newest]`: how a delegation went, and how long the job took:
from the oldest start of this worker's open jobs (the newest with --newest) unless --minutes says."""
from . import retro # not at the top: hooks import this module and must stay quick
minutes = None
args, newest, minutes, note = [a for a in args if a != "--newest"], "--newest" in args, None, ""
if "--minutes" in args:
i = args.index("--minutes")
v, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:]
minutes = int(v) if re.fullmatch(r"[1-9]\d{0,3}|10000", v) else 0
if len(args) != 3 or not args[0].strip() or args[1] not in ("good", "bad") or len(args[2].split()) < 3 or minutes == 0:
print('usage: sisi judge WORKER good|bad "<what it did well or badly, in a sentence>" [--minutes N]')
print('usage: sisi judge WORKER good|bad "<what it did well or badly, in a sentence>" [--minutes N] [--newest]')
return 1
sid = store.current_session(cwd)
if sid:
with store.session(sid) as s:
starts = s["starts"].get(short(args[0])) if isinstance(s.get("starts"), dict) else None
if isinstance(starts, list) and starts:
began = starts.pop(0) # a start in the future or not a number is dropped and times nothing
if type(began) in (int, float) and math.isfinite(began) and began <= time.time():
began = starts.pop(-1 if newest else 0) # one start per open job, oldest first
if type(began) in (int, float) and math.isfinite(began) and began <= time.time(): # else dropped, times nothing
minutes = minutes or max(1, int((time.time() - began) / 60))
note = " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(began)), len(starts))
log = store.data("outcomes.jsonl")
store.append(log, json.dumps(dict({"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "worker": args[0], "verdict": args[1],
"why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd))},
**{"minutes": minutes} if minutes else {}), sort_keys=True))
store.commit("delegation judged", log)
print("recorded: %d min." % minutes if minutes else "recorded, not timed.")
print("recorded: %d min%s." % (minutes, note) if minutes else "recorded, not timed.")
return 0
+2 -3
View File
@@ -47,9 +47,8 @@ def facts(state, cwd):
out += ["attention (measured): the person wrote %d message(s) in that time: read them again. Was any a correction, "
"or something they had to say twice?" % n["messages"],
"evidence (measured): %d check(s) passed, %d failed" % (n["checks_pass"], n["checks_fail"])] + d[1:-1]
out += ["value (judged): did the person get what they wanted? changed: %d commit(s), %d file(s) uncommitted" % (n["commits"], len(dirty)),
d[0], d[-1]]
return out + ["learning (measured): last 10 pieces of work named: %s" % (named or "none yet")]
out += ["value (judged): did the person get what they wanted? changed: %d commit(s), %d file(s) uncommitted" % (n["commits"], len(dirty))]
return out + d[:1] + d[1:][-1:] + ["learning (measured): last 10 pieces of work named: %s" % (named or "none yet")]
def show(d):
+88 -1
View File
@@ -441,6 +441,52 @@ class Core(unittest.TestCase):
self.assertEqual(judge()[0], 0)
self.assertEqual(self.outcomes()[-1]["minutes"], 1)
def test_judge_times_each_of_a_workers_open_jobs_from_its_own_start(self):
self.table(WORKERS)
self.hook("tick")
self.hook("prompt", prompt="go")
self.done()
delegate = lambda: (self.sisi("pick", "hard", sid="s1")[0], self.tool("Agent", tool_input={"model": "sonnet"})[0])
judge = lambda *a: self.sisi("judge", "sonnet", "good", "did the job in one pass", *a, sid="s1")
line = lambda m, t, k: "recorded: %d min (job started %s, %d more open for this worker)." % (m, time.strftime("%H:%M", time.localtime(t)), k)
def open_starts(starts): # the clock: sonnet's starts still open, as `sisi pick` would have stored them
with open(os.path.join(self.tmp, "state", "core-sessions", "s1.json"), "r+") as f:
st = json.load(f)
st["starts"]["sonnet"] = starts
f.seek(0), f.truncate(), json.dump(st, f)
t0 = time.time() - 30 * 60 - 5
self.assertEqual(delegate() + delegate(), (0, 0, 0, 0)) # two jobs of one worker at once
open_starts([t0, t0 + 600]) # the second began ten minutes after the first
rc, out, _ = judge() # half an hour after the first
self.assertEqual((rc, out.strip(), self.outcomes()[-1]["minutes"]), (0, line(30, t0, 1), 30))
self.assertEqual(self.state()["starts"]["sonnet"], [t0 + 600])
open_starts([t0]) # ten minutes later: the second has run half an hour
rc, out, _ = judge()
self.assertEqual((rc, out.strip(), self.outcomes()[-1]["minutes"]), (0, line(30, t0, 0), 30))
self.assertEqual(self.state()["starts"]["sonnet"], [])
self.assertEqual(judge()[1].strip(), "recorded, not timed.") # nothing open: no minutes
self.assertEqual(delegate() + delegate(), (0, 0, 0, 0))
open_starts([t0, t0 + 600])
rc, out, _ = judge("--newest") # the job that began last is judged first
self.assertEqual((rc, out.strip(), self.outcomes()[-1]["minutes"]), (0, line(20, t0 + 600, 1), 20))
self.assertEqual(self.state()["starts"]["sonnet"], [t0])
self.assertEqual(judge()[1].strip(), line(30, t0, 0)) # the first job's start is still there
delegate()
open_starts([t0])
self.assertEqual(judge("--minutes", "7")[1].strip(), line(7, t0, 0)) # --minutes overrides; the start is still spent
self.assertEqual((self.outcomes()[-1]["minutes"], self.state()["starts"]["sonnet"]), (7, []))
delegate()
open_starts(time.time() - 600) # an old state file: one number, not a list
self.assertEqual(judge()[1].strip(), "recorded, not timed.")
delegate()
self.assertEqual(len(self.state()["starts"]["sonnet"]), 1) # the next start is a list again
speed = lambda: self.sisi("pick", "hard", sid="s1")[1].split("speed: ")[1].splitlines()[0]
was = speed()
open_starts([time.time() - 65]) # a job that failed fast
self.assertEqual(self.sisi("judge", "sonnet", "bad", "gave up after one quick wrong try", sid="s1")[0], 0)
self.assertEqual(speed(), was) # only good outcomes set a worker's speed
def jsonl(self, name, *lines):
os.makedirs(self.data, exist_ok=True)
with open(os.path.join(self.data, name), "wb") as f:
@@ -485,7 +531,7 @@ class Core(unittest.TestCase):
self.assertNotIn("minutes", self.outcomes()[-1])
self.assertEqual(self.state()["starts"]["sonnet"], [])
start({"sonnet": [time.time() - 600]})
self.assertEqual(judge()[1].strip(), "recorded: 10 min.")
self.assertRegex(judge()[1].strip(), r"recorded: 10 min \(job started \d\d:\d\d, 0 more open for this worker\)\.")
for wrong in ([], "x", 5): # starts of the wrong type
self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0)
start(wrong)
@@ -605,6 +651,12 @@ class Core(unittest.TestCase):
self.assertEqual(self.tool("Edit", agent_id="a1")[0], 0) # the host's subagent
self.assertEqual(self.tool("Agent", agent_id="a1")[0], 0)
def test_the_retro_says_once_that_no_done_was_recorded(self):
self.hook("tick")
self.assertEqual(self.sisi("retro", sid="s1")[1].count("(no done recorded)"), 1)
self.done()
self.assertEqual(self.sisi("retro", sid="s1")[1].count("done: export every row without losing any with empty names"), 1)
def test_the_retro_shows_the_done_statement_and_the_trend(self):
self.hook("tick")
self.done()
@@ -958,6 +1010,26 @@ class Core(unittest.TestCase):
self.assertIn("Always keep what the person wrote", self.read(self.data, "generated", "core.md"))
self.assertEqual(os.listdir(env["TMPDIR"]), []) # the fetched copy is gone
def test_release_through_the_installed_command_releases_the_checkout_it_came_from(self):
run = lambda exe, *a: subprocess.run([sys.executable, exe] + list(a), cwd=self.proj, env=self.env, capture_output=True, text=True,
stdin=subprocess.DEVNULL)
lib, src = self.env["SISI_LIB"], self.source("1.0.0")
subprocess.run(["git", "remote", "add", "origin", src], cwd=src, check=True, capture_output=True) # its remote is itself: SOURCE names it
self.assertEqual(run(os.path.join(src, "bin", "sisi"), "release").returncode, 0)
installed = os.path.join(lib, "current", "bin", "sisi")
self.source("2.0.0") # the checkout changes
r = run(installed, "release") # `sisi release` through the installed command
self.assertEqual((r.returncode, self.read(lib, "current", "VERSION").strip()), (0, "2.0.0"), r.stdout)
folders = sorted(os.listdir(os.path.join(lib, "releases")))
for source in (None, "https://github.com/owner/sisi.git\n"): # no checkout it came from: nothing is released
if source is None:
os.remove(os.path.join(lib, "current", "SOURCE"))
else:
self.write(os.path.join(lib, "current", "SOURCE"), source)
r = run(installed, "release")
self.assertEqual((r.returncode, sorted(os.listdir(os.path.join(lib, "releases")))), (1, folders), (source, r.stdout))
self.assertIn("run it from the source checkout", r.stdout)
def test_doctor_says_how_every_tool_stands(self):
names = [h["name"] for h in json.loads(self.read(REPO, "canon", "harnesses.json"))]
home = self.harness(".claude", ".codex", ".grok", ".config/muse", ".pi")
@@ -1099,6 +1171,21 @@ class Core(unittest.TestCase):
self.done()
self.assertEqual(self.tool("Agent", tool_input={"model": "o3"})[0], 2) # the old pick is gone
def test_a_short_model_name_in_tool_input_matches_one_whole_segment_of_the_pick(self):
self.table(HEADER + "| claude-sonnet-5-5 | host subagent model `sonnet` | hard | per use | everything | |\n"
"| opencode-go/claude-haiku-5-5 | T3 Code delegate_task, model opencode-go/claude-haiku-5-5 | routine | flat | quick | |\n")
self.hook("tick")
self.hook("prompt", prompt="go")
self.done()
pick = lambda cls: self.sisi("pick", cls, sid="s1")[0]
for model, rc in (("sonnet", 0), ("Sonnet", 0), ("opus", 2), ("son", 2), ("5", 2)): # the Agent tool names models shortly
self.assertEqual((pick("hard"), self.tool("Agent", tool_input={"model": model})[0]), (0, rc), model)
self.assertEqual(len(self.state()["picked"]), 3) # a refusal spends no pick
self.assertEqual((pick("routine"), self.tool("Agent", tool_input={"model": "haiku"})[0]), (0, 0))
task = lambda model: self.tool("mcp__t3__delegate_task", tool_input={"target": {"model": model}})[0]
for model, rc in (("claude-haiku-5-5", 0), ("haiku", 2), ("5", 2)): # target.model: whole names only, as before
self.assertEqual((pick("routine"), task(model)), (0, rc), model)
def test_the_maker_column_is_read_by_name_and_both_shapes_record(self):
sys.path.insert(0, REPO)
from sisi import models