From b15a9e1b45e5fb0da51426692b26697fd51e7514 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Mon, 12 Oct 2026 08:14:42 +0000 Subject: [PATCH] gateway: answer spoken approvals, route off-gate results New-skill authoring via the voice gateway never completed: STT emits "Approve." / "Yes." / "retry." with sentence punctuation, but the approval/repair maps were matched with an exact lookup, so a spoken answer fell through to submit_request while the pending approval timed out and nothing was registered. - gateway/service: normalize the reply before the action lookup (`_normalize_action`: lowercase, strip edge punctuation, first-word fallback) and broaden the approval/repair vocabularies, so a spoken "Approve." / "Yes." / "retry." matches like a typed one. - scheduler: buffer the replies of a background drain (the codegen worker's post-authoring re-run, a repair retry) in an outbox instead of returning them into a thread that discards them; a front end's `drain_outbox()` routes them, so the answer to the user's own request is no longer swallowed. - cli/dashboard: drain the outbox alongside the queue. - tests: normalization + spoken approval/repair routing, outbox routing, and the async requeue assertion. --- AGENTS.md | 18 +++-- semif_agent/cli.py | 8 ++- semif_agent/dashboard.py | 2 +- semif_agent/gateway/service.py | 96 ++++++++++++++++++++++----- semif_agent/scheduler.py | 45 ++++++++++++- tests/test_gateway.py | 117 +++++++++++++++++++++++++++++++++ tests/test_skills.py | 12 +++- 7 files changed, 269 insertions(+), 29 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 40d7b79..07d66c4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1010,7 +1010,10 @@ CLI, unit tests (24) + integration tests (2). `codegen.test_max_attempts`. On success the body is materialized (`materialize_skill`), hot-merged, the leaf's `writing` flag clears, and the **original request is re-queued** and - re-runs navigation onto the new leaf (`skill_requeued`). On + re-runs navigation onto the new leaf (`skill_requeued`). The worker drains it + with `run_queue_buffered`, so the re-run's reply lands in the scheduler's + outbox and a front end (`drain_outbox`) routes it to the chat — the worker + must not swallow the answer to the user's own request. On failure (`CodegenError`/`ValueError`) the user is notified, the leaf stays a restartable stub, and the request is NOT re-dispatched. A re-dispatched request whose skill is still unwritten reports the pending write instead of @@ -1302,12 +1305,19 @@ CLI, unit tests (24) + integration tests (2). so a resume/repair failure never propagates into a front end. A *different* chat — **including a chat on another platform** — during that pause is told to wait: the single-slot scheduler must not silently abandon the first chat's run, and one service fronts all - adapters so the guard spans them. A background poll calls - `Scheduler.run_queue()` (routing each `[run_id] summary` to its owner) and + adapters so the guard spans them. A background poll drains + `Scheduler.drain_outbox()` (replies a background path buffered — the codegen + worker's post-authoring re-run, a repair retry — so an off-gate completion + still reaches its chat) then `Scheduler.run_queue()` (routing each + `[run_id] summary` to its owner) and surfaces newly posted authoring questions / repair offers (`defer_questions = True`; the service routes them by `run_id` → `(platform, chat)`, falling back to that platform's `home_channel`); a chat's plain reply answers the - question or picks the repair action (`retry`/`repair`/`ask`/`no`). + question or picks the repair action (`retry`/`repair`/`ask`/`no`). The + approval/repair vocabulary is matched **case- and punctuation-insensitively** + (`_normalize_action`), with a first-word fallback: speech-to-text emits + "Approve." / "Yes." / "retry.", and an exact lookup silently dropped those + into `submit_request`, so the approval timed out and nothing was created. - **Optional result cleanup** (`gateway/humanize.py`): a gateway-only presentation layer that rewrites a completed skill's result line from the scheduler's deterministic `: — ` into one diff --git a/semif_agent/cli.py b/semif_agent/cli.py index 337ee60..ca06f9b 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -502,9 +502,13 @@ def _print_reply(reply, show_run_id: bool = False, verbosity: str = "result") -> def _drain_queue(scheduler: Scheduler) -> None: - """Run queued work, printing each outcome with its run id.""" + """Run queued work, printing each outcome with its run id. + + Routes any replies a background drain buffered (a post-authoring re-run, a + repair retry) before the queued work, so an off-gate completion still prints. + """ verbosity = getattr(scheduler, "verbosity", "result") - for reply in scheduler.run_queue(): + for reply in [*scheduler.drain_outbox(), *scheduler.run_queue()]: _print_reply(reply, show_run_id=True, verbosity=verbosity) diff --git a/semif_agent/dashboard.py b/semif_agent/dashboard.py index 1729d62..c4f65a7 100644 --- a/semif_agent/dashboard.py +++ b/semif_agent/dashboard.py @@ -389,7 +389,7 @@ class DashboardHandler(BaseHTTPRequestHandler): def _drain_chain(self) -> list: """Run queued chain steps, bounded like `GatewayService.drain`.""" - replies = [] + replies = list(self.scheduler.drain_outbox()) for _ in range(100): batch = self.scheduler.run_queue() if not batch: diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index e2f87e5..8d9ea69 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -37,28 +37,72 @@ _RESULT_SEP = " — " _REPAIR_ACTIONS = { "retry": "retry", "repair": "repair_skill", + "fix": "repair_skill", "repair_skill": "repair_skill", "ask": "ask_user", "ask_user": "ask_user", "no": "no_repair", "skip": "no_repair", + "cancel": "no_repair", "no_repair": "no_repair", } _APPROVAL_ACTIONS = { "yes": True, "y": True, + "yeah": True, + "yep": True, + "yup": True, "approve": True, + "approved": True, "ok": True, + "okay": True, + "sure": True, + "confirm": True, + "affirmative": True, + "go ahead": True, + "do it": True, "no": False, "n": False, + "nope": False, "deny": False, + "denied": False, + "cancel": False, "skip": False, + "never mind": False, + "nevermind": False, + "dont": False, + "don't": False, + "stop": False, } #: An owner target is `(platform, chat_id)`. Target = tuple[str, str] +#: Characters stripped from the edges of a spoken reply before matching an +#: action. STT emits sentence punctuation the fixed vocabulary does not carry +#: ("Approve.", "Yes."), so a bare `in _APPROVAL_ACTIONS` lookup silently misses. +_ACTION_PUNCT = " \t\r\n.,!?;:\"'()[]{}" + + +def _normalize_action(text: str) -> str: + """Normalize a spoken reply into a command-vocabulary key. + + Speech-to-text appends sentence punctuation ("Approve.", "Yes.") that the + fixed `_REPAIR_ACTIONS` / `_APPROVAL_ACTIONS` maps do not carry, so an exact + lookup drops a perfectly clear answer into `submit_request` and the pending + approval times out. Lowercase, strip edge whitespace/punctuation, then fall + back to the first word so "yes please" / "approve it" match. Returns "" for + empty input. This stays a deterministic command vocabulary — no model. + """ + cleaned = (text or "").strip().lower().strip(_ACTION_PUNCT) + if not cleaned: + return "" + if cleaned in _REPAIR_ACTIONS or cleaned in _APPROVAL_ACTIONS: + return cleaned + first = cleaned.split(None, 1)[0] + return first.strip(_ACTION_PUNCT) + def _result_detail(text: str) -> str: """Unwrap the scheduler's `": — "` summary. @@ -304,6 +348,10 @@ class GatewayService: platform = self.platforms[0] if self.platforms else "" with self._route_lock: reply_to: Target = (platform, msg.chat_id) + #: A single command-vocabulary key for this reply (punctuation- and + #: case-insensitive), so a spoken "Approve." / "Yes." matches the + #: approval and repair maps exactly like a typed "yes". + action = _normalize_action(msg.text) pending = self.scheduler.pending if pending is not None and self._pending_owner is None: self._pending_owner = self._owner_from_source(pending.request.source) @@ -329,15 +377,16 @@ class GatewayService: status, detail = self.scheduler.answer_question(question_id, msg.text) self._surfaced.add(question_id) self._reply(*reply_to, detail, kind="notice") - elif reply_to in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS: + elif reply_to in self._repair_for_chat and action in _REPAIR_ACTIONS: offer_id = self._repair_for_chat.pop(reply_to) - action = _REPAIR_ACTIONS[msg.text.strip().lower()] - status, detail = self.scheduler.resolve_repair(offer_id, action) + status, detail = self.scheduler.resolve_repair( + offer_id, _REPAIR_ACTIONS[action] + ) self._surfaced.add(offer_id) self._reply(*reply_to, detail, kind="notice") - elif reply_to in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS: + elif reply_to in self._approval_for_chat and action in _APPROVAL_ACTIONS: approval_id = self._approval_for_chat.pop(reply_to) - approved = _APPROVAL_ACTIONS[msg.text.strip().lower()] + approved = _APPROVAL_ACTIONS[action] status, detail = self.scheduler.answer_approval(approval_id, approved) self._surfaced.add(approval_id) self._reply(*reply_to, detail, kind="notice") @@ -358,23 +407,34 @@ class GatewayService: self.surface(origin=reply_to) def drain(self) -> None: - """Run queued work and route each outcome back to its owner.""" + """Run queued work and route each outcome back to its owner. + + A background drain (the codegen worker's post-authoring re-run, a repair + retry) buffers its replies in the scheduler outbox; route those first so + an off-gate completion still reaches the chat, then drain the queue. + """ + drain_outbox = getattr(self.scheduler, "drain_outbox", None) + if callable(drain_outbox): + self._route(drain_outbox()) for _ in range(100): results = self.scheduler.run_queue() if not results: break - for reply in results: - if self._hidden(reply): - continue - owner = self._owner_of(reply.run_id) - if reply.status == "needs_input" and owner: - self._pending_owner = owner - target = owner or self._fallback_target() - if target: - self._reply( - *target, reply.text, kind=_reply_kind(reply.status), - skill_ref=reply.skill_ref, result=reply.result, - ) + self._route(results) + + def _route(self, results) -> None: + for reply in results: + if self._hidden(reply): + continue + owner = self._owner_of(reply.run_id) + if reply.status == "needs_input" and owner: + self._pending_owner = owner + target = owner or self._fallback_target() + if target: + self._reply( + *target, reply.text, kind=_reply_kind(reply.status), + skill_ref=reply.skill_ref, result=reply.result, + ) def _hidden(self, reply) -> bool: """Hide an intermediate chain step at `result` verbosity. diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 9e4d4ee..89c98b5 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -358,6 +358,12 @@ class Scheduler: approval_cfg = codegen_cfg.get("approval", {}) or {} self.approval_wait = float(approval_cfg.get("wait_timeout", 900.0)) self.defer_questions = False + #: Replies produced by a *background* drain (the codegen worker's + #: post-authoring re-run, a repair retry) whose caller has no front end to + #: hand them to. A front end's `drain_outbox()` picks them up, so a + #: re-run that completes off the gate still reaches the chat instead of + #: being swallowed. Bounded like the request queue. + self._outbox: deque[SchedulerReply] = deque(maxlen=256) #: Global new-skill creation mode: "allow" (default), "deny", or "ask". #: A category may override it in its category config. self.new_skill_mode = ( @@ -614,10 +620,42 @@ class Scheduler: Safe to call from any thread: guarded by the scheduler lock (RLock, so the async codegen worker can drain the queue from its completion path). + A *front end* calls this and routes the returned replies; a background + caller must use `run_queue_buffered` so its replies are not swallowed. """ with self._lock: return self._run_queue_locked() + def run_queue_buffered(self) -> None: + """Drain the queue from a background path that has no front end. + + Used by the codegen worker (post-authoring re-run) and the repair-retry + path. The replies are buffered, not returned, so a front end's + `drain_outbox()` can route them; returning them here would let a + background thread consume a reply that then never reaches the chat + (the voice gateway's "authoring... will re-run when it is ready" that + was never followed by the answer). + """ + # Hold the lock across the drain and the buffer so a reply is never in + # neither place at once (a front-end drain sees it either in run_queue's + # return or in the outbox). + with self._lock: + replies = self._run_queue_locked() + if replies: + self._outbox.extend(replies) + + def drain_outbox(self) -> list[SchedulerReply]: + """Replies a background drain buffered for the front end, oldest first. + + A front end calls this before `run_queue()` so an off-gate completion + (a re-run after a skill body lands, a repair retry) is routed to its + chat. Consuming clears the buffer. + """ + with self._lock: + replies = list(self._outbox) + self._outbox.clear() + return replies + def _run_queue_locked(self) -> list[SchedulerReply]: results = [] while self.current is None and len(self.queue) > 0: @@ -1293,7 +1331,7 @@ class Scheduler: with self._lock: offer.status = "done" self.trace.append("repair_retry", offer.run_id, skill=offer.skill) - self.run_queue() + self.run_queue_buffered() return "running", f"retrying {offer.category}.{offer.skill}" if chosen == "no_repair": self.trace.append("repair_declined", offer.run_id, skill=offer.skill) @@ -2105,7 +2143,10 @@ class Scheduler: f"[codegen] body ready for {job.category}.{job.draft.name}; " "original request re-queued." ) - self.run_queue() + # The re-run completes off the gate; buffer its reply so a front end + # (the voice gateway's poll loop, the REPL) routes it to the chat + # instead of the worker swallowing it. + self.run_queue_buffered() def _discard_cancelled_write(self, job: SkillWrite) -> None: """Clean up a write that was cancelled mid-flight. diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 06e1089..0533673 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -345,6 +345,123 @@ def test_service_surfaces_and_resolves_approval(tmp_path): assert any("approved" in text for text in drain_outbound(service)) +# ---- service: spoken action vocabulary (punctuation, phrases) ---- + +def test_normalize_action_strips_punctuation_and_phrases(): + from semif_agent.gateway.service import _normalize_action + + assert _normalize_action("Approve.") == "approve" + assert _normalize_action("Yes.") == "yes" + assert _normalize_action(" no! ") == "no" + assert _normalize_action("yes please") == "yes" + assert _normalize_action("approve it") == "approve" + assert _normalize_action("Retry.") == "retry" + assert _normalize_action("never mind") == "never mind" + assert _normalize_action("") == "" + assert _normalize_action("what is 255 times 12?") == "what" + + +def test_service_approval_accepts_spoken_punctuation(tmp_path): + # STT emits "Approve." / "Yes." with a trailing period; the exact-map lookup + # used to miss it and fall through to submit_request, so the approval timed + # out and nothing was ever created (the voice authoring failure). + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + scheduler.approvals.append( + PendingApproval( + id="a1", + run_id="r1", + kind="skill", + category="tracking", + skill="track_live", + description="Follow a package.", + ) + ) + service._owners["r1"] = ("simplex", "4") + service.surface() + drain_outbound(service) + + service.handle_inbound(InboundMessage(text="Approve.", chat_id="4", contact_id="4")) + assert scheduler.pending_approvals() == [] + assert any("approved" in text for text in drain_outbound(service)) + assert not any( + e["kind"] == "submit" and e.get("text") == "Approve." + for e in scheduler.trace.read() + ), "a spoken approval must not be dispatched as a new request" + + +def test_service_approval_accepts_spoken_no(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + scheduler.approvals.append( + PendingApproval( + id="a1", + run_id="r1", + kind="category", + category="text_analysis", + skill="", + description="Analyze text.", + ) + ) + service._owners["r1"] = ("simplex", "4") + service.surface() + drain_outbound(service) + + service.handle_inbound(InboundMessage(text="No thanks.", chat_id="4", contact_id="4")) + assert scheduler.pending_approvals() == [] + assert any("denied" in text for text in drain_outbound(service)) + + +def test_service_repair_accepts_spoken_punctuation(tmp_path): + from semif_agent.scheduler import RepairOffer + + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + scheduler.repairs.append( + RepairOffer( + id="r1", + run_id="run1", + category="tracking", + skill="track_live", + selected="retry", + reason="failed", + request_text="track it", + failure="boom", + ) + ) + service._owners["run1"] = ("simplex", "4") + service.surface() + drain_outbound(service) + + service.handle_inbound(InboundMessage(text="retry.", chat_id="4", contact_id="4")) + offer = next(r for r in scheduler.repairs if r.id == "r1") + assert offer.status == "done" + assert not any( + e["kind"] == "submit" and e.get("text") == "retry." + for e in scheduler.trace.read() + ), "a spoken repair action must not be dispatched as a new request" + + +# ---- service: background-drain outbox routing ---- + +def test_service_drain_routes_background_outbox(tmp_path): + # A background drain (the codegen worker's post-authoring re-run, a repair + # retry) buffers its reply; the front end's drain must still route it. + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + request = Request("queued work", source="simplex:4") + scheduler.queue.push(request) + service._owners[request.id] = ("simplex", "4") + + scheduler.run_queue_buffered() # the off-gate completion + assert len(scheduler._outbox) == 1 + + service.drain() + assert drain_outbound(service), "the buffered background reply must reach the owner" + assert list(scheduler._outbox) == [] + + + # ---- service: result-only front end (voice) ---- class FakeResultOnlyAdapter: diff --git a/tests/test_skills.py b/tests/test_skills.py index 9d40ca4..4362386 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -1700,12 +1700,20 @@ def test_async_skill_write_materializes_merges_and_requeues(tmp_path): assert not upgraded.is_noop() assert callable(upgraded.act) - # The worker drains the queue when idle (run_queue), so an empty queue - # is a valid end state; the requeue trace proves the push happened. + # The worker drains the queue when idle (run_queue_buffered), so an empty + # queue is a valid end state; the requeue trace proves the push happened. events = [e["kind"] for e in scheduler.trace.read()] assert "skill_requeued" in events assert "skill_testing" in events assert "skill_ready" in events + # The off-gate re-run's reply is buffered for a front end, not swallowed: + # the worker must not consume the answer to the user's own request. + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and not scheduler._outbox: + time.sleep(0.02) + buffered = scheduler.drain_outbox() + assert buffered, "the post-authoring re-run must be routable by a front end" + assert buffered[0].run_id == request.id # The full deliverable set landed in the skill folder. directory = scheduler.body_store.dir("tracking", "track_live") assert sorted(p.name for p in directory.iterdir() if not p.name.startswith("__")) == [