diff --git a/README.md b/README.md index 427f760..9145d80 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,15 @@ organizes the rules. **Delegation.** The lead agent is told to delegate everything, and is stopped when it does the work itself. It routes by a models table: which workers you have, what each is good at, what it costs. A research worker -rebuilds that table when it gets old, and every judged delegation feeds the next research. +rebuilds that table when it gets old, and every judged delegation feeds the next research. The lead does not +choose the worker: `sisi pick CLASS` spins a wheel over the workers of that class (weighted by table order), +and a delegation to a worker the wheel did not give is refused. One pick, one delegation. + +**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 is refused 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. Each record in `retro.jsonl` carries the numbers +(minutes, messages, tool calls, delegations, checks) and `sisi retro` shows their trend. ## Install @@ -26,6 +34,9 @@ Python 3 standard library only. `sisi rollback` goes back to the release before. | Command | What it is for | |---|---| +| `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 pick routine\|ordinary\|hard [--review-of WORKER] [--not WORKER]` | The wheel gives one worker; a review goes to a different maker | | `sisi retro` | Print what happened in this piece of work, to set against the objective | | `sisi retro --gap … --cause … --improve … [--scope user]` | Record the gap; the improvement is a rule at once | | `sisi retro --no-gap …` / `--later …` | Nothing fell short; or the work is not finished yet | @@ -45,4 +56,8 @@ Python 3 standard library only. `sisi rollback` goes back to the release before. - **The rulebook every session loads** is generated from the two: `canon/core.md`, then your learned rules. Settings go under `"core"` in `config.json` in your store: `gate`, `meter`, `direct_calls` (8), -`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7). +`direct_extension` (8), `rules_lines` (30), `rules_chars` (4000), `organize_after` (8), `research_days` (7), +`shell_workers` (false). Workers are started with the host's own delegation tool, so by default a shell command +that starts a worker (`opencode`, `muse`, `agy`: the first word of a command line in your models table) is +refused. Set `"shell_workers": true` to allow it: it is then free on the meter, and needs a pick like any +delegation, and `sisi pick` prints the command line. diff --git a/canon/core.md b/canon/core.md index 32082aa..0320428 100644 --- a/canon/core.md +++ b/canon/core.md @@ -5,20 +5,28 @@ you own getting it right. These rules give direction; work out the tactics yours ## The objective -In this order: stay inside the lines (rule 7); meet the acceptance criteria with evidence that -fits the risk; solve the person's actual problem; spend as little of their time, money and -attention as you can; and leave the organization better at the next piece of work. +Maximize the long-term, verified value of what you deliver to the person, per unit of elapsed +time, compute and tool cost, and their attention; and get better at it with every piece of work. +Two things are never traded: the lines in rule 7, and done: work that misses an agreed check is +not finished, however fast or cheap. Among results that pass, prefer the one that best gives the +person what they want, including what the request implies and what they will need next, and that +stays cheap to live with and change. Then cut time, cost and attention. Judge by outcomes, never +by activity. -## 1. Own the outcome +## 1. Know what they want -Read a request as the outcome wanted, not as a string to execute. Work out what done means from -the project, its conventions and what the person has said before, including what the request -implies and what they will foreseeably need next. Do not expand the scope on speculation. Find -out before you ask. Assume when a wrong guess is cheap to undo, and say what you assumed. Ask -when interpretations differ materially, when the action is hard to undo, or when the answer -cannot be found: few questions, each with options and your recommendation, through the tool's -question dialog. If a better way than the one requested would serve the goal, say so and let -them decide. Treat feedback as a narrow amendment: change what it covers and re-check the rest. +A request is evidence of what the person wants, not a string to execute. Before working, think +one level above it: what are they trying to achieve, what does that imply, and what will they +need next? Decide each foreseeable need on purpose: build it now, leave room for it, record it as +a follow-up, or drop it. That is not a licence to add features: build the final solution to the +real problem and nothing speculative. Then record it with `sisi done`: the goal in their words, +the checks that decide success, each one able to fail, and what comes next. Nothing starts until +it is recorded. Find out before you ask. Assume when a wrong guess is cheap to undo, and say what +you assumed. Ask when interpretations differ materially, when the action is hard to undo, or when +the answer cannot be found: few questions, each with options and your recommendation, through the +tool's question dialog. If a better way than the one requested would serve the goal, say so and +let them decide. Treat feedback as a narrow amendment: change what it covers and re-check the +rest. ## 2. Keep it simple @@ -30,8 +38,9 @@ the person pays every day afterwards. ## 3. Define done, then prove it Before building anything above trivial, state what done means: the goal in the person's words, -and the checks that decide success, each one able to fail. Size the care by what could go wrong, -not by the number of lines: a wording change needs a look at the diff; stored data, +and the checks that decide success, each one able to fail. Before you finish, give every check a +verdict with its evidence: `sisi done --pass N` or `--fail N`. Size the care by what could go +wrong, not by the number of lines: a wording change needs a look at the diff; stored data, authorization and anything hard to reverse need a way back and evidence from someone other than the author. Use the least evidence that is enough for the way the thing can fail, and watch a new test fail once. Report exactly what was shown: passed, failed, skipped, not run. Never let @@ -50,9 +59,11 @@ a weaker check. You own the outcome; workers do the work. Delegate reading, searching, building, testing, research and first reviews, and keep your own context for intent, design, judgement and the final call. Do something yourself only when briefing it would cost more than doing it. -`sisi models` lists the workers you have, what each is good at and what it costs: give each task -to the least expensive one that is capable enough, counting rework as cost, and always to the -newest version of a model. When the choice is not obvious, have a cheap worker route it. Run +`sisi models` lists the workers you have. Decide the class of the task (routine, ordinary, hard), +counting rework as cost, then `sisi pick CLASS` spins the wheel over the workers of that class and +gives you one: use it. A review always goes to a different maker than the author: +`sisi pick CLASS --review-of WORKER`. Start the worker with the host's own delegation tool; do not +shell out to a worker's command line. When the choice is not obvious, have a cheap worker route it. Run independent work in parallel. 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. Its report is evidence for you to judge, not a fact to pass on; record how it went with `sisi judge`. When a worker fails diff --git a/sisi/cli.py b/sisi/cli.py index 7b1b635..0dd8337 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -3,6 +3,12 @@ import os, sys, time HELP = """sisi: a self-improvement loop for AI coding agents. +Before and after the work + sisi done --goal G --check C [--check C ...] --next N + 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 + 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 [--scope user] @@ -19,6 +25,8 @@ Delegation 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 pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] + the wheel gives you one worker of that class; one pick, one delegation sisi judge WORKER good|bad WHY how a delegation went sisi direct REASON allow yourself more direct tool calls this turn, with the reason @@ -30,7 +38,7 @@ Hooks (the agent tool calls these): sisi tick | prompt | watch | gate Your rules, models table and retro log live in ~/.local/share/sisi, a git repository. Settings: "core" in its config.json (gate, meter, direct_calls, direct_extension, rules_lines, rules_chars, organize_after, -research_days).""" +research_days, shell_workers).""" def main(argv): @@ -49,6 +57,10 @@ def main(argv): return retro.run(args) if cmd == "rules": return rules.run(args) + if cmd == "done": + return retro.done(args) + if cmd == "pick": + return models.pick(args) if cmd == "learn": return rules.learn(args) if cmd == "models": diff --git a/sisi/hooks.py b/sisi/hooks.py index 04a2edf..14ff746 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -18,6 +18,15 @@ GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi "happened. Set that against the objective and record the gap and the improvement, or that there was " "none. If the work is not finished and you are only pausing (for the person, for background work), say " "so instead: `sisi retro --later \"\"`.") +NODONE = ("sisi: nothing starts before done is recorded. Work out what the person wants and what they will need " + "next, then: sisi done --goal \"\" --check \"\" [--check ...] " + "--next \"\"\n") +NOPICK = ("sisi: this delegation goes to a worker the wheel did not give you. sisi pick routine|ordinary|hard gives " + "you one for this task (--review-of WORKER for a review, --not WORKER if one is out); one pick, one " + "delegation.\n") +NOSHELL = "sisi: do not shell out to a worker; start it with the host's delegation tool.\n" +OPEN = ("sisi: these checks have no verdict yet: %s. Give each one: sisi done --pass N \"\" or --fail N " + "\"\". If the work is only pausing: sisi retro --later \"\".") def payload(): @@ -79,16 +88,30 @@ def watch(p): sid, tool = p.get("session_id"), str(p.get("tool_name") or "") if p.get("hook_event_name") not in (None, "PreToolUse") or not sid or subagent(p): return 0 - command = str((p.get("tool_input") or {}).get("command") or "") - cfg = store.config() + ti = p.get("tool_input") if isinstance(p.get("tool_input"), dict) else {} + command, cfg = str(ti.get("command") or ""), store.config() with store.session(sid) as s: _begin(s, p.get("cwd") or os.getcwd()) if s.get("worker"): return 0 - if delegation(tool): + if tool == "Bash" and OWN.fullmatch(command): + return 0 + shell = tool == "Bash" and models.is_call(command) + if shell and not cfg["shell_workers"]: + sys.stderr.write(NOSHELL) + return 2 + if (delegation(tool) or shell or tool in EDITS) and not s.get("done"): + sys.stderr.write(NODONE) + return 2 + if delegation(tool) or shell: + target = ti.get("target") if isinstance(ti.get("target"), dict) else {} + text = command if shell else str((target if tool.endswith("delegate_task") else ti).get("model") or "") + if tool != "Workflow" and store.read(models.table()) and not models.claim(s, text): + sys.stderr.write(NOPICK) + return 2 s["delegations_since"] = s.get("delegations_since", 0) + 1 return 0 - if tool not in DIRECT or (tool == "Bash" and OWN.fullmatch(command)): + if tool not in DIRECT: return 0 limit = cfg["direct_calls"] + s.get("extra", 0) if cfg["meter"] and s.get("direct", 0) >= limit: @@ -121,9 +144,19 @@ def gate(p, for_subagent=False): return 0 with store.session(sid) as s: _begin(s, cwd) + if s.get("worker"): + return 0 + checks = (s.get("done") or {}).get("checks") or [] + unsaid = ["%d. %s" % (i, c["text"]) for i, c in enumerate(checks, 1) if not c["verdict"]] + failed = any(c["verdict"] == "fail" for c in checks) worked = s.get("changed") or store.snapshot(cwd) != s.get("snapshot") - if s.get("worker") or not worked or s.get("blocks", 0) >= 2: + if checks and not unsaid and not failed and not worked: + from . import retro + retro.record(s, cwd, {}) # every check passed and nothing changed: the work closes itself + return 0 + reason = OPEN % "; ".join(unsaid) if unsaid and not s.get("later") else GATE if worked or failed else "" + if not reason or s.get("blocks", 0) >= 2: return 0 s["blocks"] = s.get("blocks", 0) + 1 - print(json.dumps({"decision": "block", "reason": GATE})) + print(json.dumps({"decision": "block", "reason": reason})) return 0 diff --git a/sisi/models.py b/sisi/models.py index ffa170f..34bf258 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -2,7 +2,7 @@ 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, os, time +import json, os, re, time from . import rules, store RESEARCH = """You are a worker. Do this task yourself; do not delegate it further. @@ -21,8 +21,10 @@ the table an engineering lead will route by. Answer with exactly this and nothing else. First a markdown table of at most 40 rows, the cheapest capable worker first within each level, with these columns: | worker | how to call it | use for | cost | good at, bad at | notes | -"use for" is one or more of: routine, ordinary, hard. "how to call it" is exact: the host's subagent model -name, or the full command line with where the brief goes. +"use for" is one or more of: routine, ordinary, hard. "how to call it" is exact: where the host has its own +tool for starting workers on other harnesses (T3 Code's delegate_task), the provider and the model id to give +it; the host's subagent model name where it has subagents; the full command line with where the brief +goes only for a worker the host's tool cannot reach. Then one line starting "Fallback order:" that says who takes over when a worker is out, level by level. === The table now === @@ -59,6 +61,98 @@ def stale(): return "" +def rows(text): + """The table's worker rows, each a list of six cells: worker, how to call it, use for, cost, good, notes.""" + out = [] + for line in text.splitlines(): + c = [x.strip() for x in line.strip().strip("|").split("|")] if line.startswith("|") else [] + if len(c) >= 5 and c[0].lower() != "worker" and not set(c[0]) <= set("-: "): + out.append((c + [""] * 6)[:6]) + return out + + +def short(cell): + w = str(cell).split() + return w[0].lower() if w else "" + + +def maker(name, call=""): + """Who made a worker: claude for the host's subagents, else the leading letters of the model's own name.""" + m = re.match(r"[a-z]+", name.rsplit("/", 1)[-1]) + return "claude" if "host subagent" in call.lower() else m.group() if m else name + + +def command(row): + """A row that is called by a shell command line (it has in it, and is not a host subagent).""" + return "" in row[1] and "host subagent" not in row[1].lower() + + +def is_call(command_line): + """Does this shell command start one of the workers in the table?""" + words = command_line.split() + return bool(words) and os.path.basename(words[0]) in {r[1].replace("`", "").split()[0] for r in rows(store.read(table())) if command(r)} + + +def claim(s, text): + """Spend the pick that this delegation's model text names; False when none of the picks fits.""" + for name in s.get("picked") or []: + if name in text.lower() or name.rsplit("/", 1)[-1] in text.lower(): + s["picked"].remove(name) + s.setdefault("workers_since", []).append(name) + return True + return False + + +def choose(text, cls, skip=(), review=None, rand=None, today=None): + """One worker of this class, by a wheel weighted by table order (the first of n has weight n, the last 1).""" + table_rows, today = rows(text), today or time.strftime("%Y-%m-%d") + bad = None + if review: + bad = next((maker(short(r[0]), r[1]) for r in table_rows if short(r[0]) == short(review)), maker(short(review))) + left = [r for r in table_rows if cls in r[2].lower() and short(r[0]) not in skip and maker(short(r[0]), r[1]) != bad + and not any(d > today for d in re.findall(r"out until (\d{4}-\d{2}-\d{2})", " ".join(r).lower()))] + if not left: + return None + if rand is None: + import random + rand = random.random + x = rand() * len(left) * (len(left) + 1) / 2 + for weight, r in zip(range(len(left), 0, -1), left): + x -= weight + if x < 0: + return r + return left[-1] + + +def pick(args, cwd=None, rand=None): + """`sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...]`: the wheel gives one worker.""" + cls, skip, review, i = (args[0] if args and args[0] in ("routine", "ordinary", "hard") else None), set(), 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] + else: + cls = None + i += 2 + if not cls: + print("usage: sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...]") + return 1 + r = choose(store.read(table()), cls, skip, review, rand) + if not r: + print("sisi pick: every worker of that class is out or excluded.") + return 1 + sid = store.current_session(cwd) + if sid: + with store.session(sid) as s: + s.setdefault("picked", []).append(short(r[0])) + 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 store.config()["shell_workers"] or not command(r): + print("how to call it: " + r[1]) + print("good at, bad at: %s\nnotes: %s" % (r[4], r[5])) + return 0 + + def outcomes(n): out = [] for line in store.read(store.data("outcomes.jsonl")).splitlines()[-n:]: diff --git a/sisi/retro.py b/sisi/retro.py index 8d5f9cc..f978161 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -3,6 +3,9 @@ prevented it. That instruction becomes a learned rule at once.""" import json, os, re, time from . import rules, store +DONE_USAGE = """usage: sisi done --goal "" --check "" [--check ...] \\ + --next "" + sisi done --pass N "" | --fail N "" sisi done: show it""" FLAGS = ("--gap", "--cause", "--improve", "--no-gap", "--later", "--scope") SECRET = re.compile(r"\b(sk-[a-z0-9_-]{16,}|gh[pousr]_[a-z0-9]{20,}|xox[abp]-[a-z0-9-]{10,}|akia[0-9a-z]{16}|[a-f0-9]{40,})|\b(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S+", re.I) USAGE = """Record one of these: @@ -18,21 +21,52 @@ def clean(text): return SECRET.sub("", " ".join(str(text or "").split())) -def facts(state, cwd): +def counts(state, cwd): since = state.get("retro_at") or state.get("started") or time.time() - commits = store.git(["log", "--oneline", "--since=@%d" % since], cwd)[1].splitlines() - dirty = store.git(["status", "--porcelain"], cwd)[1].splitlines() - out = [" time: %d minutes since %s" % ((time.time() - since) / 60, - "the last retro" if state.get("retro_at") else "the session began"), + checks = (state.get("done") or {}).get("checks") or [] + return {"minutes": int((time.time() - since) / 60), "messages": state.get("prompts_since", 0), + "direct": state.get("direct_since", 0), "delegations": state.get("delegations_since", 0), + "commits": len(store.git(["log", "--oneline", "--since=@%d" % since], cwd)[1].splitlines()), + "checks_pass": sum(c["verdict"] == "pass" for c in checks), "checks_fail": sum(c["verdict"] == "fail" for c in checks)} + + +def facts(state, cwd): + n, dirty = counts(state, cwd), store.git(["status", "--porcelain"], cwd)[1].splitlines() + out = [" time: %d minutes since %s" % (n["minutes"], "the last retro" if state.get("retro_at") else "the session began"), " the person wrote %d message(s) in that time: read them again. Was any a correction, or something " - "they had to say twice?" % state.get("prompts_since", 0), - " changed: %d commit(s), %d file(s) uncommitted" % (len(commits), len(dirty)), - " you made %d tool call(s) yourself and %d delegation(s)" % (state.get("direct_since", 0), - state.get("delegations_since", 0))] + "they had to say twice?" % n["messages"], + " changed: %d commit(s), %d file(s) uncommitted" % (n["commits"], len(dirty)), + " you made %d tool call(s) yourself and %d delegation(s)" % (n["direct"], n["delegations"])] out += [' you extended your own direct work: "%s"' % r for r in state.get("reasons_since") or []] return out +def show(d): + mark = lambda c: "[%s: %s]" % (c["verdict"], c["evidence"]) if c["verdict"] else "[no verdict yet]" + return (["done: " + d["goal"]] + [" %d. %s %s" % (i, c["text"], mark(c)) for i, c in enumerate(d["checks"], 1)] + + ["next: " + d["next"]]) + + +def trend(): + """The measured trend over the records that carry numbers: the last 10 pieces of work and the 10 before.""" + units = [] + for line in store.read(store.data("retro.jsonl")).splitlines(): + try: + if isinstance(json.loads(line).get("unit"), dict): + units.append(json.loads(line)) + except (ValueError, AttributeError): + pass + median = lambda v: (lambda s: (s[(len(s) - 1) // 2] + s[len(s) // 2]) / 2.0)(sorted(v)) + out = [] + for label, group in (("last", units[-10:]), ("before", units[-20:-10])): + if group: + u = [r["unit"] for r in group] + out.append(" %s %d: median %g min, median %g messages, %d checks failed, %d with a gap" % ( + label, len(group), median([x.get("minutes", 0) for x in u]), median([x.get("messages", 0) for x in u]), + sum(x.get("checks_fail", 0) for x in u), sum("gap" in r for r in group))) + return ["measured (pieces of work with numbers):"] + out if len(units) >= 2 else [] + + def report(sid, cwd): state = {} if sid: @@ -40,10 +74,61 @@ def report(sid, cwd): state = dict(s) print("sisi retro: what happened in this piece of work.") print("\n".join(facts(state, cwd))) + if state.get("done"): + print("\n" + "\n".join(show(state["done"]))) print("\nThe objective: %s" % rules.objective()) print("\nSet what happened against the objective, term by term. Where did the work fall short, why, and what " "instruction would have prevented it? Name the root cause; general advice is not an improvement.\n") print(USAGE) + if trend(): + print("\n" + "\n".join(trend())) + + +def record(s, cwd, opt): + """Append one record for the piece of work in this session state, and begin the next one.""" + d, now = s.get("done") or {}, time.time() + entry = dict(opt, ts=time.strftime("%Y-%m-%dT%H:%M:%S"), project=os.path.basename(store.project_root(cwd)), + unit=counts(s, cwd), goal=d.get("goal", ""), workers=s.get("workers_since", [])) + if d: + entry["done"] = d + log = store.data("retro.jsonl") + store.append(log, json.dumps(entry, sort_keys=True)) + store.commit("retro recorded", log) + s["snapshot"], s["changed"], s["blocks"], s["retro_at"] = store.snapshot(cwd), False, 0, now + for key in ("prompts_since", "direct_since", "delegations_since", "reasons_since", "workers_since", "done", "later"): + s.pop(key, None) + + +def done(args, cwd=None): + """`sisi done`: define done before the work (goal, checks, what comes next), then give every check a verdict.""" + sid, opt, verdict, i = store.current_session(cwd or os.getcwd()), {}, None, 0 + while i < len(args): + if args[i] in ("--goal", "--next", "--check") and i + 1 < len(args): + opt.setdefault(args[i][2:], []).append(clean(args[i + 1])) + i += 2 + elif args[i] in ("--pass", "--fail") and i + 2 < len(args) and not verdict: + verdict, i = (args[i][2:], args[i + 1], clean(args[i + 2])), i + 3 + else: + i = len(args) + 1 + words = lambda key, least: all(len(x.split()) >= least for x in opt[key]) + new = bool(opt) and not verdict and set(opt) == {"goal", "next", "check"} and len(opt["goal"]) == len(opt["next"]) == 1 \ + and words("goal", 5) and words("next", 4) and words("check", 4) + if i != len(args) or not sid or not (new or (verdict and not opt) or not (opt or verdict)): + print(DONE_USAGE) + return 1 + with store.session(sid) as s: + if new: + s["done"] = {"goal": opt["goal"][0], "next": opt["next"][0], + "checks": [{"text": c, "verdict": None, "evidence": ""} for c in opt["check"]]} + elif verdict: + kind, n, why = verdict + if not (s.get("done") and n.isdigit() and 1 <= int(n) <= len(s["done"]["checks"]) and len(why.split()) >= 3): + print(DONE_USAGE) + return 1 + s["done"]["checks"][int(n) - 1].update(verdict=kind, evidence=why) + s.pop("later", None) if new or verdict else None + print("\n".join(show(s["done"])) if s.get("done") else "no done recorded yet.\n" + DONE_USAGE) + return 0 def _options(args): @@ -77,20 +162,19 @@ def run(args, cwd=None): print("sisi retro: that is not a retro yet (each part needs a real sentence; an improvement is at most " "400 characters).\n" + USAGE) return 1 - if kind != "later": - entry = dict(opt, ts=time.strftime("%Y-%m-%dT%H:%M:%S"), project=os.path.basename(store.project_root(cwd))) - if kind == "gap": - entry["scope"] = scope - log = store.data("retro.jsonl") - store.append(log, json.dumps(entry, sort_keys=True)) - store.commit("retro recorded", log) if sid: with store.session(sid) as s: - s["snapshot"], s["changed"], s["blocks"] = store.snapshot(cwd), False, 0 - if kind != "later": - s["retro_at"] = time.time() - for counter in ("prompts_since", "direct_since", "delegations_since", "reasons_since"): - s.pop(counter, None) + if kind == "no-gap" and any(c["verdict"] == "fail" for c in (s.get("done") or {}).get("checks", [])): + print("sisi retro: a failed check is a gap; record it with --gap.") + return 1 + if kind == "gap": + opt["scope"] = scope + if kind == "later": + s["snapshot"], s["changed"], s["blocks"], s["later"] = store.snapshot(cwd), False, 0, True + else: + record(s, cwd, opt) + elif kind != "later": + record({}, cwd, dict(opt, scope=scope) if kind == "gap" else opt) if kind == "gap": print("recorded. In force from the next session%s: %s" % ( " in every project" if scope == rules.USER else " in this project", rules.add(opt["improve"], scope, "retro", cwd))) diff --git a/sisi/store.py b/sisi/store.py index 0471e3d..e93f795 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -12,7 +12,7 @@ LIB = os.environ.get("SISI_LIB") or os.path.join(HOME, ".local", "lib", "sisi") # Every setting there is. The person overrides one under "core" in config.json in their store. DEFAULTS = {"gate": True, "meter": True, "direct_calls": 8, "direct_extension": 8, - "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "research_days": 7} + "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "research_days": 7, "shell_workers": False} def config(): diff --git a/tests/test_core.py b/tests/test_core.py index 726cb8f..664f07e 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -3,15 +3,43 @@ 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 models table is researched, read and kept fresh.""" -import glob, hashlib, json, os, shutil, subprocess, sys, tempfile, time, unittest +import glob, hashlib, json, os, random, shutil, subprocess, sys, tempfile, time, unittest REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GAP = ("--gap", "the export dropped rows with empty names until the person noticed", "--cause", "no check compared the row counts before and after") +HEADER = "| worker | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|\n" +GOAL = ("--goal", "export every row without losing any with empty names", "--check", "row counts match before and after the export", + "--check", "an empty name still exports as a row", "--next", "the person will want the same for imports: follow-up") +WORKERS = HEADER + ( + "| agy (Gemini) | `agy --print \"\"` | routine | free | fast | |\n" + "| zai-coding-plan/glm-5.4 | `opencode run -m zai-coding-plan/glm-5.4 \"\"` | ordinary | flat | edits | the default |\n" + "| sonnet (Sonnet 5.5) | host subagent model `sonnet` | hard | per use | everything | |\n") +FIXTURE = HEADER + ( + "| zai-coding-plan/glm-5.4 | `opencode run -m zai-coding-plan/glm-5.4 \"\"` | ordinary | flat | edits | |\n" + "| zai-coding-plan/glm-5.3-flash | `opencode run -m zai-coding-plan/glm-5.3-flash \"\"` | ordinary | flat | cheap edits | |\n" + "| muse/muse-wonder-1.0 | `muse exec --model muse-wonder-1.0 \"\"` | ordinary | flat | research | out until 2999-01-01 |\n" + "| muse/muse-ember-1.0 | `muse exec --model muse-ember-1.0 \"\"` | ordinary | flat | checks | out until 2000-01-01 |\n" + "| sonnet (Sonnet 5.5) | host subagent model `sonnet` | ordinary, hard | per use | everything | |\n" + "| opus (Opus 5.5) | host subagent model `opus` | hard | per use | hardest | |\n") + + +def tree(): + """A fingerprint of the product tree, so a test that writes into it is caught.""" + out = hashlib.sha1() + for p in sorted(glob.glob(os.path.join(REPO, "sisi", "*")) + glob.glob(os.path.join(REPO, "canon", "*"))): + if os.path.isfile(p): + with open(p, "rb") as f: + out.update(p.encode() + f.read()) + return out.hexdigest() + + class Core(unittest.TestCase): def setUp(self): + before = tree() + self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) self.tmp = tempfile.mkdtemp(prefix="sisi-test-") self.addCleanup(shutil.rmtree, self.tmp, True) self.data = os.path.join(self.tmp, "data") @@ -40,6 +68,20 @@ class Core(unittest.TestCase): def tool(self, name, sid="s1", **fields): return self.hook("watch", sid=sid, hook_event_name="PreToolUse", tool_name=name, **fields) + def done(self, sid="s1", *extra): + rc, out, _ = self.sisi("done", *(extra or GOAL), sid=sid) + self.assertEqual(rc, 0, out) + + def table(self, text): + self.write(os.path.join(self.data, "models.md"), text) if os.path.isdir(self.data) else ( + os.makedirs(self.data), self.write(os.path.join(self.data, "models.md"), text)) + + def state(self, sid="s1"): + return json.loads(self.read(self.tmp, "state", "core-sessions", sid + ".json")) + + def records(self): + return [json.loads(l) for l in self.read(self.data, "retro.jsonl").splitlines()] + def read(self, *parts): with open(os.path.join(*parts), encoding="utf-8") as f: return f.read() @@ -55,10 +97,11 @@ class Core(unittest.TestCase): self.hook("tick") self.hook("prompt", prompt="add the export") self.assertEqual(self.hook("gate")[1], "") # nothing changed: nothing is asked + self.done() self.tool("Edit") self.assertIn('"block"', self.hook("gate")[1]) # work was done: the retro is forced report = self.sisi("retro", sid="s1")[1] - self.assertIn("The objective: In this order: stay inside the lines", report) + self.assertIn("The objective: Maximize the long-term, verified value", report) self.assertIn("you made 1 tool call(s) yourself", report) rc, out, _ = self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export change", sid="s1") self.assertEqual(rc, 0, out) @@ -74,6 +117,7 @@ class Core(unittest.TestCase): def test_a_retro_needs_real_sentences_and_no_gap_needs_its_evidence(self): self.hook("tick") + self.done() self.tool("Write") for args in (["--gap", "bad"], ["--no-gap", "fine"], GAP + ("--improve", "be careful"), ["--later", "x"], GAP + ("--improve", "Compare the row counts every time", "--scope", "everyone")): @@ -85,6 +129,7 @@ class Core(unittest.TestCase): def test_later_lets_unfinished_work_pause_until_it_changes_again(self): self.hook("tick") self.hook("prompt", prompt="start") + self.done() self.tool("Write") self.assertEqual(self.sisi("retro", "--later", "the person's answer about the format", sid="s1")[0], 0) self.assertEqual(self.hook("gate")[1], "") @@ -132,6 +177,7 @@ class Core(unittest.TestCase): def test_the_lead_is_stopped_when_it_should_be_delegating(self): self.hook("tick") self.hook("prompt", prompt="build it") + self.done() for _ in range(8): self.assertEqual(self.tool("Read")[0], 0) rc, _, err = self.tool("Bash", tool_input={"command": "grep -r x ."}) @@ -184,6 +230,172 @@ class Core(unittest.TestCase): os.utime(os.path.join(self.data, "models.md"), (old, old)) self.assertIn("9 days old", self.hook("tick", sid="s3")[1]) + # done, the wheel, the numbers + + def test_nothing_starts_before_done_is_recorded(self): + self.table(WORKERS) + self.hook("tick") + self.hook("prompt", prompt="build it") + rc, _, err = self.tool("Agent", tool_input={"model": "sonnet"}) + self.assertEqual((rc, "nothing starts before done is recorded" in err), (2, True)) + self.assertEqual(self.tool("Edit")[0], 2) + self.assertEqual(self.tool("Write")[0], 2) + self.assertEqual(self.tool("Workflow")[0], 2) + self.assertEqual(self.tool("Read")[0], 0) + self.assertEqual(self.tool("Bash", tool_input={"command": "sisi done"})[0], 0) + for bad in (["--goal", "too short", "--check", "a check that can fail", "--next", "follow-up work later"], + ["--goal", "export every row without losing any", "--next", "follow-up work later"], + ["--pass", "1", "it worked"], ["--bogus"]): + self.assertEqual(self.sisi("done", *bad, sid="s1")[0], 1, bad) + rc, out, _ = self.sisi("done", *GOAL, sid="s1") + self.assertEqual(rc, 0) + self.assertIn("2. an empty name still exports as a row", out) + self.assertEqual(self.tool("Edit")[0], 0) + self.assertEqual(self.tool("Agent", tool_input={"model": "sonnet"})[0], 2) # no pick yet + self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0) + self.assertEqual(self.tool("Agent", tool_input={"model": "sonnet"})[0], 0) + self.assertEqual(self.tool("Workflow")[0], 0) # a workflow is not matched + + def test_the_gate_wants_a_verdict_for_every_check_then_closes_or_forces_the_retro(self): + self.hook("tick") + self.hook("prompt", prompt="go") + self.done() + self.tool("Edit") + out = self.hook("gate")[1] + self.assertIn("these checks have no verdict yet: 1. row counts match before and after export; 2. an empty", out.replace("the export", "export")) + self.assertIn('"block"', self.hook("gate")[1]) + self.assertEqual(self.hook("gate")[1], "") # at most two blocks, whatever the cause + self.assertEqual(self.sisi("done", "--pass", "1", "counts equal at 120 rows", sid="s1")[0], 0) + self.assertEqual(self.sisi("done", "--fail", "2", "the row was dropped", sid="s1")[0], 0) + self.assertEqual(self.sisi("done", "--pass", "3", "no such check", sid="s1")[0], 1) + self.hook("prompt", prompt="again") + self.assertIn("no retro yet", self.hook("gate")[1]) # changed and failed: the retro + self.assertEqual(self.sisi("retro", "--no-gap", "the person accepted it first time and every check passed", sid="s1")[0], 1) + self.assertEqual(self.sisi("retro", *GAP, "--improve", "Compare row counts before and after every export change", sid="s1")[0], 0) + rec = self.records()[-1] + self.assertEqual((rec["unit"]["checks_pass"], rec["unit"]["checks_fail"], rec["done"]["checks"][1]["verdict"]), (1, 1, "fail")) + self.assertIn("without losing any", rec["goal"]) + self.assertNotIn("done", self.state()) + # nothing changed and every check passed: the gate closes the piece of work itself + self.hook("prompt", prompt="and now") + self.done("s1", "--goal", "list the empty names in the export", "--check", "each empty name appears once", "--next", "nothing: a one-off report") + self.assertEqual(self.sisi("done", "--pass", "1", "listed 3 names once each", sid="s1")[0], 0) + self.assertEqual(self.hook("gate")[1], "") + self.assertEqual(len(self.records()), 2) + self.assertEqual(self.records()[-1]["unit"]["checks_pass"], 1) + self.assertNotIn("gap", self.records()[-1]) + self.assertNotIn("done", self.state()) + self.assertEqual(self.hook("gate")[1], "") + self.assertEqual(len(self.records()), 2) # closed once + + def test_the_wheel_gives_only_what_is_in_and_follows_table_order(self): + sys.path.insert(0, REPO) + from sisi import models + name = lambda r: r[0].split()[0].lower() + for _ in range(300): + self.assertNotIn("muse-wonder", name(models.choose(FIXTURE, "ordinary", rand=random.random))) # out until 2999 + self.assertNotEqual(name(models.choose(FIXTURE, "ordinary", skip=["zai-coding-plan/glm-5.4"], rand=random.random)), "zai-coding-plan/glm-5.4") + self.assertNotIn("glm", name(models.choose(FIXTURE, "ordinary", review="zai-coding-plan/glm-5.4", rand=random.random))) + self.assertIsNone(models.choose(FIXTURE, "hard", review="sonnet", rand=random.random)) # both are claude + picked = lambda x: name(models.choose(FIXTURE, "ordinary", rand=lambda: x)) + # four candidates (the expired "out until" is back in), weights 4, 3, 2, 1 of 10 + self.assertEqual([picked(x) for x in (0.0, 0.39, 0.4, 0.69, 0.7, 0.89, 0.9, 0.999)], + ["zai-coding-plan/glm-5.4"] * 2 + ["zai-coding-plan/glm-5.3-flash"] * 2 + ["muse/muse-ember-1.0"] * 2 + ["sonnet"] * 2) + self.assertEqual(name(models.choose(FIXTURE, "ordinary", review="zai-coding-plan/glm-5.4", rand=lambda: 0.0)), "muse/muse-ember-1.0") + self.assertIsNone(models.choose(FIXTURE, "routine", rand=lambda: 0.0)) + self.assertEqual(models.maker("agy", ""), "agy") + self.assertEqual(models.maker("opencode-go/gpt-6-luna", "`opencode run`"), "gpt") + self.assertEqual(models.maker("sonnet", "host subagent model `sonnet`"), "claude") + + def test_pick_prints_the_worker_and_remembers_it(self): + self.table(FIXTURE) + self.hook("tick") + rc, out, _ = self.sisi("pick", "hard", "--not", "opus", sid="s1") + self.assertEqual(rc, 0) + self.assertIn("sonnet", out) + self.assertIn("start it with the host's delegation tool", out) + self.assertEqual(self.state()["picked"], ["sonnet"]) + rc, out, _ = self.sisi("pick", "hard", "--not", "opus", "--not", "sonnet", sid="s1") + self.assertEqual((rc, "out or excluded" in out), (1, True)) + self.assertEqual(self.sisi("pick", "easy")[0], 1) + self.assertEqual(self.sisi("pick")[0], 1) + + def test_a_delegation_needs_a_pick_and_one_pick_buys_one_delegation(self): + self.table(WORKERS) + self.hook("tick") + self.hook("prompt", prompt="go") + self.done() + self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0) + self.assertEqual(self.tool("Agent", tool_input={"model": "sonnet", "prompt": "use agy"})[0], 0) + rc, _, err = self.tool("Agent", tool_input={"model": "sonnet"}) + self.assertEqual((rc, "the wheel did not give you" in err), (2, True)) # the pick is spent + self.assertEqual(self.tool("Agent", tool_input={"prompt": "no model"})[0], 2) + self.assertEqual(self.sisi("pick", "ordinary", sid="s1")[0], 0) + self.assertEqual(self.tool("Agent", tool_input={"model": "sonnet"})[0], 2) # a different worker than picked + self.assertEqual(self.tool("mcp__t3__delegate_task", tool_input={"target": {"model": "ZAI-coding-plan/GLM-5.4"}})[0], 0) + self.assertEqual(self.tool("mcp__t3__delegate_task", tool_input={"target": {"model": "zai-coding-plan/glm-5.4"}})[0], 2) + self.assertEqual(self.tool("Bash", tool_input={"command": "ls"})[0], 0) # not a worker command + # no table: nothing about picks is enforced + os.remove(os.path.join(self.data, "models.md")) + self.assertEqual(self.tool("Agent", tool_input={"model": "sonnet"})[0], 0) + + def test_a_worker_is_not_started_from_the_shell_unless_the_person_allows_it(self): + self.table(WORKERS) + self.hook("tick") + self.hook("prompt", prompt="go") + self.done() + shell = {"command": 'opencode run -m zai-coding-plan/glm-5.4 "x"'} + rc, out, _ = self.sisi("pick", "ordinary", sid="s1") + self.assertIn("zai-coding-plan/glm-5.4", out) + self.assertNotIn("opencode run", out) # no command line by default + rc, _, err = self.tool("Bash", tool_input=shell) # denied even with a pick + self.assertEqual((rc, "do not shell out to a worker" in err), (2, True)) + self.assertEqual(self.tool("mcp__t3__delegate_task", tool_input={"target": {"model": "zai-coding-plan/glm-5.4"}})[0], 0) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"shell_workers": True}})) + self.assertIn("opencode run -m zai-coding-plan/glm-5.4", self.sisi("pick", "ordinary", sid="s1")[1]) + self.assertEqual(self.tool("Bash", tool_input={"command": 'opencode run -m other/model "x"'})[0], 2) # needs the pick + self.assertEqual(self.tool("Bash", tool_input=shell)[0], 0) + self.assertEqual(self.tool("Bash", tool_input=shell)[0], 2) # one pick, one delegation + s = self.state() + self.assertEqual((s.get("direct", 0), s["delegations_since"]), (0, 2)) # free on the meter, counted + + def test_a_worker_is_never_asked_for_done_or_a_pick(self): + self.table(WORKERS) + self.hook("tick", sid="w") + self.hook("prompt", sid="w", prompt="You are a worker. Do this task yourself.") + for name, fields in (("Edit", {}), ("Agent", {}), ("Workflow", {}), ("mcp__t3__delegate_task", {}), + ("Bash", {"tool_input": {"command": 'opencode run -m x/y "z"'}})): + self.assertEqual(self.tool(name, sid="w", **fields)[0], 0, name) + self.assertEqual(self.hook("gate", sid="w")[1], "") + self.hook("tick") + self.hook("prompt", prompt="lead") + self.assertEqual(self.tool("Edit", agent_id="a1")[0], 0) # the host's subagent + self.assertEqual(self.tool("Agent", agent_id="a1")[0], 0) + + def test_the_retro_shows_the_done_statement_and_the_trend(self): + self.hook("tick") + self.done() + self.sisi("done", "--fail", "1", "the counts differ by two rows", sid="s1") + log = os.path.join(self.data, "retro.jsonl") + rec = lambda m, n, f, gap: json.dumps({"ts": "2026-01-01T00:00:00", "project": "p", "unit": { + "minutes": m, "messages": n, "direct": 1, "delegations": 1, "commits": 0, "checks_pass": 1, "checks_fail": f}, **({"gap": "g"} if gap else {"no-gap": "n"})}) + self.write(log, json.dumps({"ts": "2026-01-01T00:00:00", "gap": "an old record without numbers"}) + "\n" + rec(10, 2, 0, False) + "\n") + out = self.sisi("retro", sid="s1")[1] + self.assertIn("export every row without losing any", out) # the done statement + self.assertIn("[fail: the counts differ by two rows]", out) + self.assertIn("follow-up", out) + self.assertNotIn("measured", out) # one numbered record is not a trend + self.write(log, self.read(log) + "\n".join(rec(m, n, f, g) for m, n, f, g in ((20, 4, 1, True), (30, 6, 0, False), (40, 8, 2, True))) + "\n") + out = self.sisi("retro", sid="s1")[1] + self.assertIn("measured", out) + self.assertRegex(out, r"median 25 min.*median 5 messages.*3 checks failed.*2 with a gap") + + def test_the_new_objective_is_the_one_the_retro_reads(self): + sys.path.insert(0, REPO) + from sisi import rules + self.assertTrue(rules.objective().startswith("Maximize the long-term, verified value of what you deliver")) + self.assertTrue(rules.objective().endswith("Judge by outcomes, never by activity.")) + # setting up def test_install_adds_the_hooks_once_and_keeps_the_rest(self):