From df744edc7c831ea3099da3588b2af1d735e0a71d Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Wed, 2 Dec 2026 09:15:23 -0700 Subject: [PATCH] Plan fixes: issued chores only, brief from any field, first-line node, exact judge match, concurrency-based isolation, running nodes kept on re-record, lead join, damaged state; single claim path, one outcomes pass Co-Authored-By: Claude Opus 5.5 --- sisi/hooks.py | 77 +++++++------- sisi/models.py | 41 ++++---- sisi/plan.py | 246 ++++++++++++++++++++++++--------------------- sisi/rules.py | 5 +- tests/test_core.py | 4 +- tests/test_plan.py | 115 +++++++++++++++++++-- 6 files changed, 301 insertions(+), 187 deletions(-) diff --git a/sisi/hooks.py b/sisi/hooks.py index 3d10eb1..6531523 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -15,13 +15,11 @@ METER = ("sisi: %d direct tool calls this turn (the limit is %d). Delegate the r GATE = ("sisi: this piece of work changed things and has no retro yet. Run `sisi retro` to see what happened, then record `sisi retro --gap \"\" --cause \"\" --improve \"\" --term --problem N|\"\" --level core|user|project` " "or `sisi retro --no-gap \"\" --term --better \"\"` (or pause: `sisi retro --later \"\"`).") NODONE = "sisi: no done is recorded yet. Define what the person wants and what comes next now: `sisi done --goal \"\" --check \"\" [--check ...] --next \"\"`." -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." +UNKNOWN = "sisi: the worker you named is not in the models table, so the table is out of date. Rebuild it now with a research worker (`sisi models research` prints the brief; `sisi models research --record FILE` records the answer), and use `sisi pick` next time." NOSHELL = "sisi: do not shell out to a worker; start it with the host's delegation tool next time." FAILED = "sisi: check %s failed. A failed check is a gap: record `sisi retro --gap \"\" --cause \"\" --improve \"\" --term --problem N|\"\" --level core|user|project` (or pause: `sisi retro --later \"\"`)." OPEN = "sisi: these checks have no verdict yet: %s. Give each one: `sisi done --pass N \"\"` or `sisi done --fail N \"\"` (or pause: `sisi retro --later \"\"`)." @@ -183,30 +181,23 @@ def watch(p): return 0 shell = kind == "shell" and models.is_call(command) 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)) + fields = [command] if shell else [v[:20000] for v in ti.values() if isinstance(v, str)][:20] # the brief may be in any field 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)), "") - stop, node = _outside(s, tool, ti, brief, text, shell, names, cfg) - if stop and cfg["enforce"]: - deny = stop + stop, soft, node, chore, probe = _outside(s, tool, ti, fields, text, shell, names, cfg) + # deny only a lead (it has had a request) whose call sisi can read; anything else is reminded, never stopped + if stop and cfg["enforce"] and s.get("prompts") and any(f.strip() for f in fields): + deny = stop + soft 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"): + notes += stop + soft + screen_brief_without_look(" ".join(fields)) and notes.append(NOLOOK) + s.update(probe) # the pick this delegation spent, if any + chore and s["chores"].remove(chore) + if node and probe.get("claimed"): from . import plan - w = s["workers_since"][-1] - plan.start(s, node, w, ((s.get("starts") or {}).get(w) or [time.time()])[-1]) + plan.start(s, node, *probe["claimed"]) + s.pop("claimed", None) s["delegations_since"] = s.get("delegations_since", 0) + 1 s.pop("paused", None) elif kind == "edit" and not s.get("done"): @@ -225,30 +216,30 @@ def watch(p): 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.""" +def _outside(s, tool, ti, fields, text, shell, names, cfg): + """(why it strays, reminder lines, the plan node it starts, the issued chore it spends, the state with its pick spent).""" from . import plan - why, chore = [], bool(plan.CHORE_LINE.search(brief)) + why, soft = [], [] + stray, node, chore = plan.deny(s, fields) 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 + stray and (cfg["enforce"] or plan.get(s)) and why.append(stray) # as reminders, plan notes only once there is a plan + probe = json.loads(json.dumps({k: s.get(k) for k in ("picked", "starts", "pending", "meta", "workers_since") if k in s})) + table_text = store.read(models.table()) + if tool != "workflow" and not models.claim(probe, text, not shell and bool(names[0]), node): + known = models.known(table_text, text) + if models.usable(table_text): # with no usable table there is nothing to pick from: `sisi models` says to research it + not shell and text.strip() and not known and models.stale(text) + why.append(UNKNOWN if not shell and text.strip() and not known else UNPICKED) + elif tool != "workflow": + w = probe["workers_since"][-1] + probe["claimed"] = (w, probe["starts"][w][-1]) + m = (probe.get("meta") or {}).get("%s %r" % probe["claimed"]) or {} + node and m.get("node") not in (None, node) and why.append("sisi: this worker was picked for node %s, not %s; pick again with `sisi pick --node %s`." % (m["node"], node, node)) + if node and plan.concurrent(s, node) and ti.get("isolation") != "worktree": + (why if tool in ("agent", "task") or tool.endswith("delegate_task") else soft).append( + "sisi: node %s runs beside others: start it with isolation \"worktree\" so it gets its own checkout." % node) + return why, soft, node, chore, probe def direct(args, cwd=None): diff --git a/sisi/models.py b/sisi/models.py index 4cf14de..2f5238c 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -160,8 +160,8 @@ def is_call(command_line): def known(table_text, text): return claim({"picked": [short(r[0]) for r in rows(table_text)]}, text, True) -def claim(s, text, segment=False): - """Spend the pick that this delegation's model text names; False when none of the picks fits. With `segment` (the +def claim(s, text, segment=False, node=None): + """Spend the pick that this delegation's model text names (the one made for `node` first); False when none fits. With `segment` (the host names its models shortly: `fast` for `maker-fast-2`) one whole `-` segment of a picked id's last `/` part that has a letter fits.""" for name in s.get("picked") or []: if any(re.search(r"(?" | sisi plan --fail ID ""\n' " FILE holds one markdown table: | node | class | needs | branch | files | check | why | (why is optional)") @@ -74,20 +74,16 @@ def parse(text): 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 + 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: - 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 + busy.add(i) + out[i] = set(by[i]["needs"]).union(*(walk(j) for j in by[i]["needs"])) + busy.discard(i) return out[i] - return out if all(walk(i, frozenset()) is not None for i in by) else None + try: return {i: walk(i) for i in by} + except ValueError: return None def overlap(a, b): @@ -95,36 +91,36 @@ def overlap(a, b): 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 = [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"] + ids, seen = {n["id"] for n in nodes}, set() 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] + 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 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)] + 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(sinks)) - return "" + 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): @@ -134,11 +130,22 @@ def waves(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 + p["state"] = {k: v for k, v in p["state"].items() if isinstance(v, dict)} 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.""" - 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] + 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) @@ -161,40 +168,47 @@ def record_line(): def show(p): - st, rd, now = p.get("state") or {}, ready(p), time.time() - out = [] + rd, now, out = ready(p), time.time(), [] 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") + 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 issue(name, cwd=None): + """A chore brief sisi printed in this session: one delegation may carry its `sisi chore: NAME` line without done or a plan.""" + if sid := store.current_session(cwd): + with store.session(sid) as s: + s["chores"] = ((s["chores"] if isinstance(s.get("chores"), list) else []) + [name])[-10:] + + 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 {} + 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 + issue("plan", cwd) 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}} + 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): @@ -205,40 +219,41 @@ def run(args, cwd=None): 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 + 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 = 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])} + 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: its worker's verdict closes it (`sisi judge WORKER good|bad \"\"`)" % args[1] + if args[0] == "--done" and 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 = 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 + 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 print(USAGE) return 1 +def why_not(p, i): + return "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 = (args[1] if len(args) > 1 else ""), store.current_session(cwd) - p = None + i, sid, p = (args[1] if len(args) > 1 else ""), store.current_session(cwd), None if sid: with store.session(sid) as s: - p = s.get("plan") if isinstance(s.get("plan"), dict) else None + 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 \"\"`" % (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 "") + else "node %s is not ready (%s)" % (i, why_not(p, i)) if i not in ready(p) else "") if why: print("sisi pick: %s." % why) return None, None @@ -246,59 +261,62 @@ def for_pick(args, cwd=None): 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"], + n = node(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["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 "-")]) + "needs done: " + (", ".join("%s (%s)" % (x, p["state"].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} + 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 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) + """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: - st[hit] = {"st": "done", "evidence": "judged good"} if verdict == "good" else {"st": "failed", "why": "judged " + verdict} + p["state"][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 +def first(fields, rx): + """The match of `rx` on the first non-empty line of any of these texts, else None.""" + return next((m for f in fields if (line := next((l for l in f.splitlines() if l.strip()), "")) and (m := rx.match(line.strip()))), None) + + +def deny(s, fields): + """(why this delegation strays from the plan or "", the plan node it starts, the issued chore it spends).""" + p, c = get(s), first(fields, CHORE_LINE) + if c and c.group(1) in (s.get("chores") if isinstance(s.get("chores"), list) else []): + return "", None, c.group(1) + if c: + return ("sisi: `sisi chore: %s` was not printed by sisi in this session; print that chore's brief again (`sisi plan brief`, " + "`sisi models research` or `sisi rules organize`) and send it as printed." % c.group(1)), 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 " - "(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 + "(it carries its `sisi chore: plan` line), then `sisi plan --record FILE`."), None, None + m = first(fields, 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 \"\"`." % (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 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) + 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)." % ( diff --git a/sisi/rules.py b/sisi/rules.py index 1b33a99..31a0c22 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -22,7 +22,8 @@ _NOTE = re.compile(r"(?:\s+\(p\d+: (?:came back \d+x|not seen) since(?:; p\d+: ( _RETRO_TAG, _DATE = re.compile(r"(?:\s*\[retro\b[^\]]*\])+$"), re.compile(r"\d{4}-\d{2}-\d{2}") _DKEY = lambda s: " ".join(re.sub(r"(?i)(?:\s*\[(?:retro|agent)\b[^\]]*\])+$", "", _NOTE.sub("", re.sub(r"^\s*(?:[-*]|\d+\.)\s+", "", s.replace("`", "")).strip())).lower().split()) -ORGANIZE = """You are a worker. Do this task yourself; do not delegate it further. +ORGANIZE = """sisi chore: rules organize +You are a worker. Do this task yourself; do not delegate it further. Audit and organize the learned rules below. They are instructions an AI engineering agent reads at the start of every session: the first list in every project, the second only in the project "%(name)s". Retros add to @@ -615,6 +616,8 @@ def run(args, cwd=None): show(cwd) return 0 if args[0] == "organize" and len(args) == 1: + from . import plan + plan.issue("rules organize", cwd) print(organize_brief(cwd)) return 0 if args[0] == "organize" and len(args) == 3 and args[1] == "--record": diff --git a/tests/test_core.py b/tests/test_core.py index 06b9e31..00a6232 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -3100,7 +3100,7 @@ cli.main(["tick"]) self.assertIn("8 direct tool calls this turn (the limit is 8)", msg) self.assertIn('sisi direct ""', msg) self.assertEqual(self.state()["direct"], 9) - # unpicked known and unknown delegations both go through, remind of sisi pick, and record starts for sisi judge + # unpicked known and unknown delegations both go through (reminder mode) and remind of sisi pick; jobs started earlier are judged self.table(self.CLAUDE) self.hook("tick", sid="s2") self.hook("prompt", sid="s2", prompt="go") @@ -3109,7 +3109,7 @@ cli.main(["tick"]) self.assertIn("sisi pick", self.note(self.tool("Agent", sid="s2", tool_input={"model": "new-maker-9"}))) with open(os.path.join(self.tmp, "state", "core-sessions", "s2.json"), "r+") as f: st = json.load(f) - st["starts"]["claude-sonnet-5-5"] = [time.time() - 12 * 60 - 5] + st.setdefault("starts", {})["claude-sonnet-5-5"] = [time.time() - 12 * 60 - 5] st["starts"]["new-maker-9"] = [time.time() - 7 * 60 - 5] f.seek(0), f.truncate(), json.dump(st, f) self.assertEqual(self.sisi("judge", "sonnet", "good", "finished the job cleanly", sid="s2")[0], 0) diff --git a/tests/test_plan.py b/tests/test_plan.py index 813ae2b..e672222 100644 --- a/tests/test_plan.py +++ b/tests/test_plan.py @@ -1,7 +1,10 @@ """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 +try: # the module, not its class: its tests must not run twice + from tests import test_core +except ImportError: + import test_core sys.path.insert(0, test_core.REPO) TABLE = test_core.HEADER + ( @@ -96,6 +99,13 @@ class Plan(unittest.TestCase): 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_a_final_join_that_is_not_the_leads(self): + self.refused(PLAN.replace("| join | lead | c | - | - |", "| join | hard | c | p-j | docs |"), "the final join join must be class lead") + + def test_refuses_a_worker_node_without_files_or_check(self): + self.refused(PLAN.replace("| sisi/b.py |", "| - |"), "worker node b needs files it may change and a check") + self.refused(PLAN.replace("| test b passes |", "| - |"), "worker node b needs files it may change and a check") + def test_refuses_no_table(self): self.refused("just words", "no table found") @@ -130,7 +140,14 @@ class Plan(unittest.TestCase): 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(), {}) + self.assertEqual(self.nodes(), {"a": "running"}) # a running node keeps its state by id + rc, out, _ = self.record(PLAN.replace("| sisi/a.py |", "| sisi/a2.py |")) + self.assertEqual(rc, 1, out) + self.assertIn("node a is running", out) + self.assertIn("a", self.nodes()) + rc, out, _ = self.record(PLAN.replace("| a | routine | - |", "| a2 | routine | - |").replace("| a, b |", "| a2, b |")) + self.assertEqual(rc, 1, out) + self.assertIn("node a is running", out) def pick_header(self, node, sid="s1"): st = self.state(sid) @@ -192,8 +209,29 @@ class Plan(unittest.TestCase): self.table(TABLE) self.hook("prompt", prompt="build it") self.done() + brief = self.sisi("plan", "brief", sid="s1")[1] self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0) - self.assertEqual(self.decision(self.agent("gamma", "sisi chore: plan\nYou are a worker.")), {}) + self.assertEqual(self.decision(self.agent("gamma", brief)), {}) + self.assertEqual(self.state().get("chores"), []) # spent + self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0) + self.denied(self.agent("gamma", brief), "was not printed by sisi in this session") + + def test_an_invented_chore_line_is_denied(self): + self.table(TABLE) + self.hook("prompt", prompt="build it") + self.assertEqual(self.sisi("pick", "hard", sid="s1")[0], 0) + why = self.denied(self.agent("gamma", "sisi chore: anything\nDo it."), "`sisi chore: anything` was not printed by sisi") + self.assertIn("no done is recorded", why) + + def test_sisis_own_chore_briefs_carry_their_line_and_pass(self): + self.table(TABLE) + self.hook("prompt", prompt="tidy up") + for args, line in ((("rules", "organize"), "sisi chore: rules organize"), (("models", "research"), "sisi chore: models research")): + rc, brief, _ = self.sisi(*args, sid="s1") + self.assertEqual((rc, brief.splitlines()[0]), (0, line)) + self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0) + self.assertNotIn("permissionDecision", self.decision(self.agent("alpha", brief)), line) + self.assertEqual(self.state()["chores"], []) def test_deny_an_unpicked_model(self): self.ready_plan() @@ -208,12 +246,17 @@ class Plan(unittest.TestCase): 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") + self.denied(self.agent("zeta", self.pick_header("a")), "not in the models table") 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") + self.denied(self.agent("alpha", "You are a worker. Do it."), "first line must be `sisi node: ID`") + + def test_deny_a_node_line_that_is_not_the_first_line(self): + self.ready_plan() + self.pick("a") + self.denied(self.agent("alpha", "Do this.\nsisi node: a"), "first line must be `sisi node: ID`") def test_deny_a_node_that_is_not_ready(self): self.ready_plan() @@ -288,7 +331,7 @@ class Plan(unittest.TestCase): 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("first line must be `sisi node: ID`", d["additionalContext"]) self.assertIn("the wheel did not give you", d["additionalContext"]) self.assertEqual(self.state()["delegations_since"], 1) @@ -302,6 +345,66 @@ class Plan(unittest.TestCase): self.assertEqual((rc, out), (0, "")) self.assertIn("boom", self.read(self.tmp, "state", "core-errors.log")) + def test_a_brief_in_another_field_is_read(self): + self.ready_plan() + self.pick("a") + res = self.tool("subagent_spawn", tool_input={"objective": self.pick_header("a"), "model": "alpha"}) + d = self.decision(res) + self.assertNotIn("permissionDecision", d) # a tool with no isolation field: reminded only + self.assertIn('isolation "worktree"', d["additionalContext"]) + self.assertEqual(self.nodes(), {"a": "running"}) + + def test_a_call_with_no_text_is_reminded_not_denied(self): + self.ready_plan() + d = self.decision(self.tool("Workflow", tool_input={"steps": [1, 2]})) + self.assertNotIn("permissionDecision", d) + self.assertIn("first line must be", d["additionalContext"]) + + def test_a_session_with_no_request_yet_is_reminded_not_denied(self): + self.table(TABLE) + d = self.decision(self.agent("alpha", "Do it.", sid="fresh")) + self.assertNotIn("permissionDecision", d) + self.assertIn("no done is recorded", d["additionalContext"]) + + def test_a_node_in_sequence_needs_no_worktree(self): + seq = COLS + ("| a | routine | - | p-a | sisi/a.py | test a passes | x |\n| b | routine | a | p-b | sisi/b.py | test b passes | x |\n" + "| join | lead | b | - | - | suite passes | x |\n") + self.ready_plan(text=seq) + self.pick("a") + self.assertEqual(self.decision(self.agent("alpha", self.pick_header("a"), isolation=None)), {}) + + def test_done_refuses_a_running_worker_node(self): + self.ready_plan() + self.pick("a") + self.agent("alpha", self.pick_header("a")) + rc, out, _ = self.sisi("plan", "--done", "a", "it looks finished to me", sid="s1") + self.assertEqual(rc, 1) + self.assertIn("sisi judge WORKER", out) + self.assertEqual(self.nodes(), {"a": "running"}) + + def test_a_damaged_plan_state_does_not_crash(self): + self.ready_plan() + path = os.path.join(self.tmp, "state", "core-sessions", "s1.json") + s = self.state() + s["plan"]["state"] = {"a": "junk", "b": {"st": 5}, "c": None} + self.write(path, json.dumps(s)) + rc, out, err = self.sisi("plan", sid="s1") + self.assertEqual((rc, err), (0, ""), out) + self.assertIn("ready: a, b", out) + self.assertEqual(self.sisi("pick", "--node", "a", sid="s1")[0], 0) + s["plan"]["state"] = ["junk"] + self.write(path, json.dumps(s)) + self.assertEqual(self.sisi("plan", sid="s1")[0], 0) + + def test_judge_moves_only_the_node_its_job_started(self): + from sisi import plan + s = {"plan": {"nodes": [{"id": "a", "cls": "routine", "needs": [], "branch": "b", "files": ["x"], "check": "c"}], + "state": {"a": {"st": "running", "worker": "alpha", "since": 100.0}}}} + plan.judged(s, "alpha", 200.0, "good") + self.assertEqual(s["plan"]["state"]["a"]["st"], "running") + plan.judged(s, "alpha", 100.0, "good") + self.assertEqual(s["plan"]["state"]["a"]["st"], "done") + # judge and the end of the turn def test_judge_good_marks_done_and_bad_reopens(self):