Merge fix/sisi-36-37: attach running jobs to nodes; honour stated quota resets per pool
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
c1d301fe85
11 files changed
+240
-135
No files matched your search
@@ -14,8 +14,13 @@ 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 is off the wheel for 6 hours, then the wheel tries it again (at most
|
limit is judged `out` with the provider's message: it is off the wheel until the reset the message states (`resets at
|
||||||
4 times a day), and the pick that hands it out says it is a retry. A host that names its models
|
2026-12-07T00:00:00Z`, `Resets in 108h11m37s`, `try again in 45 minutes`, `resets Dec 2, 2pm (America/Denver)`), else for
|
||||||
|
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
|
||||||
|
`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
|
||||||
by its full model id (`claude-sonnet-5-5`); anywhere else the name must match whole.
|
by its full model id (`claude-sonnet-5-5`); anywhere else the name must match whole.
|
||||||
|
|
||||||
@@ -91,7 +96,7 @@ its limits are.
|
|||||||
| `sisi done --goal … --check … [--check …] --next …` | Record what done means and what comes next; nothing starts before |
|
| `sisi done --goal … --check … [--check …] --next …` | Record what done means and what comes next; nothing starts before |
|
||||||
| `sisi done --pass N "…"` / `--fail N "…"` | Give a check its verdict and evidence; `sisi done` alone shows it |
|
| `sisi done --pass N "…"` / `--fail N "…"` | Give a check its verdict and evidence; `sisi done` alone shows it |
|
||||||
| `sisi fault "<what is wrong>"` / `--started\|--blocked\|--fixed N "…"` | Record an open fault in this project, start a fix, name a blocker, or close it; `sisi fault` alone lists them |
|
| `sisi fault "<what is wrong>"` / `--started\|--blocked\|--fixed N "…"` | Record an open fault in this project, start a fix, name a blocker, or close it; `sisi fault` alone lists them |
|
||||||
| `sisi pick routine\|ordinary\|hard\|deep [--review-of WORKER] [--not WORKER] [--limit MINUTES] [--branch REF]` | The wheel gives one worker (a `deep` pick falls back to `hard` when the table has no `deep` row); a review goes to a different maker. `--limit` sets this delegation's lateness limit (default `worker_minutes`) and `--branch` names the branch whose last commit shows its progress; picks of one worker are matched to its delegations in order. A job past twice its limit becomes a late-worker fault in the session that started it (only that session is stopped by it; `sisi fault --fixed N "…"` from any other session clears it) |
|
| `sisi pick routine\|ordinary\|hard\|deep [--review-of WORKER] [--not WORKER] [--limit MINUTES] [--branch REF]` | The wheel gives one worker (a `deep` pick falls back to `hard` when the table has no `deep` row); a review goes to a different maker. `--limit` sets this delegation's lateness limit (default `worker_minutes`) and `--branch` names the branch whose last commit shows its progress; `sisi pick --node ID --started WORKER` records that a job already running does the node, without spinning the wheel; picks of one worker are matched to its delegations in order. A job past twice its limit becomes a late-worker fault in the session that started it (only that session is stopped by it; `sisi fault --fixed N "…"` from any other session clears it) |
|
||||||
| `sisi retro` | Print what happened in this piece of work and known problems, to set against the objective |
|
| `sisi retro` | Print what happened in this piece of work and known problems, to set against the objective |
|
||||||
| `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" --level core\|user\|project` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault |
|
| `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" --level core\|user\|project` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault |
|
||||||
| `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) |
|
| `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) |
|
||||||
@@ -102,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: 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 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
-55
@@ -1,66 +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 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: 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
@@ -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
@@ -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 ():
|
||||||
|
|||||||
+69
-31
@@ -1,7 +1,4 @@
|
|||||||
"""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."""
|
||||||
|
|
||||||
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 json, math, os, re, sys, time
|
import json, math, os, re, sys, time
|
||||||
from . import rules, store
|
from . import rules, store
|
||||||
|
|
||||||
@@ -273,32 +270,72 @@ def waiting(s):
|
|||||||
return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values())
|
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
|
OUT = 6 * 3600 # a worker judged `out` with no reset stated sits out this long, then the wheel tries it again: 24 h / 6 h = at most 4 tries a day
|
||||||
clock = lambda t: time.strftime("%m-%d %H:%M", time.localtime(t))
|
clock = lambda t: time.strftime("%m-%d %H:%M", time.localtime(t))
|
||||||
SINCE = "out since %s, back on the wheel at %s"
|
SINCE = "out since %s, back on the wheel at %s"
|
||||||
|
|
||||||
|
|
||||||
def outs(log, now=None):
|
RESET = r"(?i)\b(?:resets?|try again|retry)"
|
||||||
"""{worker: (since, why)}: each worker last said to be out, and when: an `out` verdict in the log says it, and any
|
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)?)"
|
||||||
later verdict takes it back. A time OUT or more ahead of `now` is a wrong clock and says nothing."""
|
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/+-]+)\))?"
|
||||||
last, now = {}, now or time.time()
|
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])"
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
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."""
|
||||||
|
import datetime, zoneinfo # not at the top: hooks import this module and must stay quick
|
||||||
|
until = None
|
||||||
|
if m := re.search(STAMP, why):
|
||||||
|
try: until = datetime.datetime.fromisoformat(m.group(1).replace("Z", "+00:00")).timestamp()
|
||||||
|
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):
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def outs(log, now=None, pool=None):
|
||||||
|
"""{worker: (since, why, until)}: each worker that is or was last said to be out, until the reset the `out` message
|
||||||
|
states, else for OUT; a message that states a reset or names a shared quota (SHARED) says it for every worker on its
|
||||||
|
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 {}
|
||||||
for o in log:
|
for o in log:
|
||||||
try:
|
try:
|
||||||
t = time.mktime(time.strptime(o["ts"], "%Y-%m-%dT%H:%M:%S"))
|
t = time.mktime(time.strptime(o["ts"], "%Y-%m-%dT%H:%M:%S"))
|
||||||
t - now < OUT and last.__setitem__(short(o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]), (t, o.get("verdict"), str(o.get("why") or "")))
|
w, verdict, why = short(o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]), o.get("verdict"), str(o.get("why") or "")
|
||||||
except (KeyError, TypeError, ValueError):
|
except (KeyError, TypeError, ValueError):
|
||||||
pass # a damaged line is no verdict
|
continue # a damaged line is no verdict
|
||||||
return {w: (t, why) for w, (t, verdict, why) in last.items() if verdict == "out"}
|
if t - now >= OUT: continue
|
||||||
|
if verdict != "out":
|
||||||
|
last.pop(w, None)
|
||||||
|
continue
|
||||||
|
until = stated(why, t)
|
||||||
|
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))
|
||||||
|
return last
|
||||||
|
|
||||||
|
|
||||||
def away(): return outs(store.records("outcomes.jsonl"), time.time())
|
def away():
|
||||||
|
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 outs(store.records("outcomes.jsonl"), time.time(), pool)
|
||||||
|
|
||||||
|
|
||||||
def out(r, skip, bad, gone, now):
|
def out(r, skip, bad, gone, now):
|
||||||
"""Why this worker is off the wheel, "" when it is on: excluded, the maker of the work under review, or out."""
|
"""Why this worker is off the wheel, "" when it is on: excluded, the maker of the work under review, or out."""
|
||||||
since = gone.get(short(r[0]))
|
gone = gone.get(short(r[0]))
|
||||||
return ("excluded" if short(r[0]) in skip else "same maker as the work under review" if maker(r) == bad
|
return ("excluded" if short(r[0]) in skip else "same maker as the work under review" if maker(r) == bad
|
||||||
else SINCE % (clock(since[0]), clock(since[0] + OUT)) if since and now - since[0] < OUT else "")
|
else SINCE % (clock(gone[0]), clock(gone[2])) if gone and now < gone[2] else "")
|
||||||
|
|
||||||
|
|
||||||
def median(v):
|
def median(v):
|
||||||
@@ -317,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())
|
||||||
|
|
||||||
@@ -361,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 last said out less than OUT seconds ago (`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)]
|
||||||
@@ -385,6 +417,7 @@ def pick(args, cwd=None, rand=None):
|
|||||||
node = None
|
node = None
|
||||||
if args[:1] == ["--node"]: # the class and branch come from the plan node
|
if args[:1] == ["--node"]: # the class and branch come from the plan node
|
||||||
from . import plan
|
from . import plan
|
||||||
|
if "--started" in args: return plan.attach(args, cwd)
|
||||||
args, node = plan.for_pick(args, cwd)
|
args, node = plan.for_pick(args, cwd)
|
||||||
if node is None: return 1
|
if node is None: return 1
|
||||||
cls, skip, review, limit, branch, i = (args[0] if args and args[0] in CLASSES else None), set(), None, None, None, 1
|
cls, skip, review, limit, branch, i = (args[0] if args and args[0] in CLASSES else None), set(), None, None, None, 1
|
||||||
@@ -396,7 +429,8 @@ def pick(args, cwd=None, rand=None):
|
|||||||
else: cls = None
|
else: cls = None
|
||||||
i += 2
|
i += 2
|
||||||
if not cls:
|
if not cls:
|
||||||
print("usage: sisi pick routine|ordinary|hard|deep [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]")
|
print("usage: sisi pick routine|ordinary|hard|deep [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]\n"
|
||||||
|
" sisi pick --node ID [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] | sisi pick --node ID --started WORKER")
|
||||||
return 1
|
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
|
||||||
@@ -412,7 +446,7 @@ def pick(args, cwd=None, rand=None):
|
|||||||
if not r:
|
if not r:
|
||||||
bad = next((maker(x) for x in rows(text) if short(x[0]) == short(review)), None)
|
bad = next((maker(x) for x in rows(text) if short(x[0]) == short(review)), None)
|
||||||
again = {"routine": " Choose again from ordinary.", "ordinary": " Choose again from hard.", "deep": " Choose again from hard."}.get(picked_cls, "")
|
again = {"routine": " Choose again from ordinary.", "ordinary": " Choose again from hard.", "deep": " Choose again from hard."}.get(picked_cls, "")
|
||||||
first = min((gone[short(x[0])][0] + OUT for x in mine if out(x, skip, bad, gone, now).startswith("out since")), default=None)
|
first = min((gone[short(x[0])][2] for x in mine if out(x, skip, bad, gone, now).startswith("out since")), default=None)
|
||||||
print(("sisi pick: every worker of class %s is out or excluded: %s." % (picked_cls, "; ".join(
|
print(("sisi pick: every worker of class %s is out or excluded: %s." % (picked_cls, "; ".join(
|
||||||
"%s (%s)" % (x[0], out(x, skip, bad, gone, now)) for x in mine)) if mine
|
"%s (%s)" % (x[0], out(x, skip, bad, gone, now)) for x in mine)) if mine
|
||||||
else "sisi pick: the models table has no worker of class %s." % picked_cls)
|
else "sisi pick: the models table has no worker of class %s." % picked_cls)
|
||||||
@@ -512,10 +546,16 @@ def sync_late(s, cwd, sid, add=True):
|
|||||||
except OSError: pass
|
except OSError: pass
|
||||||
|
|
||||||
|
|
||||||
|
def named(name):
|
||||||
|
"""The rows a worker's name means: those with that id, else those it names shortly. A worker's wheel row wins over its
|
||||||
|
table row (the list is the truth), and is counted once."""
|
||||||
|
wrows = rows(wheel()[0])
|
||||||
|
trows = wrows + [r for r in rows(store.read(table())) if short(r[0]) not in {short(x[0]) for x in wrows}]
|
||||||
|
return [r for r in trows if short(r[0]) == short(name)] or [r for r in trows if claim({"picked": [short(r[0])]}, name, True)]
|
||||||
|
|
||||||
|
|
||||||
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:
|
||||||
@@ -533,9 +573,7 @@ def judge(args, cwd=None):
|
|||||||
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):
|
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 | --chore ID] | extend MINUTES "<reason, 3+ words>" [--newest] [--node ID | --chore ID]')
|
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]')
|
||||||
return 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
|
hits = named(args[0])
|
||||||
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)]
|
|
||||||
sid, ohits = store.current_session(cwd), []
|
sid, ohits = store.current_session(cwd), []
|
||||||
if not hits and sid:
|
if not hits and sid:
|
||||||
try: st = json.loads(store.read(store._session_path(sid)) or "{}")
|
try: st = json.loads(store.read(store._session_path(sid)) or "{}")
|
||||||
@@ -616,8 +654,8 @@ 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, u) for w, (t, _, u) in gone.items() if w in listed and now < u):
|
||||||
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(u))) for t, w, u in sitting))
|
||||||
if use := plan_use(text, cwd, now):
|
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(
|
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())))
|
"%s: %s" % (p, ", ".join("%s %d%%" % (w, round(100 * x)) for w, x in u.items())) for p, u in sorted(use.items())))
|
||||||
|
|||||||
+27
-8
@@ -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
|
||||||
|
|
||||||
@@ -224,9 +220,8 @@ def run(args, cwd=None):
|
|||||||
why = why or check(nodes) or ("" if sid else "no session; run this from the agent's session")
|
why = why or check(nodes) or ("" if sid else "no session; run this from the agent's session")
|
||||||
with store.session(sid) if sid else contextlib.nullcontext({}) as s:
|
with store.session(sid) if sid else contextlib.nullcontext({}) as s:
|
||||||
old, new = get(s) or {"nodes": [], "state": {}}, {n["id"]: n for n in nodes or []}
|
old, new = get(s) or {"nodes": [], "state": {}}, {n["id"]: n for n in nodes or []}
|
||||||
moved = [i for i, v in old["state"].items() if v.get("st") == "running" and (i not in new or (
|
moved = [i for i, v in old["state"].items() if v.get("st") == "running" and (i not in new or new[i]["branch"] != node(old, i)["branch"])]
|
||||||
new[i]["branch"], new[i]["files"]) != (node(old, i)["branch"], node(old, i)["files"]))]
|
why = why or (moved and "node %s is running: keep its id and branch in the new plan, or judge it first" % moved[0])
|
||||||
why = why or (moved and "node %s is running: keep its id, branch and files in the new plan, or judge it first" % moved[0])
|
|
||||||
if why:
|
if why:
|
||||||
return print("sisi plan: %s. Nothing was recorded." % why) or 1
|
return print("sisi plan: %s. Nothing was recorded." % why) or 1
|
||||||
keep = {i for i, v in old["state"].items() if v.get("st") == "running" or node(old, i) == new.get(i)}
|
keep = {i for i, v in old["state"].items() if v.get("st") == "running" or node(old, i) == new.get(i)}
|
||||||
@@ -277,6 +272,30 @@ def for_pick(args, cwd=None):
|
|||||||
return [n["cls"]] + args[2:] + ["--branch", n["branch"]], i
|
return [n["cls"]] + args[2:] + ["--branch", n["branch"]], i
|
||||||
|
|
||||||
|
|
||||||
|
def attach(args, cwd=None):
|
||||||
|
"""Record that a job already running (continued with a message, which no hook sees) does a node; a pick for it is withdrawn."""
|
||||||
|
from . import models
|
||||||
|
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
|
||||||
|
if for_pick(args[:2], cwd)[1] is None: return 1
|
||||||
|
hits = models.named(args[3])
|
||||||
|
i, w = args[1], models.short(hits[0][0] if len(hits) == 1 else args[3])
|
||||||
|
with store.session(store.current_session(cwd)) as s:
|
||||||
|
q = s["pending"] if isinstance(s.get("pending"), dict) else {}
|
||||||
|
for other, picks in q.items():
|
||||||
|
for m in [m for m in picks if isinstance(m, dict) and m.get("node") == i]:
|
||||||
|
picks.remove(m)
|
||||||
|
other in s.get("picked", []) and s["picked"].remove(other)
|
||||||
|
s["pending"] = {**q, w: q.get(w, []) + [{"node": i, "branch": node(get(s), i)["branch"]}]}
|
||||||
|
s.setdefault("picked", []).insert(0, w)
|
||||||
|
models.claim(s, w, node=i) # from here on it is a delegation like one the hooks saw
|
||||||
|
s["delegations_since"] = s.get("delegations_since", 0) + 1
|
||||||
|
s.pop("paused", None)
|
||||||
|
start(s, i, w, s["starts"][w][-1])
|
||||||
|
print('node %s is running on %s. When it reports: `sisi judge %s good|bad|out "<why>" --node %s`' % (i, w, w, i))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def header(p, i):
|
def header(p, i):
|
||||||
return "\n".join(["paste at the top of the brief (its first line):", "sisi node: " + i, "branch: %s (its own worktree and build folder)" % (n := node(p, i))["branch"],
|
return "\n".join(["paste at the top of the brief (its first line):", "sisi node: " + i, "branch: %s (its own worktree and build folder)" % (n := node(p, i))["branch"],
|
||||||
"may change: " + (", ".join(n["files"]) or "nothing"), "check: " + n["check"],
|
"may change: " + (", ".join(n["files"]) or "nothing"), "check: " + n["check"],
|
||||||
|
|||||||
+1
-10
@@ -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
@@ -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__)))
|
||||||
|
|||||||
+74
-4
@@ -3,7 +3,7 @@
|
|||||||
Learning: work is done, the retro is forced, its improvement is a rule in the next session, the rules are
|
Learning: work is done, the retro is forced, its improvement is a rule in the next session, the rules are
|
||||||
organized and the change can be undone. Delegation: the lead is stopped when it should be delegating, and the
|
organized and the change can be undone. Delegation: the lead is stopped when it should be delegating, and the
|
||||||
models table is researched, read and kept fresh."""
|
models table is researched, read and kept fresh."""
|
||||||
import glob, hashlib, json, os, random, re, shlex, shutil, subprocess, sys, tempfile, time, unittest
|
import calendar, glob, hashlib, json, os, random, re, shlex, shutil, subprocess, sys, tempfile, time, unittest
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__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):
|
||||||
@@ -3038,6 +3038,76 @@ cli.main(["tick"])
|
|||||||
first = time.mktime(time.strptime("2026-" + out.split("The first is back on the wheel at ")[1][:11], "%Y-%m-%d %H:%M"))
|
first = time.mktime(time.strptime("2026-" + out.split("The first is back on the wheel at ")[1][:11], "%Y-%m-%d %H:%M"))
|
||||||
self.assertLess(abs(first - (time.time() + 5 * 3600)), 120)
|
self.assertLess(abs(first - (time.time() + 5 * 3600)), 120)
|
||||||
|
|
||||||
|
def test_a_stated_reset_time_keeps_the_whole_plan_off_the_wheel_until_then(self):
|
||||||
|
"""Fault 37, with the providers' own messages."""
|
||||||
|
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 (("muse-wonder", "Muse Code", "ordinary"), ("muse-ember", "Muse Code", "routine"),
|
||||||
|
("gemini-4-neon", "Antigravity", "ordinary"), ("gemini-4-hydrogen", "Antigravity", "routine"),
|
||||||
|
("alpha", "Other", "routine"))))
|
||||||
|
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, reset = utc("2026-12-02T21:33:21"), utc("2026-12-07T00:00:00")
|
||||||
|
muse = "API error 429: Subscription quota exhausted. Your usage window resets at 2026-12-07T00:00:00Z."
|
||||||
|
pool = {"muse-wonder": "muse code", "muse-ember": "muse code", "alpha": "other"}
|
||||||
|
verdict = lambda why, t, w="muse-wonder", kind="out": {"ts": stamp(t), "worker": w, "verdict": kind, "why": why}
|
||||||
|
for log in ([verdict(muse, said)], [verdict(muse, said), verdict("connection lost again here", said + 60, "muse-ember")]):
|
||||||
|
gone = models.outs(log, reset - 60, pool)
|
||||||
|
self.assertEqual(sorted(gone), ["muse-ember", "muse-wonder"])
|
||||||
|
self.assertEqual({w: g[2] for w, g in gone.items()}, dict.fromkeys(gone, reset)) # a later message with no time shortens nothing
|
||||||
|
gone = models.outs([verdict(muse, said)], reset - 60, pool)
|
||||||
|
off = lambda now: models.out(["muse-ember"] + [""] * 8, set(), None, gone, now)
|
||||||
|
self.assertEqual((off(reset - 60).startswith("out since"), off(reset)), (True, ""))
|
||||||
|
self.assertEqual(sorted(models.outs([verdict(muse, said), verdict("did it all well", said + 60, "muse-ember", "good")], said + 90, pool)), ["muse-wonder"])
|
||||||
|
for why, wait in (("Individual quota reached. Resets in 108h11m37s.", 108 * 3600 + 11 * 60 + 37), ("limit hit, resets in 3 days", 3 * 86400),
|
||||||
|
("Rate limited: try again in 45 minutes", 45 * 60), ("Resets in 4h 14m (shared account quota)", 4 * 3600 + 14 * 60),
|
||||||
|
(LIMIT, 6 * 3600), ("started 2026-12-30T00:00:00Z and hit a limit", 6 * 3600),
|
||||||
|
("usage window resets at 2026-11-01T00:00:00Z", 6 * 3600), ("resets in 9000 days", 6 * 3600)):
|
||||||
|
self.assertEqual(models.outs([verdict(why, said)], said)["muse-wonder"][2] - said, wait, why)
|
||||||
|
# through the command: the model out and its sibling are both off, long after six hours
|
||||||
|
self.judged("gemini-4-neon", "out", "Individual quota reached. Resets in 108h11m37s.")
|
||||||
|
self.dated(108 * 60 + 10)
|
||||||
|
for cls, args in (("ordinary", ("--not", "muse-wonder")), ("routine", ("--not", "alpha", "--not", "muse-ember"))):
|
||||||
|
got, out = self.picked(cls, *args)
|
||||||
|
self.assertEqual((got, "(out since" in out), (False, True), out)
|
||||||
|
self.assertIn("gemini-4-hydrogen: out since", self.sisi("models")[1])
|
||||||
|
self.assertEqual(self.picked("routine", "--not", "muse-ember", "--not", "gemini-4-hydrogen")[0], True) # another plan stays on
|
||||||
|
self.dated(108 * 60 + 12)
|
||||||
|
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)
|
||||||
|
|||||||
@@ -58,6 +58,10 @@ class ModelsResearch(unittest.TestCase):
|
|||||||
CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude"))
|
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"):
|
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.env.pop(name, None)
|
||||||
|
hide = mock.patch.dict(os.environ) # in-process calls read os.environ: the harness running this suite must not leak in
|
||||||
|
hide.start()
|
||||||
|
self.addCleanup(hide.stop)
|
||||||
|
os.environ.pop("CLAUDE_CODE_ENTRYPOINT", None)
|
||||||
subprocess.run(["git", "init", "-q", self.data], check=True, capture_output=True, stdin=subprocess.DEVNULL)
|
subprocess.run(["git", "init", "-q", self.data], check=True, capture_output=True, stdin=subprocess.DEVNULL)
|
||||||
|
|
||||||
def in_process(self, fn, *args):
|
def in_process(self, fn, *args):
|
||||||
|
|||||||
+31
-5
@@ -142,13 +142,39 @@ class Plan(unittest.TestCase):
|
|||||||
self.assertEqual(self.nodes(), {"a": "running"})
|
self.assertEqual(self.nodes(), {"a": "running"})
|
||||||
self.assertEqual(self.record(PLAN.replace("test a passes", "test a2 passes"))[0], 0)
|
self.assertEqual(self.record(PLAN.replace("test a passes", "test a2 passes"))[0], 0)
|
||||||
self.assertEqual(self.nodes(), {"a": "running"}) # a running node keeps its state by id
|
self.assertEqual(self.nodes(), {"a": "running"}) # a running node keeps its state by id
|
||||||
rc, out, _ = self.record(PLAN.replace("| sisi/a.py |", "| sisi/a2.py |"))
|
self.assertEqual(self.record(PLAN.replace("| sisi/a.py |", "| sisi/a.py, sisi/a2.py |"))[0], 0)
|
||||||
self.assertEqual(rc, 1, out)
|
self.assertEqual(self.nodes(), {"a": "running"}) # same id and branch: still running
|
||||||
self.assertIn("node a is running", out)
|
for changed in (PLAN.replace("| p-a |", "| p-a2 |"), PLAN.replace("| a | routine | - |", "| a2 | routine | - |").replace("| a, b |", "| a2, b |")):
|
||||||
self.assertIn("a", self.nodes())
|
rc, out, _ = self.record(changed)
|
||||||
rc, out, _ = self.record(PLAN.replace("| a | routine | - |", "| a2 | routine | - |").replace("| a, b |", "| a2, b |"))
|
|
||||||
self.assertEqual(rc, 1, out)
|
self.assertEqual(rc, 1, out)
|
||||||
self.assertIn("node a is running", out)
|
self.assertIn("node a is running", out)
|
||||||
|
self.assertEqual(self.nodes(), {"a": "running"})
|
||||||
|
|
||||||
|
def test_a_job_already_running_is_attached_to_a_node_without_a_delegation(self):
|
||||||
|
"""Fault 36: a node continued on an existing worker by a message stayed "ready and not started"."""
|
||||||
|
self.ready_plan()
|
||||||
|
self.assertEqual(self.sisi("plan", "--done", "b", "done by hand and tested", sid="s1")[0], 0)
|
||||||
|
attach = lambda node, worker: self.sisi("pick", "--node", node, "--started", worker, sid="s1")
|
||||||
|
rc, out, _ = attach("c", "gamma")
|
||||||
|
self.assertEqual((rc, "not ready" in out), (1, True), out)
|
||||||
|
self.assertIn("ready and not started", self.hook("gate")[1])
|
||||||
|
self.pick("a") # the wheel said alpha, but the lead sent it to a running agent
|
||||||
|
rc, out, _ = attach("a", "gate-solver")
|
||||||
|
self.assertEqual(rc, 0, out)
|
||||||
|
self.assertEqual(self.nodes()["a"], "running")
|
||||||
|
self.assertEqual(self.state()["picked"], []) # the pick made for this node is withdrawn
|
||||||
|
self.assertNotIn("ready and not started", self.hook("gate")[1])
|
||||||
|
rc, out, _ = attach("a", "gate-solver")
|
||||||
|
self.assertEqual((rc, "already running" in out), (1, True), out)
|
||||||
|
self.assertEqual(self.record(PLAN.replace("test a passes", "test a2 passes"))[0], 0)
|
||||||
|
self.assertEqual(self.nodes()["a"], "running")
|
||||||
|
rc, out, _ = self.sisi("judge", "gate-solver", "good", "did the node in one pass", "--node", "a", sid="s1")
|
||||||
|
self.assertEqual(rc, 0, out)
|
||||||
|
self.assertEqual(self.nodes()["a"], "done")
|
||||||
|
self.pick("c") # a table worker named shortly is stored as the table names it
|
||||||
|
self.assertEqual(attach("c", "GAMMA")[0], 0)
|
||||||
|
self.assertEqual((list(self.state()["starts"]).count("gamma"), self.state()["picked"]), (1, []))
|
||||||
|
self.assertEqual(self.sisi("judge", "gamma", "good", "did the node in one pass", "--node", "c", sid="s1")[0], 0)
|
||||||
|
|
||||||
def pick_header(self, node, sid="s1"):
|
def pick_header(self, node, sid="s1"):
|
||||||
st = self.state(sid)
|
st = self.state(sid)
|
||||||
|
|||||||
Reference in new issue
Block a user