diff --git a/README.md b/README.md index 51beed2..e7eecbf 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ by its full model id (`claude-sonnet-5-5`); anywhere else the name must match wh **Done.** Nothing starts before `sisi done` has recorded the goal, the checks that decide success and what the person will need next: delegating or editing gets a note until then. Every check needs a verdict (`sisi done --pass N` or `--fail N`) before the turn ends; a turn that changed things, or failed a check, -is sent to the retro, and any other closes itself, as does work that took under `retro_minutes`, passed every check and delegated nothing. While a delegated job is open and not late, a stop is not held up for checks without a verdict. Each record in `retro.jsonl` carries `session_id`, `retro_seconds` (when demanded), +is sent to the retro, and any other closes itself, as does work that took under `retro_minutes`, passed every check and delegated nothing. A retro recorded while a check has no verdict or a plan node is running records its gap and rule but keeps the done, the plan and the running jobs: only a retro of finished work closes them. While a delegated job is open and not late, a stop is not held up for checks without a verdict. Each record in `retro.jsonl` carries `session_id`, `retro_seconds` (when demanded), the numbers (minutes, messages, tool calls, delegations, checks), the `term` it fell short on (`value`, `evidence`, `time`, `cost`, `attention` or `learning`: the terms of the objective), and (for gap retros) the `problem` name. `sisi retro` lays the facts out under those terms, lists known problems (most recently cited first), and shows their trend. Citing the same problem a third time (2nd miss) and after opens a fault requiring a hook or automatic check rather than another rule. Problems are shared across all projects in your store while the fault opens in the project where the problem was cited, and a reworded name opens a new problem (matching is by the same words, ignoring case and spacing), so cite by number. @@ -91,7 +91,7 @@ its limits are. | `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 fault ""` / `--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 [--review-of WORKER] [--not WORKER] [--limit MINUTES] [--branch REF]` | The wheel gives one worker; 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; 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 --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) | @@ -100,7 +100,7 @@ its limits are. | `sisi rules move "" core\|user\|project\|canon [--project PATH]` | Move one rule line, verbatim, to another level, and print the command that moves it back: `sisi rules revert` does not undo a move (core is a queue for the product, in force as a user rule until it is added to canon/core.md, then `canon` takes it out of the queue); a level is always named, `project` needs a git repo, and organize also audits placement every `audit_after` (12) retros | | `sisi rules` / `sisi rules organize [--record FILE]` / `sisi rules revert` | See the learned rules; have a worker organize them (using known problems, prior attempts, and past drop reasons; an optional `## drops` section can record a reason and matching problem number for any dropped or merged rule, with `none given` recorded when omitted); undo the last rule change made with `learn`, a retro or `organize` (including any drop reasons recorded by that `organize`), in the user list or a project's `.sisi/rules.md` (not the one-time move of old rules; after `sisi rules move`, or an `organize` that moved lines between levels, it changes nothing and prints the command(s) that move them back, which that command also printed; a second `revert` re-applies what the first undid; it declines, changing nothing, when the project file changed since or its folder moved or is gone) | | `sisi plan brief` / `sisi plan --record FILE` / `sisi plan` / `sisi plan --done\|--fail ID "…"` | The dependency graph of a piece of work, recorded before any delegation: `\| node \| class \| needs \| branch \| files \| check \| why \|`, one join every node reaches; refused on a cycle, a missing need, a shared branch, or overlapping files between nodes that can run at once. Prints the waves to dispatch together. `sisi pick --node ID` gives the worker and a header for the brief; the hook denies a lead's delegation outside the plan, out of order, unpicked, or without its own worktree, and the end of a turn sends the lead back while ready nodes wait. `sisi judge` closes or reopens the node. A `sisi chore:` brief (models research, plan brief) needs no plan. `"enforce": false` turns denials into reminders | -| `sisi models` / `sisi models research [--record FILE]` | The workers table: at most one row per provider (the plan or account a call draws on) per class, the one whose published allowance goes furthest, with its source and quota windows (`5h: N req; week: N req`); the wheel picks a plan less the more of its windows sisi's own delegations have used (never below 5%); research is redone every 3 days by a hard worker. (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it | +| `sisi models` / `sisi models research [--record FILE]` | The workers table: at most one row per provider (the plan or account a call draws on) per class (`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 judge WORKER good\|bad\|out "…" [--minutes N] [--newest] [--node ID \| --chore ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first (and if another open job has `--node`/`--chore`, a note names the closed job and the remaining ones with their targeting flags), `--newest` the newest, `--node ID` closes or reopens the job running that plan node, and `--chore ID` closes that chore job | | `sisi judge WORKER extend MINUTES "" [--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 | diff --git a/canon/core.md b/canon/core.md index c83d27a..dbc80f9 100644 --- a/canon/core.md +++ b/canon/core.md @@ -69,10 +69,15 @@ buy speed with a weaker check. You own the outcome. You are the dearest model, so delegate reading, searching, measuring, building, testing, research, first reviews and the fact-finding a brief needs, and keep your context for intent, design, judgement and the final call. Choose each piece's -class (routine, ordinary, hard) by total cost (your specifying, the work, the redo). Near-free routine models take anything specified exactly (files, change, a check that decides) and keep being tried on such work; judgement and design go to hard: a cheap job redone is waste. Plan first: `sisi plan brief` goes to a hard worker, and `sisi plan --record FILE` keeps the +class (routine, ordinary, hard, deep) by total cost (your specifying, the work, the redo). Near-free routine models take anything specified exactly (files, change, a check that decides) and keep being tried on such work; judgement and design go to hard: a cheap job redone is waste. Plan first: `sisi plan brief` goes to a hard worker, and `sisi plan --record FILE` keeps the graph: many small exact nodes (class, needs, branch, files, quick check); joins merge and run slow checks. Nodes that run together get their own worktrees and disjoint files. Before the first pick, and whenever sisi asks, give `sisi models offered` the host's full raw list of models its delegation tool can start, and hand its brief to a routine worker. For each ready node `sisi pick --node ID` spins the wheel over that class, among models the host offers (new ones tried at once), and gives a worker and brief header; dispatch every -ready node in one message. sisi refuses a handoff outside the plan, out of order or unpicked. The wheel keeps one most-efficient model per provider and class and spreads load so no quota runs out. A review goes to a different maker than the author (`--review-of WORKER`). Start +ready node in one message. sisi refuses a handoff outside the plan, out of order or unpicked. The wheel keeps one most-efficient model per provider and class and spreads load so no quota runs out. Most efficient means cheapest among models within one point of the class's best score, so a +tie never goes to the dearer model. The dearest tier is its own class, deep: the lead picks it on purpose +for the hardest jobs that need the most deep thought and highest intelligence (novel design, hard root +causes, the central mechanism); it is never banned and never a default for hard, ordinary or routine. +Finishing or follow-up nodes (compile, fix, test an existing design) are ordinary, never inherited as hard +or deep. A review goes to a different maker than the author (`--review-of WORKER`). Start workers with the host's delegation tool, never a worker's command line. Brief a worker as a peer who starts cold: the outcome, what is known and ruled out, what done looks like, the files it may change, what it may create, and a time limit (`--limit MINUTES`). At the limit it stops and reports what is proven, failed and not run. The lead may extend once, with a reason (`sisi diff --git a/sisi/cli.py b/sisi/cli.py index d2a56e1..7e8d77e 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -38,7 +38,7 @@ Delegation 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 ` and do what it says" sisi pick --node ID [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] - sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME] + 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] diff --git a/sisi/hooks.py b/sisi/hooks.py index 1d0593d..c9cb804 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -10,13 +10,13 @@ from . import models, rules, store WORKER = re.compile(r"(?im)^\W*(you are a (worker|subagent|sub-agent|delegate)\b|do this task yourself|do not delegate)|\A\s*\[[^\]\n]{0,200}\bsent this message, not the user\.?\]") DIRECT = ("shell", "read", "edit", "search", "web") # the classes of tool call the meter counts -METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the rest: `sisi models` lists your workers and `sisi pick routine|ordinary|hard` " +METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the rest: `sisi models` lists your workers and `sisi pick routine|ordinary|hard|deep` " "chooses one; if doing this yourself costs less than briefing it, say why with `sisi direct \"\"` (%d more).") GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro` to see what happened, then record `sisi retro --gap \"\" --cause \"\" --improve \"\" --term --problem N|\"\" --level core|user|project` " "or `sisi retro --no-gap \"\" --term --better \"\"` (or pause: `sisi retro --later \"\"`).") NODONE = "sisi: no done is recorded yet. Define what the person wants and what comes next now: `sisi done --goal \"\" --check \"\" [--check ...] --next \"\"`." UNPICKED = ("sisi: the wheel did not give you this worker (or no model is named, so it would run on your own). Run `sisi pick --node ID` " - "(`sisi pick routine|ordinary|hard` for a `sisi chore:` brief) and name the model it gives.") + "(`sisi pick routine|ordinary|hard|deep` for a `sisi chore:` brief) and name the model it gives.") NOLOOK = ("sisi: this brief asks for something the person will look at but states no look (typefaces, sizes, colours, spacing, layout at each width). " "Choose it with the person from previews and put it in the brief, or add a line 'Look: '.") UNKNOWN = "sisi: the worker you named is not in the models table, so the table is out of date. Rebuild it now with a research worker (`sisi models research` prints the brief; `sisi models research --record FILE` records the answer), and use `sisi pick` next time." @@ -286,9 +286,10 @@ def gate(p, for_subagent=False): quick = 0 <= time.time() - s.get("began", 0) < 60 * store.config()["retro_minutes"] and not s.get("delegations_since") and not s.get("fails_since") if checks and not unsaid and not failed and (not worked or quick): from . import retro - retro.record(s, cwd, {}, sid) # every check passed and nothing changed, or it was quick and alone: the work closes itself + if not retro.unfinished(s): + retro.record(s, cwd, {}, sid) # every check passed and nothing changed, or it was quick and alone: the work closes itself else: - reason = "" if unsaid and models.waiting(s) else OPEN % "; ".join(unsaid) if unsaid else GATE if worked else FAILED % ", ".join(failed) if failed else "" + reason = "" if models.waiting(s) else OPEN % "; ".join(unsaid) if unsaid else GATE if worked else FAILED % ", ".join(failed) if failed else "" demand = bool(reason and not unsaid) reason = " ".join(x for x in (open_f, reason) if x) if reason and s.get("blocks", 0) < 2: diff --git a/sisi/models.py b/sisi/models.py index 67498c9..dbe42c2 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -28,8 +28,12 @@ Find out %(intro)s, and write the personal table an engineering lead will route quotes the provider's own published allowance or price for that model with the plan/pricing page URL (or "measured: ..." from our record), and its quota windows exactly as `5h: N req; week: N req; month: N req` (`req` only when N counts requests; else name the unit). sisi spreads delegations by these so no plan runs dry early. - Among models that truly perform at a class, keep the one whose allowance goes furthest (flat plan: most requests - per window; per use: lowest cost per benchmark task): at most one row per provider per class; drop the rest. + Most efficient means cheapest among models within one point of the class's best score, so a tie never goes to the + dearer model. Among them keep the one whose allowance goes furthest (flat plan: most requests per window; per use: + lowest cost per benchmark task): at most one row per provider per class; drop the rest. The dearest tier is its own + class, deep: the lead picks it on purpose for the hardest jobs that need the most deep thought and highest + intelligence (novel design, hard root causes, the central mechanism); it is never banned and never a default for + hard, ordinary or routine. Notes hold `usage: ` where one exists. 4. %(step4)s 5. What the person has said, below, stands exactly and outranks all of this: it is not yours to change. @@ -38,9 +42,11 @@ Answer with exactly this and nothing else. First a markdown table of at most 40 per class, ordered within each class most efficient first (the wheel weights by row order), with these columns: | worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes | "provider" names the account or plan as the person knows it. "maker" is the company or lab that trained the model, lower case, one word. "use for" is exactly one of: routine, -ordinary, hard. It is the model's capability class, not a list of tasks it could do. Routine is the small, fast, +ordinary, hard, deep. It is the model's capability class, not a list of tasks it could do. Routine is the small, fast, cheap tier (the level of a maker's smallest current model); ordinary is the mid tier (a maker's main everyday -model); hard is the top tier (a maker's strongest model). Place each model by comparing it with its peers from +model); hard is the top everyday tier (a maker's strong model for judgement and design); deep is the dearest tier for +the hardest jobs needing the most deep thought and highest intelligence (never a default for hard, ordinary or routine). +Place each model by comparing it with its peers from other makers (benchmarks and the maker's own positioning), so that every class holds models of like strength from several makers. A model that seems to fit two classes goes in the lower one only if it truly performs at that level, never in both. "how to call it" is exact: the host delegation tool's provider and model id (T3 Code's @@ -69,7 +75,7 @@ You are a worker. Do this task yourself; do not delegate it further. Below is the host's raw list of the models it offers, and the researched table. Write one table row per offered model (at most 80) in the table's columns (| worker | provider | maker | how to call it | use for | cost | efficiency | good at, bad at | notes |). A known model: copy its row, with "how to call it" replaced by the exact dispatch from the list. An unknown model: a provisional row (provider, maker, use for -exactly one of routine|ordinary|hard as a guess, the dispatch, notes starting `new: `). Skip any provider the list marks +exactly one of routine|ordinary|hard|deep as a guess, the dispatch, notes starting `new: `). Skip any provider the list marks disabled or unable to run child tasks. An id like default that names no specific model is never a row. Never invent an id: each worker id must appear verbatim in the list and in its dispatch. Write the table to a file and run `sisi models offered --record FILE`. @@ -147,6 +153,8 @@ def stale(mark=None): return ("sisi: a delegation named `%s`, which the models table does not list. " % who + ASK) if who and not known(store.read(table()) + "\n" + wtext, who) else "" +CLASSES = ("routine", "ordinary", "hard", "deep") +CLASS_RE = r"\b(?:routine|ordinary|hard|deep)\b" KEYS = ("worker", "how", "use", "cost", "good", "notes", "maker", "provider", "efficiency") # a column is known by its header's first word LAUNCHERS = {"python", "python3", "bash", "sh", "zsh", "cd", "env", "npx", "npm", "node", "uv", "uvx", "make", "ssh", "git", "docker", "sudo"} @@ -164,7 +172,7 @@ def rows(text): return out -def usable(text): return any(re.search(r"routine|ordinary|hard", r[2].lower()) for r in rows(text)) +def usable(text): return any(re.search(CLASS_RE, r[2].lower()) for r in rows(text)) first = lambda cell: (str(cell).split() or [""])[0] # a worker's id as its row writes it: it must appear so in the host's list @@ -373,13 +381,13 @@ def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, no def pick(args, cwd=None, rand=None): - """`sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]`: the wheel gives one worker.""" + """`sisi pick routine|ordinary|hard|deep [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]`: the wheel gives one worker.""" node = None if args[:1] == ["--node"]: # the class and branch come from the plan node from . import plan args, node = plan.for_pick(args, cwd) if node is None: return 1 - cls, skip, review, limit, branch, i = (args[0] if args and args[0] in ("routine", "ordinary", "hard") 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 while cls and i < len(args): if args[i] == "--not" and i + 1 < len(args): skip.add(short(args[i + 1])) elif args[i] == "--review-of" and i + 1 < len(args): review = args[i + 1] @@ -388,27 +396,30 @@ def pick(args, cwd=None, rand=None): else: cls = None i += 2 if not cls: - print("usage: sisi pick routine|ordinary|hard [--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]") return 1 text, why = wheel() if why: return print("sisi pick: %s: %s" % (why, "run `sisi models offered < FILE` and hand the printed `models offered` chore to any model the host offers." if why == "no offered model has a row" else REFRESH)) or 1 mine = [r for r in rows(text) if r[2].strip().lower() == cls] + picked_cls = "hard" if cls == "deep" and not mine else cls + if picked_cls != cls: + mine = [r for r in rows(text) if r[2].strip().lower() == picked_cls] if review is not None and not any(short(r[0]) == short(review) for r in rows(text)): print("sisi pick: %r is not a worker in the models table; --review-of names the worker whose work is reviewed." % review) return 1 (speed, qual, tried), gone, now = track(), away(), time.time() - r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual, share=shares(plan_use(text, cwd, now)), tried=tried) + r = choose(text, picked_cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual, share=shares(plan_use(text, cwd, now)), tried=tried) if not r: 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."}.get(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) - print(("sisi pick: every worker of class %s is out or excluded: %s." % (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 - else "sisi pick: the models table has no worker of class %s." % cls) + else "sisi pick: the models table has no worker of class %s." % picked_cls) + (" The first is back on the wheel at %s." % clock(first) if first is not None else "") + again) return 1 for x in rows(text): - if len(re.findall(r"routine|ordinary|hard", x[2].lower())) > 1: + if len(re.findall(CLASS_RE, x[2].lower())) > 1: print("%s is in more than one class and is on no wheel: rebuild the table" % short(x[0])) sid, also = store.current_session(cwd), [] if sid: @@ -422,6 +433,8 @@ def pick(args, cwd=None, rand=None): q = s["pending"] if isinstance(s.get("pending"), dict) else {} s["pending"] = {**q, w: (q[w] if isinstance(q.get(w), list) else []) + [{"limit": limit, "branch": branch, "node": node}]} # one entry per pick, claimed in order print("worker: %s (model id: %s)\nstart it with the host's delegation tool; one pick buys one delegation" % (r[0], short(r[0]))) + if picked_cls != cls: + print("fallback: no deep worker in the models table; picked from hard") print("how to call it: " + r[1]) print("good at, bad at: %s\nnotes: %s" % (r[4], r[5])) t = speed.get(short(r[0])) @@ -471,8 +484,8 @@ def research_record(answer_file): if key in seen: return "keep at most one row per provider per class, the most efficient: %s and %s are both %s at %s" % (seen[key], r[0], r[2].strip(), r[7]) seen[key] = r[0] - if len(re.findall(r"routine|ordinary|hard", r[2].lower())) != 1: - return "each row's \"use for\" must name exactly one of routine, ordinary or hard: | %s |" % " | ".join(r[:6]) + if len(re.findall(CLASS_RE, r[2].lower())) != 1: + return "each row's \"use for\" must name exactly one of routine, ordinary, hard or deep: | %s |" % " | ".join(r[:6]) if len(lines) > 42 or len(text) > 12000: return "the answer is too long (at most 40 rows and 12,000 characters)" if shared and ("|" not in shared or not _shared_date(shared)[0]): @@ -583,6 +596,8 @@ def judge(args, cwd=None): rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1], "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)), "project_key": store.project_key(cwd)} + cls_hit = re.findall(CLASS_RE, hits[0][2].lower()) if len(hits) == 1 else [] + if len(cls_hit) == 1: rec["class"] = cls_hit[0] if sid: rec["session_id"] = sid if began is not None: rec["started"] = iso(began) if minutes: rec["minutes"] = minutes @@ -626,7 +641,7 @@ def run(args, cwd=None): return plan.issue("models offered", OFFERED % (store.read(table()).rstrip() or "(none yet)", raw), cwd) or 0 if len(args) == 3 and args[:2] == ["offered", "--record"]: raw, text = store.read(offered("txt")).partition("\n")[2], store.read(args[2]) - bad = [r[0] for r in rows(text) if not (_has(raw, first(r[0])) and _has(r[1].lower(), short(r[0])) and len(re.findall(r"routine|ordinary|hard", r[2].lower())) == 1)] + bad = [r[0] for r in rows(text) if not (_has(raw, first(r[0])) and _has(r[1].lower(), short(r[0])) and len(re.findall(CLASS_RE, r[2].lower())) == 1)] if not raw.strip() or not rows(text) or bad or len(rows(text)) > 80: return print("sisi models: %s. Nothing was changed." % ("needs the list first (`sisi models offered < FILE`) and 1 to 80 rows" if not raw or not rows(text) or len(rows(text)) > 80 else "not in the list verbatim, in the how-to-call cell, or not one class: " + ", ".join(bad))) or 1 with store.lock("models"): diff --git a/sisi/plan.py b/sisi/plan.py index b0feea0..db644b4 100644 --- a/sisi/plan.py +++ b/sisi/plan.py @@ -6,7 +6,7 @@ ready and not started. The plan lives in the session state and closes with the p import contextlib, fnmatch, hashlib, os, re, time from . import store -CLASSES = ("routine", "ordinary", "hard", "lead") +CLASSES = ("routine", "ordinary", "hard", "deep", "lead") COLS = ("node", "class", "needs", "branch", "files", "check", "why") NODE_LINE = re.compile(r"\W{0,6}sisi node:\s*([a-z0-9-]{1,30})\s*$", re.I) CHORE_LINE = re.compile(r"\W{0,6}sisi chore:\s*(.+?)(?:\s+([0-9a-f]{8}))?\s*$", re.I) @@ -28,7 +28,7 @@ Next: %(next)s Answer with exactly one markdown table and nothing else: | node | class | needs | branch | files | check | why | - node: a short id, [a-z0-9-], at most 30 characters, unique. -- class: routine, ordinary, hard, or lead (done by the lead itself: the final join, and judgement only it can make). +- class: routine, ordinary, hard, deep, or lead (done by the lead itself: the final join, and judgement only it can make). - needs: the node ids that must be done first, comma-separated, or -. - branch: its own git branch (each worker node gets its own worktree and build folder); - for a lead node. - files: the paths, folders or globs it may change, comma-separated (- for none). Nodes that can run at the same @@ -45,7 +45,10 @@ spending its own quota on meta work. The lead is almost always the most expensiv measuring that feed a brief (gather the facts for node X, list call sites, measure) are routine nodes whenever their output can be checked; the lead keeps only the judgement. Near-free routine models take any task that can be specified exactly (exact files, exact change, a test that decides), and keep being tried on such tasks so their -record grows; judgement-heavy or design work goes straight to hard. +record grows; judgement-heavy or design work goes to hard; deep (the dearest tier) is picked on purpose only for the +hardest jobs that need the most deep thought and highest intelligence (novel design, hard root causes, the central +mechanism) — never banned and never a default for hard, ordinary or routine. Finishing or follow-up nodes (compile, +fix, test an existing design) are ordinary, never inherited as hard or deep. %(record)s """ @@ -161,14 +164,15 @@ def record_line(): from . import models cls = {} for r in models.rows(store.read(models.table())): - c = re.findall(r"routine|ordinary|hard", r[2].lower()) + c = re.findall(models.CLASS_RE, r[2].lower()) len(c) == 1 and cls.setdefault(models.short(r[0]), c[0]) by = {} for o in store.records("outcomes.jsonl"): w = o.get("model") if isinstance(o.get("model"), str) and o["model"].strip() else o.get("worker") - if o.get("verdict") in ("good", "bad") and isinstance(w, str) and (c := cls.get(models.short(w))): + c = (cls.get(models.short(w)) if isinstance(w, str) else None) or (o.get("class") if o.get("class") in models.CLASSES else None) + if o.get("verdict") in ("good", "bad") and c: by.setdefault(c, []).append(o["verdict"] == "good") - parts = ["%s %d/%d good" % (c, sum(by[c][-20:]), len(by[c][-20:])) if by.get(c) else "%s none judged yet" % c for c in CLASSES[:3]] + parts = ["%s %d/%d good" % (c, sum(by[c][-20:]), len(by[c][-20:])) if by.get(c) else "%s none judged yet" % c for c in models.CLASSES] return "record (last 20 judged per class): " + ", ".join(parts) diff --git a/sisi/retro.py b/sisi/retro.py index ae1f1ac..3834fff 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -159,12 +159,22 @@ def rulebook(cwd): return {"hash": hashlib.sha256(t.encode()).hexdigest()[:12], "chars": len(t), "lines": len(rules._parse(t))} +def unfinished(s): + """Why this piece of work is still open (a check without a verdict, a plan node running), or "".""" + from . import plan + unsaid = [str(i) for i, c in enumerate((s.get("done") or {}).get("checks") or [], 1) if not c["verdict"]] + busy = [n["id"] for n in p["nodes"] if plan.st(p, n["id"]) == "running"] if (p := plan.get(s)) else [] + return "; ".join(["checks %s have no verdict" % ", ".join(unsaid)] * bool(unsaid) + ["nodes %s are running" % ", ".join(busy)] * bool(busy)) + + def record(s, cwd, opt, sid=None): - """Append one record for the piece of work in this session state, and begin the next one.""" - d, now, dem = s.get("done") or {}, time.time(), s.get("retro_demanded") + """Append one record. Finished work is closed and the next piece begins; open work keeps its done, plan, jobs and counts (returns why).""" + d, now, dem, left = s.get("done") or {}, time.time(), s.get("retro_demanded"), unfinished(s) entry = dict(opt, ts=time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(now)), project=os.path.basename(store.project_root(cwd)), unit=counts(s, cwd), goal=d.get("goal", ""), workers=s.get("workers_since", []), rules=rulebook(cwd)) + if left: + entry["open"] = entry.pop("unit") and True # not a piece of work of its own: the trend counts it once, when it closes if d: entry["done"] = d if sid: @@ -175,10 +185,12 @@ def record(s, cwd, opt, sid=None): store.append(log, json.dumps(entry, sort_keys=True)) if not store.commit("retro recorded", log): print("sisi: retro saved, but store git commit failed (%s)." % store.GIT_ERROR) - s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now - for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "paused", - "fails_since", "picked", "starts", "pending", "meta", "reminded", "retro_demanded", "began", "plan"): + if not left: + s["snapshot"], s["changed"], s["retro_at"] = store.snapshot(cwd), False, now + for key in ("paused", "retro_demanded") + (() if left else ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", + "done", "fails_since", "picked", "starts", "pending", "meta", "reminded", "began", "plan")): s.pop(key, None) + return left def done(args, cwd=None): @@ -272,6 +284,7 @@ def run(args, cwd=None): if plines else "\nknown problems: none yet.\nRe-run with --problem \"\".")) return 1 opt.update({"term": term, "problem": prob["name"]} if kind == "gap" else {"term": term, "better": clean(better)} if kind == "no-gap" else {}) + left = "" if sid: with store.session(sid) as s: if kind == "no-gap" and any(c["verdict"] == "fail" for c in (s.get("done") or {}).get("checks", [])): @@ -282,7 +295,7 @@ def run(args, cwd=None): if kind == "later": s["paused"] = True else: - record(s, cwd, opt, sid) + left = record(s, cwd, opt, sid) elif kind != "later": record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt) if kind == "gap": @@ -319,4 +332,5 @@ def run(args, cwd=None): else: print("recorded." if kind == "no-gap" else "noted: the retro waits until this work ends.") scope and print("(--level goes only with --gap; it was ignored.)") + left and print("sisi retro: the work stays open (%s): done and the plan are kept. It closes with a retro once every check has a verdict and no node runs." % left) return 0 diff --git a/tests/test_core.py b/tests/test_core.py index ca07081..6ebe058 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -168,6 +168,8 @@ class Core(unittest.TestCase): report = self.sisi("retro", sid="s1")[1] self.assertIn("The objective: Maximize the long-term, verified value", report) self.assertIn("you made 1 tool call(s) yourself", report) + self.done("s1", "--pass", "1", "counts matched at 120") + self.done("s1", "--pass", "2", "empty name exported ok") rc, out, _ = self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export change", sid="s1") self.assertEqual(rc, 0, out) self.assertEqual(self.hook("gate")[1], "") # held: the turn may end @@ -204,6 +206,8 @@ class Core(unittest.TestCase): GAP[:-2] + ("--improve", "Compare the row counts every time", "--scope", "everyone")): self.assertEqual(self.sisi("retro", *args, sid="s1")[0], 1, args) self.assertIn('"block"', self.hook("gate")[1]) + self.done("s1", "--pass", "1", "counts matched at 120") + self.done("s1", "--pass", "2", "empty name exported ok") self.assertEqual(self.sisi("retro", "--no-gap", "the person accepted it first time and every check passed", *NG, sid="s1")[0], 0) self.assertEqual(self.hook("gate")[1], "") @@ -2007,6 +2011,8 @@ cli.main(["tick"]) self.assertEqual(judge()[1].strip(), "recorded, not timed.") self.assertEqual(delegate(), (0, 0)) # a retro ends the stored starts self.assertIn("starts", self.state()) + self.done("s1", "--pass", "1", "counts matched at 120") + self.done("s1", "--pass", "2", "empty name exported ok") self.assertEqual(self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export change", sid="s1")[0], 0) self.assertNotIn("starts", self.state()) self.assertEqual(judge()[1].strip(), "recorded, not timed.") # no stale start left to time it @@ -3100,6 +3106,8 @@ cli.main(["tick"]) self.assertEqual(self.tool("Agent", tool_input={"model": "glm"}), (0, "", "")) self.sisi("pick", "ordinary", sid="s1") self.assertIn("not in the models table", self.note(self.tool("Agent", tool_input={"model": "claude-3-o3ghost"}))) + self.done("s1", "--pass", "1", "counts matched at 120") + self.done("s1", "--pass", "2", "empty name exported ok") self.sisi("retro", "--no-gap", "the person accepted it and the checks all passed", *NG, sid="s1") self.assertNotIn("picked", self.state()) self.done() @@ -4741,10 +4749,10 @@ cli.main(["tick"]) def test_the_product_stays_small(self): code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py"))) - self.assertLessEqual(code, 3230, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 3264, "sisi is two loops. If it needs more than this, find the simpler shape.") rulebook = self.read(REPO, "canon", "core.md") self.assertLess(len(rulebook.splitlines()), 144) - self.assertLessEqual(len(rulebook), 11269) + self.assertLessEqual(len(rulebook), 11778) if __name__ == "__main__": diff --git a/tests/test_models_research.py b/tests/test_models_research.py index a8bf4e4..a61a917 100644 --- a/tests/test_models_research.py +++ b/tests/test_models_research.py @@ -126,6 +126,44 @@ class ModelsResearch(unittest.TestCase): other = twin.replace("| routine |", "| ordinary |") # the same provider in another class is fine self.assertEqual(self.record(HEAD + GO + other + FALL)[0], 0) + def test_brief_and_rulebook_say_a_tie_never_goes_to_the_dearer_model(self): + text = lambda s: " ".join(s.split()) + rulebook = text(models.store.read(os.path.join(models.store.ROOT, "canon", "core.md"))) + brief = text(self.in_process(models.research_brief)[0]) + for where in (brief, rulebook): + for want in ("cheapest among models within one point of the class's best score", "tie never goes to the dearer model", + "dearest tier is its own class, deep", "never banned and never a default for hard, ordinary or routine"): + self.assertIn(want, where) + self.assertIn("never inherited as hard or deep", rulebook) + self.assertIn("routine, ordinary, hard, deep", brief) + + def test_deep_class_records_picks_falls_back_to_hard_and_tracks_outcomes(self): + from sisi import plan + deep = "| fable | Anthropic | anthropic | host subagent `fable` | deep | flat | 5h: none; week: 50% sub-cap (https://example.test/c) | deepest | |\n" + opus = "| opus | Anthropic | anthropic | host subagent `opus` | hard | flat | 5h: none; week: 10x Pro (https://example.test/c) | strong | |\n" + self.assertEqual(self.record(HEAD + GO + HOST + opus + deep + FALL)[0], 0) # same provider may hold hard and deep + offered(self.data, HEAD + GO + HOST + opus + deep + FALL) + twin = deep.replace("fable", "fable2") + self.assertEqual(self.record(HEAD + GO + opus + deep + twin + FALL)[0], 1) # two deep rows for one provider refused + self.assertEqual(self.record(HEAD + GO + deep.replace("| deep |", "| hard, deep |") + FALL)[0], 1) # multi-class refused + rc, out = self.in_process(models.pick, ["deep"], self.tmp, lambda: 0.0) + self.assertEqual((rc, "worker: fable" in out, "fallback:" in out), (0, True, False), out) + rc, out = self.in_process(models.pick, ["deep", "--not", "fable"], self.tmp, lambda: 0.0) + self.assertEqual((rc, "Choose again from hard." in out), (1, True), out) + rc, out = self.in_process(models.judge, ["fable", "good", "solved the hard root cause"], self.tmp) + self.assertEqual(rc, 0, out) + import json + rec = json.loads(self.read(self.data, "outcomes.jsonl").splitlines()[-1]) + self.assertEqual(rec.get("class"), "deep") + self.assertIn("deep 1/1 good", self.in_process(plan.record_line)[0]) + # with no deep row in the table, `sisi pick deep` falls back to hard + self.assertEqual(self.record(HEAD + GO + HOST + opus + FALL)[0], 0) + offered(self.data, HEAD + GO + HOST + opus + FALL) + rc, out = self.in_process(models.pick, ["deep"], self.tmp, lambda: 0.0) + self.assertEqual((rc, out.splitlines()[0].startswith("worker: opus"), "no deep worker" in out), (0, True, True), out) + # judge record's saved class still counts in record_line even after fable left the table + self.assertIn("deep 1/1 good", self.in_process(plan.record_line)[0]) + def test_brief_asks_for_provider_efficiency_and_one_row_per_provider_class(self): rc, brief = self.in_process(models.run, ["research"]) self.assertEqual(rc, 0) diff --git a/tests/test_plan.py b/tests/test_plan.py index 87ffe93..afaa31e 100644 --- a/tests/test_plan.py +++ b/tests/test_plan.py @@ -24,6 +24,7 @@ class Plan(unittest.TestCase): setUp, project, sisi, hook, tool, done, table, state, read, write, in_process = ( test_core.Core.setUp, test_core.Core.project, test_core.Core.sisi, test_core.Core.hook, test_core.Core.tool, test_core.Core.done, test_core.Core.table, test_core.Core.state, test_core.Core.read, test_core.Core.write, test_core.Core.in_process) + records = test_core.Core.records def record(self, text, sid="s1"): return self.sisi("plan", "--record", self.write(os.path.join(self.tmp, "plan.md"), text), sid=sid) @@ -124,13 +125,13 @@ class Plan(unittest.TestCase): self.assertIn("wave 1: a (routine), b (ordinary)", out) def test_record_line_counts_the_last_twenty_judged_per_class(self): - self.table(TABLE) + self.table(TABLE + "| delta | host subagent model `delta` | deep | per use | deepest | |\n") line = lambda w, v: json.dumps({"ts": "2026-11-20T10:00:00", "worker": w, "verdict": v, "why": "did it fine"}) self.write(os.path.join(self.data, "outcomes.jsonl"), "\n".join( - [line("alpha", "bad")] * 5 + [line("alpha", "good")] * 18 + [line("beta", "bad")] + [line("gamma", "out")] + [line("nobody", "good")]) + "\n") + [line("alpha", "bad")] * 5 + [line("alpha", "good")] * 18 + [line("beta", "bad")] + [line("gamma", "out")] + [line("delta", "good")] + [line("nobody", "good")]) + "\n") from sisi import plan self.assertEqual(self.in_process(plan.record_line)[0], - "record (last 20 judged per class): routine 18/20 good, ordinary 0/1 good, hard none judged yet") + "record (last 20 judged per class): routine 18/20 good, ordinary 0/1 good, hard none judged yet, deep 1/1 good") def test_rerecording_keeps_the_state_of_unchanged_nodes(self): self.ready_plan() @@ -160,7 +161,8 @@ class Plan(unittest.TestCase): self.assertEqual(rc, 0, out) self.assertRegex(out.splitlines()[0], r"^sisi chore: plan [0-9a-f]{8}$") for want in ("export every row without losing any", "1. row counts match", "| node | class | needs | branch | files | check | why |", - "Class by total cost", "routine nodes whenever their", "record (last 20 judged per class)", + "routine, ordinary, hard, deep, or lead", "Class by total cost", "routine nodes whenever their", + "deep (the dearest tier)", "never inherited as hard or deep", "record (last 20 judged per class)", "prefer many small nodes", "quick test of its own change", "merges its needs, runs them once and fixes what broke"): self.assertIn(want, out) @@ -174,10 +176,98 @@ class Plan(unittest.TestCase): self.assertEqual(self.sisi("plan", "--done", n, "test %s ok" % n, sid="s1")[0], 0) self.assertIn("needs done: a on p-a (test a ok), b on p-b (test b ok)", self.pick("merge")) - def test_a_retro_clears_the_plan(self): + def test_a_retro_clears_the_plan_of_finished_work(self): self.ready_plan() + for n in (1, 2): + self.done("s1", "--pass", str(n), "seen in the test output") self.assertEqual(self.sisi("retro", "--no-gap", "every check passed with the tests shown", *test_core.NG, sid="s1")[0], 0) self.assertNotIn("plan", self.state()) + self.assertNotIn("done", self.state()) + self.assertIn("unit", self.records()[-1]) + + # a retro recorded while the work is still open + + def running_a(self): + self.ready_plan() + self.pick("a") + self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {}) + self.assertEqual(self.sisi("plan", "--done", "b", "done by hand and tested", sid="s1")[0], 0) + + def gap(self): + rc, out, _ = self.sisi("retro", "--gap", "the worker ran out of time", "--cause", "the brief was far too wide", "--improve", "Split a wide brief into two nodes", + "--term", "time", "--problem", "briefs too wide", "--level", "core", sid="s1") + self.assertEqual(rc, 0, out) + return out + + def test_a_retro_while_work_is_open_keeps_done_and_the_plan(self): # fault 34 + self.running_a() + self.assertEqual(self.sisi("learn", "--level", "user", "Always split a wide brief", sid="s1")[0], 0) + out = self.gap() + self.assertIn("the work stays open (checks 1, 2 have no verdict; nodes a are running)", out) + self.assertNotIn("no done recorded", self.sisi("done", sid="s1")[1]) + self.assertIn("a [routine] running (alpha", self.sisi("plan", sid="s1")[1]) + self.assertEqual(self.nodes(), {"a": "running", "b": "done"}) + self.assertEqual((self.records()[-1]["open"], "unit" in self.records()[-1]), (True, False)) + self.assertEqual(self.sisi("judge", "alpha", "good", "did the work well", sid="s1")[0], 0) # the running job is still tracked + self.assertEqual(self.nodes(), {"a": "done", "b": "done"}) + + def test_node_states_survive_a_retro_and_rerecording_done_and_the_plan(self): # fault 29 + self.running_a() + self.gap() + self.done() + self.assertEqual(self.record(PLAN)[0], 0) + self.assertEqual(self.nodes(), {"a": "running", "b": "done"}) + self.assertNotIn("nodes a", self.hook("gate")[1]) + + def test_rerecording_done_alone_keeps_every_node_state(self): + self.running_a() + self.done() + self.assertEqual(self.nodes(), {"a": "running", "b": "done"}) + + def test_passed_checks_do_not_close_work_while_a_node_runs(self): + self.running_a() + for n in (1, 2): + self.done("s1", "--pass", str(n), "seen in the test output") + self.hook("gate") + self.assertEqual(self.nodes(), {"a": "running", "b": "done"}) + self.assertIn("nodes a are running", self.gap()) + self.hook("gate") + self.assertEqual(self.nodes(), {"a": "running", "b": "done"}) + self.assertEqual(len(self.records()), 1) + + def test_midwork_retro_keeps_changed_state_until_work_closes(self): + self.running_a() + self.tool("Edit") + self.gap() + self.assertTrue(self.state().get("changed")) + self.assertEqual(self.sisi("judge", "alpha", "good", "finished node a cleanly", sid="s1")[0], 0) + self.assertEqual(self.sisi("plan", "--done", "c", "done by hand and tested", sid="s1")[0], 0) + for n in (1, 2): + self.done("s1", "--pass", str(n), "seen in the test output") + self.assertIn("no retro yet", self.hook("gate")[1]) + + def test_deep_plan_node_picks_deep_or_falls_back_to_hard(self): + deep_plan = COLS + ( + "| d | deep | - | p-d | sisi/d.py | test d passes | novel central mechanism |\n" + "| join | lead | d | - | - | full suite passes | the lead merges |\n") + self.ready_plan(text=deep_plan) + # no deep row in TABLE -> falls back to hard (gamma) + out = self.pick("d") + self.assertIn("worker: gamma", out) + self.assertIn("no deep worker", out) + self.assertIn("sisi node: d", out) + self.assertEqual(self.decision(self.agent("gamma", self.pick_header("d"))), {}) + self.assertEqual(self.nodes(), {"d": "running"}) + self.assertEqual(self.sisi("judge", "gamma", "bad", "try again with deep model", sid="s1")[0], 0) + # add a deep row -> pick --node d picks delta directly + self.table(TABLE + "| delta | host subagent model `delta` | deep | per use | deepest | |\n") + out = self.pick("d") + self.assertIn("worker: delta", out) + self.assertNotIn("no deep worker", out) + self.assertIn("sisi node: d", out) + self.assertEqual(self.decision(self.agent("delta", self.pick_header("d"))), {}) + self.assertEqual(self.sisi("judge", "delta", "good", "designed the central mechanism cleanly", sid="s1")[0], 0) + self.assertEqual(self.nodes(), {"d": "done"}) # pick --node