From b5814dd1040e9a9a8e9c4021fd7df2247916f269 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Thu, 3 Dec 2026 10:14:10 -0700 Subject: [PATCH] judge --chore: restore the unrelated lines squashed to fit the size cap The previous commit rewrote about 40 unrelated statements as one-liners to stay under the line cap. Those are back to main's text, and the feature's own code is written in the surrounding plain style. Behaviour of the feature is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- sisi/hooks.py | 13 +++-- sisi/models.py | 131 +++++++++++++++++++++++++++++++++---------------- 2 files changed, 97 insertions(+), 47 deletions(-) diff --git a/sisi/hooks.py b/sisi/hooks.py index 25c6f27..1d0593d 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -250,20 +250,25 @@ def _outside(s, tool, ti, brief, text, shell, names, cfg): def direct(args, cwd=None): """`sisi direct ""`: the lead says why doing more itself costs less than delegating it.""" reason, sid, cfg = " ".join(" ".join(args).split()), store.current_session(cwd), store.config() - if len(reason.split()) < 4 or not sid: return print('usage: sisi direct ""') or 1 + if len(reason.split()) < 4 or not sid: + print('usage: sisi direct ""') + return 1 with store.session(sid) as s: s["extra"] = s.get("extra", 0) + cfg["direct_extension"] s.setdefault("reasons_since", []).append(reason[:200]) - return print("%d more direct calls this turn. The reason goes into the retro." % cfg["direct_extension"]) or 0 + print("%d more direct calls this turn. The reason goes into the retro." % cfg["direct_extension"]) + return 0 def gate(p, for_subagent=False): """End of turn: when the lead changed things and has not held the retro, send it back to hold it.""" sid, cwd = p["session_id"], p["cwd"] or os.getcwd() - if for_subagent or not sid or p["subagent"] or not store.config()["gate"]: return 0 + if for_subagent or not sid or p["subagent"] or not store.config()["gate"]: + return 0 with store.session(sid) as s: _begin(s, cwd) - if s.get("worker"): return 0 + if s.get("worker"): + return 0 models.sync_late(s, cwd, sid) open_f, starts = _faults(cwd, True, None, sid), s["starts"] if isinstance(s.get("starts"), dict) else {} seen = [x for x in (s["reminded"] if isinstance(s.get("reminded"), list) else []) diff --git a/sisi/models.py b/sisi/models.py index acf084a..67498c9 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -237,24 +237,32 @@ def overdue(s): def _job_info(s, w, t): - """(tag, flag, hhmm) for open job (w, t): tag is `node X`, `chore Y`, or ``.""" - m = ((s.get("meta") if isinstance(s.get("meta"), dict) else {}).get("%s %r" % (w, t))) + """(tag, flag, hhmm) for the open job of worker w started at t: tag is `node X`, `chore Y` or empty.""" + meta = s["meta"] if isinstance(s.get("meta"), dict) else {} + m = meta.get("%s %r" % (w, t)) m = m if isinstance(m, dict) else {} nid = m.get("node") or next((k for k, v in ((s.get("plan") or {}).get("state") or {}).items() if isinstance(v, dict) and v.get("st") == "running" and v.get("worker") == w and v.get("since") == t), None) cid, hhmm = m.get("chore"), time.strftime("%H:%M", time.localtime(t)) - return ("node %s" % nid, "--node %s" % nid, hhmm) if nid else ("chore %s" % cid, "--chore %s" % cid, hhmm) if cid else ("", "", hhmm) + if nid: return "node %s" % nid, "--node %s" % nid, hhmm + if cid: return "chore %s" % cid, "--chore %s" % cid, hhmm + return "", "", hhmm def unjudged(s): - """['WORKER (node X | chore Y, started HH:MM)', ...] for valid open jobs in `s['starts']`, oldest first.""" - starts = s.get("starts") if isinstance(s.get("starts"), dict) else {} - return [text for _, _, text in sorted((t, w, "%s (%s)" % (w, "%s, started %s" % (tag, hhmm) if tag else "started %s" % hhmm)) - for w, v in starts.items() for t in (v if isinstance(v, list) else ()) if type(t) in (int, float) and math.isfinite(t) - for tag, _, hhmm in [_job_info(s, w, t)])] + """['WORKER (node X | chore Y, started HH:MM)', ...] for the open jobs in `s["starts"]`, oldest first.""" + starts, jobs = s.get("starts") if isinstance(s.get("starts"), dict) else {}, [] + for w, v in starts.items(): + for t in (v if isinstance(v, list) else ()): + if type(t) in (int, float) and math.isfinite(t): + tag, _, hhmm = _job_info(s, w, t) + jobs.append((t, "%s (%sstarted %s)" % (w, tag + ", " if tag else "", hhmm))) + return [text for _, text in sorted(jobs)] -waiting = lambda s: isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values()) +def waiting(s): + """A delegation of this piece of work is open: started and not yet judged.""" + return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values()) OUT = 6 * 3600 # a worker judged `out` sits out this long, then the wheel tries it again: 24 h / 6 h = at most 4 tries a day @@ -285,7 +293,9 @@ def out(r, skip, bad, gone, now): else SINCE % (clock(since[0]), clock(since[0] + OUT)) if since and now - since[0] < OUT else "") -median = lambda v: (lambda x: (x[len(x) // 2] + x[(len(x) - 1) // 2]) / 2)(sorted(v)) +def median(v): + v = sorted(v) + return (v[len(v) // 2] + v[(len(v) - 1) // 2]) / 2 def track(): @@ -349,7 +359,9 @@ def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, no bad = next((maker(r) for r in table_rows if short(r[0]) == short(review)), None) if review else None left = [r for r in table_rows if r[2].strip().lower() == cls and not out(r, skip, bad, gone, now)] if not left: return None - if rand is None: import random; rand = random.random + if rand is None: + import random + rand = random.random 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 = [(len(left) if (tried or {}).get(short(r[0]), 0) < 3 else w) * (max(0.02, (fast / med[short(r[0])]) ** 3) if short(r[0]) in med else 1) @@ -375,11 +387,15 @@ def pick(args, cwd=None, rand=None): elif args[i] == "--branch" and i + 1 < len(args) and re.fullmatch(r"[A-Za-z0-9._/-]{1,100}", args[i + 1]) and not args[i + 1].startswith("-"): branch = args[i + 1] else: cls = None i += 2 - if not cls: return print("usage: sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]") or 1 + if not cls: + print("usage: sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]") + return 1 text, why = wheel() if why: return print("sisi pick: %s: %s" % (why, "run `sisi models offered < FILE` and hand the printed `models offered` chore to any model the host offers." if why == "no offered model has a row" else REFRESH)) or 1 mine = [r for r in rows(text) if r[2].strip().lower() == cls] - if review is not None and not any(short(r[0]) == short(review) for r in rows(text)): return print("sisi pick: %r is not a worker in the models table; --review-of names the worker whose work is reviewed." % review) or 1 + if review is not None and not any(short(r[0]) == short(review) for r in rows(text)): + 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, qual, tried), gone, now = track(), away(), time.time() r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual, share=shares(plan_use(text, cwd, now)), tried=tried) if not r: @@ -391,7 +407,9 @@ def pick(args, cwd=None, rand=None): else "sisi pick: the models table has no worker of class %s." % cls) + (" The first is back on the wheel at %s." % clock(first) if first is not None else "") + again) return 1 - for x in rows(text): len(re.findall(r"routine|ordinary|hard", x[2].lower())) > 1 and print("%s is in more than one class and is on no wheel: rebuild the table" % short(x[0])) + for x in rows(text): + if len(re.findall(r"routine|ordinary|hard", x[2].lower())) > 1: + print("%s is in more than one class and is on no wheel: rebuild the table" % short(x[0])) sid, also = store.current_session(cwd), [] if sid: with store.session(sid) as s: @@ -457,14 +475,17 @@ def research_record(answer_file): return "each row's \"use for\" must name exactly one of routine, ordinary or hard: | %s |" % " | ".join(r[:6]) if len(lines) > 42 or len(text) > 12000: return "the answer is too long (at most 40 rows and 12,000 characters)" - if shared and ("|" not in shared or not _shared_date(shared)[0]): return "the shared section needs a `researched YYYY-MM-DD` line and a table" + if shared and ("|" not in shared or not _shared_date(shared)[0]): + return "the shared section needs a `researched YYYY-MM-DD` line and a table" paths = [table()] + ([shared_store()] if shared else []) with store.lock("models"): store.write(table(), text + "\n") - shared and store.write(shared_store(), shared + "\n") + if shared: + store.write(shared_store(), shared + "\n") os.path.isfile(store.data("models.stale")) and os.remove(store.data("models.stale")) ok = store.commit("models table researched", *paths) - return print("models table recorded: %d workers.%s" % (len(lines) - 2, "" if ok else " (store commit failed)")) or None + print("models table recorded: %d workers.%s" % (len(lines) - 2, "" if ok else " (store commit failed)")) + return None def sync_late(s, cwd, sid, add=True): @@ -480,19 +501,25 @@ def sync_late(s, cwd, sid, add=True): def judge(args, cwd=None): """`sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "" [--newest] [--node ID | --chore ID]`. - Without --node/--chore a verdict closes the worker's oldest open job (--newest: its newest); with --node/--chore, that exact job.""" + Without --node/--chore a verdict closes the worker's oldest open job (--newest: its newest); with --node, the job that runs that + plan node; with --chore, the job started under that chore id.""" from . import retro # not at the top: hooks import this module and must stay quick - args, newest, opt, note, warn = [a for a in args if a != "--newest"], "--newest" in args, {}, "", "" - for k in ("--minutes", "--node", "--chore"): - if k in args: - i = args.index(k) - opt[k], args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:] - minutes = (int(opt["--minutes"]) if re.fullmatch(r"[1-9]\d{0,3}|10000", opt["--minutes"]) else 0) if "--minutes" in opt else None - node, chore = opt.get("--node"), (opt["--chore"].lower() if "--chore" in opt else None) + args, newest, minutes, note, node, chore, warn = [a for a in args if a != "--newest"], "--newest" in args, None, "", None, 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 "--node" in args: # the plan node whose job is judged: one worker may run several + i = args.index("--node") + node, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:] + if "--chore" in args: # the chore whose job is judged + i = args.index("--chore") + chore, args = (args[i + 1:i + 2] or [""])[0].lower(), args[:i] + args[i + 2:] ext = len(args) == 4 and args[1] == "extend" and minutes is None and re.fullmatch(r"[1-9]\d{0,3}|10000", args[2]) if not args or not args[0].strip() or not (ext or (len(args) == 3 and args[1] in ("good", "bad", "out") and minutes != 0)) or len(args[-1].split()) < 3 \ or (node is not None and not re.fullmatch(r"[a-z0-9-]{1,30}", node)) or chore == "" or (node is not None and chore is not None): - return print('usage: sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "" [--newest] [--node ID | --chore ID]') or 1 + print('usage: sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "" [--newest] [--node ID | --chore ID]') + return 1 wrows = rows(wheel()[0]) # a worker's wheel row wins over its table row (the list is the truth), and is counted once trows = wrows + [r for r in rows(store.read(table())) if short(r[0]) not in {short(x[0]) for x in wrows}] hits = [r for r in trows if short(r[0]) == short(args[0])] or [r for r in trows if claim({"picked": [short(r[0])]}, args[0], True)] @@ -508,7 +535,7 @@ def judge(args, cwd=None): wkey, now, began = short(model), time.time(), None if sid: with store.session(sid) as s: - starts, meta = s["starts"].get(wkey) if isinstance(s.get("starts"), dict) else None, s.get("meta") if isinstance(s.get("meta"), dict) else {} + starts = s["starts"].get(wkey) if isinstance(s.get("starts"), dict) else None open_ = starts if isinstance(starts, list) else [] # this worker's open starts if node is not None: # --node: the job that runs this plan node from . import plan @@ -518,11 +545,13 @@ def judge(args, cwd=None): cand = v["since"] if type(v.get("since")) in (int, float) and v["since"] in open_ else None not ext and cand is not None and open_.remove(cand) elif chore is not None: # --chore: the job started under this chore id - cand = next((t for t in open_ if isinstance(meta.get("%s %r" % (wkey, t)), dict) and meta["%s %r" % (wkey, t)].get("chore") == chore), None) + meta = s["meta"] if isinstance(s.get("meta"), dict) else {} + cand = next((t for t in open_ if isinstance(m := meta.get("%s %r" % (wkey, t)), dict) and m.get("chore") == chore), None) if cand is None: - jobs = ["%s (started %s)" % (k, h) if k else "started %s" % h for t in open_ if type(t) in (int, float) and math.isfinite(t) for k, _, h in [_job_info(s, wkey, t)]] + infos = [_job_info(s, wkey, t) for t in open_ if type(t) in (int, float) and math.isfinite(t)] + jobs = ["%s (started %s)" % (tag, hhmm) if tag else "started %s" % hhmm for tag, _, hhmm in infos] return print("sisi judge: chore %s is not an open job for %s (open: %s). Nothing was changed." % (chore, wkey, ", ".join(jobs) or "none")) or 1 - not ext and open_.remove(cand) + if not ext: open_.remove(cand) else: cand = (open_.pop(-1 if newest else 0) if not ext else open_[-1 if newest else 0]) if open_ else None if ext and not newest: # the job that is late, not just the oldest open one @@ -534,26 +563,34 @@ def judge(args, cwd=None): m[k], s["meta"] = {**(m[k] if isinstance(m.get(k), dict) else {}), "limit": lim, "extended": now, "reason": retro.clean(args[3])}, m isinstance(s.get("reminded"), list) and s.__setitem__("reminded", [x for x in s["reminded"] if x != [wkey, cand]]) return sync_late(s, cwd, sid, False) or print("extended %s limit to %d min." % (wkey, lim)) or 0 - if ok_t and node is None and chore is None and open_: - ck, cf, ch = _job_info(s, wkey, cand) + if ok_t and node is None and chore is None and open_: # no target named: say which job closed when it could have been another + tag, flag, hhmm = _job_info(s, wkey, cand) others = [_job_info(s, wkey, t) for t in open_ if type(t) in (int, float) and math.isfinite(t)] - if cf or any(f for _, f, _ in others): - warn = "closed %s; still open: %s" % ("%s (started %s)" % (ck, ch) if ck else "started %s" % ch, ", ".join("%s (started %s, %s)" % (k, h, f) if f else "started %s" % h for k, f, h in others)) + if flag or any(f for _, f, _ in others): + closed = "%s (started %s)" % (tag, hhmm) if tag else "started %s" % hhmm + left = ", ".join("%s (started %s, %s)" % (k, h, f) if f else "started %s" % h for k, f, h in others) + warn = "closed %s; still open: %s" % (closed, left) isinstance(s.get("meta"), dict) and s["meta"].pop("%s %r" % (wkey, cand), None) if node is not None: s["plan"]["state"][node] = {"st": "done", "evidence": "judged good"} if args[1] == "good" else {"st": "failed", "why": "judged " + args[1]} # as plan.judged moves the node its job started elif s.get("plan"): from . import plan; plan.judged(s, wkey, cand, args[1]) - if ok_t: began, minutes, note = cand, minutes or max(1, int((now - cand) / 60)), " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(cand)), len(open_)) + if ok_t: + began = cand + minutes = minutes or max(1, int((now - began) / 60)) + note = " (job started %s, %d more open for this worker)" % (time.strftime("%H:%M", time.localtime(began)), len(open_)) sync_late(s, cwd, sid, False) elif ext or node is not None or chore is not None: return print("sisi judge: no open job for %s." % args[0]) or 1 iso = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t)) rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1], - "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)), "project_key": store.project_key(cwd)} - sid and rec.__setitem__("session_id", sid); began is not None and rec.__setitem__("started", iso(began)); minutes and rec.__setitem__("minutes", minutes) + "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)), + "project_key": store.project_key(cwd)} + if sid: rec["session_id"] = sid + if began is not None: rec["started"] = iso(began) + if minutes: rec["minutes"] = minutes log = store.data("outcomes.jsonl") store.append(log, json.dumps(rec, sort_keys=True)) ok = store.commit("delegation judged", log) print("%s%s" % ("recorded: %d min%s." % (minutes, note) if minutes else "recorded, not timed.", "" if ok else " (store commit failed)")) - warn and print(warn) + if warn: print(warn) return 0 @@ -564,13 +601,20 @@ def run(args, cwd=None): if text: print("\n(researched %d days ago)" % age_days()) 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 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 - if args == ["research"]: from . import plan; return plan.issue("models research", research_brief(), cwd) or 0 - if len(args) == 3 and args[:2] == ["research", "--record"]: return (print("sisi models: %s. Nothing was changed." % why) or 1) if (why := research_record(args[2])) else 0 + if args == ["research"]: + from . import plan + return plan.issue("models research", research_brief(), cwd) or 0 + if len(args) == 3 and args[:2] == ["research", "--record"]: + why = research_record(args[2]) + return (print("sisi models: %s. Nothing was changed." % why) or 1) if why else 0 if args == ["offered"]: raw = sys.stdin.read(200001).strip() if not raw or len(raw) > 200000: return print("sisi models: give the host's raw list of offered models on stdin (1 to 200,000 characters). Nothing was changed.") or 1 @@ -591,4 +635,5 @@ def run(args, cwd=None): new = [short(r[0]) for r in rows(text) if r[5].lower().startswith("new:")] print("recorded %d offered models.%s" % (len(rows(text)), " " + ASK.replace("sisi models research`", "sisi models research` (its brief names: %s)" % ", ".join(new), 1) if new else "")) return 0 - return print("usage: sisi models | sisi models research [--record FILE] | sisi models offered [--record FILE]") or 1 + print("usage: sisi models | sisi models research [--record FILE] | sisi models offered [--record FILE]") + return 1