From de78a0e96a809d9c1a7e89a7fe589b18da5d1249 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Thu, 1 Oct 2026 14:16:29 +0000 Subject: [PATCH] tune category selection --- AGENTS.md | 31 +++- README.md | 34 ++-- config.example.json | 6 +- data/codegen-watch.jsonl | 0 scripts/tune_navigation.py | 192 +++++++++++++++++++ semif_agent/scheduler.py | 12 +- semif_agent/skills.py | 271 ++++++++++++++++----------- tests/integration/test_pipeline.py | 68 ++++--- tests/test_skills.py | 283 ++++++++++++++++++++--------- 9 files changed, 655 insertions(+), 242 deletions(-) delete mode 100644 data/codegen-watch.jsonl create mode 100644 scripts/tune_navigation.py diff --git a/AGENTS.md b/AGENTS.md index a727c60..950790b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -313,14 +313,29 @@ CLI, unit tests (24) + box integration tests (2). graceful (traced `draft_failed`, user notified, request not re-dispatched); only SemIf availability is fatal. Authoring is still a single pass — validating/reusing written bodies across runs is future work. - **Create-branch confidence gate** (Sep 2026): `create_skill`/`create_category` - compete in a softmax with the real options, so a weak plurality win is not - evidence that nothing matches. Navigation fires a create branch only when - `P(create) >= navigation.create_tau` **and** it leads the best existing option - by `navigation.create_margin`; otherwise it falls back to the best existing - option (a genuinely unmatched action still reaches authoring through the - intent guard) and traces `create_suppressed` with the probs. An empty - tree/category still short-circuits straight to create. + **Navigation is two-stage at both levels; the guards are the create doors** + (Oct 2026). Category level: the softmax offers every existing category **with + its description** plus `create_category`, and the winner is confirmed by + `confirm_category_fit` (phase `navigate:category_scope`, P(covers) >= + `navigation.category_tau`); a rejected winner or a `create_category` win + authors a new category. Descriptions are load-bearing — with bare names the + model sent "book a flight to japan" to `simplex` (0.49 vs create_category + 0.12); with descriptions it picks `create_category` 0.87. `Skill` carries + `category_description`, seeded by `CATEGORY_DESCRIPTIONS` for the built-ins + (response/calendar/simplex) and read from the registry for authored + categories; `category_descriptions(tree)` collapses it per category so an + empty bucket is never offered bare. The old category threshold gate + (`create_tau`/`create_margin`) is **retired**. Leaf level: the softmax + contains **only existing skills** — `create_skill` was removed because sharing + a softmax with the real skills diluted its probability and let a crowded tree + drift into create on a weak plurality (real runs scored `create_skill` + 0.585–0.803 on requests a seed skill clearly matched). The reuse-vs-create + decision is the **intent guard** (`confirm_skill_fit`, phase + `navigate:intent`) at `navigation.intent_tau`. Both taus are separate from the + top-level `tau`, so tuning reuse-vs-create does not move + assessment/fidelity. The guards are deliberately permissive (in-scope scores + 0.9–1.0): a borderline over-cover routes into a plausible category and the + leaf guard catches it. Empty and single-skill categories skip their softmax. - **No handle/ignore gate; the `response` tree is the catchall** (Sep 2026): the top-level `_contains_request` handle/ignore gate is gone. Every input is scored and dispatched; inputs that are not tasks fall through navigation into diff --git a/README.md b/README.md index 5e63cb2..46e65df 100644 --- a/README.md +++ b/README.md @@ -112,17 +112,27 @@ Skills are leaves: categories → skills → actions. Navigation is a chain of S choices, one per level (`navigate` in `semif_agent/skills.py`), and **every choice is logged** (`navigate:category`, `navigate:leaf`, `navigate:response`). -- The category level offers a `create_category` branch; the leaf level offers - `create_skill`. -- **Create-confidence gate.** `create_skill`/`create_category` share a softmax - with the real options, so a weak plurality win is not evidence that nothing - matches. A create branch fires only when `P(create) >= navigation.create_tau` - **and** it leads the best existing option by `navigation.create_margin`; - otherwise navigation falls back to the best existing option and traces - `create_suppressed` with the probabilities. An empty tree/category still - short-circuits straight to create. -- There is a second door to authoring: an **intent guard** - (`confirm_skill_fit`, phase `navigate:intent`) for genuinely unmatched actions. +- **Two-stage at both levels; the guards are the create doors.** +- **Category.** The softmax offers every existing category **with its + description** plus a `create_category` branch, and the winner is confirmed by + the **scope guard** (`confirm_category_fit`, phase `navigate:category_scope`): + a name-anchored SemIf check at `navigation.category_tau` asking whether that + category's scope covers the request. Confirmed → descend; rejected (or a + `create_category` win) → author a new category. Descriptions are load-bearing: + with bare names the model sent "book a flight to japan" to `simplex` (0.49 vs + `create_category` 0.12); with descriptions it picks `create_category` 0.87. + An empty tree short-circuits straight to create. +- **Leaf.** The leaf softmax picks only among the existing skills (a create + option diluted its probability and let a crowded tree drift into create on a + weak plurality). The picked skill then goes through the **intent guard** + (`confirm_skill_fit`, phase `navigate:intent`): an action comparison at + `navigation.intent_tau` asking whether the skill performs the same action the + request asks for. Same → run it; different → author a new leaf in that + category. An empty (or single-skill) category skips the softmax and goes + straight to the guard. +- Both guards are deliberately permissive; with real descriptions the in-scope + cases score 0.9–1.0, so a borderline over-cover routes into a plausible + category and the leaf guard catches it. ### The skill run loop @@ -463,7 +473,7 @@ Key blocks: | `engine` | SemIf source/revision, GGUF path, context, threads | | `llm` | small model endpoint that authors new category/skill title + description | | `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget | -| `navigation` | create-gate `create_tau` / `create_margin` | +| `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` | | `tau` | decision threshold; `max_reentries` requeue bound | | `queue` | `max_size`, `age_rate` | | `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) | diff --git a/config.example.json b/config.example.json index b9e7beb..184cfb4 100644 --- a/config.example.json +++ b/config.example.json @@ -3,9 +3,9 @@ "tau": 0.6, "max_reentries": 3, "navigation": { - "_comment": "Confidence gate on the create branches. create_skill/create_category share a softmax with the real skills/categories, so a weak plurality win is not evidence that nothing matches. The create branch only fires when P(create) >= create_tau AND it leads the best existing option by create_margin; otherwise navigation falls back to the best existing option (a genuinely unmatched action still reaches authoring through the intent guard). Suppressed picks are traced as create_suppressed with their probs so the thresholds can be calibrated from real runs. A level with nothing to choose from still short-circuits to create.", - "create_tau": 0.5, - "create_margin": 0.35 + "_comment": "Navigation is two-stage at BOTH levels and the guards are the create doors (no threshold gate). Category: the softmax offers each existing category WITH its description (bare names carried no signal) plus create_category; confirm_category_fit then confirms the winner's scope (phase navigate:category_scope, P(covers) >= category_tau) and a rejected winner authors a new category. Leaf: the softmax offers only existing skills; confirm_skill_fit then compares the winner's action to the request (phase navigate:intent, P(same) >= intent_tau) and a mismatch authors a new leaf. Both taus are separate from the top-level tau so tuning reuse-vs-create does not move run assessment/fidelity. The check is deliberately permissive: with real descriptions in-scope requests score 0.9-1.0, so a borderline over-cover routes into a plausible category and the leaf guard catches it.", + "intent_tau": 0.6, + "category_tau": 0.75 }, "queue": {"max_size": 100, "age_rate": 0.01}, "engine": { diff --git a/data/codegen-watch.jsonl b/data/codegen-watch.jsonl deleted file mode 100644 index e69de29..0000000 diff --git a/scripts/tune_navigation.py b/scripts/tune_navigation.py new file mode 100644 index 0000000..c545e3c --- /dev/null +++ b/scripts/tune_navigation.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Tune the two-stage navigation guards. + +Navigation is two-stage at both levels, and the guards are the create doors: + +- **Category**: the softmax offers every existing category WITH its description + plus `create_category`; `confirm_category_fit` confirms the winner's scope. + `navigation.category_tau` is that guard's P(covers) floor. +- **Leaf**: the softmax offers only existing skills; `confirm_skill_fit` + compares the winner's action to the request. `navigation.intent_tau` is that + guard's P(same) floor. + +This replays a hand-labeled eval set through the **real** decision engine and +the **real** skill tree, measuring each guard's probability per request so the +floors can be placed between the true matches and the true mismatches. Run it on +a box with the pinned engine (jarvis): + + .runtime/venv/bin/python scripts/tune_navigation.py + .runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6 + +The tree is whatever the box currently has loaded (committed seeds + the runtime +`data/skills/`), so an expectation naming a skill that is not present is +reported as N/A rather than counted wrong. Labels are hand-written ground truth; +self-labeled decision rows are not evidence. Nothing is written to the runtime +logs. +""" + +from __future__ import annotations + +import argparse +import sys +import tempfile +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO)) + +from semif_agent.cli import build_scheduler, load_config +from semif_agent.decisions import Request +from semif_agent.log import DecisionLog +from semif_agent.skills import ( + CreateCategory, + category_descriptions, + confirm_category_fit, + confirm_skill_fit, + navigate, +) +from semif_agent.trace import TraceLog + +# (request, expected) at the LEAF level: "category.skill" or "create". +LEAF_EVAL: list[tuple[str, str]] = [ + ("what is my next message on simplex?", "simplex.next_message"), + ("check my next message on simplex", "simplex.next_message"), + ("read the next simplex message", "simplex.next_message"), + ("show me my simplex messages", "simplex.next_message"), + ('send a message on simplex to pepper: "hey!"', "simplex.send_simplex_message"), + ("send a simplex message to pepper saying hi", "simplex.send_simplex_message"), + ("what is my simplex connection link?", "simplex.connect_link"), + ("give me my simplex contact link", "simplex.connect_link"), + ("tell me the next event in my nextcloud calendar", "calendar.next_event"), + ("translate my last simplex message to French", "create"), + ("delete my next simplex message", "create"), + ("book a flight to japan", "create"), +] + +# (request, expected) at the CATEGORY level: a category name or "create". +CATEGORY_EVAL: list[tuple[str, str]] = [ + ("what is my next message on simplex?", "simplex"), + ("send a simplex message to pepper saying hi", "simplex"), + ("what is my simplex connection link?", "simplex"), + ("tell me the next event in my nextcloud calendar", "calendar"), + ("hello there", "response"), + ("thanks!", "response"), + ("book a flight to japan", "create"), + ("what is the weather in paris", "create"), + ("order me a pizza", "create"), + ("tell me if my package was delivered", "create"), +] + +SWEEP = [0.30, 0.40, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90] + + +def _present(tree: dict, qualified: str) -> bool: + if qualified == "create": + return True + if "." not in qualified: + return qualified in tree + category, _, name = qualified.partition(".") + return any(s.name == name for s in tree.get(category, [])) + + +def measure( + scheduler, log, trace, request: Request, level: str, tau: float +) -> dict: + """Run one navigation pass and return the guard probability for `level`.""" + before = len(trace.read()) + nav = navigate( + scheduler.engine, log, trace, request, scheduler.tree, category_tau=tau + ) + events = trace.read()[before:] + + if level == "category": + if isinstance(nav, CreateCategory): + return {"picked": "create", "p": None} + # navigate already ran the guard internally; read its event. + guard = next((e for e in events if e["kind"] == "category_scope"), None) + return {"picked": nav.category, "p": guard["probs"]["covers"] if guard else None} + + # leaf: navigate returns a Skill, CreateSkill, or CreateCategory. + if not hasattr(nav, "name"): + return {"picked": "create", "p": None} + confirm_skill_fit(scheduler.engine, log, trace, request, nav, tau=tau) + events = trace.read()[before:] + guard = next((e for e in events if e["kind"] == "intent_guard"), None) + return {"picked": f"{nav.category}.{nav.name}", "p": guard["probs"]["same"] if guard else None} + + +def verdict(measured: dict, tau: float) -> str: + if measured["p"] is None: + return measured["picked"] + if measured["p"] >= tau: + return measured["picked"] + return "create" + + +def run_level(scheduler, log, trace, level: str, tau: float, eval_set, sweep) -> None: + print(f"### {level.upper()} level (real engine; ~1s/decision)\n") + results = [] + for text, expected in eval_set: + present = _present(scheduler.tree, expected) + measured = measure(scheduler, log, trace, Request(text), level, tau) + results.append((text, expected, present, measured)) + + print(f"{'request':52s} {'picked':28s} {'p':>8s} {'expected':24s}") + print("-" * 116) + for text, expected, present, m in results: + picked = m["picked"] or "(create)" + p = f"{m['p']:.3f}" if m["p"] is not None else " -" + exp = expected + ("" if present else " [N/A]") + print(f"{text[:52]:52s} {picked:28s} {p:>8s} {exp:24s}") + + print(f"\n{'tau':>6s} {'correct':>8s} {'false_create':>13s} {'false_reuse':>12s} {'na':>4s}") + print("-" * 46) + for t in sweep: + correct = fc = fr = na = 0 + for _text, expected, present, m in results: + if not present: + na += 1 + continue + got = verdict(m, t) + if got == expected: + correct += 1 + elif expected == "create": + fr += 1 + else: + fc += 1 + print(f"{t:6.2f} {correct:8d} {fc:13d} {fr:12d} {na:4d}") + print() + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", default=str(REPO / "config.json")) + parser.add_argument("--tau", type=float, default=None, help="report a single tau only") + parser.add_argument( + "--level", choices=["leaf", "category", "both"], default="both" + ) + args = parser.parse_args() + + config = load_config(args.config) + scheduler, _ = build_scheduler(config) + scratch = Path(tempfile.mkdtemp(prefix="tune_navigation.")) + log = DecisionLog(str(scratch / "decisions.jsonl")) + trace = TraceLog(str(scratch / "runs.jsonl")) + sweep = [args.tau] if args.tau is not None else SWEEP + + if args.level in ("category", "both"): + run_level( + scheduler, log, trace, "category", args.tau or 0.5, CATEGORY_EVAL, sweep + ) + if args.level in ("leaf", "both"): + run_level(scheduler, log, trace, "leaf", args.tau or 0.6, LEAF_EVAL, sweep) + + print( + "false_create = should have reused something existing but authored a new one\n" + "false_reuse = should have authored something new but used an existing one" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 3194a8d..13054bf 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -198,8 +198,8 @@ class Scheduler: self.config = config self.tau = tau nav_cfg = config.get("navigation", {}) or {} - self.create_tau = float(nav_cfg.get("create_tau", 0.5)) - self.create_margin = float(nav_cfg.get("create_margin", 0.35)) + self.intent_tau = float(nav_cfg.get("intent_tau", 0.6)) + self.category_tau = float(nav_cfg.get("category_tau", 0.75)) self.max_reentries = max_reentries self.codegen = codegen self.degeneration_check_factory = degeneration_check_factory @@ -428,8 +428,7 @@ class Scheduler: self.trace, request, self.tree, - create_tau=self.create_tau, - create_margin=self.create_margin, + category_tau=self.category_tau, ) if isinstance(navigation, CreateCategory): return self._dispatch_create_category(request, weight) @@ -438,9 +437,8 @@ class Scheduler: fallback = self._canned_fallback(navigation.category) if fallback is not None: self.trace.append( - "create_suppressed", + "canned_fallback", request.id, - level="canned_category", category=navigation.category, fallback=fallback.name, ) @@ -449,7 +447,7 @@ class Scheduler: if navigation.category in CANNED_CATEGORIES: return self._run_skill(navigation, request) if not confirm_skill_fit( - self.engine, self.log, self.trace, request, navigation, self.tau + self.engine, self.log, self.trace, request, navigation, self.intent_tau ): self.trace.append( "intent_mismatch", diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 8ee8005..28cb49b 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -59,6 +59,7 @@ class Skill: contract: dict = field(default_factory=dict) integration: dict = field(default_factory=dict) integration_source: str = "unknown" + category_description: str = "" def is_noop(self) -> bool: """A stub leaf: authored (title + description) but no runnable body yet.""" @@ -349,6 +350,9 @@ def merge_skill_store( for skill in entry.get("skills", []): if skill.get("name") == name: description = skill.get("description", "") + category_description = str( + entry.get("description") or CATEGORY_DESCRIPTIONS.get(category, "") + ) try: module = load_skill_module(category, name, store.path) except Exception: @@ -371,6 +375,7 @@ def merge_skill_store( contract=contract, integration=integration, integration_source=integration_source, + category_description=category_description, ) skills = tree.setdefault(category, []) for index, existing in enumerate(skills): @@ -425,6 +430,7 @@ def merge_seed_store( contract=contract, integration=integration, integration_source=integration_source, + category_description=CATEGORY_DESCRIPTIONS.get(category, ""), ) skills = tree.setdefault(category, []) for index, existing in enumerate(skills): @@ -527,6 +533,27 @@ _CANNED_RESPONSES = [ _RESPONSE_MESSAGES = {f"response.{name}": message for name, _, message in _CANNED_RESPONSES} +# Built-in category descriptions. A category level that offers only bare names +# carries no signal (real runs sent "book a flight to japan" to the `simplex` +# bucket 0.49 vs create_category 0.12); giving the model the category's scope +# flips that to create_category 0.87 vs simplex 0.02. Authored categories carry +# their own description from the registry; this is the seed for the built-ins and +# the fallback for a legacy entry with no description. +CATEGORY_DESCRIPTIONS: dict[str, str] = { + "response": ( + "Anything that is not a request to perform an action: greetings, thanks, " + "chit-chat, off-topic statements, and inputs the agent cannot act on." + ), + "calendar": ( + "Calendar and scheduling: reading or changing the user's calendar " + "events and reminders." + ), + "simplex": ( + "SimpleX messaging: reading incoming messages, sending messages to " + "contacts, and showing the user's contact link." + ), +} + def build_skills(config: dict) -> list[Skill]: """The hardcoded built-ins: internal behaviors only. @@ -547,11 +574,32 @@ def build_skills(config: dict) -> list[Skill]: category="response", description=description, act=_canned_response(f"response.{name}", message), + category_description=CATEGORY_DESCRIPTIONS["response"], ) for name, description, message in _CANNED_RESPONSES ] +def category_descriptions(tree: dict[str, list[Skill]]) -> dict[str, str]: + """The description to offer for each category, best-effort. + + An authored skill carries the registry description on its `Skill` + (merge_registry/merge_skill_store); a seed or a legacy entry with no + description falls back to `CATEGORY_DESCRIPTIONS`. An empty category bucket + (no skills to carry it) falls back too, so a category is never offered bare. + """ + merged: dict[str, str] = {} + for category, skills in tree.items(): + for skill in skills: + if skill.category_description: + merged[category] = skill.category_description + break + for category in tree: + if not merged.get(category): + merged[category] = CATEGORY_DESCRIPTIONS.get(category, "") + return merged + + def build_tree(skills: list[Skill]) -> dict[str, list[Skill]]: tree: dict[str, list[Skill]] = {} @@ -570,6 +618,7 @@ def merge_registry(tree: dict[str, list[Skill]], categories: dict[str, dict]) -> """ for category, data in categories.items(): tree.setdefault(category, []) + description = str(data.get("description") or CATEGORY_DESCRIPTIONS.get(category, "")) existing = {s.name for s in tree[category]} for skill in data.get("skills", []): name = skill.get("name") @@ -580,36 +629,12 @@ def merge_registry(tree: dict[str, list[Skill]], categories: dict[str, dict]) -> name=name, category=category, description=skill.get("description", ""), + category_description=description, ) ) existing.add(name) -def _clears_create_gate( - result, - create_id: str, - existing_ids: list[str], - tau: float, - margin: float, -) -> bool: - """Should the create branch actually fire, or is it a weak plurality win? - - The create option shares a softmax with the real categories/skills, so its - probability is diluted by every existing option — it is not a measure of - "confidence that nothing matches". Require both an absolute floor (`tau`) - and a clear lead over the best existing option (`margin`); a create that - only squeaks past on a crowded tree is suppressed and navigation falls back - to the best existing branch (the intent guard remains a second door to - authoring). Returns True when the gate is effectively disabled. - """ - probs = result.probs - if create_id not in probs: - return True - create_p = probs[create_id] - best = max((probs[i] for i in existing_ids if i in probs), default=0.0) - return create_p >= tau and (create_p - best) >= margin - - def _navigate_canned( engine: SemIfEngine, log: DecisionLog, @@ -656,30 +681,39 @@ def navigate( trace: TraceLog, request: Request, tree: dict[str, list[Skill]], - create_tau: float = 0.5, - create_margin: float = 0.35, + category_tau: float = 0.75, ) -> Skill | CreateCategory | CreateSkill: """Descend the tree one SemIf choice per level. Every choice is logged. - The category level offers a "create_category" branch and the leaf level a - "create_skill" branch; both are handled live by dispatch and log a - suggestion event to the trace. A level with nothing to choose from - (an empty tree, or a category with no skills yet) short-circuits straight to - the create branch: SemIf decisions need at least two options, and asking - "which of one?" is meaningless. + The category level is **two-stage** (mirroring the leaf). The softmax offers + every existing category **with its description** plus a `create_category` + branch; the winner is then confirmed by `confirm_category_fit`, a name-anchored + scope check. A confirmed winner is descended into; a winner that does not + cover the request (or a `create_category` win) authors a new category. Bare + category names carry no signal — real runs sent "book a flight to japan" to + the `simplex` bucket (0.49 vs create_category 0.12) until the descriptions + were added — so the descriptions are load-bearing, and the confirm guard is + the create door (there is no threshold gate any more). A level with nothing + to choose from (an empty tree) short-circuits straight to create: SemIf + decisions need at least two options. - A create branch that wins the softmax but fails the confidence gate - (`create_tau` floor and `create_margin` lead over the best existing option) - is suppressed: navigation falls back to the best existing option so a - genuinely unmatched action still reaches authoring through the intent guard, - while a crowded tree no longer drifts into create on a weak plurality. + The leaf level is two-stage too: navigation only ever picks among the + existing skills (`create_skill` is deliberately NOT in the softmax), and the + reuse-vs-create decision is the intent guard in dispatch + (`confirm_skill_fit`), keyed by `navigation.intent_tau`. """ categories = sorted(tree.keys()) - create_category = Option("create_category", "Suggest a new category for this.") + descriptions = category_descriptions(tree) + create_category = Option( + "create_category", + "No existing category covers this request; a new top-level category is " + "needed.", + ) top = DecisionRequest( state=compose_state(request), question="Which top-level category handles this request?", - options=[Option(c, c) for c in categories] + [create_category], + options=[Option(c, descriptions.get(c, c)) for c in categories] + + [create_category], ) if not categories: trace.append( @@ -695,23 +729,17 @@ def navigate( top_result = engine.call(top) log.append(top, top_result, extra={"phase": "navigate:category", "run_id": request.id}) category = top_result.selected - if category == "create_category" and not _clears_create_gate( - top_result, "create_category", categories, create_tau, create_margin + if category != "create_category" and not confirm_category_fit( + engine, log, trace, request, category, descriptions.get(category, ""), + category_tau, ): - fallback = max( - (c for c in categories if c in top_result.probs), - key=lambda c: top_result.probs[c], - ) trace.append( - "create_suppressed", + "category_scope_rejected", request.id, - level="category", - fallback=fallback, + category=category, probs=top_result.probs, - tau=create_tau, - margin=create_margin, ) - category = fallback + category = "create_category" if category == "create_category": trace.append( "create_category", @@ -726,62 +754,96 @@ def navigate( skills = tree[category] if category in CANNED_CATEGORIES: return _navigate_canned(engine, log, trace, request, category, skills) - create_skill = Option( - "create_skill", - "No existing skill performs this action; create a new skill for it.", - ) - leaf = DecisionRequest( - state=compose_state(request, current=category), - question=f"Which {category} skill performs the action this request asks for? " - "Choose create_skill if none does.", - options=[Option(s.name, s.description) for s in skills] + [create_skill], - ) if not skills: trace.append( "skill_needed", request.id, category=category, - state=leaf.state, - question=leaf.question, - options=[o.id for o in leaf.options], + state=compose_state(request, current=category), + question="(this category has no skills yet)", + options=[], selected="create_skill", probs={}, ) return CreateSkill(category=category) + if len(skills) == 1: + # A one-option softmax is meaningless; hand the sole skill to the intent + # guard, which owns the reuse-vs-create decision. + return skills[0] + leaf = DecisionRequest( + state=compose_state(request, current=category), + question=f"Which {category} skill performs the action this request asks for?", + options=[Option(s.name, s.description) for s in skills], + ) leaf_result = engine.call(leaf) log.append(leaf, leaf_result, extra={"phase": "navigate:leaf", "run_id": request.id}) pick = leaf_result.selected - if pick == "create_skill" and not _clears_create_gate( - leaf_result, "create_skill", [s.name for s in skills], create_tau, create_margin - ): - fallback = max( - (s.name for s in skills if s.name in leaf_result.probs), - key=lambda n: leaf_result.probs[n], - ) - trace.append( - "create_suppressed", - request.id, - level="leaf", - category=category, - fallback=fallback, - probs=leaf_result.probs, - tau=create_tau, - margin=create_margin, - ) - pick = fallback - if pick == "create_skill": - trace.append( - "skill_needed", - request.id, - category=category, - state=leaf.state, - question=leaf.question, - options=[o.id for o in leaf.options], - selected=leaf_result.selected, - probs=leaf_result.probs, - ) - return CreateSkill(category=category) - return next(s for s in skills if s.name == pick) + return next((s for s in skills if s.name == pick), skills[0]) + + +def confirm_category_fit( + engine: SemIfEngine, + log: DecisionLog, + trace: TraceLog, + request: Request, + category: str, + description: str, + tau: float = 0.75, +) -> bool: + """Does this category's scope actually cover what the request asks for? + + The category-level counterpart of `confirm_skill_fit`, and the create door + at that level: the described-category softmax proposes the best category, + and this name-anchored scope check confirms it. A rejected winner (or a + `create_category` win) authors a new category instead. The threshold is + `navigation.category_tau` (default 0.75 — measured so true non-tasks, which + score 0.87–0.999 on `response`, sit above it and a task misrouted into + `response` at 0.61 sits below). + + Name-anchored on purpose: asking whether *the winner we picked* covers the + request is far cleaner than a global "does any category cover this?" — the + global wording collapsed in-scope and out-of-scope requests into one band + (0.47-0.98) and over-covered a non-task ("thank pepper ..."). This compares + one category's stated scope to the request. The check is deliberately + permissive: with real descriptions the in-scope cases score 0.9-1.0, so a + borderline over-cover routes into a plausible category and the leaf intent + guard catches it (a skill is only authored if no existing leaf matches). + """ + decision = DecisionRequest( + state=( + f"Request: {request.text}\n" + f"Category: {category}\n" + f"Scope: {description}" + ), + question=f"Does the scope of the {category} category cover this request?", + options=[ + Option("covers", "Yes, this category covers the request."), + Option( + "none", + "No, this category does not cover the request; a new category is needed.", + ), + ], + ) + result = engine.call(decision) + log.append( + decision, + result, + extra={ + "phase": "navigate:category_scope", + "run_id": request.id, + "category": category, + }, + ) + fits = result.prob("covers") >= tau + trace.append( + "category_scope", + request.id, + category=category, + selected=result.selected, + probs=result.probs, + fits=fits, + ) + return fits def confirm_skill_fit( @@ -794,16 +856,21 @@ def confirm_skill_fit( ) -> bool: """Does this skill's action actually match what the request asks for? - Navigation picks the closest leaf; a seeded read skill can outscore the - generic "create a new skill" branch on a request whose verb (send) no - existing action performs. This one SemIf decision guards against silently - running the wrong skill: a mismatch sends dispatch to author a new leaf - instead. Wording tuned against the real model: comparing the two *actions* + Navigation picks the closest existing leaf; this guard is now the **sole** + leaf-level reuse-vs-create decision (create_skill is no longer an option in + the leaf softmax). If the skill's action is not the same action the request + asks for, dispatch authors a new leaf instead. The threshold is + `navigation.intent_tau` (deliberately separate from the run-assessment + `tau`, so tuning reuse-vs-create does not move assessment/fidelity). + + Wording tuned against the real model: comparing the two *actions* ("different action") is unambiguous where "can this serve the request" was not — e.g. "message Sam" (an implicit send in instant-messaging syntax) reads as a different action from "read the next message". Do not add an instant-messaging context hint: it over-fires and pulls read phrasings to - the send side. + the send side. The comparison is over-permissive on near-synonyms (read vs + send score "same" ~0.74-0.78), so it is paired with the softmax that + disambiguates them — the guard only ever sees the softmax winner. """ decision = DecisionRequest( state=( diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index 3fabbdb..9f9d80c 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -27,7 +27,6 @@ from semif_agent.scheduler import SkillWrite from semif_agent.skills import ( ActionResult, CategoryDraft, - CreateSkill, Skill, SkillDraft, SkillStore, @@ -93,6 +92,7 @@ def _install_tracking_fixture(scheduler): category="tracking", description="Check the delivery status of a package.", act=act, + category_description="Package tracking: checking the delivery status of parcels and shipments.", ) ] @@ -120,7 +120,6 @@ def test_pipeline_end_to_end(tmp_path): phases = [r.get("extra", {}).get("phase") for r in rows] assert "navigate:category" in phases, "navigation decisions must be logged" - assert "navigate:leaf" in phases, "navigation decisions must be logged" for row in rows: assert row.get("extra", {}).get("run_id"), "every decision must carry a run_id" @@ -150,7 +149,18 @@ def test_navigation_routes_noise_into_the_response_tree(tmp_path): "what is the next event in my nextcloud calendar?", "tell me the next even in my calendar", ] - noise = ["hello there", "thanks!", "the sky is blue", "what's up"] + noise = [ + "hello there", + "thanks!", + "the sky is blue", + "what's up", + # Stray statements not addressed to the agent: these have no action to + # perform, so they must fall to the `response` catchall, not author a + # category. Regression: an under-covering `response` description sent + # "the sky is blue"/"1+1=2"/"random thought here" to create_category. + "1+1=2", + "random thought here", + ] for text in lookups: result = navigate( scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree @@ -166,23 +176,32 @@ def test_navigation_routes_noise_into_the_response_tree(tmp_path): def test_navigate_routes_unmatched_action_to_create_skill(tmp_path): - """A send request must navigate to create_skill, not silently to the read - skill that merely shares the word 'message'. + """Two-stage leaf: navigation picks the closest existing skill, then the + intent guard decides reuse-vs-create. A send request must reach create_skill + for simplex — not silently run the read skill that merely shares the word + 'message'; a read request must reuse next_message. - Regression: every send phrasing picked simplex.next_message (P 0.46-0.73) - while the create_skill fallback scored only 0.007-0.09, because its option - description named the mechanism ("suggest creating a new skill") instead of - the trigger. This asserts the navigation outcome only — no codegen write. + Regression: the old single-stage leaf put create_skill in the softmax with + the real skills, so a send phrasing could win on a weak plurality while the + read skill stayed high. Now create_skill is never an option; the guard's + action comparison is the door. Asserts the routing outcome only — the draft + queue is stubbed and the read leaf's act is a stub, so no codegen write and + no network. """ config = load_config() require_real(config) _isolate_runtime(config, tmp_path) scheduler, config = build_scheduler(config) + + def read_act(ctx, request): + return ActionResult(action_log="read fixture", new_state="read") + scheduler.tree["simplex"] = [ Skill( name="next_message", category="simplex", description="Read the next unread SimpleX message bridge.", + act=read_act, ), Skill( name="connect_link", @@ -190,36 +209,29 @@ def test_navigate_routes_unmatched_action_to_create_skill(tmp_path): description="Show (creating if needed) the SimpleX contact link others use to connect to this agent.", ), ] + queued: list = [] + scheduler._queue_draft = lambda request, category, kind, weight: queued.append( + (category, kind) + ) for text in [ "send a simplex message to pepper saying hi", "send a new simplex message to pepper: hey", ]: before = len(scheduler.log.read()) - result = navigate( - scheduler.engine, - scheduler.log, - scheduler.trace, - Request(text), - scheduler.tree, - ) + result = scheduler._dispatch(Request(text)) leaf_rows = [ r for r in scheduler.log.read()[before:] if r.get("extra", {}).get("phase") == "navigate:leaf" ] - print(f"[nav] {leaf_rows[-1]['predicted_probs'] if leaf_rows else '-'} :: {text!r} -> {result}") - assert isinstance(result, CreateSkill), f"send must route to create_skill, got {result!r}" - assert result.category == "simplex" + print(f"[nav] {leaf_rows[-1]['predicted_probs'] if leaf_rows else '-'} :: {text!r} -> {result.kind}") + assert result.kind == "create_skill", f"send must route to create_skill, got {result!r}" + assert queued and all(category == "simplex" for category, _ in queued) - read = navigate( - scheduler.engine, - scheduler.log, - scheduler.trace, - Request("read the next simplex message"), - scheduler.tree, - ) - print(f"[nav control] read -> {read}") - assert getattr(read, "name", None) == "next_message", "a read request must still route to the read skill" + read = scheduler._dispatch(Request("read the next simplex message")) + print(f"[nav control] read -> {read.kind} {read.skill}") + assert read.kind == "ran", "a read request must still run the read skill" + assert read.skill == "next_message" def test_busy_choice_path(tmp_path): diff --git a/tests/test_skills.py b/tests/test_skills.py index 86850bb..cde14f3 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -42,7 +42,10 @@ from semif_agent.skills import ( build_skill_prompt, build_skills, build_tree, + confirm_category_fit, confirm_skill_fit, + category_descriptions, + CATEGORY_DESCRIPTIONS, generate_category, generate_skill, merge_registry, @@ -392,6 +395,28 @@ def test_merge_registry_loads_categories_and_skills(tmp_path): assert tree["delivery"][0].category == "delivery" +def test_category_descriptions_never_bare_and_seeded(tmp_path): + """Every category must carry a usable description at the softmax — a bare + name carries no signal. Built-ins come from CATEGORY_DESCRIPTIONS; an + authored category carries its registry description; a legacy/empty entry + falls back to the built-in or empty string without crashing.""" + tree = build_tree(build_skills({"skills": {}})) + assert tree["response"][0].category_description # built-in seed + + registry = CategoryRegistry(str(tmp_path / "categories.json")) + registry.register("travel", "Booking flights, hotels, and trips.") + registry.register_skill("travel", "book_flight", "Book a flight.") + merge_registry(tree, registry.read()) + assert tree["travel"][0].category_description == "Booking flights, hotels, and trips." + + descriptions = category_descriptions(tree) + assert descriptions["response"] == CATEGORY_DESCRIPTIONS["response"] + assert descriptions["travel"] == "Booking flights, hotels, and trips." + # an empty bucket (no skill to carry the description) still resolves to text + tree["orphan"] = [] + assert category_descriptions(tree)["orphan"] == "" + + def _write_seed(seed_store, category, name, description=""): directory = seed_store.dir(category, name) directory.mkdir(parents=True, exist_ok=True) @@ -581,11 +606,10 @@ def test_canned_response_runs_without_assessment(tmp_path): -def test_navigate_leaf_offers_create_for_unmatched_action(tmp_path): - """The create_skill fallback must describe the *trigger* (no skill performs - the action), not the mechanism ('suggest creating a new skill'): the - decision model only sees option descriptions, and the generic wording lost - 0.03-0.06 to a read skill on send requests.""" +def test_navigate_leaf_picks_among_existing_skills_only(tmp_path): + """Two-stage leaf: create_skill is NOT an option in the leaf softmax. The + leaf decision offers only the existing skills, and navigation returns the + best-matching one; the intent guard in dispatch owns reuse-vs-create.""" class Recording: def __init__(self): @@ -601,16 +625,22 @@ def test_navigate_leaf_offers_create_for_unmatched_action(tmp_path): engine = Recording() log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) - tree = {"simplex": [Skill(name="next_message", category="simplex", description="Read the next SimpleX message.")]} - navigate(engine, log, trace, Request("send a simplex message"), tree) - create = next(o for o in engine.request.options if o.id == "create_skill") - assert "No existing skill performs this action" in create.description - assert "action" in engine.request.question + tree = { + "simplex": [ + Skill(name="next_message", category="simplex", description="Read the next SimpleX message."), + Skill(name="connect_link", category="simplex", description="Show the contact link."), + ] + } + result = navigate(engine, log, trace, Request("send a simplex message"), tree) + ids = [o.id for o in engine.request.options] + assert ids == ["next_message", "connect_link"] + assert "create_skill" not in ids + assert getattr(result, "name", None) in ids class _ProbEngine: """Returns caller-specified probabilities, keyed by a substring of the - decision question, so a test can force a weak create plurality.""" + decision question, so a test can force a specific navigation outcome.""" def __init__(self, by_question: dict[str, dict[str, float]]): self.by_question = by_question @@ -626,6 +656,9 @@ class _ProbEngine: if key in request.question: probs_map = value break + if not probs_map: + probs_map = {ids[0]: 1.0} + probs_map = {k: v for k, v in probs_map.items() if k in ids} if not probs_map: probs_map = {ids[0]: 1.0} return DecisionResult( @@ -642,111 +675,197 @@ def _leaf_tree(): name="next_message", category="simplex", description="Read the next SimpleX message.", - ) + ), + Skill( + name="connect_link", + category="simplex", + description="Show the contact link.", + ), ] } -def test_navigate_suppresses_weak_create_plurality(tmp_path): - """create_skill wins the softmax by a hair but fails the margin gate: the - weak plurality must fall back to the best existing skill, not author.""" +def test_navigate_leaf_returns_best_existing_skill(tmp_path): + """The leaf softmax picks the highest-probability existing skill; no create + branch competes with it (that was the dilution bug).""" log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) engine = _ProbEngine( { "top-level category": {"simplex": 1.0}, - "skill performs": {"next_message": 0.45, "create_skill": 0.5}, + "Does the scope": {"covers": 1.0}, + "skill performs": {"next_message": 0.45, "connect_link": 0.55}, } ) result = navigate( engine, log, trace, Request("send a simplex message"), _leaf_tree() ) + assert getattr(result, "name", None) == "connect_link" + assert not isinstance(result, CreateSkill) + + +def test_navigate_single_skill_category_skips_the_softmax(tmp_path): + """A one-option softmax is meaningless; the sole skill is returned directly + and the guard decides reuse-vs-create.""" + log = DecisionLog(str(tmp_path / "decisions.jsonl")) + trace = TraceLog(str(tmp_path / "runs.jsonl")) + engine = _ProbEngine( + {"top-level category": {"simplex": 1.0}, "Does the scope": {"covers": 1.0}} + ) + tree = { + "simplex": [ + Skill(name="next_message", category="simplex", description="Read the next SimpleX message.") + ] + } + result = navigate(engine, log, trace, Request("read the next message"), tree) assert getattr(result, "name", None) == "next_message" - suppressed = [e for e in trace.read() if e["kind"] == "create_suppressed"] - assert len(suppressed) == 1 - assert suppressed[0]["level"] == "leaf" - assert suppressed[0]["fallback"] == "next_message" + # only the category decision was made; the leaf softmax was skipped + assert all("Which simplex skill" not in c.question for c in engine.calls) -def test_navigate_create_clears_margin_and_tau(tmp_path): - """A create that leads the best skill by >= margin and clears tau fires.""" +def test_navigate_empty_category_short_circuits_to_create(tmp_path): log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) - engine = _ProbEngine( - { - "top-level category": {"simplex": 1.0}, - "skill performs": {"next_message": 0.2, "create_skill": 0.7}, - } - ) - result = navigate( - engine, log, trace, Request("send a simplex message"), _leaf_tree() - ) + engine = _ProbEngine({"top-level category": {"simplex": 1.0}}) + result = navigate(engine, log, trace, Request("anything"), {"simplex": []}) assert isinstance(result, CreateSkill) assert result.category == "simplex" - assert not [e for e in trace.read() if e["kind"] == "create_suppressed"] + assert any(e["kind"] == "skill_needed" for e in trace.read()) -def test_navigate_create_below_tau_is_suppressed(tmp_path): - """Even with a clear lead, a create below the absolute floor is suppressed - (all options weak => nothing is a confident match).""" +def test_navigate_category_options_carry_descriptions(tmp_path): + """The category softmax must offer each category WITH its description — bare + names carry no signal (the misroute bug).""" + engine = _ProbEngine({"top-level category": {"simplex": 1.0}}) log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) + tree = { + "simplex": [ + Skill( + name="next_message", + category="simplex", + description="Read the next SimpleX message.", + category_description="SimpleX messaging: read/send messages.", + ) + ] + } + navigate(engine, log, trace, Request("read the next message"), tree) + cat_decision = next(c for c in engine.calls if "top-level category" in c.question) + by_id = {o.id: o.description for o in cat_decision.options} + assert by_id["simplex"] == "SimpleX messaging: read/send messages." + assert "new top-level category is needed" in by_id["create_category"] + + +def test_navigate_category_rejected_scope_authors_category(tmp_path): + """The confirm guard is the category create door: a softmax winner whose + scope the guard rejects authors a new category.""" + log = DecisionLog(str(tmp_path / "decisions.jsonl")) + trace = TraceLog(str(tmp_path / "runs.jsonl")) + tree = _leaf_tree() engine = _ProbEngine( { "top-level category": {"simplex": 1.0}, - "skill performs": {"next_message": 0.1, "create_skill": 0.3}, - } - ) - result = navigate( - engine, log, trace, Request("send a simplex message"), _leaf_tree() - ) - assert getattr(result, "name", None) == "next_message" - assert any(e["kind"] == "create_suppressed" for e in trace.read()) - - -def test_navigate_category_create_gate_suppresses_and_falls_back(tmp_path): - """The same gate applies to create_category: a weak plurality win falls back - to the best existing category and descends into it.""" - log = DecisionLog(str(tmp_path / "decisions.jsonl")) - trace = TraceLog(str(tmp_path / "runs.jsonl")) - tree = _leaf_tree() - tree["calendar"] = [ - Skill(name="next_event", category="calendar", description="Report the next event.") - ] - engine = _ProbEngine( - { - "top-level category": { - "calendar": 0.30, - "simplex": 0.32, - "create_category": 0.38, - }, - "skill performs": {"next_message": 1.0}, - } - ) - result = navigate(engine, log, trace, Request("send a simplex message"), tree) - assert getattr(result, "name", None) == "next_message" - suppressed = [e for e in trace.read() if e["kind"] == "create_suppressed"] - assert len(suppressed) == 1 and suppressed[0]["level"] == "category" - assert suppressed[0]["fallback"] == "simplex" - - -def test_navigate_category_create_clears_gate(tmp_path): - log = DecisionLog(str(tmp_path / "decisions.jsonl")) - trace = TraceLog(str(tmp_path / "runs.jsonl")) - tree = _leaf_tree() - engine = _ProbEngine( - { - "top-level category": { - "simplex": 0.1, - "create_category": 0.8, - }, + "Does the scope": {"none": 1.0}, } ) result = navigate(engine, log, trace, Request("book a flight"), tree) assert isinstance(result, CreateCategory) - assert not [e for e in trace.read() if e["kind"] == "create_suppressed"] + assert any(e["kind"] == "category_scope_rejected" for e in trace.read()) + assert any(e["kind"] == "create_category" for e in trace.read()) +def test_navigate_category_confirmed_scope_descends(tmp_path): + """A softmax winner the guard confirms is descended into (no create).""" + log = DecisionLog(str(tmp_path / "decisions.jsonl")) + trace = TraceLog(str(tmp_path / "runs.jsonl")) + engine = _ProbEngine( + { + "top-level category": {"simplex": 1.0}, + "Does the scope": {"covers": 1.0}, + "skill performs": {"next_message": 1.0, "connect_link": 0.0}, + } + ) + result = navigate(engine, log, trace, Request("read a message"), _leaf_tree()) + assert getattr(result, "name", None) == "next_message" + assert not isinstance(result, CreateCategory) + assert any(e["kind"] == "category_scope" and e["fits"] for e in trace.read()) + + +def test_confirm_category_fit_threshold(tmp_path): + log = DecisionLog(str(tmp_path / "decisions.jsonl")) + trace = TraceLog(str(tmp_path / "runs.jsonl")) + engine = ScriptedEngine(choices={"Does the scope": "covers"}) + assert ( + confirm_category_fit( + engine, log, trace, Request("check my calendar"), "calendar", "Calendars.", tau=0.5 + ) + is True + ) + assert log.read()[-1]["extra"]["phase"] == "navigate:category_scope" + + engine = ScriptedEngine(choices={"Does the scope": "none"}) + assert ( + confirm_category_fit( + engine, log, trace, Request("order pizza"), "calendar", "Calendars.", tau=0.5 + ) + is False + ) + + + +def test_dispatch_intent_tau_controls_reuse_vs_create(tmp_path): + """The leaf reuse-vs-create knob is navigation.intent_tau, separate from the + top-level tau: a borderline guard verdict flips on it while assessment is + untouched.""" + def build(intent_tau: float): + engine = _ProbEngine( + { + "top-level category": {"simplex": 1.0}, + "Does the scope": {"covers": 1.0}, + "skill performs": {"next_message": 1.0, "connect_link": 0.0}, + "same action": {"same": 0.8, "different": 0.2}, + } + ) + scheduler = Scheduler( + engine=engine, + llm=LLMClient(base_url="http://localhost:1/v1", model="test"), + log=DecisionLog(str(tmp_path / "decisions.jsonl")), + config={ + "skills": {}, + "navigation": {"intent_tau": intent_tau}, + "category_registry": str(tmp_path / "categories.json"), + "skill_bodies": str(tmp_path / "skills"), + "skill_seeds": str(tmp_path / "seeds"), + }, + trace=TraceLog(str(tmp_path / "runs.jsonl")), + ) + + def act(ctx, request): + return ActionResult(action_log="read fixture", new_state="read") + + scheduler.tree = { + "simplex": [ + Skill(name="next_message", category="simplex", description="Read the next SimpleX message.", act=act), + Skill(name="connect_link", category="simplex", description="Show the contact link."), + ] + } + queued: list = [] + scheduler._queue_draft = lambda request, category, kind, weight: queued.append( + (category, kind) + ) + return scheduler, queued + + low, queued_low = build(0.5) + assert low.intent_tau == 0.5 + ran = low._dispatch(Request("read the next simplex message")) + assert ran.kind == "ran", "guard same=0.8 clears intent_tau=0.5: reuse" + assert not queued_low + + high, queued_high = build(0.95) + created = high._dispatch(Request("read the next simplex message")) + assert created.kind == "create_skill", "guard same=0.8 fails intent_tau=0.95: author" + assert queued_high == [("simplex", "skill")] + def test_confirm_skill_fit_returns_true_when_action_matches(tmp_path): log = DecisionLog(str(tmp_path / "decisions.jsonl"))