diff --git a/sisi/cli.py b/sisi/cli.py index a2de998..903f584 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -30,8 +30,14 @@ 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 plan brief | --record FILE the brief for a planning worker; record its graph (| node | class | needs | branch + | files | check | why |) before handing out any work; `sisi plan` shows each node + sisi plan --done ID EVIDENCE | --fail ID WHY + a node you did yourself (the join) is done; or reopen a node + sisi pick --node ID [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] sisi pick routine|ordinary|hard [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME] - the wheel gives you one worker of that class; one pick, one delegation + 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] how a delegation went (`out` with the provider's own message when it hit a limit: sisi tries it again by itself), or give a running job more time @@ -49,7 +55,7 @@ Hooks (the agent tool calls these): sisi tick | prompt | watch | gate Your own rules, models table and retro log live in ~/.local/share/sisi ($SISI_DATA, else $XDG_DATA_HOME/sisi), a git repository; a project's rules live in its .sisi/rules.md. Settings: "core" in its config.json (gate, meter, direct_calls, direct_extension, rules_lines, rules_chars, organize_after, -research_days, shell_workers, worker_minutes, retro_minutes, disk_free_percent, disk_drop_percent, checkouts).""" +research_days, shell_workers, enforce, worker_minutes, retro_minutes, disk_free_percent, disk_drop_percent, checkouts).""" def main(argv): @@ -67,6 +73,9 @@ def main(argv): if cmd in ("retro", "done"): from . import retro return (retro.run if cmd == "retro" else retro.done)(args) + if cmd == "plan": + from . import plan + return plan.run(args) if cmd == "fault": from . import faults return faults.run(args) diff --git a/sisi/hooks.py b/sisi/hooks.py index e07d26a..3d10eb1 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -17,6 +17,8 @@ GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi NODONE = "sisi: no done is recorded yet. Define what the person wants and what comes next now: `sisi done --goal \"\" --check \"\" [--check ...] --next \"\"`." NOPICK = ("sisi: this delegation went to a worker the wheel did not give you (recorded so `sisi judge` still works). Use `sisi pick routine|ordinary|hard` next time " "(--review-of WORKER for a review, --not WORKER if one is out); one pick, one delegation.") +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.") 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 (recorded so `sisi judge` still works), 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." @@ -174,43 +176,81 @@ def watch(p): return 0 kind, cfg = tool_class(tool), store.config() command = next((v for k in ("command", "cmd", "CommandLine") if isinstance(v := ti.get(k), str) and v), "") - notes = [] + notes, deny = [], [] with store.session(sid) as s: _begin(s, p["cwd"] or os.getcwd()) if s.get("worker") or (kind == "shell" and own(command)): return 0 shell = kind == "shell" and models.is_call(command) - shell and not cfg["shell_workers"] and notes.append(NOSHELL) - (kind in ("delegate", "edit") or shell) and not s.get("done") and notes.append(NODONE) if kind == "delegate" or shell: brief = command if shell else " ".join(v for k in ("prompt", "task", "message", "instructions", "description", "content", "text") if isinstance(v := ti.get(k), str)) - screen_brief_without_look(brief) and notes.append(NOLOOK) target = ti.get("target") if isinstance(ti.get("target"), dict) else {} names = (ti.get("model"),) if tool == "agent" else (ti.get("model"), target.get("model"), ti.get("agent")) text = command if shell else next((n for n in names if n and isinstance(n, str)), "") - table_text = store.read(models.table()) - if tool != "workflow" and not models.claim(s, text, not shell and bool(names[0])): - known = models.claim(probe := {"picked": [models.short(r[0]) for r in models.rows(table_text)]}, text, True) - if models.usable(table_text): - not shell and text.strip() and not known and models.stale(text) - notes.append(UNKNOWN if not shell and text.strip() and not known else NOPICK) - w = (probe.get("workers_since") or [models.short(text) if not shell else ""])[0] - if re.fullmatch(r"[a-z0-9._/:+-]{1,80}", w): - d = {"picked": [w], "starts": s.get("starts"), "workers_since": s.get("workers_since") if isinstance(s.get("workers_since"), list) else []} - models.claim(d, w) and s.update(starts=d["starts"], workers_since=d["workers_since"]) - s["delegations_since"] = s.get("delegations_since", 0) + 1 - s.pop("paused", None) - elif kind in DIRECT: + stop, node = _outside(s, tool, ti, brief, text, shell, names, cfg) + if stop and cfg["enforce"]: + deny = stop + else: + notes += [x for x in stop if x is not UNPICKED] # the reminder below says it, as before + screen_brief_without_look(brief) and notes.append(NOLOOK) + table_text = store.read(models.table()) + if tool != "workflow" and not models.claim(s, text, not shell and bool(names[0])): + known = models.claim(probe := {"picked": [models.short(r[0]) for r in models.rows(table_text)]}, text, True) + if models.usable(table_text): + not shell and text.strip() and not known and models.stale(text) + notes.append(UNKNOWN if not shell and text.strip() and not known else NOPICK) + w = (probe.get("workers_since") or [models.short(text) if not shell else ""])[0] + if re.fullmatch(r"[a-z0-9._/:+-]{1,80}", w): + d = {"picked": [w], "starts": s.get("starts"), "workers_since": s.get("workers_since") if isinstance(s.get("workers_since"), list) else []} + models.claim(d, w) and s.update(starts=d["starts"], workers_since=d["workers_since"]) + if node and s.get("workers_since"): + from . import plan + w = s["workers_since"][-1] + plan.start(s, node, w, ((s.get("starts") or {}).get(w) or [time.time()])[-1]) + s["delegations_since"] = s.get("delegations_since", 0) + 1 + s.pop("paused", None) + elif kind == "edit" and not s.get("done"): + notes.append(NODONE) + if kind in DIRECT and not shell: limit = cfg["direct_calls"] + s.get("extra", 0) cfg["meter"] and s.get("direct", 0) >= limit and notes.append(METER % (s.get("direct", 0), limit, cfg["direct_extension"])) if kind == "edit": s["changed"] = True s.pop("paused", None) s["direct"], s["direct_since"] = s.get("direct", 0) + 1, s.get("direct_since", 0) + 1 + if deny: # Claude Code, Codex and Qwen Code all read this shape; the reason goes to the model + return print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", + "permissionDecisionReason": say("\n".join(deny + notes))}})) or 0 notes and print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": say("\n".join(notes))}})) return 0 +ISOLATED = ("agent", "task") # delegation tools with an `isolation` field (and any `*delegate_task`) + + +def _outside(s, tool, ti, brief, text, shell, names, cfg): + """([why, ...], node): every way this delegation strays from what sisi told the lead, and the plan node it starts.""" + from . import plan + why, chore = [], bool(plan.CHORE_LINE.search(brief)) + shell and not cfg["shell_workers"] and why.append(NOSHELL) + s.get("done") or chore or why.append(NODONE) + stray, node = plan.deny(s, brief, chore) + stray and (cfg["enforce"] or s.get("plan")) and why.append(stray) # as reminders, plan notes only once there is a plan + for q in (s["pending"].values() if node and isinstance(s.get("pending"), dict) else ()): + isinstance(q, list) and q.sort(key=lambda m: not (isinstance(m, dict) and m.get("node") == node)) # this node's pick is spent first + if tool != "workflow": + probe = json.loads(json.dumps({k: s.get(k) for k in ("picked", "starts", "pending", "meta")})) + if not models.claim(probe, text, not shell and bool(names[0])): + why.append(UNPICKED) + elif node and (m := next((v for k, v in (probe.get("meta") or {}).items() if k not in (s.get("meta") or {})), None)) is not None and m.get("node") not in (None, node): + why.append("sisi: this worker was picked for node %s, not %s; pick again with `sisi pick --node %s`." % (m.get("node"), node, node)) + p = s.get("plan") if isinstance(s.get("plan"), dict) else None + if node and (tool in ISOLATED or tool.endswith("delegate_task")) and ti.get("isolation") != "worktree" \ + and sum(n["cls"] != "lead" for n in p["nodes"]) >= 2: + why.append("sisi: node %s runs beside others: start it with isolation \"worktree\" so it gets its own checkout." % node) + return why, node + + def direct(args, cwd=None): """`sisi direct ""`: the lead says why doing more itself costs less than delegating it.""" reason, sid, cfg = " ".join(" ".join(args).split()), store.current_session(cwd), store.config() @@ -239,6 +279,9 @@ def gate(p, for_subagent=False): if isinstance(x, list) and len(x) == 2 and x[1] in (starts.get(x[0]) if isinstance(starts.get(x[0]), list) else ())] late = models.overdue({"starts": {w: [t for t in v if [w, t] not in seen] for w, v in starts.items() if isinstance(v, list)}, "meta": s.get("meta")}) reason, demand = " ".join("sisi: " + LATE % (w, time.strftime("%H:%M", time.localtime(t))) for w, t in late), False + if not reason and isinstance(s.get("plan"), dict): # ready nodes not started: dispatch them before the turn ends + from . import plan + reason = plan.gate(s) if not reason and not s.get("paused"): 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"]] diff --git a/sisi/models.py b/sisi/models.py index 34a603f..4cf14de 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -323,6 +323,11 @@ 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.""" + 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 while cls and i < len(args): if args[i] == "--not" and i + 1 < len(args): skip.add(short(args[i + 1])) @@ -358,7 +363,7 @@ def pick(args, cwd=None, rand=None): with store.session(sid) as s: s.setdefault("picked", []).append(w := short(r[0])) 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}]} # one entry per pick, claimed in order + 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 store.config()["shell_workers"] or not command(r): print("how to call it: " + r[1]) @@ -368,6 +373,10 @@ def pick(args, cwd=None, rand=None): if g := gone.get(short(r[0])): # its last verdict was `out`: a retry, so a quick failure is expected and cheap print("retry: this worker hit a limit at %s: %s; if it fails for the limit again, judge it out again and pick another" % ( clock(g[0]), g[1][:160] + ("…" if len(g[1]) > 160 else ""))) + from . import plan + print(plan.record_line()) + if node and sid: + with store.session(sid) as s: print(plan.header(s["plan"], node)) return 0 @@ -467,6 +476,7 @@ def judge(args, cwd=None): isinstance(s.get("reminded"), list) and s.__setitem__("reminded", [x for x in s["reminded"] if x != [wkey, cand]]) return sync_late(s, cwd, sid, False) or print("extended %s limit to %d min." % (wkey, lim)) or 0 isinstance(s.get("meta"), dict) and s["meta"].pop("%s %r" % (wkey, cand), None) + if s.get("plan"): from . import plan; plan.judged(s, wkey, cand, args[1]) if ok_t: began = cand minutes = minutes or max(1, int((now - began) / 60)) diff --git a/sisi/plan.py b/sisi/plan.py new file mode 100644 index 0000000..9deb4e2 --- /dev/null +++ b/sisi/plan.py @@ -0,0 +1,308 @@ +"""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 fnmatch, json, re, time +from . import store + +CLASSES = ("routine", "ordinary", "hard", "lead") +COLS = ("node", "class", "needs", "branch", "files", "check", "why") +NODE_LINE = re.compile(r"(?im)^\W{0,6}sisi node:\s*([a-z0-9-]{1,30})\b") +CHORE_LINE = re.compile(r"(?im)^\W{0,6}sisi chore:\s*\S") +USAGE = ('usage: sisi plan | sisi plan --record FILE | sisi plan brief | sisi plan --done ID "" | sisi plan --fail ID ""\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 = {n["id"]: n for n in nodes}, {} + def walk(i, path): + if i in path: + return None + if i not in out: + acc = set() + for j in by[i]["needs"]: + r = walk(j, path | {i}) + if r is None: + return None + acc |= r | {j} + out[i] = acc + return out[i] + return out if all(walk(i, frozenset()) is not None for i in by) else 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 check(nodes): + """The first problem with this plan, or "".""" + ids = [n["id"] for n in nodes] + for n in nodes: + if not re.fullmatch(r"[a-z0-9-]{1,30}", n["id"]): + return "node id %r is not [a-z0-9-]{1,30}" % n["id"] + if ids.count(n["id"]) > 1: + return "node %s appears twice" % n["id"] + if n["cls"] not in CLASSES: + return "node %s has class %r; use one of %s" % (n["id"], n["cls"], ", ".join(CLASSES)) + if miss := [x for x in n["needs"] if x not in ids]: + return "node %s needs %s, which is not a node" % (n["id"], ", ".join(miss)) + if n["cls"] != "lead" and (not re.fullmatch(r"[A-Za-z0-9._/-]{1,100}", n["branch"]) or n["branch"].startswith("-")): + return "node %s needs a branch of its own" % n["id"] + branches = [n["branch"] for n in nodes if n["cls"] != "lead"] + if dup := sorted({b for b in branches if branches.count(b) > 1}): + return "branch %s is given to more than one node; each worker node gets its own" % dup[0] + r = reach(nodes) + if r is None: + return "the needs hold a cycle" + for i, a in enumerate(nodes): + for b in nodes[i + 1:]: + if a["id"] not in r[b["id"]] and b["id"] not in r[a["id"]]: + hit = 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["id"] 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(sinks)) + return "" + + +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 ready(p): + """Ids of nodes whose needs are all done and that are neither running nor done, in plan order.""" + st = p.get("state") or {} + done = {i for i, v in st.items() if v.get("st") == "done"} + return [n["id"] for n in p["nodes"] if st.get(n["id"], {}).get("st") not in ("running", "done") and set(n["needs"]) <= done] + + +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): + st, rd, now = p.get("state") or {}, ready(p), time.time() + out = [] + for n in p["nodes"]: + v = st.get(n["id"], {}) + s = v.get("st") + label = ("running (%s, since %s, %d min)" % (v.get("worker"), time.strftime("%H:%M", time.localtime(v.get("since", now))), (now - v.get("since", now)) / 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 run(args, cwd=None): + sid = store.current_session(cwd) + if args == ["brief"]: + if not sid: + return print("sisi plan: no session; run this from the agent's session.") or 1 + 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 print(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))}) or 0 + if len(args) == 2 and args[0] == "--record": + nodes, why = parse(store.read(args[1])) + why = why or check(nodes) + if why: + return print("sisi plan: %s. Nothing was recorded." % why) or 1 + if not sid: + return print("sisi plan: no session; run this from the agent's session. Nothing was recorded.") or 1 + with store.session(sid) as s: + old = s.get("plan") if isinstance(s.get("plan"), dict) else {} + keep = {n["id"] for n in nodes if node(old, n["id"]) == n} if old.get("nodes") else set() + s["plan"] = p = {"nodes": nodes, "state": {i: v for i, v in (old.get("state") or {}).items() if i in keep}} + 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: + if not sid: + return print("sisi plan: no session.") or 1 + with store.session(sid) as s: + p = s.get("plan") if isinstance(s.get("plan"), dict) else None + if not p or not node(p, args[1]): + return print("sisi plan: no node %r in the plan." % args[1]) or 1 + p.setdefault("state", {})[args[1]] = {"st": "done" if args[0] == "--done" else "failed", ("evidence" if args[0] == "--done" else "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 = s.get("plan") if isinstance(s.get("plan"), dict) else None + if not p: + return print("no plan recorded. `sisi plan brief` prints the brief for a planning worker; `sisi plan --record FILE` records its table.") or 0 + return print("\n".join(show(p))) or 0 + print(USAGE) + return 1 + + +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 = (args[1] if len(args) > 1 else ""), store.current_session(cwd) + p = None + if sid: + with store.session(sid) as s: + p = s.get("plan") if isinstance(s.get("plan"), dict) else None + 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 \"\"`" % (i, i) if n["cls"] == "lead" + else "node %s is not ready (%s)" % (i, (p.get("state") or {}).get(i, {}).get("st") or "needs not done: " + ", ".join( + x for x in n["needs"] if (p.get("state") or {}).get(x, {}).get("st") != "done")) if i not in ready(p) else "") + if why: + print("sisi pick: %s." % why) + return None, None + return [n["cls"]] + args[2:] + ["--branch", n["branch"]], i + + +def header(p, i): + n, st = node(p, i), p.get("state") or {} + return "\n".join(["paste at the top of the brief:", "sisi node: " + i, "branch: %s (its own worktree and build folder)" % n["branch"], + "may change: " + (", ".join(n["files"]) or "nothing"), "check: " + n["check"], + "needs done: " + (", ".join("%s (%s)" % (x, st.get(x, {}).get("evidence", "")) for x in n["needs"]) or "-")]) + + +def start(s, i, worker, t): + p = s.get("plan") + if isinstance(p, dict) and node(p, i): + p.setdefault("state", {})[i] = {"st": "running", "worker": worker, "since": t} + + +def judged(s, worker, t, verdict): + """A verdict on a worker's job moves its node: good to done, bad or out back to ready.""" + p = s.get("plan") + if not isinstance(p, dict): + return + st = p.get("state") or {} + mine = sorted((v.get("since", 0), i) for i, v in st.items() if v.get("st") == "running" and v.get("worker") == worker) + hit = next((i for since, i in mine if since == t), mine[0][1] if mine else None) + if hit: + st[hit] = {"st": "done", "evidence": "judged good"} if verdict == "good" else {"st": "failed", "why": "judged " + verdict} + + +def deny(s, brief, chore): + """Why this delegation is outside the plan, or "" (the node id it starts is returned too).""" + p = s.get("plan") if isinstance(s.get("plan"), dict) else None + if chore: + return "", 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 " + "(that delegation carries its `sisi chore: plan` line), then `sisi plan --record FILE`. Housekeeping briefs sisi prints carry a `sisi chore: ` line."), None + m = NODE_LINE.search(brief) + if not m: + return "sisi: this brief names no plan node. Pick with `sisi pick --node ID` and paste the header it prints (its first line is `sisi node: ID`) at the top of the brief. Ready: %s." % (", ".join(ready(p)) or "none"), None + i = m.group(1) + if not node(p, i): + return "sisi: the brief names node %s, which is not in the plan (`sisi plan` shows it)." % i, None + if node(p, i)["cls"] == "lead": + return "sisi: node %s is the lead's own; do it yourself and run `sisi plan --done %s \"\"`." % (i, i), None + if i not in ready(p): + st = (p.get("state") or {}).get(i, {}).get("st") + return "sisi: node %s is not ready (%s). Ready now: %s (`sisi plan` shows all)." % (i, "already " + st if st else "needs not done: " + ", ".join( + x for x in node(p, i)["needs"] if (p.get("state") or {}).get(x, {}).get("st") != "done"), ", ".join(ready(p)) or "none"), None + return "", i + + +def gate(s): + """End of turn: the ready nodes not started, as a message, or "".""" + p = s.get("plan") if isinstance(s.get("plan"), dict) else None + if not p: + return "" + rd = ready(p) + 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)) + if rd: + return "sisi: node %s is yours and ready: %s. Do it, then `sisi plan --done %s \"\"`." % (rd[0], node(p, rd[0])["check"], rd[0]) + return "" diff --git a/sisi/retro.py b/sisi/retro.py index dc35457..ae1f1ac 100644 --- a/sisi/retro.py +++ b/sisi/retro.py @@ -177,7 +177,7 @@ def record(s, cwd, opt, sid=None): 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"): + "fails_since", "picked", "starts", "pending", "meta", "reminded", "retro_demanded", "began", "plan"): s.pop(key, None) diff --git a/sisi/store.py b/sisi/store.py index d9386ea..5bcaab9 100644 --- a/sisi/store.py +++ b/sisi/store.py @@ -24,7 +24,7 @@ GIT_ERROR = "" # why the last git call that failed did: the first line of its s # 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, "audit_after": 12, "research_days": 3, "shell_workers": False, + "rules_lines": 30, "rules_chars": 4000, "organize_after": 8, "audit_after": 12, "research_days": 3, "shell_workers": False, "enforce": True, "worker_minutes": 90, "retro_minutes": 5, "disk_free_percent": 20, "disk_drop_percent": 5, "checkouts": 8} def config(): diff --git a/tests/test_core.py b/tests/test_core.py index cdd3357..06b9e31 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -60,6 +60,8 @@ REAL_HOME = os.path.expanduser("~") class Core(unittest.TestCase): + ENFORCE = False + def setUp(self): before = tree() self.addCleanup(lambda: self.assertEqual(tree(), before, "a test wrote into the product tree")) @@ -84,6 +86,9 @@ class Core(unittest.TestCase): for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME"): self.env.pop(name, None) self.proj = self.project("alpha") + if not self.ENFORCE: # these tests hold the reminders; tests/test_plan.py holds the denials + os.makedirs(self.data, exist_ok=True) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False}})) def project(self, name): path = os.path.join(self.tmp, name) @@ -1216,7 +1221,7 @@ class Core(unittest.TestCase): self.assertNotIn("could not be recorded", out, (rnd, out)) self.assertNotIn("commit failed", out, (rnd, out)) self.assertFalse(os.path.exists(old_c), rnd) - dirty = [l for l in subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True, check=True).stdout.splitlines() if not l.startswith(("?? generated/", "?? locks/"))] + dirty = [l for l in subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True, check=True).stdout.splitlines() if not l.startswith(("?? generated/", "?? locks/", "?? config.json"))] self.assertEqual(dirty, [], rnd) def test_concurrent_learns_hold_project_lock_through_store_commit(self): @@ -2227,7 +2232,7 @@ cli.main(["tick"]) def test_a_worker_called_from_the_shell_is_never_marked_unknown(self): marker = self.lead(WORKERS) - self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"shell_workers": True}})) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False, "shell_workers": True}})) err = self.note(self.tool("Bash", tool_input={"command": 'opencode run -m other/model "fix the login bug in auth.py"'})) self.assertEqual(("the wheel did not give you" in err, os.path.exists(marker)), (True, False)) self.assertNotIn("login bug", self.hook("tick", sid="s2")[1]) @@ -2277,7 +2282,7 @@ cli.main(["tick"]) self.assertIn("do not shell out to a worker", self.note(self.tool("Bash", tool_input=shell))) # warned even with a pick self.assertEqual(self.sisi("pick", "ordinary", sid="s1")[0], 0) self.assertEqual(self.tool("mcp__t3__delegate_task", tool_input={"target": {"model": "zai-coding-plan/glm-5.4"}}), (0, "", "")) - self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"shell_workers": True}})) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False, "shell_workers": True}})) self.assertIn("opencode run -m zai-coding-plan/glm-5.4", self.sisi("pick", "ordinary", sid="s1")[1]) self.assertIn("the wheel did not give you", self.note(self.tool("Bash", tool_input={"command": 'opencode run -m other/model "x"'}))) self.assertEqual(self.tool("Bash", tool_input=shell), (0, "", "")) @@ -2825,11 +2830,11 @@ cli.main(["tick"]) bash = lambda c: self.tool("Bash", tool_input={"command": c}) err = self.note(bash('opencode run -m x "y"')) # a shell worker before done self.assertEqual(("do not shell out" in err, "sisi done --goal" in err), (True, True)) - self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"shell_workers": True}})) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False, "shell_workers": True}})) err = self.note(bash('opencode run -m x "y"')) self.assertEqual(("sisi done --goal" in err, "do not shell out" in err), (True, False)) self.done() - os.remove(os.path.join(self.data, "config.json")) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False}})) for c in ('cd /tmp && opencode run -m x "y"', 'nohup opencode run -m x "y" &', 'echo x; opencode run -m x "y"', 'FOO=1 env time /usr/bin/agy --print "y"', 'ls | agy --print "y"'): self.assertIn("do not shell out", self.note(bash(c)), c) @@ -3068,7 +3073,7 @@ cli.main(["tick"]) self.assertNotIn("changed things", out) def test_sisi_with_quoted_operators_is_free_and_real_operators_are_not(self): - self.write(self.mkdir(self.data) + "/config.json", json.dumps({"core": {"direct_calls": 0}})) + self.write(self.mkdir(self.data) + "/config.json", json.dumps({"core": {"enforce": False, "direct_calls": 0}})) self.hook("tick") self.hook("prompt", prompt="go") bash = lambda c: self.tool("Bash", tool_input={"command": c}) @@ -3144,7 +3149,7 @@ cli.main(["tick"]) def test_the_gate_blocks_on_a_worker_that_was_started_and_never_reported(self): self.table(WORKERS) - self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"worker_minutes": 15}})) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False, "worker_minutes": 15}})) self.hook("tick") self.hook("prompt", prompt="go") self.done() @@ -3208,7 +3213,7 @@ cli.main(["tick"]) def test_retro_row_records_session_id_and_demand_to_record_seconds(self): self.table(WORKERS) - self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"worker_minutes": 15}})) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False, "worker_minutes": 15}})) self.hook("tick") self.hook("prompt", prompt="go") self.done() @@ -3306,7 +3311,7 @@ cli.main(["tick"]) def test_a_lead_waiting_on_a_worker_that_is_not_late_is_not_stopped_for_open_checks(self): self.table(WORKERS) - self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"worker_minutes": 15}})) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False, "worker_minutes": 15}})) self.hook("tick") self.hook("prompt", prompt="go") self.done() @@ -3353,7 +3358,7 @@ cli.main(["tick"]) self.assertIn("no retro yet", work("f", -1)) # a clock that went backwards: the retro self.assertIn("no retro yet", work("d", 4, delegate=True)) # a delegation: the retro self.assertEqual(len(self.records()), 1) - self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"retro_minutes": 10}})) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False, "retro_minutes": 10}})) self.assertEqual(work("e", 6), "") # the limit is a setting self.assertEqual(len(self.records()), 2) @@ -3399,7 +3404,7 @@ cli.main(["tick"]) self.hook("tick", sid="w1") self.hook("prompt", sid="w1", prompt="You are a worker. Do this task yourself.") self.assertEqual(self.hook("gate", sid="w1")[1], "") # worker skipped - self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"gate": False}})) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False, "gate": False}})) self.assertEqual(self.hook("gate", sid="s2")[1], "") # gate setting off def test_faults_shown_on_tick_prompt_retro_meter_free_and_scoped_to_project(self): @@ -3426,7 +3431,7 @@ cli.main(["tick"]) self.assertIn("linker crashed ten times", rep) self.assertIn("scratch folder filled up", rep) # meter lets `sisi fault ...` through even with direct_calls=0 - self.write(self.mkdir(self.data) + "/config.json", json.dumps({"core": {"direct_calls": 0}})) + self.write(self.mkdir(self.data) + "/config.json", json.dumps({"core": {"enforce": False, "direct_calls": 0}})) self.assertEqual(self.tool("Bash", sid="s2", tool_input={"command": 'sisi fault "new crash in test runner"'})[0], 0) # a different project's faults are not shown or gated beta = self.project("beta") @@ -3696,7 +3701,7 @@ cli.main(["tick"]) wt5 = self.mkdir(p5, ".git", "worktrees") for i in range(10): self.mkdir(wt5, "w%d" % i) - self.write(self.mkdir(self.data) + "/config.json", json.dumps({"core": {"disk_free_percent": 0, "disk_drop_percent": 0, "checkouts": 0}})) + self.write(self.mkdir(self.data) + "/config.json", json.dumps({"core": {"enforce": False, "disk_free_percent": 0, "disk_drop_percent": 0, "checkouts": 0}})) self.env["SISI_TEST_STATVFS"] = "1000000000000:50000000000" self.assertEqual(self.hook("prompt", sid="off1", cwd=p5, prompt="all off")[1], "") self.assertIn("no open faults", self.sisi("fault", cwd=p5)[1]) diff --git a/tests/test_plan.py b/tests/test_plan.py new file mode 100644 index 0000000..813ae2b --- /dev/null +++ b/tests/test_plan.py @@ -0,0 +1,343 @@ +"""The plan: a dependency graph recorded before any work is handed out, and the hooks that hold the lead to it.""" +import io, json, os, sys, unittest +from unittest import mock +import test_core # the module, not its class: its tests must not run twice +sys.path.insert(0, test_core.REPO) + +TABLE = test_core.HEADER + ( + "| alpha | host subagent model `alpha` | routine | free | quick | |\n" + "| beta | host subagent model `beta` | ordinary | free | edits | |\n" + "| gamma | host subagent model `gamma` | hard | per use | everything | |\n") +COLS = "| node | class | needs | branch | files | check | why |\n|---|---|---|---|---|---|---|\n" +PLAN = COLS + ( + "| a | routine | - | p-a | sisi/a.py | test a passes | exact spec, test decides |\n" + "| b | ordinary | - | p-b | sisi/b.py | test b passes | some judgement |\n" + "| c | hard | a, b | p-c | sisi/c.py | test c passes | design judgement, redo costly |\n" + "| join | lead | c | - | - | full suite passes | the lead merges |\n") + + +class Plan(unittest.TestCase): + ENFORCE = True + 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) + + def record(self, text, sid="s1"): + return self.sisi("plan", "--record", self.write(os.path.join(self.tmp, "plan.md"), text), sid=sid) + + def refused(self, text, why): + rc, out, _ = self.record(text) + self.assertEqual(rc, 1, out) + self.assertIn(why, out) + self.assertIn("Nothing was recorded", out) + self.assertNotIn("plan", self.state() if os.path.exists(os.path.join(self.tmp, "state", "core-sessions", "s1.json")) else {}) + + def ready_plan(self, sid="s1", text=PLAN): + self.table(TABLE) + self.hook("prompt", sid=sid, prompt="build it") + self.done(sid) + rc, out, _ = self.record(text, sid) + self.assertEqual(rc, 0, out) + return out + + def pick(self, node, sid="s1"): + rc, out, _ = self.sisi("pick", "--node", node, sid=sid) + self.assertEqual(rc, 0, out) + return out + + def agent(self, model, brief, sid="s1", **extra): + return self.tool("Agent", sid=sid, tool_input=dict({"model": model, "prompt": brief, "isolation": "worktree"}, **extra)) + + def decision(self, res): + rc, out, err = res + self.assertEqual((rc, err), (0, ""), res) + return json.loads(out)["hookSpecificOutput"] if out.strip() else {} + + def denied(self, res, why): + d = self.decision(res) + self.assertEqual(d.get("permissionDecision"), "deny", d) + self.assertIn(why, d["permissionDecisionReason"]) + return d["permissionDecisionReason"] + + def nodes(self, sid="s1"): + return {i: v.get("st") for i, v in self.state(sid)["plan"]["state"].items()} + + # recording: each refusal + + def test_refuses_a_bad_node_id(self): + self.refused(PLAN.replace("| a |", "| A_1 |"), "node id 'A_1' is not") + + def test_refuses_a_duplicate_node(self): + self.refused(PLAN.replace("| b | ordinary | - | p-b | sisi/b.py", "| a | ordinary | - | p-b | sisi/b.py"), "node a appears twice") + + def test_refuses_a_missing_need(self): + self.refused(PLAN.replace("| a, b |", "| a, zz |"), "node c needs zz, which is not a node") + + def test_refuses_a_cycle(self): + self.refused(PLAN.replace("| a | routine | - |", "| a | routine | c |"), "cycle") + + def test_refuses_an_unknown_class(self): + self.refused(PLAN.replace("| routine |", "| cheap |"), "class 'cheap'") + + def test_refuses_two_worker_nodes_on_one_branch(self): + self.refused(PLAN.replace("| p-b |", "| p-a |"), "branch p-a is given to more than one node") + + def test_refuses_a_worker_node_without_a_branch(self): + self.refused(PLAN.replace("| p-b |", "| - |"), "node b needs a branch of its own") + + def test_refuses_parallel_nodes_that_share_files(self): + for a, b in (("sisi/a.py", "sisi/a.py"), ("sisi", "sisi/b.py"), ("sisi/*.py", "sisi/b.py")): + self.refused(PLAN.replace("| sisi/a.py |", "| %s |" % a).replace("| sisi/b.py |", "| %s |" % b), + "nodes a and b can run at the same time") + + def test_nodes_in_sequence_may_share_files(self): + self.ready_plan(text=PLAN.replace("| sisi/c.py |", "| sisi/a.py, sisi/b.py |")) + + def test_refuses_more_than_one_sink(self): + self.refused(PLAN.replace("| c | hard | a, b |", "| c | hard | a |"), "exactly one final join") + + def test_refuses_no_table(self): + self.refused("just words", "no table found") + + def test_record_prints_waves_critical_path_dispatch_line_why_and_record(self): + out = self.ready_plan() + self.assertIn("critical path 3 wave(s)", out) + self.assertIn("wave 1: a (routine: exact spec, test decides), b (ordinary: some judgement)", out) + self.assertIn("dispatch wave 1 now, all in one message: a, b", out) + self.assertIn("record (last 20 judged per class): routine none judged yet", out) + self.assertEqual(self.nodes(), {}) + + def test_a_table_without_the_why_column_records(self): + six = "\n".join("|".join(l.split("|")[:-2]) + "|" if l.startswith("|") else l for l in PLAN.splitlines()) + "\n" + self.assertNotIn("why", six) + out = self.ready_plan(text=six) + self.assertIn("wave 1: a (routine), b (ordinary)", out) + + def test_record_line_counts_the_last_twenty_judged_per_class(self): + self.table(TABLE) + 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") + 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") + + def test_rerecording_keeps_the_state_of_unchanged_nodes(self): + self.ready_plan() + self.pick("a") + self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {}) + self.assertEqual(self.nodes(), {"a": "running"}) + self.assertEqual(self.record(PLAN.replace("test b passes", "test b and b2 pass"))[0], 0) + self.assertEqual(self.nodes(), {"a": "running"}) + self.assertEqual(self.record(PLAN.replace("test a passes", "test a2 passes"))[0], 0) + self.assertEqual(self.nodes(), {}) + + def pick_header(self, node, sid="s1"): + st = self.state(sid) + n = next(x for x in st["plan"]["nodes"] if x["id"] == node) + return "sisi node: %s\nbranch: %s\nYou are a worker.\nDo it." % (node, n["branch"]) + + def test_plan_brief_is_a_chore_built_from_done_with_the_total_cost_rule(self): + self.ready_plan() + rc, out, _ = self.sisi("plan", "brief", sid="s1") + self.assertEqual(rc, 0, out) + self.assertEqual(out.splitlines()[0], "sisi chore: plan") + 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)"): + self.assertIn(want, out) + + def test_a_retro_clears_the_plan(self): + self.ready_plan() + 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()) + + # pick --node + + def test_pick_node_takes_class_and_branch_and_prints_the_header(self): + self.ready_plan() + out = self.pick("a") + self.assertIn("worker: alpha", out) + for want in ("sisi node: a", "branch: p-a (its own worktree and build folder)", "may change: sisi/a.py", "check: test a passes", "needs done: -"): + self.assertIn(want, out) + self.assertIn("record (last 20 judged per class)", out) + self.assertEqual(self.state()["pending"]["alpha"], [{"limit": None, "branch": "p-a", "node": "a"}]) + + def test_pick_node_refuses_a_waiting_or_lead_node(self): + self.ready_plan() + rc, out, _ = self.sisi("pick", "--node", "c", sid="s1") + self.assertEqual(rc, 1) + self.assertIn("node c is not ready (needs not done: a, b)", out) + rc, out, _ = self.sisi("pick", "--node", "join", sid="s1") + self.assertEqual(rc, 1) + self.assertIn('sisi plan --done join', out) + + # the hook: each reason to deny + + def test_deny_without_done(self): + self.table(TABLE) + self.hook("prompt", prompt="build it") + self.denied(self.agent("alpha", "Do it."), "no done is recorded yet") + + def test_deny_without_a_plan(self): + self.table(TABLE) + self.hook("prompt", prompt="build it") + self.done() + self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0) + why = self.denied(self.agent("alpha", "Do it."), "no plan is recorded") + self.assertIn("sisi plan brief", why) + self.assertEqual(self.state().get("delegations_since", 0), 0) # a denied call is no delegation + self.assertEqual(self.state()["picked"], ["alpha"]) # and spends no pick + + def test_a_chore_brief_passes_without_a_plan(self): + self.table(TABLE) + self.hook("prompt", prompt="build it") + self.done() + self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0) + self.assertEqual(self.decision(self.agent("gamma", "sisi chore: plan\nYou are a worker.")), {}) + + def test_deny_an_unpicked_model(self): + self.ready_plan() + self.denied(self.agent("alpha", self.pick_header("a")), "the wheel did not give you this worker") + + def test_deny_a_call_with_no_model(self): + self.ready_plan() + self.pick("a") + res = self.tool("Agent", tool_input={"prompt": self.pick_header("a"), "isolation": "worktree"}) + self.denied(res, "no model is named") + + def test_deny_a_model_not_in_the_table(self): + self.ready_plan() + self.pick("a") + self.denied(self.agent("zeta", self.pick_header("a")), "sisi pick --node ID") + + def test_deny_a_brief_without_a_node_line(self): + self.ready_plan() + self.pick("a") + self.denied(self.agent("alpha", "You are a worker. Do it."), "names no plan node") + + def test_deny_a_node_that_is_not_ready(self): + self.ready_plan() + self.pick("a") + self.denied(self.agent("alpha", "sisi node: c\nDo it."), "node c is not ready (needs not done: a, b)") + + def test_deny_a_node_already_running(self): + self.ready_plan() + self.pick("a") + self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {}) + self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0) + self.denied(self.agent("alpha", self.pick_header("a")), "node a is not ready (already running)") + + def test_deny_a_worker_picked_for_another_node(self): + self.ready_plan(text=PLAN.replace("| b | ordinary |", "| b | routine |")) + self.pick("a") + self.denied(self.agent("alpha", "sisi node: b\nDo it."), "picked for node a, not b") + + def test_two_picks_of_one_worker_are_spent_by_node_not_by_order(self): + self.ready_plan(text=PLAN.replace("| b | ordinary |", "| b | routine |")) + self.pick("a") + self.pick("b") + self.assertEqual(self.decision(self.agent("alpha", self.pick_header("b"))), {}) + self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {}) + self.assertEqual(self.nodes(), {"a": "running", "b": "running"}) + + def test_deny_a_shell_out_to_a_worker(self): + self.table(test_core.WORKERS) + self.hook("prompt", prompt="build it") + self.done() + self.denied(self.tool("Bash", tool_input={"command": 'agy --print "sisi chore: x"'}), "do not shell out to a worker") + + def test_deny_a_parallel_node_without_its_own_worktree(self): + self.ready_plan() + self.pick("a") + self.denied(self.agent("alpha", self.pick_header("a"), isolation=None), 'isolation "worktree"') + self.pick("b") + res = self.tool("mcp__t3-code__delegate_task", tool_input={"task": self.pick_header("b"), "target": {"model": "beta"}, "isolation": "shared"}) + self.denied(res, 'isolation "worktree"') + + def test_the_deny_is_the_decision_not_a_reminder(self): + """Fails if watch stops printing a deny: the call would go through with only a note.""" + self.ready_plan() + d = self.decision(self.agent("alpha", "Do it.")) + self.assertEqual(d.get("permissionDecision"), "deny") + self.assertNotIn("additionalContext", d) + + def test_the_planned_delegation_passes_and_runs_its_node(self): + self.ready_plan() + self.pick("a") + self.pick("b") + self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"))), {}) + res = self.tool("mcp__t3-code__delegate_task", tool_input={"task": self.pick_header("b"), "target": {"model": "beta"}, "isolation": "worktree"}) + self.assertEqual(self.decision(res), {}) + self.assertEqual(self.nodes(), {"a": "running", "b": "running"}) + self.assertEqual(self.state()["delegations_since"], 2) + + def test_sisi_commands_and_direct_edits_are_never_denied(self): + self.ready_plan() + self.assertEqual(self.decision(self.tool("Bash", tool_input={"command": "sisi plan"})), {}) + d = self.decision(self.tool("Edit", tool_input={"file_path": "x"})) + self.assertNotIn("permissionDecision", d) + + def test_workers_are_never_denied(self): + self.table(TABLE) + self.assertEqual(self.decision(self.tool("Agent", sid="w1", agent_id="sub1", tool_input={"prompt": "Do it."})), {}) + self.hook("prompt", sid="w2", prompt="You are a worker. Do this task yourself.") + self.assertEqual(self.decision(self.tool("Agent", sid="w2", tool_input={"prompt": "Do it."})), {}) + + def test_enforce_false_gives_reminders(self): + self.ready_plan() + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"enforce": False}})) + d = self.decision(self.agent("alpha", "Do it.")) + self.assertNotIn("permissionDecision", d) + self.assertIn("names no plan node", d["additionalContext"]) + self.assertIn("the wheel did not give you", d["additionalContext"]) + self.assertEqual(self.state()["delegations_since"], 1) + + def test_an_error_inside_watch_lets_the_call_through(self): + self.ready_plan() + from sisi import cli, plan + stdin = io.StringIO(json.dumps({"session_id": "s1", "cwd": self.proj, "hook_event_name": "PreToolUse", "tool_name": "Agent", + "tool_input": {"model": "alpha", "prompt": "Do it."}})) + with mock.patch.object(plan, "deny", side_effect=RuntimeError("boom")), mock.patch.object(sys, "stdin", stdin): + rc, out = self.in_process(cli.main, ["watch"]) + self.assertEqual((rc, out), (0, "")) + self.assertIn("boom", self.read(self.tmp, "state", "core-errors.log")) + + # judge and the end of the turn + + def test_judge_good_marks_done_and_bad_reopens(self): + self.ready_plan() + self.pick("a") + self.pick("b") + self.agent("alpha", self.pick_header("a")) + self.tool("Agent", tool_input={"model": "beta", "prompt": self.pick_header("b"), "isolation": "worktree"}) + self.assertEqual(self.sisi("judge", "alpha", "good", "did the work well", sid="s1")[0], 0) + self.assertEqual(self.sisi("judge", "beta", "bad", "broke the tests badly", sid="s1")[0], 0) + self.assertEqual(self.nodes(), {"a": "done", "b": "failed"}) + out = self.sisi("plan", sid="s1")[1] + self.assertIn("ready: b", out) + self.assertIn("a [routine] done", out) + + def test_gate_sends_the_lead_back_while_nodes_are_ready_and_not_started(self): + self.ready_plan() + rc, out, _ = self.hook("gate") + self.assertIn('"block"', out) + self.assertIn("nodes a, b are ready and not started", out) + self.assertIn("`sisi pick --node a` `sisi pick --node b`", out) + + def test_gate_lets_the_turn_end_while_nodes_only_run(self): + self.ready_plan() + for n, m in (("a", "alpha"), ("b", "beta")): + self.pick(n) + self.assertEqual(self.decision(self.agent(m, self.pick_header(n))), {}) + self.assertEqual(self.hook("gate")[1], "") + + def test_gate_names_the_lead_join_when_only_it_is_ready(self): + self.ready_plan() + for n in ("a", "b", "c"): + self.assertEqual(self.sisi("plan", "--done", n, "done by hand and tested", sid="s1")[0], 0) + out = self.hook("gate")[1] + self.assertIn("node join is yours and ready: full suite passes", out) + + +if __name__ == "__main__": + unittest.main()