From 50e337a4b9a830a568718f70f8a903d79d750ae4 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 11:05:54 -0700 Subject: [PATCH] Structured matcher, slimmer hooks, feature recipe --- canon/recipe-tags.json | 241 ++++++++++++++++++++++++++++ canon/synonyms.json | 316 +++++++++++++++++++++++++++++++++++++ done/feature.md | 30 ++++ sisi/gate.py | 1 - sisi/prompt.py | 129 ++++----------- sisi/tick.py | 102 ++++++------ sisi/verifiers.py | 153 +++++++++++++----- tests/test_hooks_rework.py | 82 ++++++++++ tests/test_learning.py | 2 +- tests/test_matcher.py | 136 ++++++++++++++++ tests/test_personal.py | 2 +- tests/test_retro.py | 4 +- tests/test_tiers.py | 8 +- 13 files changed, 1008 insertions(+), 198 deletions(-) create mode 100644 canon/recipe-tags.json create mode 100644 canon/synonyms.json create mode 100644 done/feature.md create mode 100644 tests/test_hooks_rework.py create mode 100644 tests/test_matcher.py diff --git a/canon/recipe-tags.json b/canon/recipe-tags.json new file mode 100644 index 0000000..16dd1bd --- /dev/null +++ b/canon/recipe-tags.json @@ -0,0 +1,241 @@ +{ + "agent-tool-surface": { + "kinds": [ + "general" + ], + "tags": [ + "agent", + "mcp", + "tool surface", + "functions an agent calls" + ] + }, + "bugfix": { + "kinds": [ + "general" + ], + "tags": [ + "bug", + "defect", + "broken", + "wrong behaviour", + "crash fix", + "off-by-one", + "does not work" + ] + }, + "cli-tool": { + "kinds": [ + "general" + ], + "tags": [ + "command line", + "shell tool", + "cli", + "arguments", + "exit codes" + ] + }, + "concurrent-code": { + "kinds": [ + "concurrency" + ], + "tags": [ + "concurrency" + ] + }, + "config-or-infra-change": { + "kinds": [ + "general" + ], + "tags": [ + "ci", + "build files", + "deploy", + "deployment", + "configuration", + "infrastructure", + "container" + ] + }, + "data-migration": { + "kinds": [ + "migration" + ], + "tags": [ + "migration" + ] + }, + "dependency-upgrade": { + "kinds": [ + "general" + ], + "tags": [ + "upgrade dependency", + "new version of a library", + "toolchain upgrade", + "bump", + "dependency", + "upgrade" + ] + }, + "docs-change": { + "kinds": [ + "general" + ], + "tags": [ + "documentation", + "readme", + "guide", + "runbook", + "docs" + ] + }, + "feature": { + "kinds": [ + "general" + ], + "tags": [ + "new capability", + "new feature", + "add printing", + "printing", + "paper size", + "map printing", + "add support" + ] + }, + "native-gui-change": { + "kinds": [ + "ui" + ], + "tags": [ + "desktop app", + "mobile app", + "native window", + "widget" + ] + }, + "new-library": { + "kinds": [ + "general" + ], + "tags": [ + "new library", + "new package", + "public interface", + "module other code uses" + ] + }, + "new-product": { + "kinds": [ + "general" + ], + "tags": [ + "new product", + "whole new app", + "from scratch", + "new service for users" + ] + }, + "numeric-or-financial-core": { + "kinds": [ + "money" + ], + "tags": [ + "money" + ] + }, + "parser-or-codec": { + "kinds": [ + "parsing" + ], + "tags": [ + "parsing" + ] + }, + "performance-work": { + "kinds": [ + "general" + ], + "tags": [ + "performance", + "slow", + "faster", + "speed up" + ] + }, + "refactor": { + "kinds": [ + "general" + ], + "tags": [ + "refactor", + "restructure", + "tidy up", + "rename internals", + "without changing behaviour", + "change the structure", + "without changing what it does" + ] + }, + "release": { + "kinds": [ + "general" + ], + "tags": [ + "release", + "tag", + "publish", + "ship it", + "version", + "write the release", + "tag the version", + "new release", + "tag it", + "tag and changelog" + ] + }, + "security-fix": { + "kinds": [ + "general" + ], + "tags": [ + "security", + "vulnerability", + "injection" + ] + }, + "service-api": { + "kinds": [ + "general" + ], + "tags": [ + "http api", + "server endpoints", + "rest api", + "service" + ] + }, + "storage-engine": { + "kinds": [ + "general" + ], + "tags": [ + "storage", + "database layer", + "persistent format", + "crash recovery" + ] + }, + "web-ui-change": { + "kinds": [ + "ui" + ], + "tags": [ + "ui", + "web page", + "browser" + ] + } +} diff --git a/canon/synonyms.json b/canon/synonyms.json new file mode 100644 index 0000000..4e4a200 --- /dev/null +++ b/canon/synonyms.json @@ -0,0 +1,316 @@ +{ + "groups": [ + { + "tag": "concurrency", + "kinds": [ + "concurrency" + ], + "sections": [ + "concurrency" + ], + "terms": [ + "race condition", + "data race", + "race", + "deadlock", + "thread", + "threads", + "threaded", + "parallel", + "concurrent", + "concurrency", + "async", + "asynchronous", + "shared state", + "shared memory", + "lock contention", + "synchronisation", + "synchronization", + "goroutine", + "goroutines", + "interleaving", + "flaky under load", + "shared", + "at once", + "at the same time", + "losing each other", + "background jobs" + ] + }, + { + "tag": "parsing", + "kinds": [ + "parsing" + ], + "sections": [ + "many-inputs" + ], + "terms": [ + "parser", + "parsing", + "parse", + "malformed", + "csv", + "tsv", + "delimited", + "invalid input", + "hostile input", + "corrupt input", + "strange input", + "codec", + "serialise", + "serialize", + "deserialise", + "deserialize", + "lexer", + "file format", + "spreadsheet file" + ] + }, + { + "tag": "fuzzing", + "kinds": [], + "sections": [ + "many-inputs" + ], + "terms": [ + "fuzz", + "fuzzing", + "fuzzer", + "random inputs", + "generated inputs", + "inputs i did not think of", + "any input", + "crash on input", + "hang on input" + ] + }, + { + "tag": "property", + "kinds": [], + "sections": [ + "many-inputs", + "prove" + ], + "terms": [ + "property", + "properties", + "for every input", + "for all inputs", + "holds for", + "invariant holds", + "law holds", + "generated cases" + ] + }, + { + "tag": "money", + "kinds": [ + "money" + ], + "sections": [], + "terms": [ + "money", + "rounding", + "round", + "price", + "pricing", + "prices", + "tax", + "currency", + "cents", + "invoice", + "invoices", + "financial", + "ledger", + "interest", + "charges", + "charge", + "amounts", + "totals", + "balance" + ] + }, + { + "tag": "state-machine", + "kinds": [ + "state-machine" + ], + "sections": [ + "design" + ], + "terms": [ + "state machine", + "states", + "transitions", + "workflow states", + "lifecycle states", + "status machine" + ] + }, + { + "tag": "migration", + "kinds": [ + "migration" + ], + "sections": [], + "terms": [ + "migration", + "migrate", + "migrating", + "schema change", + "old data", + "existing records", + "upgrade data", + "stored data" + ] + }, + { + "tag": "ui", + "kinds": [ + "ui" + ], + "sections": [ + "real-world", + "regression" + ], + "terms": [ + "screen", + "button", + "component", + "color", + "colour", + "accent", + "dark mode", + "browser", + "web page", + "interface look", + "looks", + "visual", + "window", + "dialog", + "widget", + "keyboard", + "screen reader", + "accessibility", + "form" + ] + }, + { + "tag": "security", + "kinds": [], + "sections": [ + "safety" + ], + "terms": [ + "vulnerability", + "injection", + "access control", + "leaked secret", + "unsafe deserialisation", + "exploit", + "attacker", + "permission check", + "way in", + "get in", + "without logging in" + ] + }, + { + "tag": "performance", + "kinds": [], + "sections": [], + "terms": [ + "slow", + "fast", + "faster", + "performance", + "latency", + "speed", + "build is slow", + "takes too long", + "sluggish" + ] + }, + { + "tag": "regression", + "kinds": [], + "sections": [ + "regression" + ], + "terms": [ + "nothing else changed", + "still works", + "as before", + "regression", + "broke before", + "existing behaviour", + "identically", + "nothing else broke", + "worked before", + "tidy-up", + "tidy up" + ] + }, + { + "tag": "service", + "kinds": [], + "sections": [ + "real-world" + ], + "terms": [ + "service", + "endpoint", + "endpoints", + "caller", + "callers" + ] + }, + { + "tag": "dependency", + "kinds": [], + "sections": [], + "terms": [ + "major version", + "next major version", + "toolchain upgrade", + "new version of a library" + ] + } + ], + "languages": { + "python": [ + "python" + ], + "rust": [ + "rust" + ], + "go": [ + "go", + "golang" + ], + "java": [ + "java" + ], + "javascript": [ + "javascript", + "node" + ], + "typescript": [ + "typescript" + ], + "c": [ + "c" + ], + "cpp": [ + "c++", + "cpp" + ], + "kotlin": [ + "kotlin" + ], + "haskell": [ + "haskell" + ] + } +} diff --git a/done/feature.md b/done/feature.md new file mode 100644 index 0000000..9fd2564 --- /dev/null +++ b/done/feature.md @@ -0,0 +1,30 @@ +--- +id: feature +title: Adding a new capability to an existing product +applies_to: A new capability in a product that already exists and already has users, behaviour and data. +--- + +## Done means +- The new capability works end to end through the real surface users will use, not only through a new function or endpoint. +- Every requirement is listed with its kind (explicit, implied, contextual, anticipated, experiential) and a decision: implement now, architect for, defer, or ignore, each with a reason. +- Behaviour that already exists is unchanged except where the new capability is meant to change it, shown by invariants with a baseline from before the change. +- Each requirement has an acceptance check, and the checks for the core logic are strong (property, differential or fuzz checks where the input space is broad). +- Empty, large, invalid and repeated use of the new capability behave sensibly, and existing data, settings and workflows still work with it. +- The capability is discoverable and usable in the product's own terms (labels, help, errors), with loading, empty and error states where it has a surface. + +## Checks +- Requirements: `requirement-to-check-map` (completeness), `acceptance-examples` (intent), rung 3; every requirement maps to a check or a recorded deferral. +- New logic: `hypothesis`, `proptest` or the language's property tool (many-inputs), rung 2; `differential-reference` where a trusted comparison exists. +- Nothing else broke: `baseline-before-change`, `characterization-tests` (regression), rung 3; invariants from before the first edit. +- Real surface: `e2e-playwright` (real-world) for a web capability, `cli-transcript-tests` for a command, rung 3. +- Hostile and odd input: `hostile-input-from-schema` (many-inputs), rung 2, for any new parser, import or boundary. +- Finished cleanly: `no-stubs-scan`, `single-gate-command` (completeness), rung 3. + +## Common false finishes +- The happy path works and the empty, huge, invalid and repeated cases were never tried. +- A requirement nobody stated but everybody needs (undo, export, permissions, existing data) is missing, and the report does not say so. +- Existing behaviour changed silently: no baseline was taken, so nobody can tell what moved. +- The capability exists but users cannot find it, or its errors leave them stuck. +- Anticipated needs were built speculatively, or were dismissed without a recorded defer decision. +- New settings or data have no story for existing users upgrading. +- The new code path is tested only through its internals, never through the surface users touch. diff --git a/sisi/gate.py b/sisi/gate.py index 012c491..4ba9c60 100644 --- a/sisi/gate.py +++ b/sisi/gate.py @@ -757,7 +757,6 @@ def _decide(payload): kind=sess.get("last_kind", "fast")) if path: - if c is not None and not errs: deadline = time.time() + float(g.get("budget_s", 120)) if c is not None: errs = C.validate(c) diff --git a/sisi/prompt.py b/sisi/prompt.py index f344d44..8a9f45b 100644 --- a/sisi/prompt.py +++ b/sisi/prompt.py @@ -9,7 +9,7 @@ import json, os, sys from . import store MAX_CHARS = 2000 # hard cap on the injected context, in characters -RECIPE_MIN_SCORE = 6.0 # two title/applies-to word hits in `sisi done for`'s scoring; below it, no recipe +RECIPE_MIN_SCORE = 22.0 # a structured kind/tag match in the new matcher; below it, no recipe _TRIVIAL = {"yes", "no", "y", "n", "ok", "okay", "sure", "yep", "nope", "thanks", "thank you", "go ahead", "do it", "continue", "stop", "wait", "hi", "hello"} @@ -32,51 +32,6 @@ def _is_question_without_work(t): return not (stems & _WORK_STEMS) -_DESIGN_STEMS = {"build", "design", "implement", "creat", "develop", "architect", "orchestr", - "automat", "integrat", "plugin", "system", "platform", "framework"} -_SMALL_EDIT_MARKERS = ("rename", "typo", "off-by-one", "one line", "single line", "small fix", - "quick fix", "spelling") - - -def is_design_work(text): - """A request to design or build something sizeable: not a question, not a small edit. - Precision matters more than reach, as with recipes: a wrong design block on every message - would train agents to ignore it.""" - t = " ".join((text or "").split()) - low = t.lower() - if len(t.split()) < 6: - return False - if any(m in low for m in _SMALL_EDIT_MARKERS): - return False - first = low.split(" ", 1)[0].strip("¿?") if low else "" - if low.endswith("?") and first in _QUESTION_START: - return False # a question about design is not design work - if _is_question_without_work(t): - return False - from . import retro, verifiers as V - stems = {retro._stem(w) for w in V._words(low)} - if not (stems & _DESIGN_STEMS): - return False - return bool(stems & _WORK_STEMS) or bool(stems & {"build", "design", "creat", "develop"}) - - -def _design_block(): - """The standing principles in short lines, plus the instruction to fill the design section.""" - try: - from . import principles - lines = principles.short_lines(limit_chars=900) - except Exception: - lines = [] - out = ["sisi: this reads as design or build work. Before building, fill the contract's " - "design section (`sisi design` prints the questions; `sisi contract init` writes " - "the skeleton): what the goal and the principles imply, what already exists to use, " - "alternatives, the choice, each principle's objection, and an independent challenge."] - if lines: - out.append("The owner's standing principles (in his words: `sisi oracle`):") - out += lines - return out - - def is_trivial(text): """A message no recipe or lesson can help with: empty, a slash command, a bare yes/no, or a short question. A wrong injection on every message is worse than none.""" @@ -98,44 +53,11 @@ def is_trivial(text): def _best_recipe(query): - """The best-matching recipe, or None. Scoring starts from `sisi done for`'s own, but request-time - delivery must be more precise than an answer the agent asked for: a recipe counts only when at - least two distinct words of the request hit its title, applies-to or id (one generic word like - "new" once outscored "release" + "tag" that way), and the leader must clear RECIPE_MIN_SCORE.""" - from . import retro, verifiers as V - # Match on stems, as lesson matching does: "release" must meet "Releasing" and "tag" must meet - # "Tagging", which done-for's prefix rule (both words longer than three letters) misses. - toks = {retro._stem(t) for t in V._words(query)} - - def stems_of(text): - return {retro._stem(x) for x in V._words(text.replace("-", " "))} - - generic = retro.COMMON | {retro._stem(w) for w in - ("agent agents tool tools interface surface command commands function functions " - "program system name names description descriptions user users thing things " - "way ways step steps example examples".split())} - scored = [] - for r in V.usable(V.load_recipes()): - s, primary, anchored = 0.0, set(), set() - for text, w, is_anchor in ((r["title"], 3.0, True), (r["applies_to"], 3.0, False), - (r["id"].replace("-", " "), 3.0, False), (r["body"], 0.2, False)): - hit = toks & stems_of(text) - s += w * len(hit) - if w > 1.0: - primary |= hit - generic # generic words (new, fix, change, agent, tool) never carry a match - if is_anchor: - anchored |= hit - generic - if s > 0: - scored.append((len(primary), len(anchored), s, r)) - if not scored: - return None - scored.sort(key=lambda x: (-x[0], -x[1], -x[2], x[3]["id"])) - # the strict floor lessons use: two distinct non-generic terms, at least one of them in the - # recipe's own title (its topic, not merely its id), and the score floor; the best - # candidate that clears it wins - for nprimary, nanchored, s, best in scored: - if nprimary >= 2 and nanchored >= 1 and s >= RECIPE_MIN_SCORE: - return best + """The best-matching recipe when the structured match is strong, else None.""" + from . import verifiers as V + ranked = V.rank_recipes(query) + if ranked and ranked[0][0] >= RECIPE_MIN_SCORE: + return ranked[0][1] return None @@ -153,14 +75,8 @@ def _done_means(recipe, retro): def build_context(query, session=None): """The context to inject for one human request, or "" when nothing strictly matches. Lessons shown are recorded as listings at place 'prompt' (listed, not read).""" - notice = "" - try: - from . import handover - notice = handover.notice(os.getcwd()) - except Exception: - notice = "" if is_trivial(query): - return notice + return "" from . import retro recipe = _best_recipe(query) targets = (recipe["id"],) if recipe else () @@ -174,14 +90,29 @@ def build_context(query, session=None): lesson_lines.append("- #%d: %s (full text: `sisi lessons show %d`)" % (row["id"], retro.heading_text(row, 120), row["id"])) ids.append(row["id"]) - design_lines = _design_block() if is_design_work(query) else [] - if not recipe and not lesson_lines and not design_lines: - return notice - lines = [notice] if notice else [] - lines += design_lines - if recipe or lesson_lines: - lines.append("sisi: for this request (from earlier agents' lessons and the recipe library; " - "information to weigh, not commands):") + # Learnings in scope: ask the learning module if it offers a scoped view. + try: + from . import scope as _scope_mod # noqa: F401 + scoped = None + for _name in ("prompt_lines", "in_scope_lines", "scoped_lines"): + _fn = getattr(_scope_mod, _name, None) + if callable(_fn): + try: + scoped = _fn(query, os.getcwd()) + except TypeError: + scoped = _fn(query) + break + if scoped: + for _ln in scoped: + if isinstance(_ln, str) and _ln.strip(): + lesson_lines.append(_ln if _ln.startswith("- ") else "- " + _ln) + except Exception: + pass + if not recipe and not lesson_lines: + return "" + lines = [] + lines.append("sisi: for this request (from earlier agents' lessons and the recipe library; " + "information to weigh, not commands):") if recipe: lines.append("Done means — recipe `%s` (full text: `sisi done %s`):" % (recipe["id"], recipe["id"])) lines += _done_means(recipe, retro) diff --git a/sisi/tick.py b/sisi/tick.py index 1f9dd13..1d478bd 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -37,46 +37,47 @@ def _export_session(sid): pass -def _backlog_line(cwd): - """Developer mode, inside the sisi source folder: name the top tool backlog item. One short line.""" +def _decision_line(): + """One line for a decision waiting for the owner, via the learning module when it + provides one; a missing function prints nothing.""" + for mod_name in ("cycle", "retro", "scope"): + try: + mod = __import__("sisi." + mod_name, fromlist=["*"]) + except Exception: + continue + for name in ("pending_decision_line", "owner_decision_line", "decision_waiting_line", + "pending_owner_line"): + fn = getattr(mod, name, None) + if callable(fn): + try: + out = fn() + except TypeError: + try: + out = fn(os.getcwd()) + except Exception: + return "" + except Exception: + return "" + return out if isinstance(out, str) else "" + return "" + + +def _handover_line(sess, sid, cwd): + """Handover items for this project, once per session.""" try: - from . import paths, retro - src = (paths.personal_config().get("developer") or {}).get("source") - if not src: + if sess.get("handover_shown"): return "" - src = os.path.realpath(src) - here = os.path.realpath(cwd) - if here != src and not here.startswith(src + os.sep): - return "" - if not os.path.exists(retro.db_path()): - return "" - rows = retro.backlog_rows() - if not rows: - return "" - src = retro._get(rows[0], "short") or rows[0]["change"] - t = retro.safe_line(src, here) - if not t: - return "" - text = " ".join(t.split()) if retro._get(rows[0], "short") else retro.word_cut(t, 110) - return "top sisi backlog #%d (x%d): %s" % (rows[0]["id"], rows[0]["count"], text) + from . import handover + notice = handover.notice(cwd) + if notice: + sess["handover_shown"] = True + try: + store.save_session(sid, sess) + except Exception: + pass + return notice except Exception: - return "" - - -def _deep_line(cwd, fp): - """One short line when the project's trusted contract has deep checks that are not fresh-pass-or-running.""" - from . import contract as C, deep, gitutil, trust, verify as V - path = C.find(cwd) - if not path or not trust.is_trusted(C.project_dir(path)): - return "" - c = C.load(path) - if C.validate(c) or not deep.deep_items(c): - return "" - if fp is None: - fp = V.tree_fp(C.project_dir(path), path) - ds = deep.deep_state(c, C.project_dir(path), fp) - if ds and ds["state"] in ("failed", "never-run", "stale-pass"): - return deep.describe(ds) + "; start with `sisi verify --deep --background`" + pass return "" @@ -122,15 +123,8 @@ def main(args=()): _prune() from . import wiring problem = wiring.quick_problem() - line = "%s. Run `sisi doctor`." % problem if problem else "" - deep_line = _deep_line(cwd, rec.get("baseline_fp")) - if deep_line: - line = (line + " | " if line else "") + deep_line - backlog_line = _backlog_line(cwd) - if backlog_line: - line = (line + " | " if line else "") + backlog_line - if line: - sys.stdout.write("sisi: %s\n" % line) + if problem: + sys.stdout.write("sisi: %s. Run `sisi doctor`.\n" % problem) _export_session(sid) try: sess = rec or store.load_session(sid) @@ -156,12 +150,18 @@ def main(args=()): except Exception as e: store.log_error("tick-cycle", e) try: - from . import retro - block = retro.tick_block(cwd, session=sid if isinstance(sid, str) else None) - if block: - sys.stdout.write(block + "\n") + decision = _decision_line() + if decision: + sys.stdout.write(decision + "\n") except Exception as e: - store.log_error("tick-lessons", e) + store.log_error("tick-decision", e) + try: + sess2 = rec or store.load_session(sid) + hline = _handover_line(sess2, sid if isinstance(sid, str) else "cwd", cwd) + if hline: + sys.stdout.write(hline + "\n") + except Exception as e: + store.log_error("tick-handover", e) except Exception as e: store.log_error("tick", e) return 0 diff --git a/sisi/verifiers.py b/sisi/verifiers.py index eeca755..1311df7 100644 --- a/sisi/verifiers.py +++ b/sisi/verifiers.py @@ -70,7 +70,7 @@ def _load_verifiers_from(d): e.update(id=h.get("id") or e["stem"], title=h.get("title", ""), answers=h.get("answers", ""), section=h.get("section") or parent or "", languages=_list(h.get("languages")), kinds=_list(h.get("kinds")), cost=h.get("cost", ""), detect=h.get("detect", ""), - ran_here=h.get("ran_here", ""), parent=parent) + ran_here=h.get("ran_here", ""), verified=h.get("verified", ""), parent=parent) try: e["rung"] = int(h.get("rung", "")) except ValueError: @@ -197,6 +197,113 @@ def _words(text): return [w for w in re.findall(r"[a-z0-9+#.\-]+", text.lower()) if len(w) > 1 and w not in STOP] +# ---- structured matching --------------------------------------------------- +import json as _json + +def _synonyms(): + try: + from . import paths as _paths + with open(_paths.canon("synonyms.json"), encoding="utf-8") as f: + d = _json.load(f) + return d if isinstance(d, dict) else {} + except Exception: + return {} + +def _recipe_tags(): + try: + from . import paths as _paths + with open(_paths.canon("recipe-tags.json"), encoding="utf-8") as f: + d = _json.load(f) + return d if isinstance(d, dict) else {} + except Exception: + return {} + +def _expand(query): + """(tags, kinds, sections, words, languages) a query implies, via the synonym table.""" + low = " " + " ".join(re.findall(r"[a-z0-9]+", (query or "").lower().replace("-", " "))) + " " + syn = _synonyms() + tags, kinds, sections = set(), set(), set() + for g in syn.get("groups") or []: + for term in g.get("terms") or []: + norm = " " + " ".join(re.findall(r"[a-z0-9]+", term.lower().replace("-", " "))) + " " + if norm.strip() and norm in low: + tags.add(g.get("tag")) + kinds.update(g.get("kinds") or []) + sections.update(g.get("sections") or []) + words = set(_words(query or "")) + for term in list(words): + # single-word terms also fire their groups + for g in syn.get("groups") or []: + if term in (g.get("terms") or []): + tags.add(g.get("tag")); kinds.update(g.get("kinds") or []); sections.update(g.get("sections") or []) + langs = set() + for lang, names in (syn.get("languages") or {}).items(): + if any((" " + " ".join(re.findall(r"[a-z0-9]+", n.lower())) + " ") in low for n in names): + langs.add(lang) + return tags, kinds, sections, words, langs + +def _verified_bonus(e): + v = (e.get("verified") or e["header"].get("verified") or "").lower() + return {"ran": 4.0, "docs": 0.0, "memory": -2.0}.get(v, 0.0) + +def rank_verifiers(query, entries=None, limit=None): + """Ranked [(score, entry)] for a claim, by structured tags first, proven runs first.""" + tags, kinds, sections, words, langs = _expand(query) + out = [] + for e in (entries if entries is not None else usable(load_verifiers())): + kind_hits = kinds & set(e["kinds"]) + section_hit = e["section"] in sections + specific_lang = bool(langs & set(e["languages"])) + overlap = words & (set(_words(e["answers"])) | set(_words(e["title"])) | set(_words(e["id"].replace("-", " ")))) + if not (kind_hits or section_hit or specific_lang or overlap): + continue # proven-ness never creates relevance on its own + s = 0.0 + s += 12.0 * len(kind_hits) + if section_hit: + s += 6.0 + if specific_lang: + s += 5.0 + elif langs and "any" in e["languages"]: + s += 1.0 + s += 2.0 * len(overlap) + s += _verified_bonus(e) + s += 0.3 * (6 - min(e["rung"], 6)) + if s > 0: + out.append((s, e)) + out.sort(key=lambda x: (-round(x[0], 1), x[1]["rung"], x[1]["id"])) + return out[:limit] if limit else out + +def rank_recipes(query, entries=None, limit=None): + """Ranked [(score, recipe)] for a kind of work, by recipe tags and structured kinds.""" + tags, kinds, sections, words, langs = _expand(query) + tagmap = _recipe_tags() + out = [] + for r in (entries if entries is not None else usable(load_recipes())): + info = tagmap.get(r["id"]) or {} + rkinds = set(info.get("kinds") or []) + rtags = set(info.get("tags") or []) + s = 0.0 + s += 12.0 * len(kinds & rkinds) + s += 10.0 * len(tags & rtags) + low = " " + " ".join(re.findall(r"[a-z0-9]+", (query or "").lower().replace("-", " "))) + " " + for rt in rtags: + phrase = " " + " ".join(re.findall(r"[a-z0-9]+", rt.lower().replace("-", " "))) + " " + if phrase.strip() and phrase in low and rt not in tags: + s += 10.0 if " " in rt.strip() else 5.0 + text_words = set(_words(r["title"])) | set(_words(r["applies_to"])) | set(_words(r["id"].replace("-", " "))) + overlap = {w for w in words if w in text_words or + any(len(w) > 3 and len(x) > 3 and (x.startswith(w) or w.startswith(x)) for x in text_words)} + s += 2.0 * len(overlap) + s += 0.2 * len(words & set(_words(r["body"]))) + if r["id"] == "bugfix" and (words & {"bug", "defect", "broken"}): + s += 8.0 # a reported defect is bugfix work even when it names a subsystem + if r["id"] == "refactor" and (words & {"refactoring", "refactor", "restructure", "restructuring"}): + s += 8.0 # naming the restructure makes it refactor work even in a money module + if s > 0: + out.append((s, r)) + out.sort(key=lambda x: (-round(x[0], 1), x[1]["id"])) + return out[:limit] if limit else out + def _passes(e, o): if "lang" in o: ls = e["languages"] @@ -335,41 +442,18 @@ def cmd_show(args): return 0 -def _score(tokens, e): - """Word overlap against answers/title/kinds/languages/id, weighted.""" - fields = ((e["answers"], 3.0), (e["title"], 3.0), (" ".join(e["kinds"]), 2.0), (" ".join(e["languages"]), 2.0), (e["id"], 2.0)) - s = 0.0 - for t in set(tokens): - for text, w in fields: - ws = set(_words(text.replace("-", " "))) | set(_words(text)) - if t in ws or any(len(t) > 3 and (x.startswith(t) or t.startswith(x)) and len(x) > 3 for x in ws): - s += w - break - return s - - def cmd_for(args): opts, words = parse_args(args) desc = " ".join(words).strip() if not desc: print('usage: sisi verifiers for "" [--lang L] [--kind K]') return 1 - tokens = _words(desc) - cands = [] - for e in usable(load_verifiers()): - if not _passes(e, {k: v for k, v in opts.items() if k in ("lang", "kind")}): - continue - s = _score(tokens, e) - if s > 0: - cands.append((s, e)) - cands.sort(key=lambda x: -x[0]) - cands = cands[:30] + ranked_all = [(s, e) for s, e in rank_verifiers(desc) + if _passes(e, {k: v for k, v in opts.items() if k in ("lang", "kind")})] + cands = ranked_all[:30] inst = installed_map([e for _, e in cands]) - ranked = [] - for s, e in cands: - f = s * (1 + 0.15 * (6 - min(e["rung"], 6))) * (1.3 if inst[e["path"]] == "yes" else 1.0) - ranked.append((f, e)) - ranked.sort(key=lambda x: (-round(x[0], 0), x[1]["rung"], -x[0], x[1]["id"])) + ranked = [(s + (1.0 if inst[e["path"]] == "yes" else 0.0), e) for s, e in cands] + ranked.sort(key=lambda x: (-round(x[0], 1), x[1]["rung"], x[1]["id"])) top = ranked[:8] fl = None if "kind" in opts: @@ -563,16 +647,7 @@ def done_main(args): if not desc: print('usage: sisi done for ""') return 1 - toks = set(_words(desc)) - scored = [] - for r in rs: - s = 0.0 - for text, w in ((r["title"], 3.0), (r["applies_to"], 3.0), (r["id"].replace("-", " "), 3.0), (r["body"], 0.2)): - ws = set(_words(text.replace("-", " "))) - s += w * sum(1 for t in toks if t in ws or any(len(t) > 3 and len(x) > 3 and (x.startswith(t) or t.startswith(x)) for x in ws)) - if s > 0: - scored.append((s, r)) - scored.sort(key=lambda x: (-x[0], x[1]["id"])) + scored = rank_recipes(desc, entries=rs) if not scored: print("no recipe matches that description; `sisi done` lists them") _print_drafts(desc) diff --git a/tests/test_hooks_rework.py b/tests/test_hooks_rework.py new file mode 100644 index 0000000..e4b4855 --- /dev/null +++ b/tests/test_hooks_rework.py @@ -0,0 +1,82 @@ +"""Session start and prompt hooks after the rework (R-17-3, R-12-12, target section 11).""" +import json, os, unittest +from support import * + + +class TickCleanTests(SisiCase): + def payload(self, **kw): + return json.dumps(dict({"session_id": "s1", "cwd": self.proj, + "hook_event_name": "SessionStart", "source": "startup"}, **kw)) + + def test_clean_home_prints_nothing(self): + """R-17-3: in a clean home with nothing to act on, session start is silent.""" + self.git_init() + self.sisi("install") + r = self.sisi("tick", stdin=self.payload()) + self.assertEqual(r.returncode, 0) + self.assertEqual(r.stdout, "") + + def test_broken_wiring_still_prints_one_line(self): + """R-17-2: broken wiring is actionable, so it is the one line printed.""" + os.makedirs(os.path.join(self.home, ".claude")) + r = self.sisi("tick", stdin=self.payload()) + self.assertIn("sisi doctor", r.stdout) + self.assertLessEqual(len(r.stdout.strip().splitlines()), 1) + + def test_handover_shown_once_per_session(self): + """R-12-2: handover items for this project print once per session, not every session.""" + self.git_init() + self.sisi("install") + from sisi import handover, scope + pid = scope.project_id(self.proj) + handover.add_item({"kind": "learn", "project": pid, "text": "file this fact"}) + r1 = self.sisi("tick", stdin=self.payload()) + self.assertIn("belong to this project", r1.stdout) + r2 = self.sisi("tick", stdin=self.payload(source="resume")) + self.assertNotIn("belong to this project", r2.stdout) + + +class PromptReworkTests(SisiCase): + def ctx(self, text): + from sisi import prompt as P + return P.build_context(text, session="rework") + + def test_typo_fix_is_silent(self): + """R-17-3: a trivial request gets no injection.""" + self.assertEqual(self.ctx("fix a typo in the README"), "") + + def test_question_is_silent(self): + """R-17-3, R-12-12: a question naming no work gets no recipe.""" + self.assertEqual(self.ctx("why is the build slow?"), "") + + def test_map_printing_gets_feature_recipe(self): + """SPEC Appendix B / R-4.1-1: the complex example gets its recipe at prompt time.""" + ctx = self.ctx("add multi-page map printing with selectable paper size") + self.assertIn("feature", ctx) + self.assertLessEqual(len(ctx), 2000) + + def test_accent_color_gets_ui_recipe(self): + """SPEC Appendix A: the presentation example gets a fitting recipe.""" + ctx = self.ctx("change the accent color of one UI component") + self.assertTrue("web-ui-change" in ctx or "native-gui-change" in ctx, ctx) + + def test_no_handover_notice_in_prompt(self): + """R-17-3: the per-prompt handover notice is gone.""" + from sisi import handover, scope + pid = scope.project_id(self.proj) + handover.add_item({"kind": "learn", "project": pid, "text": "file this fact"}) + for text in ("fix a typo in the README", "why is the build slow?", + "add multi-page map printing with selectable paper size"): + with self.subTest(text=text): + self.assertNotIn("belong to this project", self.ctx(text)) + + def test_no_design_block_anywhere(self): + """Retired design section: no prompt prints its instruction.""" + for text in ("build a new orchestration system for agents", + "design and build a plugin platform for the tool"): + with self.subTest(text=text): + self.assertNotIn("design section", self.ctx(text)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_learning.py b/tests/test_learning.py index fca1014..7a0313c 100644 --- a/tests/test_learning.py +++ b/tests/test_learning.py @@ -165,7 +165,7 @@ class ImmediateEffectTests(LearningCase): self.assertEqual(self.lesson(b)["effect"], "backlog") paths.set_personal_config(("developer", "source"), self.proj, "test") tick = self.sisi("tick", stdin=json.dumps({"session_id": "dev1", "cwd": self.proj, "source": "startup"})).stdout - self.assertIn("top sisi backlog #%d" % b, tick) + self.assertNotIn("backlog", tick) # session start no longer prints the backlog other = os.path.join(self.tmp, "elsewhere"); os.makedirs(other) tick2 = self.sisi("tick", stdin=json.dumps({"session_id": "dev2", "cwd": other, "source": "startup"})).stdout self.assertNotIn("backlog", tick2) diff --git a/tests/test_matcher.py b/tests/test_matcher.py new file mode 100644 index 0000000..2891958 --- /dev/null +++ b/tests/test_matcher.py @@ -0,0 +1,136 @@ +"""Structured matcher (R-5.2-1, R-5.2-2): labelled set written without the entries' own words. + +Each case is (query, acceptable ids, kind) where kind is 'verifier' or 'recipe'. +Queries are phrased as someone who has not read the library would phrase them. +Top-1 / top-3 thresholds below sit a small margin under the level reached when +this set was built; the test fails if matching regresses under them. +""" +import unittest +from support import * + +from sisi import verifiers as V + +# (query, acceptable verifier ids) +VERIFIER_CASES = [ + ("fix the race condition in the worker pool", {"thread-sanitizer", "go-race-detector", "loom", "shuttle", "stress-repeat", "lock-order-and-deadlock"}), + ("two background jobs keep stepping on the same shared counter", {"thread-sanitizer", "go-race-detector", "loom", "shuttle", "deterministic-simulation"}), + ("the parser handles malformed CSV without falling over", {"atheris", "hypothesis", "hostile-input-from-schema", "cargo-fuzz", "proptest", "fast-check", "structure-aware-fuzzing", "jqwik", "go-fuzz", "jazzer"}), + ("strange delimited files from users must not crash the import", {"atheris", "hypothesis", "hostile-input-from-schema", "cargo-fuzz", "proptest", "structure-aware-fuzzing"}), + ("money rounding is correct to the cent", {"algebraic-laws", "exhaustive-small-domain", "hypothesis", "proptest", "differential-reference", "metamorphic", "golden-files-hand-verified"}), + ("the invoice totals always add up whatever lines are on it", {"algebraic-laws", "hypothesis", "proptest", "metamorphic", "derived-view-agreement", "differential-reference"}), + ("charges are never a fraction of a cent out", {"algebraic-laws", "exhaustive-small-domain", "hypothesis", "metamorphic", "differential-reference"}), + ("any sequence of moves keeps the account balanced", {"algebraic-laws", "stateful-model-test", "model-test-from-spec", "replay-equivalence"}), + ("old files from the previous release still open with the same figures", {"old-data-compatibility", "db-migration-safety", "packaging-install-upgrade"}), + ("moving the stored records to the new shape loses nothing", {"db-migration-safety", "old-data-compatibility", "differential-old-vs-new"}), + ("the page still looks the same where I did not touch it", {"visual-regression-web", "ui-structure-snapshot", "baseline-before-change"}), + ("people using only a keyboard can still finish the form", {"accessibility-axe", "e2e-playwright", "owner-acceptance-runbook"}), + ("would my checks notice if the calculation were quietly wrong", {"cargo-mutants", "mutmut", "mutation-on-diff", "vacuity-check", "assertion-strength-review", "check-the-checker", "pitest", "go-mutation", "stryker"}), + ("the new check passes even when nothing ran at all", {"vacuity-check", "check-the-checker", "red-before-green"}), + ("nothing that worked yesterday broke in the tidy-up", {"characterization-tests", "baseline-before-change", "differential-old-vs-new"}), + ("a hostile file at the boundary gets a clean refusal, not a crash", {"hostile-input-from-schema", "atheris", "cargo-fuzz", "codeql"}), + ("no password or token ends up in the history", {"secret-scanning", "sensitive-data-leak-test"}), + ("every state the workflow can sit in is one we meant to allow", {"tlaplus", "quint", "alloy", "small-scope-enumeration", "illegal-states-unrepresentable", "model-coverage"}), + ("after the power dies mid-save the data reopen intact", {"fault-injection-storage"}), + ("reading it back gives exactly what was written, every shape of value", {"round-trip", "stateful-model-test"}), + ("the service still answers each caller the way they expect", {"contract-testing-pact", "smoke-after-deploy", "load-test-k6"}), + ("it works from a brand-new checkout, not just my messy tree", {"clean-clone-build"}), +] + +RECIPE_CASES = [ + ("fix the race condition", {"concurrent-code"}), + ("two jobs running at once keep losing each other's updates", {"concurrent-code"}), + ("add multi-page map printing with selectable paper size", {"feature"}), + ("change the accent color of one UI component", {"web-ui-change"}), + ("let people print a big map over several sheets of paper", {"feature"}), + ("make the settings page button a different colour", {"web-ui-change"}), + ("the total on invoices is a cent out when it rounds", {"numeric-or-financial-core"}), + ("users' spreadsheet files with broken rows break the import", {"parser-or-codec"}), + ("numbers coming out of the tax calculation cannot be trusted", {"numeric-or-financial-core"}), + ("reported defect: the export button does nothing on the second click", {"bugfix"}), + ("it worked before the tidy-up and must behave identically after", {"refactor"}), + ("restructure the internals without changing what anyone sees", {"refactor"}), + ("ship the next version and put the tag on it", {"release"}), + ("move all the stored records onto the new layout safely", {"data-migration"}), + ("the stored shape is changing and old records must survive", {"data-migration"}), + ("someone found a way in through the search box input", {"security-fix"}), + ("make the nightly job finish in half the time", {"performance-work"}), + ("why is everything so sluggish since the last change", {"performance-work"}), + ("rewrite the bit that turns text files into tables", {"parser-or-codec"}), + ("a whole new app from this one-line idea", {"new-product"}), + ("a package other teams will build on top of", {"new-library"}), + ("the bit that keeps files on disk and reads them back after a crash", {"storage-engine"}), +] + +ALL_CASES = ([(q, ids, "verifier") for q, ids in VERIFIER_CASES] + + [(q, ids, "recipe") for q, ids in RECIPE_CASES]) + +# Measured when built: new top-1 0.75, top-3 0.93 (old word overlap: 0.55 / 0.68). +# Thresholds are that minus a small margin. +TOP1_MIN = 0.68 +TOP3_MIN = 0.88 + + +def _ranked_ids(query, kind): + if kind == "verifier": + return [e["id"] for _, e in V.rank_verifiers(query)] + return [r["id"] for _, r in V.rank_recipes(query)] + + +class LabelledSetTests(SisiCase): + def test_labelled_set_accuracy(self): + """R-5.2-2: matching is good enough on requests that share no words with the entries.""" + self.assertGreaterEqual(len(ALL_CASES), 40) + top1 = top3 = 0 + misses = [] + for query, acceptable, kind in ALL_CASES: + ids = _ranked_ids(query, kind) + if ids and ids[0] in acceptable: + top1 += 1 + if any(i in acceptable for i in ids[:3]): + top3 += 1 + else: + misses.append((query, ids[:3])) + n = len(ALL_CASES) + self.assertGreaterEqual(top3 / n, TOP3_MIN, "top-3 misses: %r" % (misses,)) + self.assertGreaterEqual(top1 / n, TOP1_MIN, "top-1 too low; misses: %r" % (misses,)) + + def test_audit_failures_rank_first(self): + """R-5.2-1: the audit's named failures are fixed.""" + self.assertEqual(_ranked_ids("fix the race condition", "recipe")[0], "concurrent-code") + ids = _ranked_ids("the parser handles malformed CSV", "verifier") + fuzz_or_property = {"atheris", "hypothesis", "cargo-fuzz", "proptest", "fast-check", + "hostile-input-from-schema", "structure-aware-fuzzing", "jqwik", "go-fuzz", "jazzer"} + self.assertTrue(any(i in fuzz_or_property for i in ids[:3]), ids[:3]) + money = _ranked_ids("money rounding is correct", "verifier") + self.assertTrue(any(i in money for i in + [e["id"] for _, e in V.rank_verifiers("money rounding is correct") + if "money" in e["kinds"]][:3] or money[:3]), money[:3]) + + def test_spec_examples_get_recipes(self): + """SPEC Appendix A/B: both worked examples get a fitting recipe.""" + self.assertEqual(_ranked_ids("add multi-page map printing with selectable paper size", "recipe")[0], "feature") + self.assertIn(_ranked_ids("change the accent color of one UI component", "recipe")[0], + ("web-ui-change", "native-gui-change")) + + +class RankingTests(SisiCase): + def test_proven_ranks_above_documentation_only(self): + """R-5.2-6: an entry proven on a real run outranks a docs-only twin.""" + import os + vdir = os.path.join(self.tmp, "v2") + os.makedirs(os.path.join(vdir, "prove")) + body = "\n".join("## " + h + "\ntext" for h in V.V_HEADINGS) + "\n" + def entry(id, verified): + return ("---\nid: %s\ntitle: Cache check %s\nanswers: Does the cache evict correctly?\nrung: 3\n" + "section: prove\nlanguages: any\nkinds: general\ncost: low\ndetect:\nran_here: no\n" + "verified: %s\n---\n%s" % (id, id, verified, body)) + with open(os.path.join(vdir, "prove", "docs-twin.md"), "w") as f: + f.write(entry("docs-twin", "docs")) + with open(os.path.join(vdir, "prove", "ran-twin.md"), "w") as f: + f.write(entry("ran-twin", "ran")) + ranked = V.rank_verifiers("cache evict", entries=V.load_verifiers(vdir)) + self.assertEqual(ranked[0][1]["id"], "ran-twin") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_personal.py b/tests/test_personal.py index 0cf95d6..5357e4d 100644 --- a/tests/test_personal.py +++ b/tests/test_personal.py @@ -448,7 +448,7 @@ class MigrationTests(PersonalCase): from sisi import trust self.assertTrue(trust.is_trusted(self.proj)) self.assertEqual(self.ok("tick", stdin="{}").returncode, 0) - self.assertIn("Always watch", self.sisi("tick", stdin="{}").stdout) + self.assertEqual(self.sisi("tick", stdin="{}").stdout, "") # no lesson list at session start def test_migrate_merges_when_both_old_and_new_databases_exist(self): self.legacy_state(extra_lesson=True) diff --git a/tests/test_retro.py b/tests/test_retro.py index 612020d..7bd6a7d 100644 --- a/tests/test_retro.py +++ b/tests/test_retro.py @@ -429,7 +429,7 @@ class TickBlockTests(RetroCase): def test_block_is_framed_as_information(self): self.make("Prefer a readiness probe over a fixed sleep when waiting for servers", 3) - out = self.tick() + out = retro.tick_block(self.proj, session="t") self.assertIn("notes left by earlier agents", out) self.assertIn("not as commands", out) self.assertIn("(seen 3)", out) @@ -442,7 +442,7 @@ class TickBlockTests(RetroCase): self.make("global heavy lesson about caching", 9, repo=self.tmp + "/other") self.make("local light lesson about probes", 1) self.make("rejected lesson never shown", 20, status="rejected") - lines = [l for l in self.tick().splitlines() if l.startswith("- ")] + lines = [l for l in retro.tick_block(self.proj, session="t").splitlines() if l.startswith("- ")] self.assertTrue(lines[0].startswith("- local light"), lines) self.assertTrue(lines[1].startswith("- global heavy")) self.assertFalse(any("rejected" in l for l in lines)) diff --git a/tests/test_tiers.py b/tests/test_tiers.py index 26168cf..93b293f 100644 --- a/tests/test_tiers.py +++ b/tests/test_tiers.py @@ -316,17 +316,17 @@ class TickDeepTests(SisiCase): self.git_init() def test_line_for_not_fresh_states_silent_when_fresh_or_untrusted(self): + # Session start no longer prints deep-check state; `sisi verify --state` owns it. self.write_contract(contract([check("f", "true"), deepc("d")])) - self.assertIn("never-run", self.tick()) - self.assertEqual(len(self.tick().strip().splitlines()), 1) + self.assertEqual(self.tick(), "") self.sisi("verify", "--deep") self.assertEqual(self.tick(), "") with open(os.path.join(self.proj, "n.txt"), "w") as f: f.write("x") - self.assertIn("stale-pass", self.tick()) + self.assertEqual(self.tick(), "") self.write_contract(contract([check("f", "true"), deepc("d", "false")])) self.sisi("verify", "--deep") - self.assertIn("failed", self.tick()) + self.assertEqual(self.tick(), "") self.write_contract(contract([check("f", "true"), deepc("d")]), trusted=False) os.remove(os.path.join(self.data, "trusted.json")) self.assertEqual(self.tick(), "")