Files
sisi/sisi/plan.py
T
swaitsandClaude Haiku 5.5 caefb1eaa6 Gate: a turn may end while only a lead-class node is ready
The lead's own join node no longer blocks the end of turn; worker nodes
ready and undispatched still block. The lead may be waiting on its own
background job.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-12-02 10:58:14 -07:00

342 lines
20 KiB
Python

"""The plan: a dependency graph of the pieces of one piece of work, recorded before anything is handed out.
Each node says what it needs first, its own branch, the files it may change and its check; one join brings everything
back. The hooks hold the lead to it: no delegation outside the plan or out of order, no turn ending while a node is
ready and not started. The plan lives in the session state and closes with the piece of work."""
import contextlib, fnmatch, hashlib, os, re, time
from . import store
CLASSES = ("routine", "ordinary", "hard", "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)
CHORE_CMD = {"plan": "sisi plan brief", "models research": "sisi models research", "rules organize": "sisi rules organize"}
USAGE = ('usage: sisi plan | sisi plan --record FILE | sisi plan brief | sisi plan --done ID "<evidence>" | sisi plan --fail ID "<why>"\n'
" FILE holds one markdown table: | node | class | needs | branch | files | check | why | (why is optional)")
BRIEF = """sisi chore: plan
You are a worker. Do this task yourself; do not delegate it further.
Plan this piece of work as a dependency graph for an engineering lead who hands each node to a worker. Read the
code you need; change nothing.
Goal: %(goal)s
Checks that decide success:
%(checks)s
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).
- 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
time must have disjoint files.
- check: how its result is proven, a check that can fail.
- why: a few words on the class choice, e.g. "exact spec, test decides" or "design judgement, redo costly".
Shape: maximize parallelism (as many nodes in each wave as the work allows); the smallest piece that can be released
on its own comes first; reviews are nodes of their own (a review needs the node it reviews); exactly one final node,
the join, needs everything and brings it back together.
Class by total cost: the lead's cost to write a fully specified brief, plus the worker's cost, plus the expected
redo. A cheap model's bad job that must be redone is waste; so is a top model on a mechanical job; so is the lead
spending its own quota on meta work. The lead is almost always the most expensive model, so reading, searching and
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)s
"""
def _cells(line): return [c.strip() for c in line.strip().strip("|").split("|")]
def _list(cell): return [] if cell.strip() in ("", "-") else [x.strip() for x in cell.split(",") if x.strip()]
def parse(text):
"""(nodes, "") from the table in `text`, or (None, why)."""
cols, nodes = None, []
for line in text.splitlines():
if not line.strip().startswith("|"):
continue
c = _cells(line)
if c and c[0].lower() == "node":
cols = [x.lower() for x in c]
if cols[:6] != list(COLS[:6]) or cols[6:] not in ([], ["why"]):
return None, "the header must be | node | class | needs | branch | files | check | (and optionally | why |)"
elif cols and not set("".join(c)) <= set("-: "):
if len(c) != len(cols):
return None, "row %r has %d cells, the header %d" % (c[0], len(c), len(cols))
r = dict(zip(cols, c))
nodes.append({"id": r["node"], "cls": r["class"].lower(), "needs": _list(r["needs"]), "branch": r["branch"],
"files": _list(r["files"]), "check": store.clean(r["check"]), "why": store.clean(r.get("why", ""))})
return (nodes, "") if nodes else (None, "no table found (a `| node | class | needs | branch | files | check |` header and rows)")
def reach(nodes):
"""{id: every id it needs, directly or not}; None when the needs hold a cycle."""
by, out, busy = {n["id"]: n for n in nodes}, {}, set()
def walk(i):
if i in busy: raise ValueError(i)
if i not in out:
busy.add(i)
out[i] = set(by[i]["needs"]).union(*(walk(j) for j in by[i]["needs"]))
busy.discard(i)
return out[i]
try: return {i: walk(i) for i in by}
except ValueError: return None
def overlap(a, b):
a, b = a.strip("/").removeprefix("./"), b.strip("/").removeprefix("./")
return a == b or b.startswith(a + "/") or a.startswith(b + "/") or fnmatch.fnmatch(a, b) or fnmatch.fnmatch(b, a)
def beside(r, a, b): return a != b and a not in r[b] and b not in r[a]
def check(nodes):
"""The first problem with this plan, or ""."""
ids, seen = {n["id"] for n in nodes}, set()
branches = [n["branch"] for n in nodes if n["cls"] != "lead"]
for n in nodes:
why = ("node id %r is not [a-z0-9-]{1,30}" % n["id"] if not re.fullmatch(r"[a-z0-9-]{1,30}", n["id"])
else "node %s appears twice" % n["id"] if n["id"] in seen
else "node %s has class %r; use one of %s" % (n["id"], n["cls"], ", ".join(CLASSES)) if n["cls"] not in CLASSES
else "node %s needs %s, which is not a node" % (n["id"], ", ".join(sorted(set(n["needs"]) - ids))) if set(n["needs"]) - ids
else "" if n["cls"] == "lead"
else "node %s needs a branch of its own" % n["id"] if not re.fullmatch(r"[A-Za-z0-9._/-]{1,100}", n["branch"]) or n["branch"].startswith("-")
else "branch %s is given to more than one node; each worker node gets its own" % n["branch"] if branches.count(n["branch"]) > 1
else "worker node %s needs files it may change and a check" % n["id"] if not n["files"] or n["check"] in ("", "-") else "")
if why: return why
seen.add(n["id"])
r = reach(nodes)
if r is None:
return "the needs hold a cycle"
for a in nodes:
for b in nodes:
hit = a["id"] < b["id"] and beside(r, a["id"], b["id"]) and next(((x, y) for x in a["files"] for y in b["files"] if overlap(x, y)), None)
if hit:
return "nodes %s and %s can run at the same time but both may change %s / %s: make the files disjoint or make one need the other" % (a["id"], b["id"], *hit)
sinks = [n for n in nodes if not any(n["id"] in m["needs"] for m in nodes)]
if len(sinks) != 1:
return "the plan needs exactly one final join that every node leads to; it ends in %d nodes: %s" % (len(sinks), ", ".join(n["id"] for n in sinks))
return "" if sinks[0]["cls"] == "lead" else "the final join %s must be class lead: the lead brings everything back" % sinks[0]["id"]
def waves(nodes):
w, by = {}, {n["id"]: n for n in nodes}
def wave(i): return w[i] if i in w else w.setdefault(i, 1 + max((wave(j) for j in by[i]["needs"]), default=0))
[wave(n["id"]) for n in nodes]
return w
def get(s):
"""The session's plan with its state cleaned (a damaged entry counts as not started); None if there is none or it is damaged."""
p = s.get("plan")
ok = lambda n: isinstance(n, dict) and all(isinstance(n.get(k), t) for k, t in (("id", str), ("cls", str), ("needs", list), ("branch", str), ("files", list), ("check", str)))
if not (isinstance(p, dict) and isinstance(p.get("nodes"), list) and p["nodes"] and all(map(ok, p["nodes"]))):
return None
ids = {n["id"] for n in p["nodes"]}
for n in p["nodes"]:
n["needs"], n["files"] = [x for x in n["needs"] if x in ids], [x for x in n["files"] if isinstance(x, str)]
p["state"] = {k: v for k, v in p["state"].items() if isinstance(v, dict) and k in ids} if isinstance(p.get("state"), dict) else {}
return p
def st(p, i): return p["state"].get(i, {}).get("st")
def ready(p):
"""Ids of nodes whose needs are all done and that are neither running nor done, in plan order."""
return [n["id"] for n in p["nodes"] if st(p, n["id"]) not in ("running", "done") and all(st(p, x) == "done" for x in n["needs"])]
def node(p, i): return next((n for n in p["nodes"] if n["id"] == i), None)
def record_line():
"""sisi's own record per class: good of judged, over the last 20 judged jobs of each class."""
from . import models
cls = {}
for r in models.rows(store.read(models.table())):
c = re.findall(r"routine|ordinary|hard", 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))):
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]]
return "record (last 20 judged per class): " + ", ".join(parts)
def show(p):
rd, now, out = ready(p), time.time(), []
for n in p["nodes"]:
v, s = p["state"].get(n["id"], {}), st(p, n["id"])
t = v.get("since") if type(v.get("since")) in (int, float) else now
label = ("running (%s, since %s, %d min)" % (v.get("worker"), time.strftime("%H:%M", time.localtime(t)), (now - t) / 60) if s == "running"
else "done" if s == "done" else "failed: %s" % v.get("why", "") if s == "failed" and n["id"] in rd else "ready" if n["id"] in rd else "waiting")
out.append(" %s [%s] %s needs: %s" % (n["id"], n["cls"], label, ", ".join(n["needs"]) or "-"))
return out + ["ready: " + (", ".join(rd) or "none")]
def _sum(text): return hashlib.sha1(text.encode("utf-8", "replace")).hexdigest()
_chore_path = lambda cid: os.path.join(store.STATE, "chores", cid + ".txt") if re.fullmatch(r"[0-9a-f]{8}", cid or "") else ""
def issue(name, text, cwd=None):
"""Print a chore brief with a one-time id and record it in this session: one delegation carrying its first line (or the full text) may go without a plan."""
cid, text = os.urandom(4).hex(), text.strip()
text = "sisi chore: %s %s\n%s" % (name, cid, text.split("\n", 1)[1] if "\n" in text else "") if text.startswith("sisi chore:") else "sisi chore: %s %s\n%s" % (name, cid, text)
store.write(_chore_path(cid), text + "\n")
if sid := store.current_session(cwd):
with store.session(sid) as s:
s["chores"] = (s["chores"] if isinstance(s.get("chores"), list) else [])[-9:] + [[name, _sum(text), len(text), cid]]
print(text)
def chore(args): # `sisi chore show ID`: print the brief printed under this one-time id (any session may read it)
if len(args) == 2 and args[0] == "show" and (text := store.read(_chore_path(args[1])) if _chore_path(args[1]) else ""):
return print(text, end="") or 0
return print("sisi chore: no brief with id %r: print the brief again (`sisi plan brief`, `sisi models research` or `sisi rules organize`)." % (args[1] if len(args) > 1 else "")) or 1
def run(args, cwd=None):
sid = store.current_session(cwd)
if args == ["brief"]:
d = {}
if sid:
with store.session(sid) as s:
d = s.get("done") or {}
if not d:
return print('sisi plan: record done first (`sisi done --goal ... --check ... --next ...`); the planning brief is built from it.') or 1
return issue("plan", BRIEF % {"goal": d["goal"], "next": d["next"], "record": "sisi's " + record_line(),
"checks": "\n".join(" %d. %s" % (i, c["text"]) for i, c in enumerate(d["checks"], 1))}, cwd) or 0
if len(args) == 2 and args[0] == "--record":
nodes, why = parse(store.read(args[1]))
why = why or check(nodes) or ("" if sid else "no session; run this from the agent's session")
with store.session(sid) if sid else contextlib.nullcontext({}) as s:
old, new = get(s) or {"nodes": [], "state": {}}, {n["id"]: n for n in nodes or []}
moved = [i for i, v in old["state"].items() if v.get("st") == "running" and (i not in new or (
new[i]["branch"], new[i]["files"]) != (node(old, i)["branch"], node(old, i)["files"]))]
why = why or (moved and "node %s is running: keep its id, branch and files in the new plan, or judge it first" % moved[0])
if why:
return print("sisi plan: %s. Nothing was recorded." % why) or 1
keep = {i for i, v in old["state"].items() if v.get("st") == "running" or node(old, i) == new.get(i)}
s["plan"] = p = {"nodes": nodes, "state": {i: v for i, v in old["state"].items() if i in keep and i in new}}
w = waves(nodes)
print("plan recorded: %d nodes, critical path %d wave(s)." % (len(nodes), max(w.values())))
for k in range(1, max(w.values()) + 1):
print(" wave %d: %s" % (k, ", ".join("%s (%s%s)" % (n["id"], n["cls"], ": " + n["why"] if n["why"] else "") for n in nodes if w[n["id"]] == k)))
rd = ready(p)
go, mine = [i for i in rd if node(p, i)["cls"] != "lead"], [i for i in rd if node(p, i)["cls"] == "lead"]
go and print("dispatch wave 1 now, all in one message: %s (`sisi pick --node ID` for each)" % ", ".join(go))
mine and print("yours to do now: %s" % ", ".join(mine))
print(record_line())
return 0
if len(args) == 3 and args[0] in ("--done", "--fail") and len(args[2].split()) >= 3 and sid:
with store.session(sid) as s:
p = get(s)
n = node(p, args[1]) if p else None
why = ("no node %r in the plan" % args[1] if not n else "node %s is running: only its worker's verdict closes or reopens it (`sisi judge WORKER good|bad \"<why>\"`)" % args[1]
if st(p, args[1]) == "running" else "")
if why:
return print("sisi plan: %s." % why) or 1
p["state"][args[1]] = {"st": "done", "evidence": store.clean(args[2])} if args[0] == "--done" else {"st": "failed", "why": store.clean(args[2])}
print("\n".join(show(p)))
return 0
if not args:
p = None
if sid:
with store.session(sid) as s: p = get(s)
return print("\n".join(show(p)) if p else "no plan recorded. `sisi plan brief` prints the brief for a planning worker; `sisi plan --record FILE` records its table.") or 0
return print(USAGE) or 1
why_not = lambda p, i: "already " + st(p, i) if st(p, i) in ("running", "done") else "needs not done: " + ", ".join(x for x in node(p, i)["needs"] if st(p, x) != "done")
def for_pick(args, cwd=None):
"""`sisi pick --node ID [rest]` as (the class pick's args, the node id), or (None, None) after saying why."""
i, sid, p = (args[1] if len(args) > 1 else ""), store.current_session(cwd), None
if sid:
with store.session(sid) as s:
p = get(s)
n = node(p, i) if p else None
why = ("no plan is recorded: `sisi plan brief`, then `sisi plan --record FILE`" if not p else "no node %r in the plan" % i if not n
else "node %s is the lead's own: do it and run `sisi plan --done %s \"<evidence>\"`" % (i, i) if n["cls"] == "lead"
else "node %s is not ready (%s)" % (i, why_not(p, i)) if i not in ready(p) else "")
if why: return print("sisi pick: %s." % why) or (None, None)
return [n["cls"]] + args[2:] + ["--branch", n["branch"]], i
def header(p, i):
return "\n".join(["paste at the top of the brief (its first line):", "sisi node: " + i, "branch: %s (its own worktree and build folder)" % (n := node(p, i))["branch"],
"may change: " + (", ".join(n["files"]) or "nothing"), "check: " + n["check"],
"needs done: " + (", ".join("%s (%s)" % (x, p["state"].get(x, {}).get("evidence", "")) for x in n["needs"]) or "-")])
def start(s, i, worker, t):
if (p := get(s)) and node(p, i):
p["state"][i] = {"st": "running", "worker": worker, "since": t}
def judged(s, worker, t, verdict):
"""A verdict on a worker's job moves the node that job started, matched by worker and start: good to done, bad or out back to ready."""
p = get(s)
hit = next((i for i, v in p["state"].items() if v.get("st") == "running" and v.get("worker") == worker and v.get("since") == t), None) if p and t is not None else None
if hit:
p["state"][hit] = {"st": "done", "evidence": "judged good"} if verdict == "good" else {"st": "failed", "why": "judged " + verdict}
def starts(brief, shell):
"""Where the brief's lines may begin: its first non-empty line, or for a shell command any line (its first is the launcher)."""
out, at = [], 0
for line in brief.splitlines(True):
line.strip() and out.append(at + len(line) - len(line.lstrip()))
at += len(line)
return out if shell else out[:1]
def deny(s, brief, shell=False):
"""(why this delegation strays from the plan or "", the plan node it starts, the index of the issued chore it spends)."""
p, at = get(s), starts(brief, shell)
line = lambda rx: next((m for i in at if (m := rx.match(brief[i:].split("\n", 1)[0].strip()))), None)
chores, c = (s["chores"] if isinstance(s.get("chores"), list) else []), line(CHORE_LINE)
if c:
name, cid = c.group(1), c.group(2)
hit = next((k for k, x in enumerate(chores) if isinstance(x, list) and len(x) == 4 and x[0] == name and x[3] == cid and type(x[2]) is int
and (any(_sum(brief[i:i + x[2]]) == x[1] for i in at) or any(len(brief) - i < x[2] for i in at))), None)
return ("", None, hit) if hit is not None else (("sisi: this `sisi chore: %s` brief is not one sisi printed in this session (a wrong, reused or other-session id): print the chore's brief again with `%s` and delegate just its first line plus \"Run `sisi chore show %s` and do what it says\"." % (name, CHORE_CMD.get(name, "sisi plan brief`, `sisi models research` or `sisi rules organize"), cid or "<id>")), None, None)
if not p:
return ("sisi: no plan is recorded. Before handing out work, plan it: `sisi plan brief` prints the brief for a hard planning worker "
"(it carries its `sisi chore: plan` line), then `sisi plan --record FILE`."), None, None
m = line(NODE_LINE)
i = m.group(1).lower() if m else None
n = node(p, i) if i else None
why = ("sisi: the brief's first line must be `sisi node: ID`: pick with `sisi pick --node ID` and paste the header it prints at the top. Ready: %s." % (", ".join(ready(p)) or "none") if not m
else "sisi: the brief names node %s, which is not in the plan (`sisi plan` shows it)." % i if not n
else "sisi: node %s is the lead's own; do it yourself and run `sisi plan --done %s \"<evidence>\"`." % (i, i) if n["cls"] == "lead"
else "sisi: node %s is not ready (%s). Ready now: %s (`sisi plan` shows all)." % (i, why_not(p, i), ", ".join(ready(p)) or "none") if i not in ready(p) else "")
return why, (None if why else i), None
def concurrent(s, i):
"""Can this worker node run at the same time as another worker node?"""
p = get(s)
r = reach(p["nodes"]) if p else None
return bool(r) and any(n["cls"] != "lead" and beside(r, i, n["id"]) for n in p["nodes"])
def gate(s):
"""End of turn: the ready worker nodes not started, as a message, or ""."""
p = get(s)
rd = ready(p) if p else []
go = [i for i in rd if node(p, i)["cls"] != "lead"]
if go:
return "sisi: nodes %s are ready and not started: pick and dispatch them all now in one message (%s)." % (
", ".join(go), " ".join("`sisi pick --node %s`" % i for i in go))
return ""