diff --git a/canon/core.md b/canon/core.md index 1fd932b..50f61bf 100644 --- a/canon/core.md +++ b/canon/core.md @@ -80,13 +80,15 @@ change, what it may create, and a time limit (`sisi pick CLASS --limit MINUTES [ limit it stops and reports as it stands: what is proven, what failed, what did not run. Extending is the lead's call, made once, with a reason (`sisi judge WORKER extend MINUTES ""`). Decide the central mechanism in the brief, set against the person's standing rules on its subject, and say what a -failed or gamed job does to each number it optimizes. For a reported fault, the report's exact inputs -are an acceptance test. For a replacement, list each behaviour of the old thing as keep, change or drop, -with a check for every keep. Always use the newest version of a model within its maker and class. Its -report is evidence for you to judge, not a fact to pass on; record how it went with `sisi judge`. When a -worker fails for a limit, a login or a connection, judge it `out` with the provider's message (sisi -retries it by itself) and give the same brief to the next one at once: do not ask the person and do -not report it. Rebuild the models table in the background when session start says it is old. +failed or gamed job does to each number it optimizes. For anything the person will look at, the brief +states the look (type, colours, spacing, layout at each width), chosen with the person from previews. +For a reported fault, the report's exact inputs are an acceptance test. For a replacement, list each +behaviour of the old thing as keep, change or drop, with a check for every keep. Always use the newest +version of a model within its maker and class. Its report is evidence for you to judge, not a fact to +pass on; record how it went with `sisi judge`. When a worker fails for a limit, a login or a connection, +judge it `out` with the provider's message (sisi retries it by itself) and give the same brief to the +next one at once: do not ask the person and do not report it. Rebuild the models table in the background +when session start says it is old. ## 6. Report plainly diff --git a/sisi/hooks.py b/sisi/hooks.py index f404121..0b01940 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.") +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." 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|\"\"` (or pause: `sisi retro --later \"\"`)." @@ -68,8 +70,7 @@ def tool_class(tool): _classes = {n: c for c, names in raw.items() for n in names} except (ValueError, AttributeError, TypeError): _classes = {} # a missing or broken table meters nothing rather than breaking the session - tool = tool.lower() - return _classes.get(tool) or ("delegate" if tool.endswith("delegate_task") else "") + return _classes.get(t := tool.lower()) or ("delegate" if t.endswith("delegate_task") else "") def own(command): @@ -118,9 +119,7 @@ def tick(p): store.append(env, "export SISI_SESSION_ID=%s" % sid, once=True) # so `sisi retro` knows its session if not os.path.exists(os.path.join(store.DATA, "generated", "core.md")): rules.build_rulebook() - text = "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x) - if text: - print(text) + (text := "\n".join(x for x in (rules.project_text(cwd), rules.due(cwd, claim=True), models.stale(), "" if worker else _faults(cwd, False, free, sid)) if x)) and print(text) return 0 @@ -151,6 +150,23 @@ def prompt(p): return 0 +# A brief states no look when it makes something (MAKING), names two or more of SCREEN and has neither a `Look:` / `Design system:` line nor three +# of the four GROUPS (type, colour, spacing, grid). Each entry is a regular expression, tried against the lowercase brief. +SCREEN = ("layouts?", "screenshots?", "viewports?", "phone[- ]widths?", "responsive", "stylesheets?", "css", "dark mode", "light and dark", + "typefaces?", "toolbars?", "sidebars?", "modals?", "dialog box(?:es)?", "cards?", "panels?", "charts?", "buttons?", "headlines?", "wraps", "scroll\\w*") +_SCREEN = re.compile(r"\b(" + r")|(".join(SCREEN) + r")\b") +MAKING = re.compile(r"\b(?:build\w*|creat\w*|mak(?:e|es|ing)\b|(?:re)?design\w*|restyle\w*|adds?\b|adding\b|lay(?:s|ing)? out|implement\w*)") +GROUPS = tuple(re.compile(p) for p in (r"fonts?|typefaces?|typography|type scale|helvetica|arial|roboto|georgia|garamond|times new roman|system-ui|sans-serif|segoe ui|sf pro|\binter\b", + r"#[0-9a-f]{3,8}\b|palettes?|colou?r schemes?", r"padding|margins?|\bgaps?\b|spacing|radius", r"\bgrids?\b|columns?|breakpoints?")) +LOOK_LINE = re.compile(r"(?im)^\W{0,6}(?:look|design system)\s*:") + + +def screen_brief_without_look(text): + """True when a brief asks for something the person will look at and states no look for it. Anything that is not text is False.""" + t = text.lower() if isinstance(text, str) else "" + return bool(MAKING.search(t)) and len({m.lastindex for m in _SCREEN.finditer(t)}) >= 2 and not LOOK_LINE.search(t) and sum(bool(g.search(t)) for g in GROUPS) < 3 + + def watch(p): """Before a tool call by the lead: count it, record delegations, and remind when off-course (never blocking).""" sid, tool, ti = p["session_id"], p["tool_name"].lower(), p["tool_input"] @@ -167,13 +183,14 @@ def watch(p): 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])): - probe = {"picked": [models.short(r[0]) for r in models.rows(table_text)]} - known = models.claim(probe, text, True) + 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) @@ -190,8 +207,7 @@ def watch(p): s["changed"] = True s.pop("paused", None) s["direct"], s["direct_since"] = s.get("direct", 0) + 1, s.get("direct_since", 0) + 1 - if notes: - print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": say("\n".join(notes))}})) + notes and print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": say("\n".join(notes))}})) return 0 diff --git a/tests/test_core.py b/tests/test_core.py index 53dd332..9d8b1b8 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1953,6 +1953,70 @@ cli.main(["tick"]) os.remove(os.path.join(self.data, "models.md")) self.assertEqual(self.tool("Agent", tool_input={"model": "sonnet"}), (0, "", "")) + PAGE = ("Build a status page for the service: a header, a toolbar with a refresh button, a sidebar listing the jobs, and a table of runs. " + "It must work at phone width. Time limit 20 minutes.") + SERVER = ("Add a /api/status endpoint that the dashboard page polls every five seconds: it returns JSON and records the user who " + "opens the browser session. Cover it with a test.") + SCREEN_BRIEFS = os.path.join(REPO, "tests", "data", "screen_briefs.jsonl") + + def test_a_brief_for_something_the_person_will_look_at_states_its_look(self): + from sisi import hooks + f = hooks.screen_brief_without_look + self.assertTrue(f(self.PAGE)) # screen work, no look + self.assertFalse(f(self.PAGE + "\nLook: the existing settings page")) # a line says which design it follows + self.assertFalse(f(self.PAGE + "\n- Design system: the one in docs/ui.md")) # in a bullet, and by its other name + self.assertFalse(f(self.PAGE + "Type: Inter at 14/16/20. Spacing: 8px padding, 12px gaps. Grid: two columns above 900px.")) # three of four groups + self.assertTrue(f(self.PAGE + "Type: Inter at 14/16/20. Grid: two columns above 900px.")) # two groups are not a look + self.assertFalse(f(self.SERVER)) # "page" and "browser" alone are not screen work + self.assertFalse(f("Review the settings page: at phone width the toolbar overlaps the sidebar and the headline wraps. " + "Report findings only.")) # looks, never makes + for bad in ("", None, 12, {"prompt": self.PAGE}, [self.PAGE]): + self.assertFalse(f(bad), bad) + + def test_a_delegation_whose_brief_states_no_look_is_noted_and_never_blocked(self): + self.hook("tick"), self.hook("prompt", prompt="go"), self.done() + for name, field in (("Agent", "prompt"), ("mcp__t3__delegate_task", "prompt"), ("spawn_agent", "message"), ("Task", "task")): + rc, out, err = self.tool(name, tool_input={field: self.PAGE}) + self.assertEqual((rc, err), (0, ""), (name, out, err)) + doc = json.loads(out) + self.assertEqual(sorted(doc), ["hookSpecificOutput"], doc) # context only: no decision, so no block + self.assertIn("states no look", doc["hookSpecificOutput"]["additionalContext"]) + self.assertIn("'Look: '", doc["hookSpecificOutput"]["additionalContext"]) + self.assertEqual(self.tool("Agent", tool_input={"prompt": self.SERVER}), (0, "", "")) # nothing to say + self.assertEqual(self.tool("Agent", tool_input={"prompt": None}), (0, "", "")) # a missing brief is no error + self.table(WORKERS) + err = self.note(self.tool("Bash", tool_input={"command": 'opencode run -m other/model "%s"' % self.PAGE})) + self.assertEqual(("states no look" in err, "do not shell out" in err), (True, True)) # a worker started from the shell too + + def test_the_screen_brief_rule_on_the_labelled_briefs(self): + if not os.path.exists(self.SCREEN_BRIEFS): + self.skipTest("tests/data/screen_briefs.jsonl is absent, so the labelled set was not scored") + from sisi import hooks + rows = [json.loads(l) for l in self.read(self.SCREEN_BRIEFS).splitlines() if l.strip()] + wrong = [r for r in rows if hooks.screen_brief_without_look(r["text"]) != (r["label"] == "note")] + acc = {} + for split in ("train", "held"): + part = [r for r in rows if r["split"] == split] + self.assertTrue(part, "no %s rows in the labelled set" % split) + acc[split] = 1 - sum(r in part for r in wrong) / len(part) + self.assertGreaterEqual(acc[split], 0.85, "screen briefs, %s %.2f; wrong: %s" % (split, acc[split], [(r["label"], r["text"][:120]) for r in wrong if r in part])) + self.assertEqual([r["text"][:120] for r in wrong if r.get("real")], [], "real briefs the rule gets wrong") + print("screen briefs: train %.2f, held %.2f" % (acc["train"], acc["held"])) + + def test_the_labelled_brief_test_scores_each_split_and_every_real_brief(self): + import contextlib, io + row = lambda split, label, real, text: json.dumps(dict(split=split, label=label, real=real, text=text)) + path = self.write(os.path.join(self.tmp, "b.jsonl"), "\n".join([row("train", "note", True, self.PAGE), row("held", "quiet", True, self.SERVER), + row("held", "quiet", False, self.SERVER)])) + with mock.patch.object(Core, "SCREEN_BRIEFS", path), contextlib.redirect_stdout(out := io.StringIO()): + self.test_the_screen_brief_rule_on_the_labelled_briefs() # every brief right: it passes and prints + self.assertEqual(out.getvalue().strip(), "screen briefs: train 1.00, held 1.00") + for held, why in (([row("held", "quiet", False, self.SERVER), row("held", "quiet", False, self.PAGE)], "held 0.50"), # one split under the bar + ([row("held", "note", True, self.SERVER)] + [row("held", "note", False, self.PAGE)] * 6, "real briefs the rule gets wrong")): # 6 of 7, but a real one + self.write(path, "\n".join([row("train", "note", True, self.PAGE)] + held)) + with mock.patch.object(Core, "SCREEN_BRIEFS", path), contextlib.redirect_stdout(io.StringIO()): + self.assertRaisesRegex(AssertionError, why, self.test_the_screen_brief_rule_on_the_labelled_briefs) + def test_unknown_worker_delegation_marks_models_table_stale(self): self.table(WORKERS) self.hook("tick") @@ -3805,10 +3869,10 @@ 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, 2267, "sisi is two loops. If it needs more than this, find the simpler shape.") + self.assertLessEqual(code, 2283, "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()), 137) - self.assertLessEqual(len(rulebook), 10561) + self.assertLess(len(rulebook.splitlines()), 139) + self.assertLessEqual(len(rulebook), 10711) if __name__ == "__main__":