Add --chore targeting to sisi judge and list unjudged jobs at stop gate

This commit is contained in:
swaits committed 2026-12-03 10:12:00 -07:00
1 parent 10688425c9
commit 894aeb7e4a
5 files changed
+257 -75

No files matched your search

+2 -2
View File
@@ -102,8 +102,8 @@ its limits are.
| `sisi plan brief` / `sisi plan --record FILE` / `sisi plan` / `sisi plan --done\|--fail ID "…"` | The dependency graph of a piece of work, recorded before any delegation: `\| node \| class \| needs \| branch \| files \| check \| why \|`, one join every node reaches; refused on a cycle, a missing need, a shared branch, or overlapping files between nodes that can run at once. Prints the waves to dispatch together. `sisi pick --node ID` gives the worker and a header for the brief; the hook denies a lead's delegation outside the plan, out of order, unpicked, or without its own worktree, and the end of a turn sends the lead back while ready nodes wait. `sisi judge` closes or reopens the node. A `sisi chore:` brief (models research, plan brief) needs no plan. `"enforce": false` turns denials into reminders | | `sisi plan brief` / `sisi plan --record FILE` / `sisi plan` / `sisi plan --done\|--fail ID "…"` | The dependency graph of a piece of work, recorded before any delegation: `\| node \| class \| needs \| branch \| files \| check \| why \|`, one join every node reaches; refused on a cycle, a missing need, a shared branch, or overlapping files between nodes that can run at once. Prints the waves to dispatch together. `sisi pick --node ID` gives the worker and a header for the brief; the hook denies a lead's delegation outside the plan, out of order, unpicked, or without its own worktree, and the end of a turn sends the lead back while ready nodes wait. `sisi judge` closes or reopens the node. A `sisi chore:` brief (models research, plan brief) needs no plan. `"enforce": false` turns denials into reminders |
| `sisi models` / `sisi models research [--record FILE]` | The workers table: at most one row per provider (the plan or account a call draws on) per class, the one whose published allowance goes furthest, with its source and quota windows (`5h: N req; week: N req`); the wheel picks a plan less the more of its windows sisi's own delegations have used (never below 5%); research is redone every 3 days by a hard worker. (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it | | `sisi models` / `sisi models research [--record FILE]` | The workers table: at most one row per provider (the plan or account a call draws on) per class, the one whose published allowance goes furthest, with its source and quota windows (`5h: N req; week: N req`); the wheel picks a plan less the more of its windows sisi's own delegations have used (never below 5%); research is redone every 3 days by a hard worker. (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it |
| `sisi models offered [--record FILE]` | Save the host's raw offered-model list from stdin and print the chore to match it against the table; `--record FILE` saves the harness's wheel so `sisi pick` only returns models this harness offers | | `sisi models offered [--record FILE]` | Save the host's raw offered-model list from stdin and print the chore to match it against the table; `--record FILE` saves the harness's wheel so `sisi pick` only returns models this harness offers |
| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest] [--node ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); 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, and `--node ID` closes or reopens the job running that plan node | | `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest] [--node ID \| --chore ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); 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 (and if another open job has `--node`/`--chore`, a note names the closed job and the remaining ones with their targeting flags), `--newest` the newest, `--node ID` closes or reopens the job running that plan node, and `--chore ID` closes that chore job |
| `sisi judge WORKER extend MINUTES "<reason>" [--newest] [--node ID]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest, or the job for `--node ID`) gets MINUTES more from now, and its late fault clears | | `sisi judge WORKER extend MINUTES "<reason>" [--newest] [--node ID \| --chore ID]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest, or the job for `--node ID` / `--chore ID`) gets MINUTES more from now, and its late fault clears |
| `sisi direct "…"` | Allow more direct tool calls this turn, with the reason | | `sisi direct "…"` | Allow more direct tool calls this turn, with the reason |
## Where things live ## Where things live
+2 -2
View File
@@ -41,10 +41,10 @@ Delegation
sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME] sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]
the wheel gives you one worker for a ready plan node (or of a class, for a the wheel gives you one worker for a ready plan node (or of a class, for a
`sisi chore:` brief); one pick, one delegation `sisi chore:` brief); one pick, one delegation
sisi judge WORKER good|bad|out WHY | extend MINUTES WHY [--newest] [--node ID] sisi judge WORKER good|bad|out WHY | extend MINUTES WHY [--newest] [--node ID | --chore ID]
how a delegation went (`out` with the provider's own message when it hit a how a delegation went (`out` with the provider's own message when it hit a
limit: sisi tries it again by itself), or give a running job more time; limit: sisi tries it again by itself), or give a running job more time;
--node ID names the job itself when one worker runs two plan nodes --node ID or --chore ID names the job itself when a worker runs several
sisi direct REASON allow yourself more direct tool calls this turn, with the reason sisi direct REASON allow yourself more direct tool calls this turn, with the reason
Setting up Setting up
+10 -10
View File
@@ -194,7 +194,10 @@ def watch(p):
notes += stop + soft notes += stop + soft
screen_brief_without_look(brief) and notes.append(NOLOOK) screen_brief_without_look(brief) and notes.append(NOLOOK)
s.update(probe) # the pick this delegation spent, if any s.update(probe) # the pick this delegation spent, if any
chore is None or s["chores"].pop(chore) cid = s["chores"].pop(chore)[3] if chore is not None else None
if (c := probe.get("claimed")) and cid:
k, m = "%s %r" % c, s.get("meta") if isinstance(s.get("meta"), dict) else {}
s["meta"] = {**m, k: {**(m.get(k) if isinstance(m.get(k), dict) else {}), "chore": cid}}
if node and probe.get("claimed"): if node and probe.get("claimed"):
from . import plan from . import plan
plan.start(s, node, *probe["claimed"]) plan.start(s, node, *probe["claimed"])
@@ -247,25 +250,20 @@ def _outside(s, tool, ti, brief, text, shell, names, cfg):
def direct(args, cwd=None): def direct(args, cwd=None):
"""`sisi direct "<reason>"`: the lead says why doing more itself costs less than delegating it.""" """`sisi direct "<reason>"`: 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() reason, sid, cfg = " ".join(" ".join(args).split()), store.current_session(cwd), store.config()
if len(reason.split()) < 4 or not sid: if len(reason.split()) < 4 or not sid: return print('usage: sisi direct "<why doing this yourself costs less than briefing a worker>"') or 1
print('usage: sisi direct "<why doing this yourself costs less than briefing a worker>"')
return 1
with store.session(sid) as s: with store.session(sid) as s:
s["extra"] = s.get("extra", 0) + cfg["direct_extension"] s["extra"] = s.get("extra", 0) + cfg["direct_extension"]
s.setdefault("reasons_since", []).append(reason[:200]) s.setdefault("reasons_since", []).append(reason[:200])
print("%d more direct calls this turn. The reason goes into the retro." % cfg["direct_extension"]) return print("%d more direct calls this turn. The reason goes into the retro." % cfg["direct_extension"]) or 0
return 0
def gate(p, for_subagent=False): 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.""" """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() sid, cwd = p["session_id"], p["cwd"] or os.getcwd()
if for_subagent or not sid or p["subagent"] or not store.config()["gate"]: if for_subagent or not sid or p["subagent"] or not store.config()["gate"]: return 0
return 0
with store.session(sid) as s: with store.session(sid) as s:
_begin(s, cwd) _begin(s, cwd)
if s.get("worker"): if s.get("worker"): return 0
return 0
models.sync_late(s, cwd, sid) models.sync_late(s, cwd, sid)
open_f, starts = _faults(cwd, True, None, sid), s["starts"] if isinstance(s.get("starts"), dict) else {} 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 []) seen = [x for x in (s["reminded"] if isinstance(s.get("reminded"), list) else [])
@@ -295,5 +293,7 @@ def gate(p, for_subagent=False):
return 0 return 0
s["blocks"] = s.get("blocks", 0) + 1 s["blocks"] = s.get("blocks", 0) + 1
demand and s.setdefault("retro_demanded", time.time()) demand and s.setdefault("retro_demanded", time.time())
if unjudged := models.unjudged(s):
reason += "\nsisi: unjudged jobs: " + ", ".join(unjudged)
print(json.dumps({"decision": "block", "reason": say(reason)})) print(json.dumps({"decision": "block", "reason": say(reason)}))
return 0 return 0
+60 -61
View File
@@ -236,9 +236,25 @@ def overdue(s):
return list(by_w.items()) return list(by_w.items())
def waiting(s): def _job_info(s, w, t):
"""A delegation of this piece of work is open: started and not yet judged.""" """(tag, flag, hhmm) for open job (w, t): tag is `node X`, `chore Y`, or ``."""
return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values()) m = ((s.get("meta") if isinstance(s.get("meta"), dict) else {}).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)
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)])]
waiting = lambda s: 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 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
@@ -269,9 +285,7 @@ def out(r, skip, bad, gone, now):
else SINCE % (clock(since[0]), clock(since[0] + OUT)) if since and now - since[0] < OUT else "") else SINCE % (clock(since[0]), clock(since[0] + OUT)) if since and now - since[0] < OUT else "")
def median(v): median = lambda v: (lambda x: (x[len(x) // 2] + x[(len(x) - 1) // 2]) / 2)(sorted(v))
v = sorted(v)
return (v[len(v) // 2] + v[(len(v) - 1) // 2]) / 2
def track(): def track():
@@ -335,9 +349,7 @@ 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 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)] 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 not left: return None
if rand is None: if rand is None: import random; rand = random.random
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]))} 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 {} 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) 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)
@@ -363,15 +375,11 @@ 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] 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 else: cls = None
i += 2 i += 2
if not cls: if not cls: return print("usage: sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]") or 1
print("usage: sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]")
return 1
text, why = wheel() 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 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] 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)): 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
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() (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) 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: if not r:
@@ -383,9 +391,7 @@ def pick(args, cwd=None, rand=None):
else "sisi pick: the models table has no worker of class %s." % cls) 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) + (" The first is back on the wheel at %s." % clock(first) if first is not None else "") + again)
return 1 return 1
for x in rows(text): 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]))
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), [] sid, also = store.current_session(cwd), []
if sid: if sid:
with store.session(sid) as s: with store.session(sid) as s:
@@ -451,17 +457,14 @@ def research_record(answer_file):
return "each row's \"use for\" must name exactly one of routine, ordinary or hard: | %s |" % " | ".join(r[:6]) 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: if len(lines) > 42 or len(text) > 12000:
return "the answer is too long (at most 40 rows and 12,000 characters)" 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]): 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"
return "the shared section needs a `researched YYYY-MM-DD` line and a table"
paths = [table()] + ([shared_store()] if shared else []) paths = [table()] + ([shared_store()] if shared else [])
with store.lock("models"): with store.lock("models"):
store.write(table(), text + "\n") store.write(table(), text + "\n")
if shared: shared and store.write(shared_store(), shared + "\n")
store.write(shared_store(), shared + "\n")
os.path.isfile(store.data("models.stale")) and os.remove(store.data("models.stale")) os.path.isfile(store.data("models.stale")) and os.remove(store.data("models.stale"))
ok = store.commit("models table researched", *paths) ok = store.commit("models table researched", *paths)
print("models table recorded: %d workers.%s" % (len(lines) - 2, "" if ok else " (store commit failed)")) return print("models table recorded: %d workers.%s" % (len(lines) - 2, "" if ok else " (store commit failed)")) or None
return None
def sync_late(s, cwd, sid, add=True): def sync_late(s, cwd, sid, add=True):
@@ -476,22 +479,20 @@ def sync_late(s, cwd, sid, add=True):
def judge(args, cwd=None): def judge(args, cwd=None):
"""`sisi judge WORKER good|bad|out "<why>" [--minutes N] [--newest] [--node ID] | extend MINUTES "<why>" [--newest] [--node ID]`. """`sisi judge WORKER good|bad|out "<why>" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "<why>" [--newest] [--node ID | --chore ID]`.
Without --node a verdict closes the worker's oldest open job (--newest: its newest); with --node, the job that runs that plan node.""" Without --node/--chore a verdict closes the worker's oldest open job (--newest: its newest); with --node/--chore, that exact job."""
from . import retro # not at the top: hooks import this module and must stay quick from . import retro # not at the top: hooks import this module and must stay quick
args, newest, minutes, note, node = [a for a in args if a != "--newest"], "--newest" in args, None, "", None args, newest, opt, note, warn = [a for a in args if a != "--newest"], "--newest" in args, {}, "", ""
if "--minutes" in args: for k in ("--minutes", "--node", "--chore"):
i = args.index("--minutes") if k in args:
v, args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:] i = args.index(k)
minutes = int(v) if re.fullmatch(r"[1-9]\d{0,3}|10000", v) else 0 opt[k], args = (args[i + 1:i + 2] or [""])[0], args[:i] + args[i + 2:]
if "--node" in args: # the plan node whose job is judged: one worker may run several minutes = (int(opt["--minutes"]) if re.fullmatch(r"[1-9]\d{0,3}|10000", opt["--minutes"]) else 0) if "--minutes" in opt else None
i = args.index("--node") node, chore = opt.get("--node"), (opt["--chore"].lower() if "--chore" in opt else None)
node, args = (args[i + 1:i + 2] or [""])[0], 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]) 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 \ 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 (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):
print('usage: sisi judge WORKER good|bad|out "<what it did well or badly, or the provider\'s message when it hit a limit, in a sentence>" [--minutes N] [--newest] [--node ID] | extend MINUTES "<reason, 3+ words>" [--newest] [--node ID]') return print('usage: sisi judge WORKER good|bad|out "<what it did well or badly, or the provider\'s message when it hit a limit, in a sentence>" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "<reason, 3+ words>" [--newest] [--node ID | --chore ID]') or 1
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 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}] 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)] 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)]
@@ -507,7 +508,7 @@ def judge(args, cwd=None):
wkey, now, began = short(model), time.time(), None wkey, now, began = short(model), time.time(), None
if sid: if sid:
with store.session(sid) as s: with store.session(sid) as s:
starts = s["starts"].get(wkey) if isinstance(s.get("starts"), dict) else None starts, meta = s["starts"].get(wkey) if isinstance(s.get("starts"), dict) else None, s.get("meta") if isinstance(s.get("meta"), dict) else {}
open_ = starts if isinstance(starts, list) else [] # this worker's open starts 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 if node is not None: # --node: the job that runs this plan node
from . import plan from . import plan
@@ -516,6 +517,12 @@ def judge(args, cwd=None):
return print("sisi judge: node %s is not a job %s is running here, so --node names nothing. Nothing was changed." % (node, wkey)) or 1 return print("sisi judge: node %s is not a job %s is running here, so --node names nothing. Nothing was changed." % (node, wkey)) or 1
cand = v["since"] if type(v.get("since")) in (int, float) and v["since"] in open_ else 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) 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)
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)]]
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)
else: else:
cand = (open_.pop(-1 if newest else 0) if not ext else open_[-1 if newest else 0]) if open_ else None 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 if ext and not newest: # the job that is late, not just the oldest open one
@@ -527,26 +534,26 @@ 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 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]]) 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 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)
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))
isinstance(s.get("meta"), dict) and s["meta"].pop("%s %r" % (wkey, cand), None) 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 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]) elif s.get("plan"): from . import plan; plan.judged(s, wkey, cand, args[1])
if ok_t: 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_))
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) sync_late(s, cwd, sid, False)
elif ext or node is not None: return print("sisi judge: no open job for %s." % args[0]) or 1 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)) 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], 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)), "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)), "project_key": store.project_key(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)
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") log = store.data("outcomes.jsonl")
store.append(log, json.dumps(rec, sort_keys=True)) store.append(log, json.dumps(rec, sort_keys=True))
ok = store.commit("delegation judged", log) 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)")) 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)
return 0 return 0
@@ -557,20 +564,13 @@ def run(args, cwd=None):
if text: if text:
print("\n(researched %d days ago)" % age_days()) print("\n(researched %d days ago)" % age_days())
gone, now, listed = away(), time.time(), {short(r[0]) for r in rows(text)} 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): 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))
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 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 recent := outcomes(15): print("\nHow recent delegations went:\n" + "\n".join(recent))
if stale(): print("\n" + stale()) if stale(): print("\n" + stale())
return 0 return 0
if args == ["research"]: if args == ["research"]: from . import plan; return plan.issue("models research", research_brief(), cwd) or 0
from . import plan 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
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"]: if args == ["offered"]:
raw = sys.stdin.read(200001).strip() 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 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,5 +591,4 @@ def run(args, cwd=None):
new = [short(r[0]) for r in rows(text) if r[5].lower().startswith("new:")] 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 "")) 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 0
print("usage: sisi models | sisi models research [--record FILE] | sisi models offered [--record FILE]") return print("usage: sisi models | sisi models research [--record FILE] | sisi models offered [--record FILE]") or 1
return 1
+183
View File
@@ -0,0 +1,183 @@
"""Tests for `sisi judge --chore ID`, multi-job warnings, and stop-gate unjudged job lines.
Black-box CLI tests in a temporary home and store."""
import glob, hashlib, json, os, re, shutil, subprocess, sys, tempfile, time, unittest
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REAL_HOME = os.path.expanduser("~")
HEADER = "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n"
ALPHA = "| alpha | host subagent model `alpha` | routine | free | quick | |\n"
BETA = "| beta | host subagent model `beta` | routine | free | quick | |\n"
def tree():
"""A fingerprint of the product tree, so a test that writes into it is caught."""
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 JudgeChore(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-test-")
self.addCleanup(shutil.rmtree, self.tmp, True)
self.data = os.path.join(self.tmp, "data")
os.makedirs(self.data)
self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": True}}))
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",
"CLAUDE_CODE_ENTRYPOINT"):
self.env.pop(name, None)
self.proj = os.path.join(self.tmp, "proj")
os.makedirs(self.proj)
subprocess.run(["git", "init", "-q"], cwd=self.proj, check=True, capture_output=True)
self.write(os.path.join(self.data, "models.md"), HEADER + ALPHA + BETA)
os.makedirs(os.path.join(self.data, "offered"), exist_ok=True)
self.write(os.path.join(self.data, "offered", "unknown.txt"),
"listed %s by harness unknown\nalpha\nbeta\n" % time.strftime("%Y-%m-%dT%H:%M:%S"))
self.hook("tick")
self.hook("prompt", prompt="work on the project")
rc, out, err = self.sisi("done", "--goal", "ship the chore judging fix cleanly",
"--check", "chore judging tests pass cleanly",
"--next", "run the full suite next")
self.assertEqual(rc, 0, out + err)
def read(self, *parts):
with open(os.path.join(*parts), encoding="utf-8") as f:
return f.read()
def write(self, path, text):
with open(path, "w", encoding="utf-8") as f:
f.write(text)
return path
def sisi(self, *args, sid="s1", stdin=""):
env = dict(self.env, SISI_SESSION_ID=sid)
r = subprocess.run([sys.executable, os.path.join(REPO, "bin", "sisi")] + list(args), cwd=self.proj,
env=env, input=stdin, capture_output=True, text=True)
return r.returncode, r.stdout, r.stderr
def hook(self, cmd, sid="s1", **payload):
body = json.dumps({"session_id": sid, "cwd": self.proj, **payload})
return self.sisi(cmd, sid=sid, stdin=body)
def tool(self, name, sid="s1", tool_input=None):
return self.hook("watch", sid=sid, hook_event_name="PreToolUse", tool_name=name, tool_input=tool_input or {})
def state(self, sid="s1"):
return json.loads(self.read(self.tmp, "state", "core-sessions", sid + ".json"))
def outcomes(self):
path = os.path.join(self.data, "outcomes.jsonl")
return [json.loads(l) for l in self.read(path).splitlines() if l.strip()] if os.path.exists(path) else []
def start_chore(self, *cmd, worker="alpha"):
rc, brief, err = self.sisi(*cmd)
self.assertEqual(rc, 0, brief + err)
m = re.match(r"sisi chore: .+? ([0-9a-f]{8})\b", brief.splitlines()[0])
self.assertIsNotNone(m, brief)
cid = m.group(1)
rc_p, out_p, err_p = self.sisi("pick", "routine", "--not", "beta" if worker == "alpha" else "alpha")
self.assertEqual(rc_p, 0, out_p + err_p)
prompt = "%s\nRun `sisi chore show %s` and do what it says." % (brief.splitlines()[0], cid)
rc_t, out_t, err_t = self.tool("Agent", tool_input={"model": worker, "prompt": prompt})
self.assertEqual((rc_t, out_t), (0, ""), out_t + err_t)
return cid
def test_1_judge_chore_closes_only_named_chore_and_refuses_unknown(self):
cid1 = self.start_chore("plan", "brief")
time.sleep(0.02)
cid2 = self.start_chore("models", "research")
starts = self.state()["starts"]["alpha"]
self.assertEqual(len(starts), 2)
t1, t2 = starts
before_state, before_out = self.state(), self.outcomes()
for bad in (("good", "finished the chore cleanly", "--chore", "deadbeef"),
("extend", "30", "needs more time here", "--chore", "deadbeef")):
rc, out, _ = self.sisi("judge", "alpha", *bad)
self.assertEqual(rc, 1, out)
self.assertEqual(len(out.strip().splitlines()), 1, out)
self.assertIn(cid1, out)
self.assertIn(cid2, out)
rc_missing, out_missing, _ = self.sisi("judge", "alpha", "good", "finished the chore cleanly", "--chore")
self.assertEqual(rc_missing, 1, out_missing)
self.assertEqual((self.state(), self.outcomes()), (before_state, before_out))
rc_ext, out_ext, _ = self.sisi("judge", "alpha", "extend", "30", "needs more time here", "--chore", cid2)
self.assertEqual(rc_ext, 0, out_ext)
self.assertIn("extended alpha limit to 30 min.", out_ext)
self.assertEqual(self.state()["meta"]["alpha %r" % t2].get("limit"), 30)
self.assertIsNone(self.state()["meta"]["alpha %r" % t1].get("limit"))
rc_j, out_j, _ = self.sisi("judge", "alpha", "good", "models research finished cleanly", "--chore", cid2)
self.assertEqual(rc_j, 0, out_j)
self.assertEqual(self.state()["starts"]["alpha"], [t1])
self.assertEqual(self.outcomes()[-1]["started"], time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t2)))
rc_again, out_again, _ = self.sisi("judge", "alpha", "good", "trying to judge closed chore", "--chore", cid2)
self.assertEqual(rc_again, 1, out_again)
self.assertEqual(len(out_again.strip().splitlines()), 1, out_again)
self.assertIn(cid1, out_again)
rc_j1, out_j1, _ = self.sisi("judge", "alpha", "good", "plan brief finished cleanly", "--chore", cid1)
self.assertEqual(rc_j1, 0, out_j1)
self.assertEqual(self.state()["starts"]["alpha"], [])
def test_2_judge_without_flag_warns_with_closed_and_open_targets(self):
cid1 = self.start_chore("plan", "brief")
time.sleep(0.02)
cid2 = self.start_chore("models", "research")
t1, t2 = self.state()["starts"]["alpha"]
rc, out, _ = self.sisi("judge", "alpha", "good", "oldest chore finished cleanly")
self.assertEqual(rc, 0, out)
self.assertEqual(self.state()["starts"]["alpha"], [t2])
lines = out.strip().splitlines()
self.assertEqual(len(lines), 2, out)
self.assertIn("job started %s" % time.strftime("%H:%M", time.localtime(t1)), lines[0])
self.assertIn(cid1, lines[1])
self.assertIn(cid2, lines[1])
self.assertIn("--chore " + cid2, lines[1])
def test_3_stop_gate_lists_unjudged_jobs_on_one_line_without_blocking_on_them(self):
graph = ("| node | class | needs | branch | files | check | why |\n|---|---|---|---|---|---|---|\n"
"| a | routine | - | feat-a | sisi/a.py | test a passes | exact spec |\n"
"| join | lead | a | - | - | suite passes | lead joins |\n")
rc, out, _ = self.sisi("plan", "--record", self.write(os.path.join(self.tmp, "plan.md"), graph))
self.assertEqual(rc, 0, out)
rc_p, out_p, _ = self.sisi("pick", "--node", "a", "--not", "beta")
self.assertEqual(rc_p, 0, out_p)
self.assertEqual(self.tool("Agent", tool_input={"model": "alpha", "prompt": "sisi node: a\nDo node a."})[1], "")
cid = self.start_chore("models", "research", worker="beta")
ta = self.state()["starts"]["alpha"][0]
tb = self.state()["starts"]["beta"][0]
# Open checks while workers run: stop gate does not block on unjudged jobs.
self.assertEqual(self.hook("gate")[1], "")
# When the stop gate already blocks (e.g. changed files + passed checks, no retro yet),
# it appends one line listing unjudged jobs in WORKER (node X | chore Y, started HH:MM) form.
self.tool("Edit")
self.assertEqual(self.sisi("done", "--pass", "1", "chore judging tests pass cleanly")[0], 0)
rc_g, out_g, _ = self.hook("gate")
self.assertEqual(rc_g, 0, out_g)
doc = json.loads(out_g)
self.assertEqual(doc["decision"], "block")
extra_lines = [l for l in doc["reason"].splitlines() if "alpha (" in l or "beta (" in l]
self.assertEqual(len(extra_lines), 1, doc["reason"])
self.assertIn("alpha (node a, started %s)" % time.strftime("%H:%M", time.localtime(ta)), extra_lines[0])
self.assertIn("beta (chore %s, started %s)" % (cid, time.strftime("%H:%M", time.localtime(tb))), extra_lines[0])
if __name__ == "__main__":
unittest.main()