From 13a512cc316587554fac24b4f4f630d26d1d0aff Mon Sep 17 00:00:00 2001 From: Denton Social Date: Mon, 28 Sep 2026 20:34:59 -0500 Subject: [PATCH] routing: send unlearned actions to codegen, fix gate + repair loop SemIf routing only sees option descriptions, but the leaf fallback said 'Suggest creating a new skill' (mechanism, not trigger), so a send request had no verb match and fell through to the read skill that shared the word 'message'. Every send phrasing picked simplex.next_message; create_skill scored ~0.03 and codegen was never reached. - navigate: reword the create_skill fallback to the trigger ('No existing skill performs this action') and make the criterion ask which skill performs the requested action. Sends now route to create_skill at P~0.93. - confirm_skill_fit: one action-vs-action SemIf guard (phase navigate:intent) after routing; a mismatch authors a new leaf instead of silently running the wrong skill. Wording tuned on the real model (no IM hint: it over-fires). - gate: imperative tasks are actionable even with no matching skill, so a casually phrased send is no longer dropped as 'no actionable request'. - finish_run: a failure whose retry is refused by the reentry budget still surfaces a repair offer. Validated on jarvis: gate accepts all tasks/rejects all noise, sends route to CreateSkill, reads still route to their skills. Dev: 265 passed; jarvis non-codegen integration: 6 passed. --- semif_agent/scheduler.py | 27 ++++-- semif_agent/skills.py | 66 +++++++++++++- tests/integration/test_pipeline.py | 75 ++++++++++++++- tests/test_skills.py | 141 ++++++++++++++++++++++++++++- 4 files changed, 294 insertions(+), 15 deletions(-) diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 5887b64..fac7e26 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -46,6 +46,7 @@ from .skills import ( build_skills, build_tree, compose_state, + confirm_skill_fit, generate_category, generate_skill, materialize_skill, @@ -82,10 +83,10 @@ def build_gate_decision(request: Request, tree: dict[str, list[Skill]]) -> Decis capabilities = tree_summary(tree)[:GATE_CAPABILITY_CHARS] or " (none yet)" state = ( f"User input: {request.text}\n" - "[Context: the user is talking to a personal task agent and expects it to " - "handle this input. The agent performs real tasks through its skills; " - "reading or looking up information from a configured service is a real " - "task, not small talk.]\n" + "[Context: the user is talking to a personal task agent. Any imperative " + "request to perform a task — send, message, tell, check, create, remind, " + "or look something up — must be handled, even if no skill matches yet. " + "Only chatter, thanks, and bare greetings should be ignored.]\n" f"[Available skills:\n{capabilities}]" ) return DecisionRequest( @@ -94,8 +95,8 @@ def build_gate_decision(request: Request, tree: dict[str, list[Skill]]) -> Decis options=[ Option( GATE_YES, - "Yes — do what it asks, including looking something up or " - "reporting information using the agent's skills.", + "Yes — do what it asks, including looking something up, reporting " + "information, or performing an action using the agent's skills.", ), Option( "no", @@ -462,6 +463,16 @@ class Scheduler: return self._dispatch_skill(request, created.skill, weight) if isinstance(navigation, CreateSkill): return self._dispatch_skill(request, navigation.category, weight) + if not confirm_skill_fit( + self.engine, self.log, self.trace, request, navigation, self.tau + ): + self.trace.append( + "intent_mismatch", + request.id, + selected_skill=f"{navigation.category}.{navigation.name}", + chosen="create_skill", + ) + return self._dispatch_skill(request, navigation.category, weight) return self._run_skill(navigation, request) def _dispatch_skill( @@ -633,13 +644,15 @@ class Scheduler: action_log=outcome.action_log, updated_request=outcome.updated_request, ) + requeued = False if outcome.updated_request and request.reentries < self.max_reentries: child = _requeue(request, outcome.updated_request) self.queue.push(child, 0.5) self.trace.append("requeued", request.id, text=outcome.updated_request) if self.on_request_requeued is not None: self.on_request_requeued(request.id, child.id) - if not outcome.success and not outcome.updated_request: + requeued = True + if not outcome.success and not (outcome.updated_request and requeued): self._propose_repair(skill, request, outcome) return DispatchResult( kind="ran", diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 6a792b2..5153eed 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -574,10 +574,14 @@ def navigate( ) return CreateCategory() skills = tree[category] - create_skill = Option("create_skill", "Suggest creating a new skill.") + 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"Within {category}, which skill?", + 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: @@ -610,6 +614,64 @@ def navigate( return next(s for s in skills if s.name == pick) +def confirm_skill_fit( + engine: SemIfEngine, + log: DecisionLog, + trace: TraceLog, + request: Request, + skill: Skill, + tau: float = 0.6, +) -> 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* + ("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. + """ + decision = DecisionRequest( + state=( + f"Requested action: {request.text}\n" + f"Action of the existing skill: {skill.description}" + ), + question="Compare the requested action and the skill's action. Are they the same action?", + options=[ + Option("same", "Same action."), + Option( + "different", + "Different action: the skill does not do what the user asks.", + ), + ], + ) + result = engine.call(decision) + log.append( + decision, + result, + extra={ + "phase": "navigate:intent", + "run_id": request.id, + "skill": f"{skill.category}.{skill.name}", + }, + ) + fits = result.prob("same") >= tau + trace.append( + "intent_guard", + request.id, + category=skill.category, + skill=skill.name, + selected=result.selected, + probs=result.probs, + fits=fits, + ) + return fits + + def tree_summary(tree: dict[str, list[Skill]]) -> str: lines = [] for category in sorted(tree): diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index 60cfc10..655a094 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -26,6 +26,7 @@ from semif_agent.scheduler import SkillWrite from semif_agent.skills import ( ActionResult, CategoryDraft, + CreateSkill, Prediction, Skill, SkillDraft, @@ -35,6 +36,7 @@ from semif_agent.skills import ( generate_category, generate_skill, materialize_skill, + navigate, ) @@ -160,12 +162,22 @@ def test_gate_accepts_information_requests_and_rejects_noise(tmp_path): "tell me the next even in my calendar", "tell me the next event in my personal calendar", ] + # Imperative tasks with no matching skill are still actionable: the agent + # learns them. Regression: "send a simplex message to pepper saying hi" + # scored 0.135 and was dropped as "no actionable request". + tasks = [ + "send a simplex message to pepper saying hi", + "send a simplex message to pepper that says hello back to them", + "send a new simplex message to pepper: hey", + "send a simplex message", + "email Sam about lunch", + ] noise = ["hello there", "thanks!", "the sky is blue", "what's up"] - for text in lookups: + for text in lookups + tasks: accepted = scheduler._contains_request(Request(text)) row = scheduler.log.read()[-1] - print(f"[lookup] {row['predicted_probs']} accepted={accepted} {text!r}") - assert accepted, f"gate dropped a lookup: {text!r}" + print(f"[task] {row['predicted_probs']} accepted={accepted} {text!r}") + assert accepted, f"gate dropped a task: {text!r}" for text in noise: accepted = scheduler._contains_request(Request(text)) row = scheduler.log.read()[-1] @@ -173,6 +185,63 @@ def test_gate_accepts_information_requests_and_rejects_noise(tmp_path): assert not accepted, f"gate accepted noise: {text!r}" +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'. + + 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. + """ + config = load_config() + require_real(config) + _isolate_runtime(config, tmp_path) + scheduler, config = build_scheduler(config) + scheduler.tree["simplex"] = [ + Skill( + name="next_message", + category="simplex", + description="Read the next unread SimpleX message through the forwarding bridge.", + ), + Skill( + name="connect_link", + category="simplex", + description="Show (creating if needed) the SimpleX contact link others use to connect to this agent.", + ), + ] + + 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, + ) + 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" + + 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" + + def test_busy_choice_path(tmp_path): config = load_config() require_real(config) diff --git a/tests/test_skills.py b/tests/test_skills.py index 90f8238..04eedf3 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -22,7 +22,9 @@ from semif_agent.decisions import Request from semif_agent.engine import EngineConfig, EngineUnavailable, SemIfEngine from semif_agent.llm import LLMClient from semif_agent.log import DecisionLog +from semif_agent.skill import RunResult from semif_agent.scheduler import ( + DispatchResult, PendingQuestion, RepairOffer, Scheduler, @@ -42,6 +44,7 @@ from semif_agent.skills import ( build_skill_prompt, build_skills, build_tree, + confirm_skill_fit, generate_category, generate_skill, merge_registry, @@ -543,21 +546,127 @@ def test_gate_decision_carries_expectation_and_capabilities(): Request("tell me the next event in my nextcloud calendar"), tree ) assert "tell me the next event in my nextcloud calendar" in decision.state - assert "expects it to handle this input" in decision.state - assert "reading or looking up information" in decision.state + assert "perform a task" in decision.state + assert "look something up" in decision.state assert "calendar: next_event" in decision.state assert decision.question == "Should the agent handle this input?" assert [o.id for o in decision.options] == ["yes", "no"] - assert "looking something up" in decision.options[0].description + assert "performing an action" in decision.options[0].description assert "greeting" in decision.options[1].description +def test_gate_decision_accepts_imperative_tasks_with_no_matching_skill(): + """A request to do something the tree has no skill for is still actionable — + the agent learns it. Regression: 'send a simplex message to pepper saying + hi' scored 0.135 and was dropped as 'no actionable request' because the gate + context only vouched for lookups.""" + tree = build_tree(build_skills({"skills": {}})) + tree["simplex"] = [ + Skill(name="next_message", category="simplex", description="Read the next SimpleX message."), + ] + decision = build_gate_decision(Request("send a simplex message to pepper saying hi"), tree) + assert "even if no skill matches yet" in decision.state + + def test_gate_decision_empty_tree_still_builds(): decision = build_gate_decision(Request("hello"), {}) assert "(none yet)" in decision.state assert decision.options[0].id == "yes" +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.""" + + class Recording: + def __init__(self): + self.request = None + + def call(self, request): + from semif_agent.decisions import DecisionResult + + self.request = request + ids = [o.id for o in request.options] + return DecisionResult(request=request, option_ids=ids, probabilities=[1.0] * len(ids)) + + 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 + + +def test_confirm_skill_fit_returns_true_when_action_matches(tmp_path): + log = DecisionLog(str(tmp_path / "decisions.jsonl")) + trace = TraceLog(str(tmp_path / "runs.jsonl")) + engine = ScriptedEngine(choices={"same action": "same"}) + skill = Skill(name="next_message", category="simplex", description="Read the next SimpleX message.") + assert confirm_skill_fit(engine, log, trace, Request("read the next simplex message"), skill) is True + row = log.read()[-1] + assert row["extra"]["phase"] == "navigate:intent" + assert row["selected"] == "same" + + +def test_confirm_skill_fit_returns_false_on_mismatch(tmp_path): + log = DecisionLog(str(tmp_path / "decisions.jsonl")) + trace = TraceLog(str(tmp_path / "runs.jsonl")) + engine = ScriptedEngine(choices={"same action": "different"}) + skill = Skill(name="next_message", category="simplex", description="Read the next SimpleX message.") + assert confirm_skill_fit(engine, log, trace, Request("send a simplex message"), skill) is False + assert any(e["kind"] == "intent_guard" and e["fits"] is False for e in trace.read()) + + +def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path): + """A routed skill whose action doesn't match the request must not run: the + guard sends dispatch to create_skill in the same category instead.""" + scheduler = _scheduler( + tmp_path, + choices={"same action": "different"}, + ) + scheduler.tree["simplex"] = [ + Skill(name="next_message", category="simplex", description="Read the next SimpleX message."), + ] + scheduler._create_skill = lambda request, category: DispatchResult( + kind="create_skill", summary="authoring requested", skill="send_message" + ) + request = Request("send a simplex message to pepper") + result = scheduler._dispatch(request) + assert result.kind == "create_skill" + phases = [r["extra"].get("phase") for r in scheduler.log.read()] + assert "navigate:intent" in phases + + +def test_dispatch_intent_match_runs_skill(tmp_path): + scheduler = _scheduler(tmp_path, choices={"same action": "same"}) + + def predict(ctx, request): + return Prediction(text="") + + def act(ctx, request, prediction): + return ActionResult(action_log="read the next message", new_state="read") + + scheduler.tree.pop("response", None) + scheduler.tree["simplex"] = [ + Skill( + name="next_message", + category="simplex", + description="Read the next SimpleX message.", + predict=predict, + act=act, + ), + ] + request = Request("read the next simplex message") + result = scheduler._dispatch(request) + assert result.kind == "ran" + assert result.skill == "next_message" + + + def test_dispatch_create_category_without_engine_is_fatal(tmp_path): """An empty tree short-circuits to CreateCategory; without an engine the category authoring is fatal — the app is marked and the caller stops.""" @@ -1084,3 +1193,29 @@ def test_resolve_repair_unknown_offer_errors(tmp_path): status, detail = scheduler.resolve_repair("missing") assert status == "error" assert "no repair offer" in detail + + +def test_exhausted_reentry_offers_repair(tmp_path): + """A failure whose retry is refused because the reentry budget is spent must + still surface a repair offer. Before, `updated_request` stayed truthy so the + offer was skipped and the failure vanished after the retry ladder.""" + scheduler = _scheduler(tmp_path) + _install_tracking_stub(scheduler) + skill = scheduler.tree["tracking"][0] + skill.predict = lambda ctx, request: Prediction(text="") + skill.act = lambda ctx, request, prediction: ActionResult( + action_log="connection refused", new_state="unchanged" + ) + request = Request("track my package") + request.reentries = scheduler.max_reentries + outcome = RunResult( + skill="tracking.check", + success=False, + summary="failed", + action_log="connection refused", + new_state="unchanged", + updated_request="track my package", + ) + scheduler._finish_run(skill, request, outcome) + assert not any(e["kind"] == "requeued" for e in scheduler.trace.read()) + assert any(e["kind"] == "repair_offered" for e in scheduler.trace.read())