From d0c1dccffde902c020f58026d033da2aaebfcfaf Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Tue, 6 Oct 2026 22:33:38 +0000 Subject: [PATCH] navigation: skip confirms on a confident softmax; per-skill humanize; 500ms VAD MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four latency/ergonomics changes from the voice-gateway diagnosis: 1. Per-skill humanize override. A skill's own recorded config (data/skills///config.json -> {"humanize": bool}) now wins over the per-platform and global defaults, so an already-speakable result (time.now) can skip the rewrite. The gateway resolves the skill ref from the result summary; `_finish_run` now emits `category.name: ok — …` (matching the assessment summary) so the ref is available. Missing store/config/key and test doubles degrade to the existing platform/global behavior. 2. Example voice endpointing: vad.silence_ms 1000 -> 500 (config.example.json). 3. Confident softmax winners skip their confirm guard. New navigation.softmax_bypass_tau (default 0.5): a category winner at/above it skips confirm_category_fit (trace `category_scope_bypassed`); a leaf winner at/above it is handed to dispatch and skips confirm_skill_fit (trace `intent_bypass`). Below the threshold the two-stage confirm is unchanged. Assumption tested first on the decision log: 28/28 category and 28/28 leaf winners >= 0.5 agreed with their guard. 4. Engine-throughput investigation saved to AGENTS.md "Later / open questions" (routing/assessment compute dominates; profile the engine, not the audio). Tests updated for the bypass threshold and added for the skill-level humanize override and bypass paths. Full suite: 486 passed, 1 skipped. --- AGENTS.md | 17 +++++++- config.example.json | 7 +-- semif_agent/gateway/service.py | 51 +++++++++++++++++++--- semif_agent/scheduler.py | 23 +++++++++- semif_agent/skills.py | 27 +++++++++++- tests/test_humanize.py | 69 ++++++++++++++++++++++++++++++ tests/test_skills.py | 78 +++++++++++++++++++++++++++++++--- 7 files changed, 256 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4f60a8e..8ad66c4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -544,6 +544,16 @@ CLI, unit tests (24) + integration tests (2). - Calibration: SemIf ships per-workload temperature scaling; adopt it before treating probabilities as confidence. - Enumerate the intake source taxonomy and per-source gating. +- **Decision-engine latency.** A single SemIf forward pass over a small prompt + can take seconds on CPU, and a trivial request pays several of them + (actionability + category + scope + leaf + intent + assess), so routing and + assessment dominate end-to-end agent latency — not audio I/O (STT/TTS are + sub-second) and not the network. Before treating latency as a front-end + problem, profile the engine: confirm thread utilization, whether the cost is + prefill vs. per-option scoring, and whether a smaller/faster decision model or + a shared-state (`score_shared`) path helps. `decision extra.timing` + (`input_tokens`/`forward_seconds`/`total_seconds`) and the voice latency + breakdown (`scripts/voice-latency.py`) are the measurement hooks. ## Constraints & gotchas (learned the hard way) @@ -1090,7 +1100,12 @@ CLI, unit tests (24) + integration tests (2). slow cleanup cannot hold the gateway poll loop for the authoring budget. Off by default: `gateway.humanize` (`enabled`/`timeout`/`max_tokens`/`max_chars`) sets the global default and a per-platform `gateway..humanize` - bool/`{enabled}` overrides it. Only `kind == "result"` lines are touched + bool/`{enabled}` overrides it. A **skill's own recorded config** + (`data/skills///config.json` -> `{"humanize": bool}`) wins + over both, so a skill whose result is already speakable (e.g. `time.now`) + skips the rewrite while a mechanical one keeps it; the gateway resolves the + skill ref from the summary prefix (`category.name:`). Only `kind == "result"` + lines are touched (questions, repair/approval notices, and status chatter pass through); like `result_only`, an enabled platform unwraps the result detail before cleaning. `_resolve_platforms` skips the reserved `humanize` key. diff --git a/config.example.json b/config.example.json index dff3eed..9cb67de 100644 --- a/config.example.json +++ b/config.example.json @@ -5,10 +5,11 @@ "creation_approval": false, "timezone": "", "navigation": { - "_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. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. 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. All three taus are separate from the top-level tau so tuning reuse-vs-create or actionability does not move run assessment/fidelity. The category 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.", + "_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. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. 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. All three taus are separate from the top-level tau so tuning reuse-vs-create or actionability does not move run assessment/fidelity. The category 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. A softmax winner at or above `softmax_bypass_tau` (default 0.5) skips its confirm guard — the winner is already decisive and each skipped guard is one fewer SemIf call on the hot path (traced `category_scope_bypassed` / `intent_bypass`); below it the two-stage confirm runs unchanged.", "intent_tau": 0.6, "category_tau": 0.75, - "action_tau": 0.5 + "action_tau": 0.5, + "softmax_bypass_tau": 0.5 }, "queue": {"max_size": 100}, "engine": { @@ -220,7 +221,7 @@ "dc_removal": true }, "vad": { - "silence_ms": 1000, + "silence_ms": 500, "min_speech_ms": 120, "max_utterance_s": 30, "aggressiveness": 2, diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index 9dc1f50..ce334ad 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -31,6 +31,13 @@ from .humanize import Humanizer _LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*") +#: A result summary starts with the skill ref (`category.name:`), optionally +#: preceded by a `[resumed]` marker. Used to look up a skill's own config +#: (`data/skills///config.json`) for a per-skill humanize override. +_SKILL_REF = re.compile( + r"^(?:\[resumed\]\s*)?([A-Za-z0-9_][A-Za-z0-9_-]*\.[A-Za-z0-9_][A-Za-z0-9_-]*):\s" +) + #: The scheduler's run summary wraps the real result as #: `": — "`. A result-only platform (the voice #: gateway) speaks just ``. @@ -66,6 +73,12 @@ def _strip_run_id(text: str) -> str: return _LEADING_RUN_ID.sub("", text or "") +def _skill_ref(text: str) -> str | None: + """The `category.name` a result summary belongs to, or None.""" + match = _SKILL_REF.match(text or "") + return match.group(1) if match else None + + def _leading_run_id(text: str) -> str: match = _LEADING_RUN_ID.match(text or "") return match.group(0)[1:-2] if match else "" @@ -202,14 +215,19 @@ class GatewayService: max_chars=int(cfg.get("max_chars", 600)), ) - def _humanize_enabled(self, platform: str) -> bool: - """Whether this platform cleans up its result line. + def _humanize_enabled(self, platform: str, skill_ref: str | None = None) -> bool: + """Whether this result is cleaned up. - A per-platform `humanize` bool (or `{enabled: bool}`) overrides the - global `gateway.humanize.enabled`. Default is off. + Precedence: the **skill's own config** (`data/skills/// + config.json` -> `{"humanize": bool}`) wins; otherwise the per-platform + override (`gateway..humanize`), otherwise the global default + (`gateway.humanize.enabled`). A missing `llm` client disables it. """ if self.humanizer is None: return False + skill_override = self._skill_humanize_override(skill_ref) + if skill_override is not None: + return skill_override override = self._platform_cfg.get(platform, {}).get("humanize") if isinstance(override, bool): return override @@ -217,6 +235,28 @@ class GatewayService: return bool(override["enabled"]) return self._humanize_default + def _skill_humanize_override(self, skill_ref: str | None) -> bool | None: + """The skill's own `humanize` config value, or None when unset. + + A skill opts in/out of result cleanup regardless of the platform default + via its recorded config: `data/skills///config.json` -> + `{"humanize": false}`. Read from the scheduler's skill store; a missing + store/config/key (or an unparseable ref) means no override. + """ + if not skill_ref or "." not in skill_ref: + return None + store = getattr(self.scheduler, "body_store", None) + if store is None: + return None + category, name = skill_ref.split(".", 1) + try: + config = store.read_config(category, name) or {} + except Exception: + return None + if "humanize" in config: + return bool(config["humanize"]) + return None + def _fallback_target(self) -> Target | None: for platform in self.platforms: home = self._home_channel(platform) @@ -438,7 +478,8 @@ class GatewayService: ) -> None: text = _strip_run_id(text) result_only = self._result_only(platform) - humanize = kind == "result" and self._humanize_enabled(platform) + skill_ref = _skill_ref(text) if kind == "result" else None + humanize = kind == "result" and self._humanize_enabled(platform, skill_ref) if result_only: # A spoken front end says the skill's result, not the scheduler's # bookkeeping: drop queue/urgency chatter. diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index bb00398..9992b5a 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -225,6 +225,10 @@ class Scheduler: self.intent_tau = float(nav_cfg.get("intent_tau", 0.6)) self.category_tau = float(nav_cfg.get("category_tau", 0.75)) self.action_tau = float(nav_cfg.get("action_tau", 0.5)) + #: A softmax winner at or above this probability skips its confirm guard + #: (scope/intent) — the winner is already decisive. Below it the guard + #: runs and can reject into create. + self.bypass_tau = float(nav_cfg.get("softmax_bypass_tau", 0.5)) self.max_reentries = max_reentries self.codegen = codegen self.degeneration_check_factory = degeneration_check_factory @@ -416,6 +420,10 @@ class Scheduler: # ---- dispatch ---- def _dispatch(self, request: Request) -> DispatchResult: + # Clear any confidence a prior dispatch left on the request (meta is + # copied across a requeue); navigation sets it fresh when a leaf softmax + # runs. + request.meta.pop("leaf_softmax_prob", None) # Explicit housekeeping commands are deterministic: they route straight # to the meta skill, bypassing the generic guards (which misread a # task-like skill name as the task). Natural-language phrasings still go @@ -443,6 +451,7 @@ class Scheduler: self.tree, category_tau=self.category_tau, action_tau=self.action_tau, + bypass_tau=self.bypass_tau, ) if isinstance(navigation, CreateCategory): return self._dispatch_create_category(request) @@ -456,6 +465,17 @@ class Scheduler: # navigation's pick directly (the meta skill asks for any missing # target as an input variable). return self._run_skill(navigation, request) + leaf_prob = request.meta.pop("leaf_softmax_prob", None) + if leaf_prob is not None and leaf_prob >= self.bypass_tau: + # A decisive leaf softmax winner skips the intent confirm. + self.trace.append( + "intent_bypass", + request.id, + category=navigation.category, + skill=navigation.name, + prob=leaf_prob, + ) + return self._run_skill(navigation, request) if not confirm_skill_fit( self.engine, self.log, self.trace, request, navigation, self.intent_tau ): @@ -653,7 +673,8 @@ class Scheduler: return DispatchResult( kind="ran", summary=( - f"{skill.name}: {'ok' if outcome.success else 'failed'} — " + f"{skill.category}.{skill.name}: " + f"{'ok' if outcome.success else 'failed'} — " f"{outcome.action_log or outcome.summary}" ), skill=skill.name, diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 7e314ca..0a82f34 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -1167,9 +1167,22 @@ def navigate( tree: dict[str, list[Skill]], category_tau: float = 0.75, action_tau: float = 0.5, + bypass_tau: float = 0.5, ) -> Skill | CreateCategory | CreateSkill: """Descend the tree one SemIf choice per level. Every choice is logged. + **Confident softmax winners skip their confirm guard.** When the category + softmax winner's probability is >= `bypass_tau` (default 0.5) the scope + confirm (`confirm_category_fit`) is skipped — the winner is taken as-is + (traced `category_scope_bypassed`); below it the guard runs and can reject + the winner into create. The leaf softmax winner's probability is handed to + dispatch (`request.meta["leaf_softmax_prob"]`) so `confirm_skill_fit` is + likewise skipped above the threshold (traced `intent_bypass`). The guards + exist to catch an unsure softmax; a winner at 0.5+ is already decisive, and + each skipped guard is one fewer SemIf call on the hot path. Below the + threshold the two-stage behavior is unchanged. The recorded data agrees: + every logged winner >= 0.5 also passed its guard. + The **actionability guard** (`confirm_non_action`, phase `navigate:actionability`, keyed by `navigation.action_tau`) runs at the **top** of navigation, before any category is considered: the closed `response` tree @@ -1258,7 +1271,16 @@ def navigate( log.append(top, top_result, extra={"phase": "navigate:category", "run_id": request.id}) category = top_result.selected if category != "create_category": - if not confirm_category_fit( + winner_prob = float(top_result.probs.get(category, 0.0)) + if winner_prob >= bypass_tau: + # Confident winner: skip the scope confirm (one fewer SemIf call). + trace.append( + "category_scope_bypassed", + request.id, + category=category, + prob=winner_prob, + ) + elif not confirm_category_fit( engine, log, trace, request, category, descriptions.get(category, ""), category_tau, ): @@ -1311,6 +1333,9 @@ def navigate( leaf_result = engine.call(leaf) log.append(leaf, leaf_result, extra={"phase": "navigate:leaf", "run_id": request.id}) pick = leaf_result.selected + # Hand the winner's confidence to dispatch so it can skip the intent guard + # when the softmax is already decisive (see `navigate` docstring). + request.meta["leaf_softmax_prob"] = float(leaf_result.probs.get(pick, 0.0)) return next((s for s in skills if s.name == pick), skills[0]) diff --git a/tests/test_humanize.py b/tests/test_humanize.py index b3564b6..84005af 100644 --- a/tests/test_humanize.py +++ b/tests/test_humanize.py @@ -142,3 +142,72 @@ def test_gateway_humanize_keeps_wrapper_when_result_only_off(): service = build_service(llm, {"humanize": {"enabled": True}, "simplex": {}}) service._reply("simplex", "c", "track.manual: ok — sent", kind="result") assert service.outbound["simplex"].get_nowait().text == "Done." + + +# ---- per-skill override (the skill's own config.json) ---- + +class FakeStore: + """Stands in for the scheduler's `body_store` (SkillStore).""" + + def __init__(self, configs): + self.configs = configs # {(category, name): {...}} + + def read_config(self, category, name): + return self.configs.get((category, name), {}) + + +class FakeSchedulerWithStore(FakeScheduler): + def __init__(self, llm, store): + super().__init__(llm) + self.body_store = store + + +def build_service_with_store(llm, config, store): + return GatewayService( + FakeSchedulerWithStore(llm, store), FakeAdapter(), config=config + ) + + +def test_gateway_skill_config_disables_humanize(): + """A skill whose own config sets humanize:false is not cleaned up, even + when the platform/global default is on.""" + llm = FakeClient(reply="should not be used") + store = FakeStore({("time", "now"): {"humanize": False}}) + service = build_service_with_store( + llm, {"humanize": {"enabled": True}, "simplex": {}}, store + ) + service._reply("simplex", "c", "time.now: ok — 12:00", kind="result") + assert service.outbound["simplex"].get_nowait().text == "time.now: ok — 12:00" + assert llm.calls == [] + + +def test_gateway_skill_config_enables_humanize_over_platform(): + """A skill's own humanize:true wins over a disabled platform/global default.""" + llm = FakeClient(reply="It is 12:00.") + store = FakeStore({("time", "now"): {"humanize": True}}) + service = build_service_with_store( + llm, + {"humanize": {"enabled": False}, "simplex": {"humanize": False}}, + store, + ) + service._reply("simplex", "c", "time.now: ok — 12:00", kind="result") + assert service.outbound["simplex"].get_nowait().text == "It is 12:00." + + +def test_gateway_skill_config_absent_falls_back_to_platform(): + """No skill override -> the platform/global default applies.""" + llm = FakeClient(reply="It is 12:00.") + store = FakeStore({}) + service = build_service_with_store( + llm, {"humanize": {"enabled": True}, "simplex": {}}, store + ) + service._reply("simplex", "c", "time.now: ok — 12:00", kind="result") + assert service.outbound["simplex"].get_nowait().text == "It is 12:00." + + +def test_skill_ref_parses_summary_and_resumed_marker(): + from semif_agent.gateway.service import _skill_ref + + assert _skill_ref("time.now: ok — 12:00") == "time.now" + assert _skill_ref("[resumed] track.manual: ok — sent") == "track.manual" + assert _skill_ref("queued") is None diff --git a/tests/test_skills.py b/tests/test_skills.py index d80cebb..977d2b1 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -768,13 +768,14 @@ def test_navigate_category_options_carry_descriptions(tmp_path): 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.""" + scope the guard rejects authors a new category. The winner is below + `softmax_bypass_tau`, so the guard actually runs.""" 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}, + "top-level category": {"simplex": 0.45}, "Does the scope": {"none": 1.0}, } ) @@ -785,12 +786,12 @@ def test_navigate_category_rejected_scope_authors_category(tmp_path): def test_navigate_category_confirmed_scope_descends(tmp_path): - """A softmax winner the guard confirms is descended into (no create).""" + """A below-threshold softmax winner the guard confirms is descended into.""" log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) engine = _ProbEngine( { - "top-level category": {"simplex": 1.0}, + "top-level category": {"simplex": 0.45}, "Does the scope": {"covers": 1.0}, "skill performs": {"next_message": 1.0, "connect_link": 0.0}, } @@ -801,6 +802,26 @@ def test_navigate_category_confirmed_scope_descends(tmp_path): assert any(e["kind"] == "category_scope" and e["fits"] for e in trace.read()) +def test_navigate_confident_category_winner_skips_scope_confirm(tmp_path): + """A category softmax winner at/above `softmax_bypass_tau` is decisive: the + scope confirm is not called (no `navigate:category_scope` decision).""" + log = DecisionLog(str(tmp_path / "decisions.jsonl")) + trace = TraceLog(str(tmp_path / "runs.jsonl")) + engine = _ProbEngine( + { + "top-level category": {"simplex": 0.9}, + "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 any(e["kind"] == "category_scope_bypassed" for e in trace.read()) + assert not any(e["kind"] == "category_scope" for e in trace.read()) + assert all("Does the scope" not in c.question for c in engine.calls) + phases = [r["extra"].get("phase") for r in log.read()] + assert "navigate:category_scope" not in phases + + def test_confirm_category_fit_threshold(tmp_path): log = DecisionLog(str(tmp_path / "decisions.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl")) @@ -994,7 +1015,8 @@ def test_dispatch_intent_tau_controls_reuse_vs_create(tmp_path): { "top-level category": {"simplex": 1.0}, "Does the scope": {"covers": 1.0}, - "skill performs": {"next_message": 1.0, "connect_link": 0.0}, + # Below softmax_bypass_tau (0.5), so the intent guard runs. + "skill performs": {"next_message": 0.45, "connect_link": 0.3}, "same action": {"same": 0.8, "different": 0.2}, } ) @@ -1105,6 +1127,52 @@ def test_dispatch_intent_match_runs_skill(tmp_path): assert result.skill == "next_message" +def test_dispatch_confident_leaf_winner_skips_intent_guard(tmp_path): + """A leaf softmax winner at/above `softmax_bypass_tau` skips the intent + confirm: the guard would reject here (same action = different), but a + decisive softmax runs the skill instead.""" + engine = _ProbEngine( + { + "top-level category": {"simplex": 1.0}, + "skill performs": {"next_message": 0.9, "connect_link": 0.1}, + "same action": {"different": 1.0}, + } + ) + scheduler = Scheduler( + engine=engine, + llm=LLMClient(base_url="http://localhost:1/v1", model="test"), + log=DecisionLog(str(tmp_path / "decisions.jsonl")), + config={ + "skills": {}, + "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."), + ] + } + result = scheduler._dispatch(Request("read the next simplex message")) + assert result.kind == "ran" + assert result.skill == "next_message" + assert any(e["kind"] == "intent_bypass" for e in scheduler.trace.read()) + phases = [r["extra"].get("phase") for r in scheduler.log.read()] + assert "navigate:intent" not in phases + + def test_dispatch_create_category_queues_draft_and_is_not_fatal(tmp_path): """An empty tree short-circuits to CreateCategory; the `llm` draft is