Take the whole plan off only for a shared quota; read date-style resets; fit the size cap

An `out` message widens to every worker on the same provider only when it
states a reset time or names a shared quota (quota, usage window, usage limit,
subscription); a crash, timeout or lost connection takes off just the one.
Resets written as dates ("resets Dec 2, 2pm (America/Denver)") are read.

sisi/ is back at the 3264-line cap: `sisi help` is shorter (README explains each
command), module docstrings keep their first sentence, and dead or single-use
wrappers are gone (rules.delivered, models.speeds/qualities/pools,
install._hooks).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-12-04 07:08:08 -07:00
1 parent 9fb2a61920
commit e2768a1377
9 files changed
+91 -124

No files matched your search

+6 -4
View File
@@ -14,9 +14,11 @@ choose the worker: `sisi pick CLASS` spins a wheel over the workers of that clas
in exactly one class, so the wheel never mixes tiers; weighted by table order and by the cube of the speed ratio), in exactly one class, so the wheel never mixes tiers; weighted by table order and by the cube of the speed ratio),
and a delegation to a worker the wheel did not give gets a note. Recent `bad` verdicts over a worker's last 10 and a delegation to a worker the wheel did not give gets a note. Recent `bad` verdicts over a worker's last 10
good/bad jobs also scale its weight down (never to zero), while workers with no bad runs keep their full weight. One pick, one delegation. A worker that failed for a good/bad jobs also scale its weight down (never to zero), while workers with no bad runs keep their full weight. One pick, one delegation. A worker that failed for a
limit is judged `out` with the provider's message: it and every worker on the same provider in the table are off the wheel limit is judged `out` with the provider's message: it is off the wheel until the reset the message states (`resets at
until the reset the message states (`resets at 2026-12-07T00:00:00Z`, `Resets in 108h11m37s`, `try again in 45 minutes`), 2026-12-07T00:00:00Z`, `Resets in 108h11m37s`, `try again in 45 minutes`, `resets Dec 2, 2pm (America/Denver)`), else for
else for 6 hours, then the wheel tries again (at most 4 times a day), and the pick that hands one out says it is a retry. 6 hours, then the wheel tries again (at most 4 times a day), and the pick that hands it out says it is a retry. When the
message states a reset or names a shared quota (quota, usage window, usage limit, subscription), every worker on the same
provider in the table is off with it; a crash, a timeout or a lost connection takes off only the one worker.
A job already running that no delegation hook saw (a worker you sent a message) is attached to its plan node with A job already running that no delegation hook saw (a worker you sent a message) is attached to its plan node with
`sisi pick --node ID --started WORKER`. A host that names its models `sisi pick --node ID --started WORKER`. 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 shortly (Claude Code's `Agent` tool says `sonnet`) may give one whole segment of the picked model id, so name a worker
@@ -105,7 +107,7 @@ 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 (`routine`, `ordinary`, `hard`, `deep`), the cheapest among those within one point of the class's best score (a tie never goes to the dearer one; the dearest tier is its own class, `deep`, never a default for `hard`, `ordinary` or `routine`), 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 (`routine`, `ordinary`, `hard`, `deep`), the cheapest among those within one point of the class's best score (a tie never goes to the dearer one; the dearest tier is its own class, `deep`, never a default for `hard`, `ordinary` or `routine`), 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 \| --chore ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: its whole provider is off the wheel until the stated reset, else 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 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 until the stated reset, else for 6 hours, then tried again; its whole provider too when the message states a reset or names a shared quota); 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 \| --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 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 |
+20 -58
View File
@@ -1,69 +1,31 @@
"""sisi: hooks that force a retro and turn what it finds into rules, and a models table to delegate by.""" """sisi: hooks that force a retro and turn what it finds into rules, and a models table to delegate by."""
import os, sys, time import os, sys, time
HELP = """sisi: a self-improvement loop for AI coding agents. HELP = """sisi: a self-improvement loop for AI coding agents. README.md beside the code explains each command.
Before and after the work sisi done --goal G --check C [--check C ...] --next N record what done means; nothing starts before
sisi done --goal G --check C [--check C ...] --next N sisi done [--pass N EVIDENCE | --fail N WHY] give a check its verdict; alone shows it
record what done means and what the person will need next; nothing starts before
sisi done --pass N EVIDENCE | --fail N WHY
give a check its verdict; `sisi done` alone shows it
sisi fault [TEXT | --started|--blocked|--fixed N NOTE] open faults in this project; alone lists them sisi fault [TEXT | --started|--blocked|--fixed N NOTE] open faults in this project; alone lists them
sisi retro [--gap G --cause C --improve I --term T --problem N|NAME --level core|user|project]
The learning loop
sisi retro what happened in this piece of work, to set against the objective
sisi retro --gap G --cause C --improve I --term T --problem N|"..." --level core|user|project
record the gap and problem; the improvement is a rule at once
sisi retro --no-gap TEXT --term T --better B | --later TEXT sisi retro --no-gap TEXT --term T --better B | --later TEXT
nothing fell short; or the work is not finished yet sisi learn --level core|user|project TEXT [--means HOW] the person's own words become a rule at once
sisi learn --level core|user|project TEXT [--means HOW] sisi rules [organize [--record FILE] | revert] the learned rules; have them organized; undo a change
the person's own words become a rule at once
sisi rules the learned rules in force here
sisi rules organize [--record FILE]
the brief for a cheap worker to audit and organize them; record its answer
sisi rules move "<start>" core|user|project|canon [--project PATH] sisi rules move "<start>" core|user|project|canon [--project PATH]
move one rule to another level (canon: out of the queue once in canon/core.md) sisi models [research|offered [--record FILE]] the workers; rebuild the table; save the host's model list
sisi rules revert undo the last learn, retro or organize (a second re-applies it); declines if the sisi plan [brief | --record FILE | --done ID EVIDENCE | --fail ID WHY]
project file changed since; a move is not undone: both print the command back sisi chore show ID print the chore brief under this one-time id
sisi pick --node ID | routine|ordinary|hard|deep [--branch NAME] the wheel gives one worker for one delegation
[--review-of WORKER] [--not WORKER ...] [--limit MINUTES]
sisi pick --node ID --started WORKER a job already running (sent a message) does this node
sisi judge WORKER good|bad|out WHY [--minutes N] [--newest] [--node ID | --chore ID]
how it went; `out`: WHY is the provider's own message
sisi judge WORKER extend MINUTES WHY give a running job more time
sisi direct REASON allow yourself more direct tool calls this turn
sisi install | uninstall | doctor rulebook and hooks into the agent tools here; show them
sisi release | rollback | update make this copy the one in use; go back; fetch the newest
sisi tick | prompt | watch | gate the hooks the agent tool calls
Delegation Your rules, models table and retro log are in ~/.local/share/sisi ($SISI_DATA), a project's rules in its .sisi/rules.md."""
sisi models the workers you have: what each is good at and what it costs
sisi models research [--record FILE]
the brief for a research worker to rebuild that table; record its answer
sisi models offered [--record FILE]
save the host's raw model list (stdin); record the worker's table of those models
sisi plan brief | --record FILE the brief for a planning worker; record its graph (| node | class | needs | branch
| files | check | why |) before handing out any work; `sisi plan` shows each node
sisi plan --done ID EVIDENCE | --fail ID WHY
a node you did yourself (the join) is done; or reopen a node
sisi chore show ID print the chore brief under this one-time id; delegate just its first line plus "Run `sisi chore show <id>` and do what it says"
sisi pick --node ID [--review-of WORKER] [--not WORKER ...] [--limit MINUTES]
sisi pick --node ID --started WORKER
record that a job already running (a worker you sent a message) does this node
sisi pick routine|ordinary|hard|deep [--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
`sisi chore:` brief); one pick, one delegation
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
limit: its whole plan is off until the reset the message states, else 6 h, and
sisi tries it again by itself), or give a running job more time;
--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
Setting up
sisi install | uninstall | doctor
put the rulebook (and hooks, where the tool has them) into every agent tool
installed here; take them out again; show how each tool stands
sisi release | rollback make this copy the one the hooks run; go back to the one before
sisi update fetch the newest sisi from where this release came from and release it
Hooks (the agent tool calls these): sisi tick | prompt | watch | gate
Your own rules, models table and retro log live in ~/.local/share/sisi ($SISI_DATA, else $XDG_DATA_HOME/sisi), a git repository;
a project's rules live in its .sisi/rules.md. Settings: "core" in
its config.json (gate, meter, direct_calls, direct_extension, rules_lines, rules_chars, organize_after,
research_days, shell_workers, enforce, worker_minutes, retro_minutes, disk_free_percent, disk_drop_percent, checkouts,
auto_update, update_hours, update_url, offered_hours)."""
def main(argv): def main(argv):
+1 -4
View File
@@ -1,7 +1,4 @@
"""The hooks the agent tool calls: session start, each request, before each tool call, end of turn. """The hooks the agent tool calls: session start, each request, before each tool call, end of turn."""
Session start loads what was learned. The tool hook counts what the lead does itself and reminds it when it
should be delegating. The end-of-turn hook forces the retro when work was done."""
import json, os, re, sys, time import json, os, re, sys, time
from . import models, rules, store from . import models, rules, store
+3 -10
View File
@@ -1,8 +1,4 @@
"""Wiring sisi into every agent tool on the machine, and putting a checked copy of the product in place. """Wiring sisi into every agent tool on the machine, and putting a checked copy of the product in place."""
The tools are plain data in canon/harnesses.json: where each keeps its always-on instructions (the rulebook goes
there) and, for the ones whose hooks have the same shape, its hooks file. Nothing is written for a tool that is
not installed, and nothing is touched that sisi cannot edit safely: it is left alone and reported."""
import json, os, re, shutil, subprocess, sys, tempfile, time import json, os, re, shutil, subprocess, sys, tempfile, time
from . import models, rules, store from . import models, rules, store
@@ -97,10 +93,6 @@ def _sync(path, wanted):
return "wired" if wanted else "removed" return "wired" if wanted else "removed"
def _hooks(h, d, mode):
return _sync(os.path.join(d, h["hooks"]["file"]), _entries(h) if mode == "add" else []) if h.get("hooks") else ""
def _clean(h, d): def _clean(h, d):
"""Take out what an older sisi left in this tool: its hook entries in a json file, or a file it generated.""" """Take out what an older sisi left in this tool: its hook entries in a json file, or a file it generated."""
done = [] done = []
@@ -162,7 +154,8 @@ def _apply(mode):
book, bad = rules.build_rulebook() if mode == "add" else _book(), 0 book, bad = rules.build_rulebook() if mode == "add" else _book(), 0
for h in _table(): for h in _table():
d = _dir(h) d = _dir(h)
steps = [("hooks", lambda: _hooks(h, d, mode)), ("old files", lambda: _clean(h, d))] wire = lambda: _sync(os.path.join(d, h["hooks"]["file"]), _entries(h) if mode == "add" else []) if h.get("hooks") else ""
steps = [("hooks", wire), ("old files", lambda: _clean(h, d))]
if h.get("rules"): if h.get("rules"):
steps.insert(0, ("rulebook", lambda: _rulebook(h, d, book, mode))) steps.insert(0, ("rulebook", lambda: _rulebook(h, d, book, mode)))
for label, step in steps if d else (): for label, step in steps if d else ():
+23 -24
View File
@@ -1,8 +1,5 @@
"""The models table: which workers this person can delegate to, what each is good at and what it costs. """The models table: which workers this person can delegate to, what each is good at and what it costs."""
import json, math, os, re, sys, time
A research worker writes it, the lead reads it to route, and `sisi judge` adds how each delegation went so the
next research knows. The table is plain text a person can read and correct."""
import datetime, json, math, os, re, sys, time
from . import rules, store 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", 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",
@@ -280,6 +277,8 @@ SINCE = "out since %s, back on the wheel at %s"
RESET = r"(?i)\b(?:resets?|try again|retry)" RESET = r"(?i)\b(?:resets?|try again|retry)"
STAMP = RESET + r"(?:\s+(?:at|on|after))?[\s:]+(\d{4}-\d\d-\d\d[T ]\d\d:\d\d(?::\d\d(?:\.\d+)?)?(?:Z|[+-]\d\d:?\d\d)?)" STAMP = RESET + r"(?:\s+(?:at|on|after))?[\s:]+(\d{4}-\d\d-\d\d[T ]\d\d:\d\d(?::\d\d(?:\.\d+)?)?(?:Z|[+-]\d\d:?\d\d)?)"
DATE = RESET + r"(?:\s+(?:at|on))?\s+([a-z]{3})[a-z]*\.?\s+(\d{1,2}),?\s+(?:at\s+)?(\d{1,2})(?::(\d\d))?\s*([ap])m(?:\s*\(([\w/+-]+)\))?"
SHARED = r"(?i)quota|usage[ -]?(?:window|limit)|subscription" # wording that names an allowance a whole plan draws on
UNIT = r"(\d+)\s*(days?|hours?|hrs?|minutes?|mins?|seconds?|secs?|d|h|m|s)(?![a-z])" UNIT = r"(\d+)\s*(days?|hours?|hrs?|minutes?|mins?|seconds?|secs?|d|h|m|s)(?![a-z])"
SPAN = RESET + r"\s+(?:in|after)\s+((?:%s[\s,]*(?:and\s+)?)+)" % UNIT SPAN = RESET + r"\s+(?:in|after)\s+((?:%s[\s,]*(?:and\s+)?)+)" % UNIT
LONGEST = 35 * 86400 # no allowance window is longer than a month: a reset stated further off is misread LONGEST = 35 * 86400 # no allowance window is longer than a month: a reset stated further off is misread
@@ -287,19 +286,28 @@ LONGEST = 35 * 86400 # no allowance window is longer than a month: a reset stat
def stated(why, said): def stated(why, said):
"""The time the provider's message says the limit resets, or None. A span counts from `said`, when it was recorded.""" """The time the provider's message says the limit resets, or None. A span counts from `said`, when it was recorded."""
import datetime, zoneinfo # not at the top: hooks import this module and must stay quick
until = None until = None
if m := re.search(STAMP, why): if m := re.search(STAMP, why):
try: until = datetime.datetime.fromisoformat(m.group(1).replace("Z", "+00:00")).timestamp() try: until = datetime.datetime.fromisoformat(m.group(1).replace("Z", "+00:00")).timestamp()
except ValueError: pass except ValueError: pass
elif m := re.search(DATE, why): # "resets Dec 2, 2pm (America/Denver)": the next such time, in that zone, else here
month, day, hour, mins, half, zone = m.groups()
try:
at = datetime.datetime.fromtimestamp(said, zoneinfo.ZoneInfo(zone) if zone else None)
at = at.replace(month=time.strptime(month, "%b").tm_mon, day=int(day), hour=int(hour) % 12 + 12 * (half.lower() == "p"), minute=int(mins or 0), second=0)
until = at.replace(year=at.year + (at.timestamp() <= said)).timestamp()
except (ValueError, KeyError, OSError): pass
elif m := re.search(SPAN, why): elif m := re.search(SPAN, why):
until = said + sum(int(n) * {"d": 86400, "h": 3600, "m": 60, "s": 1}[u[0].lower()] for n, u in re.findall("(?i)" + UNIT, m.group(1))) until = said + sum(int(n) * {"d": 86400, "h": 3600, "m": 60, "s": 1}[u[0].lower()] for n, u in re.findall("(?i)" + UNIT, m.group(1)))
return until if until and said < until <= said + LONGEST else None return until if until and said < until <= said + LONGEST else None
def outs(log, now=None, pool=None): def outs(log, now=None, pool=None):
"""{worker: (since, why, until)}: each worker that is or was last said to be out: an `out` verdict in the log says it """{worker: (since, why, until)}: each worker that is or was last said to be out, until the reset the `out` message
for the worker and every other on its plan (`pool`, from `pools`), until the reset its message states, else for OUT; states, else for OUT; a message that states a reset or names a shared quota (SHARED) says it for every worker on its
a later good or bad verdict takes that worker back. A time OUT or more ahead of `now` is a wrong clock and says nothing.""" plan (`pool`: {worker: plan}). A later good or bad verdict takes that worker back. A time OUT or more ahead of `now`
is a wrong clock and says nothing."""
last, now, pool = {}, now or time.time(), pool or {} last, now, pool = {}, now or time.time(), pool or {}
for o in log: for o in log:
try: try:
@@ -312,17 +320,15 @@ def outs(log, now=None, pool=None):
last.pop(w, None) last.pop(w, None)
continue continue
until = stated(why, t) until = stated(why, t)
for x in [w] + [x for x, p in pool.items() if x != w and p == pool.get(w)]: # a message with no reset shortens no stated one plan = pool.get(w) if until or re.search(SHARED, why) else None # a crash or one model's trouble is its own
for x in [w] + [x for x, p in pool.items() if x != w and p == plan]: # a message with no reset shortens no stated one
last[x] = (t, why if x == w else "%s, on the same plan: %s" % (w, why), until or max(t + OUT, last[x][2] if x in last else 0)) last[x] = (t, why if x == w else "%s, on the same plan: %s" % (w, why), until or max(t + OUT, last[x][2] if x in last else 0))
return last return last
def pools(): def away():
"""{worker: provider}: the plan each worker draws on, as the models table and the wheel group them.""" pool = {short(r[0]): pkey(r[7]) for r in rows(store.read(table()) + "\n" + wheel()[0]) if pkey(r[7])} # each worker's plan
return {short(r[0]): pkey(r[7]) for r in rows(store.read(table()) + "\n" + wheel()[0]) if pkey(r[7])} return outs(store.records("outcomes.jsonl"), time.time(), pool)
def away(): return outs(store.records("outcomes.jsonl"), time.time(), pools())
def out(r, skip, bad, gone, now): def out(r, skip, bad, gone, now):
@@ -348,10 +354,6 @@ def track():
return {w: v[-10:] for w, v in sp.items()}, {w: (sum(v[-10:]) + 1) / (len(v[-10:]) + 1) for w, v in ql.items()}, n return {w: v[-10:] for w, v in sp.items()}, {w: (sum(v[-10:]) + 1) / (len(v[-10:]) + 1) for w, v in ql.items()}, n
def speeds(): return track()[0]
def qualities(): return track()[1]
WINDOWS, FLOOR = {"5h": 5 * 3600, "week": 7 * 86400, "month": 30 * 86400}, 0.05 WINDOWS, FLOOR = {"5h": 5 * 3600, "week": 7 * 86400, "month": 30 * 86400}, 0.05
pkey = lambda provider: " ".join(str(provider).lower().split()) pkey = lambda provider: " ".join(str(provider).lower().split())
@@ -392,8 +394,7 @@ def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, no
fewer than 3 judged good/bad outcomes (`tried`, from `track`) has the first's weight, so a new model is tried) fewer than 3 judged good/bad outcomes (`tried`, from `track`) has the first's weight, so a new model is tried)
times its speed: the fastest candidate's median minutes over its own, cubed, at least 0.02 (1 with no timed jobs), 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. times its provider's share of plan left (`share`, from `shares`: at least FLOOR), so no plan runs dry early."""
A worker that is still out (`gone`, from `outs`) is not on the wheel."""
table_rows, gone, now = rows(text), gone or {}, now or time.time() 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 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)]
@@ -554,9 +555,7 @@ def named(name):
def judge(args, cwd=None): def judge(args, cwd=None):
"""`sisi judge WORKER good|bad|out "<why>" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "<why>" [--newest] [--node ID | --chore ID]`. """Record a verdict or an extension: for the worker's oldest open job (--newest: its newest), or the --node or --chore 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 from . import retro # not at the top: hooks import this module and must stay quick
args, newest, minutes, note, node, chore, warn = [a for a in args if a != "--newest"], "--newest" in args, None, "", None, 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: if "--minutes" in args:
+2 -7
View File
@@ -1,8 +1,4 @@
"""The plan: a dependency graph of the pieces of one piece of work, recorded before anything is handed out. """The plan: a dependency graph of the pieces of one piece of work, recorded before anything is handed out."""
Each node says what it needs first, its own branch, the files it may change and its check; one join brings everything
back. The hooks hold the lead to it: no delegation outside the plan or out of order, no turn ending while a node is
ready and not started. The plan lives in the session state and closes with the piece of work."""
import contextlib, fnmatch, hashlib, os, re, time import contextlib, fnmatch, hashlib, os, re, time
from . import store from . import store
@@ -277,8 +273,7 @@ def for_pick(args, cwd=None):
def attach(args, cwd=None): def attach(args, cwd=None):
"""`sisi pick --node ID --started WORKER`: record that a job already running does this node (a worker continued with a """Record that a job already running (continued with a message, which no hook sees) does a node; a pick for it is withdrawn."""
message, which no delegation hook sees). A pick made for the node is withdrawn; `sisi judge` closes it as any other."""
from . import models from . import models
if len(args) != 4 or args[2] != "--started" or not args[3].strip(): if len(args) != 4 or args[2] != "--started" or not args[3].strip():
return print('usage: sisi pick --node ID --started "<the running worker\'s model id, or a job id>"') or 1 return print('usage: sisi pick --node ID --started "<the running worker\'s model id, or a job id>"') or 1
+1 -10
View File
@@ -1,8 +1,4 @@
"""Learned rules: what retros and the person add to the instructions. """Learned rules: what retros and the person add to the instructions."""
A rule is one line. It is in force as soon as it is added: rules for all of the person's work become the last
section of the rulebook every session loads, and a project's rules live in `.sisi/rules.md` at its root.
Now and then a cheap worker audits and organizes them. Store changes are committed and can be undone."""
import contextlib, hashlib, json, os, re, shlex, time import contextlib, hashlib, json, os, re, shlex, time
from . import store from . import store
@@ -307,11 +303,6 @@ def _fit(ls):
return [l for i, l in enumerate(ls) if _owner(l) or i in keep] return [l for i, l in enumerate(ls) if _owner(l) or i in keep]
def delivered(p):
"""The newest rules that fit the budget, oldest first. The rest wait for organizing."""
return _fit(lines(p))
def build_rulebook(): def build_rulebook():
"""Write the always-loaded instructions: the product's rulebook, then the person's learned rules.""" """Write the always-loaded instructions: the product's rulebook, then the person's learned rules."""
text = store.read(os.path.join(store.ROOT, "canon", "core.md")).rstrip() + "\n" text = store.read(os.path.join(store.ROOT, "canon", "core.md")).rstrip() + "\n"
+1 -4
View File
@@ -1,7 +1,4 @@
"""Where sisi keeps things, and the few file operations the rest uses. """Where sisi keeps things, and the few file operations the rest uses."""
Three places: the product (this copy, never written at run time), the person's store (learned rules, the
models table, the retro log; a git repository, so every change can be undone), and scratch (session state)."""
import contextlib, fcntl, hashlib, json, os, re, stat, subprocess import contextlib, fcntl, hashlib, json, os, re, stat, subprocess
ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
+34 -3
View File
@@ -1967,7 +1967,7 @@ cli.main(["tick"])
def test_only_good_outcomes_set_a_workers_speed(self): def test_only_good_outcomes_set_a_workers_speed(self):
self.jsonl("outcomes.jsonl", *[self.outcome("flaky", "bad", 1)] * 10 + [self.outcome("steady", "good", 15)] * 10) self.jsonl("outcomes.jsonl", *[self.outcome("flaky", "bad", 1)] * 10 + [self.outcome("steady", "good", 15)] * 10)
r = subprocess.run([sys.executable, "-B", "-c", "from sisi import models; print(models.speeds())"], cwd=REPO, r = subprocess.run([sys.executable, "-B", "-c", "from sisi import models; print(models.track()[0])"], cwd=REPO,
env=self.env, capture_output=True, text=True) env=self.env, capture_output=True, text=True)
self.assertEqual(r.stdout.strip(), str({"steady": [15] * 10})) self.assertEqual(r.stdout.strip(), str({"steady": [15] * 10}))
@@ -2129,7 +2129,7 @@ cli.main(["tick"])
picked2 = [self.in_process(models.pick, ["ordinary"], self.proj, lambda i=i: i / 100)[1].splitlines()[0].split()[1] for i in range(100)] picked2 = [self.in_process(models.pick, ["ordinary"], self.proj, lambda i=i: i / 100)[1].splitlines()[0].split()[1] for i in range(100)]
self.assertEqual(picked2.count("alpha"), 16) self.assertEqual(picked2.count("alpha"), 16)
self.assertGreater(picked2.count("alpha"), 0) self.assertGreater(picked2.count("alpha"), 0)
q, _ = self.in_process(models.qualities) (_, q, _), _ = self.in_process(models.track)
self.assertAlmostEqual(q["alpha"], 1 / 11) self.assertAlmostEqual(q["alpha"], 1 / 11)
self.assertEqual(q["beta"], 1.0) self.assertEqual(q["beta"], 1.0)
# Never refuses a pick even when the sole worker has only bad verdicts. # Never refuses a pick even when the sole worker has only bad verdicts.
@@ -2159,7 +2159,7 @@ cli.main(["tick"])
self.outcome("alpha", "extend", 1), self.outcome("alpha", "extend", 1),
*[self.outcome("beta", "good", 10)] * 4) *[self.outcome("beta", "good", 10)] * 4)
self.assertEqual(spin(), (67, 33)) self.assertEqual(spin(), (67, 33))
q, _ = self.in_process(models.qualities) (_, q, _), _ = self.in_process(models.track)
self.assertEqual((q["alpha"], q["beta"]), (1.0, 1.0)) self.assertEqual((q["alpha"], q["beta"]), (1.0, 1.0))
def test_pick_and_models_show_the_minutes(self): def test_pick_and_models_show_the_minutes(self):
@@ -3077,6 +3077,37 @@ cli.main(["tick"])
self.dated(108 * 60 + 12) self.dated(108 * 60 + 12)
self.assertEqual(self.picked("routine", "--not", "alpha", "--not", "muse-ember")[0], True) self.assertEqual(self.picked("routine", "--not", "alpha", "--not", "muse-ember")[0], True)
def test_only_a_message_naming_a_shared_quota_takes_the_whole_plan_off(self):
row = "| %s | %s | host subagent model `%s` | %s | flat | work | |\n"
self.table("| worker | provider | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|---|\n" + "".join(
row % (w, p, w, c) for w, p, c in (("claude-sonnet-5-5", "Claude Ultra", "ordinary"), ("claude-haiku-5-5", "Claude Ultra", "routine"),
("gemini-4-neon", "Antigravity", "ordinary"), ("gemini-4-hydrogen", "Antigravity", "routine"))))
self.judged("claude-sonnet-5-5", "out", "Claude Code process killed by signal SIGKILL (machine out of memory)")
got, out = self.picked("routine", "--not", "gemini-4-hydrogen") # its sibling is still on
self.assertEqual((got, "worker: claude-haiku-5-5" in out), (True, True), out)
self.assertEqual(self.picked("ordinary", "--not", "gemini-4-neon")[0], False) # the killed one is off
self.judged("gemini-4-neon", "out", "Individual quota reached. Resets in 108h11m37s.")
got, out = self.picked("routine", "--not", "claude-haiku-5-5")
self.assertEqual((got, "gemini-4-hydrogen (out since" in out), (False, True), out)
sys.path.insert(0, REPO)
from sisi import models
stamp = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t))
utc = lambda s: calendar.timegm(time.strptime(s, "%Y-%m-%dT%H:%M:%S"))
said, pool = utc("2026-12-02T11:08:47"), {"a": "plan", "b": "plan"}
gone = lambda why, t=said: models.outs([{"ts": stamp(t), "worker": "a", "verdict": "out", "why": why}], t, pool)
for why in ("OpenCode Go 5 hour usage limit reached.", "Subscription quota exhausted", "your usage window is spent",
"this subscription has run out", "Rate limited: try again in 45 minutes"):
self.assertEqual(sorted(gone(why)), ["a", "b"], why)
for why in ("process terminated by signal SIGKILL", "the job timed out after an hour", "connection reset by peer",
"ZAI_API_KEY is not set", "this model is at its cap"):
self.assertEqual(sorted(gone(why)), ["a"], why)
# a reset written as a date, in the zone it names
for why, t, reset in (("You've hit your Fable limit \u00b7 resets Dec 2, 2pm (America/Denver)", said, "2026-12-02T21:00:00"),
("limit hit, resets Jan 1 at 12:30am (UTC)", utc("2026-12-31T20:00:00"), "2027-01-01T00:30:00")):
self.assertEqual(gone(why, t)["a"][2], utc(reset), why)
for why in ("resets Dec 2, 2pm (Nowhere/Atall)", "resets Foo 2, 2pm", "resets Dec 1, 2pm (UTC)"): # unreadable or past: 6 h
self.assertEqual(gone(why)["a"][2], said + 6 * 3600, why)
def test_pick_says_a_returning_worker_is_a_retry(self): def test_pick_says_a_returning_worker_is_a_retry(self):
self.table(ONE) self.table(ONE)
self.judged("alpha", "out", LIMIT + ", please try later. " * 30) self.judged("alpha", "out", LIMIT + ", please try later. " * 30)