diff --git a/sisi/hooks.py b/sisi/hooks.py index e2cc869..937d303 100644 --- a/sisi/hooks.py +++ b/sisi/hooks.py @@ -182,19 +182,19 @@ def watch(p): return 0 shell = kind == "shell" and models.is_call(command) if kind == "delegate" or shell: - fields = [command] if shell else [v[:20000] for v in ti.values() if isinstance(v, str)][:20] # the brief may be in any field + brief = command if shell else max((v[:64000] for v in ti.values() if isinstance(v, str)), key=len, default="") # the longest text field is the brief 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, soft, node, chore, probe = _outside(s, tool, ti, fields, text, shell, names, cfg) + stop, soft, node, chore, probe = _outside(s, tool, ti, brief, 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): + if stop and cfg["enforce"] and s.get("prompts") and brief.strip(): deny = stop + soft else: notes += stop + soft - screen_brief_without_look(" ".join(fields)) and notes.append(NOLOOK) + screen_brief_without_look(brief) and notes.append(NOLOOK) s.update(probe) # the pick this delegation spent, if any - chore and s["chores"].remove(chore) + chore is None or s["chores"].pop(chore) if node and probe.get("claimed"): from . import plan plan.start(s, node, *probe["claimed"]) @@ -217,13 +217,13 @@ def watch(p): return 0 -def _outside(s, tool, ti, fields, text, shell, names, cfg): +def _outside(s, tool, ti, brief, 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, soft = [], [] - stray, node, chore = plan.deny(s, fields) + stray, node, chore = plan.deny(s, brief, shell) shell and not cfg["shell_workers"] and why.append(NOSHELL) - s.get("done") or chore or why.append(NODONE) + s.get("done") or chore is not None or why.append(NODONE) 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()) diff --git a/sisi/models.py b/sisi/models.py index 2f5238c..987895d 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -512,7 +512,7 @@ def run(args, cwd=None): return 0 if args == ["research"]: from . import plan - return plan.issue("models research", cwd) or print(research_brief()) or 0 + return plan.issue("models research", research_brief(), cwd) or 0 if len(args) == 3 and args[:2] == ["research", "--record"]: why = research_record(args[2]) return (print("sisi models: %s. Nothing was changed." % why) or 1) if why else 0 diff --git a/sisi/plan.py b/sisi/plan.py index 14b2155..2ef9dfd 100644 --- a/sisi/plan.py +++ b/sisi/plan.py @@ -3,7 +3,7 @@ Each node says what it needs first, its own branch, the files it may change and its check; one join brings everything back. The hooks hold the lead to it: no delegation outside the plan or out of order, no turn ending while a node is ready and not started. The plan lives in the session state and closes with the piece of work.""" -import contextlib, fnmatch, re, time +import contextlib, fnmatch, hashlib, re, time from . import store CLASSES = ("routine", "ordinary", "hard", "lead") @@ -136,7 +136,10 @@ def get(s): 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 {} + ids = {n["id"] for n in p["nodes"]} + for n in p["nodes"]: + n["needs"], n["files"] = [x for x in n["needs"] if x in ids], [x for x in n["files"] if isinstance(x, str)] + p["state"] = {k: v for k, v in p["state"].items() if isinstance(v, dict) and k in ids} if isinstance(p.get("state"), dict) else {} return p @@ -178,11 +181,16 @@ def show(p): 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.""" +def _sum(text): return hashlib.sha1(text.encode("utf-8", "replace")).hexdigest() + + +def issue(name, text, cwd=None): + """Print a chore brief and record it in this session: one delegation whose brief starts with this exact text may go without done or a plan.""" + text = text.strip() 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:] + s["chores"] = (s["chores"] if isinstance(s.get("chores"), list) else [])[-9:] + [[name, _sum(text), len(text)]] + print(text) def run(args, cwd=None): @@ -194,9 +202,8 @@ def run(args, cwd=None): 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 + return issue("plan", BRIEF % {"goal": d["goal"], "next": d["next"], "record": "sisi's " + record_line(), + "checks": "\n".join(" %d. %s" % (i, c["text"]) for i, c in enumerate(d["checks"], 1))}, cwd) or 0 if len(args) == 2 and args[0] == "--record": nodes, why = parse(store.read(args[1])) why = why or check(nodes) or ("" if sid else "no session; run this from the agent's session") @@ -223,8 +230,8 @@ def run(args, cwd=None): with store.session(sid) as s: p = get(s) n = node(p, args[1]) if p else None - why = ("no node %r in the plan" % args[1] if not n else "node %s is running: its worker's verdict closes it (`sisi judge WORKER good|bad \"\"`)" % args[1] - if args[0] == "--done" and st(p, args[1]) == "running" else "") + why = ("no node %r in the plan" % args[1] if not n else "node %s is running: only its worker's verdict closes or reopens it (`sisi judge WORKER good|bad \"\"`)" % args[1] + if st(p, args[1]) == "running" else "") if why: return print("sisi plan: %s." % why) or 1 p["state"][args[1]] = {"st": "done", "evidence": store.clean(args[2])} if args[0] == "--done" else {"st": "failed", "why": store.clean(args[2])} @@ -280,23 +287,30 @@ def judged(s, worker, t, verdict): p["state"][hit] = {"st": "done", "evidence": "judged good"} if verdict == "good" else {"st": "failed", "why": "judged " + verdict} -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 starts(brief, shell): + """Where the brief's lines may begin: its first non-empty line, or for a shell command any line (its first is the launcher).""" + out, at = [], 0 + for line in brief.splitlines(True): + line.strip() and out.append(at + len(line) - len(line.lstrip())) + at += len(line) + return out if shell else out[:1] -def deny(s, 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) +def deny(s, brief, shell=False): + """(why this delegation strays from the plan or "", the plan node it starts, the index of the issued chore it spends).""" + p, at = get(s), starts(brief, shell) + line = lambda rx: next((m for i in at if (m := rx.match(brief[i:].split("\n", 1)[0].strip()))), None) + chores, c = (s["chores"] if isinstance(s.get("chores"), list) else []), line(CHORE_LINE) if c: - 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 + hit = next((k for k, x in enumerate(chores) if isinstance(x, list) and len(x) == 3 and x[0] == c.group(1) and type(x[2]) is int + and any(_sum(brief[i:i + x[2]]) == x[1] for i in at)), None) + return ("", None, hit) if hit is not None else (( + "sisi: this `sisi chore: %s` brief is not one sisi printed in this session: print the chore's brief again (`sisi plan brief`, " + "`sisi models research` or `sisi rules organize`) and send it unchanged at the top of the brief." % 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 " "(it carries its `sisi chore: plan` line), then `sisi plan --record FILE`."), None, None - m = first(fields, NODE_LINE) + m = line(NODE_LINE) i = m.group(1).lower() if m else None n = node(p, i) if i else None why = ("sisi: the brief's first line must be `sisi node: ID`: pick with `sisi pick --node ID` and paste the header it prints at the top. Ready: %s." % (", ".join(ready(p)) or "none") if not m diff --git a/sisi/rules.py b/sisi/rules.py index 31a0c22..7fd97c4 100644 --- a/sisi/rules.py +++ b/sisi/rules.py @@ -617,8 +617,7 @@ def run(args, cwd=None): return 0 if args[0] == "organize" and len(args) == 1: from . import plan - plan.issue("rules organize", cwd) - print(organize_brief(cwd)) + plan.issue("rules organize", organize_brief(cwd), cwd) return 0 if args[0] == "organize" and len(args) == 3 and args[1] == "--record": why = organize_record(args[2], cwd) diff --git a/tests/test_core.py b/tests/test_core.py index a24d0c2..a0a7d53 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -4642,9 +4642,9 @@ cli.main(["tick"]) def test_the_product_stays_small(self): code = sum(len(self.read(p).splitlines()) for p in glob.glob(os.path.join(REPO, "sisi", "*.py"))) - self.assertLessEqual(code, 3070, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 3080, "sisi is two loops. If it needs more than this, find the simpler shape.") rulebook = self.read(REPO, "canon", "core.md") - self.assertLess(len(rulebook.splitlines()), 139) + self.assertLess(len(rulebook.splitlines()), 144) self.assertLessEqual(len(rulebook), 11269) diff --git a/tests/test_organize_evidence.py b/tests/test_organize_evidence.py index 21f1b6a..c629e38 100644 --- a/tests/test_organize_evidence.py +++ b/tests/test_organize_evidence.py @@ -121,7 +121,7 @@ class OrganizeEvidence(unittest.TestCase): self.assertLess(shape.index("## project"), shape.index("## drops")) self.assertLess(shape.index("## drops"), shape.index("## same problems")) self.assertLess(shape.index("## same problems"), shape.index("## flags")) - self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 42) + self.assertEqual(len(brief.split("=== The first list now")[0].splitlines()), 43) proj_line = self.read(self.proj, ".sisi", "rules.md").splitlines()[0] ans = self.write(os.path.join(self.tmp, "ans.md"), "## user\n## project\n- Kept project rule [retro 2026-11-26]\n" diff --git a/tests/test_plan.py b/tests/test_plan.py index e672222..7d575bc 100644 --- a/tests/test_plan.py +++ b/tests/test_plan.py @@ -214,13 +214,68 @@ class Plan(unittest.TestCase): 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") + self.denied(self.agent("gamma", brief), "is not one sisi printed in this session") + + def test_a_chore_line_must_carry_the_printed_brief(self): + 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.denied(self.tool("Agent", tool_input={"model": "gamma", "description": "sisi chore: plan", "prompt": "Arbitrary unplanned work"}), + "no plan is recorded") # the longest field is the brief: no chore line in it + self.denied(self.tool("Agent", tool_input={"model": "gamma", "description": "x", "prompt": "sisi chore: plan\nArbitrary unplanned work"}), + "is not one sisi printed in this session") + self.denied(self.agent("gamma", brief.replace("Goal:", "Goal: and also rewrite the installer")), "is not one sisi printed") + self.assertNotIn("permissionDecision", self.decision(self.agent("gamma", brief + "\nAlso: the lead's own note after it."))) + + def test_the_longest_field_is_the_brief(self): + self.ready_plan() + self.pick("a") + self.denied(self.tool("Agent", tool_input={"model": "alpha", "isolation": "worktree", "description": self.pick_header("a"), + "prompt": "Unrelated work that is not in the plan at all, described at length here."}), "first line must be") + self.assertNotIn("a", self.nodes()) + + def test_a_shell_worker_brief_carries_its_node_or_chore_on_any_line(self): + self.ready_plan() + self.table(test_core.WORKERS) + self.write(os.path.join(self.data, "config.json"), json.dumps({"core": {"shell_workers": True}})) + self.pick("a") + d = self.decision(self.tool("Bash", tool_input={"command": 'agy --print "\n%s"' % self.pick_header("a")})) + self.assertNotIn("permissionDecision", d) + self.assertEqual(self.nodes(), {"a": "running"}) + brief = self.sisi("models", "research", sid="s1")[1] + self.assertEqual(self.sisi("pick", "routine", sid="s1")[0], 0) + self.assertNotIn("permissionDecision", self.decision(self.tool("Bash", tool_input={"command": 'agy --print "\n%s"' % brief}))) + self.assertEqual(self.state()["chores"], []) + + def test_fail_refuses_a_running_node(self): + self.ready_plan() + self.pick("a") + self.agent("alpha", self.pick_header("a")) + rc, out, _ = self.sisi("plan", "--fail", "a", "I think it went wrong", sid="s1") + self.assertEqual(rc, 1) + self.assertIn("only its worker's verdict", out) + self.assertEqual(self.nodes(), {"a": "running"}) + + def test_bad_needs_and_orphan_state_do_not_crash(self): + self.ready_plan() + path = os.path.join(self.tmp, "state", "core-sessions", "s1.json") + s = self.state() + s["plan"]["nodes"][2]["needs"] = ["a", 7, None, "b"] + s["plan"]["state"] = {"ghost": {"st": "running", "worker": "alpha", "since": 1.0}} + 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) + self.assertEqual(self.record(PLAN)[0], 0) 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") + why = self.denied(self.agent("gamma", "sisi chore: anything\nDo it."), "`sisi chore: anything` brief is not one sisi printed") self.assertIn("no done is recorded", why) def test_sisis_own_chore_briefs_carry_their_line_and_pass(self):