Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(harness): echo background task prompts to IM (#1172)
Qi Qif28a1bce0596
diff --git a/config/v2_compat.py b/config/v2_compat.pyindex fc7a3720e..6da44a570 100644--- a/config/v2_compat.py+++ b/config/v2_compat.py@@ -81,6 +81,9 @@ class AppCompatConfig:reply_enhancements: bool = Truedefault_backend: str = DEFAULT_AGENT_BACKENDresource_governance: dict = field(default_factory=lambda: {"mode": "auto"})+ # Mirrors ``V2Config.runtime.harness_prompt_echo``; read on the IM turn path, so+ # it has to reach the controller's runtime config like ``resource_governance``.+ harness_prompt_echo: bool = Truedef enabled_platforms(self) -> list[str]:enabled = self.platforms.get("enabled") if isinstance(self.platforms, dict) else None@@ -157,4 +160,5 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:include_user_info=v2.include_user_info,reply_enhancements=v2.reply_enhancements,resource_governance=v2.runtime.resource_governance,+ harness_prompt_echo=v2.runtime.harness_prompt_echo,)diff --git a/config/v2_config.py b/config/v2_config.pyindex ea4c65777..8919708da 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -283,6 +283,13 @@ class RuntimeConfig:harness_run_orphan_grace_seconds: int = DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDSharness_run_queued_ttl_seconds: int = DEFAULT_HARNESS_RUN_QUEUED_TTL_SECONDSharness_run_hold_ttl_seconds: int = DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS+ # Echo the Harness-originated prompt into the IM conversation when a background+ # task (scheduled task, watch, webhook, hook, ``vibe agent run``) starts an agent+ # turn there. The Workbench transcript already renders that prompt from the+ # ``harness`` Message row; an IM channel had no equivalent, so a scheduled reply+ # arrived as an answer to a question nobody in the channel could see. Off means+ # today's behavior (result only).+ harness_prompt_echo: bool = True@dataclass@@ -1350,6 +1357,7 @@ class V2Config:"harness_run_orphan_grace_seconds": self.runtime.harness_run_orphan_grace_seconds,"harness_run_queued_ttl_seconds": self.runtime.harness_run_queued_ttl_seconds,"harness_run_hold_ttl_seconds": self.runtime.harness_run_hold_ttl_seconds,+ "harness_prompt_echo": self.runtime.harness_prompt_echo,},"agents": {"opencode": self.agents.opencode.__dict__,diff --git a/core/controller.py b/core/controller.pyindex 99a0ff84d..081d8b905 100644--- a/core/controller.py+++ b/core/controller.py@@ -649,6 +649,7 @@ class Controller:self.config.agent_status_heartbeat_ms = v2_config.agent_status_heartbeat_msself.config.agent_status_no_output_ms = v2_config.agent_status_no_output_msself.config.resource_governance = v2_config.runtime.resource_governance+ self.config.harness_prompt_echo = v2_config.runtime.harness_prompt_echogovernor = getattr(self, "_agent_resource_governor", None)if governor is not None:governor.update_config(self.config.resource_governance)diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 3427ce874..4bb401c45 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -12,7 +12,11 @@ from core.audio_asr import (detect_audio_mime_from_sample,format_audio_transcript_echo,)-from core.message_output import terminal_output_for, terminal_turn_output+from core.message_output import (+ HARNESS_PROMPT_ECHO_SPEC_KEY,+ terminal_output_for,+ terminal_turn_output,+)from core.message_context import resolve_context_thread_idfrom core.native_dispatch_phase import (DISPATCH_PHASE_PREWRITE,@@ -634,6 +638,21 @@ class MessageHandler(BaseHandler):# removed here immediately, leaving no processing indicator# for the entire duration of the subagent run.+ # A background task's prompt is only visible in the Workbench transcript+ # (the ``harness`` Message row); stage it so the IM conversation gets the+ # question the following reply answers. Staged here because this point is+ # past every ``suppress_delivery`` resolution (the ``agent_run_target`` and+ # thread-anchor branches settle it only after ``get_session_info``) and+ # covers the durable Delivery path too, which skips the mirror branch+ # above; the send itself happens at the real turn start, once the runtime+ # gate is held (see ``_stage_harness_prompt_echo``).+ # ``control_message`` rather than ``message``: subagent routing above+ # strips a matched ``name:`` prefix off ``message``, and the echo must show+ # the prompt as it was stored (which is what the Workbench row shows too),+ # including the prefix that names the requested subagent.+ if source != self.TURN_SOURCE_HUMAN:+ self._stage_harness_prompt_echo(context, control_message)+user_message = self._get_user_message(context, message)audio_transcripts = await self._transcribe_audio_attachments(context, processed_files or [])if audio_transcripts:@@ -1079,6 +1098,25 @@ class MessageHandler(BaseHandler):except Exception as err:logger.debug("Failed to echo audio transcript: %s", err, exc_info=True)+ def _stage_harness_prompt_echo(self, context: MessageContext, message: str) -> None:+ """Stage the Harness prompt for the outward echo at turn start.++ Staged instead of sent here: ``AgentService.handle_message`` blocks on the+ runtime turn gate before this turn really starts, so posting now would+ announce a queued task's prompt while another turn is still working — and+ would leave that prompt behind if the queued turn is cancelled.+ ``AgentService._begin_turn_status`` emits it once the gate is held, right+ before the status bubble, so the channel still reads trigger -> work ->+ result. The dispatcher still owns every gate (platform,+ ``suppress_delivery``, trigger kind, the ``runtime.harness_prompt_echo``+ switch) and the delivery target.+ """+ if not (message or "").strip():+ return+ spec = dict(context.platform_specific or {})+ spec[HARNESS_PROMPT_ECHO_SPEC_KEY] = message+ context.platform_specific = spec+@staticmethoddef _sanitize_identity(value: str) -> str:"""Strip control chars and delimiters that could break the [name<id>] format."""diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex e98b56518..24610f861 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport asyncioimport hashlibimport logging+import reimport timefrom dataclasses import replacefrom datetime import datetime, timezone@@ -45,6 +46,70 @@ from vibe.i18n import t as i18n_tlogger = logging.getLogger(__name__)+# Harness prompt echo (``emit_harness_prompt``). The echo is context for the reply+# that follows, not the payload, so a long generated prompt is cut rather than split+# across messages the way a result is.+HARNESS_PROMPT_ECHO_MAX_CHARS = 800+# Bounded per-process memory of already-echoed Harness deliveries, so an in-process+# re-dispatch of one delivery cannot read as the task having fired twice.+HARNESS_PROMPT_ECHO_MEMORY = 256+# Harness kinds whose prompt is a user-authored instruction worth showing. Excludes+# ``activity_recovery``: that turn is a runtime re-injection describing a resumed+# Activity, so echoing it would explain internals nobody asked about.+HARNESS_PROMPT_ECHO_TRIGGER_KINDS = HARNESS_TRIGGER_KINDS - {"activity_recovery"}+# The subset whose dispatch text is COMPOSED by Avibe instead of written by a person:+# a watch appends the waiter's raw stdout, an ``--on-failure agent`` escalation (a+# ``hook`` run) appends the generated failure report, and a webhook appends its+# payload. That text exists for the AGENT to read, so echoing it verbatim would+# publish raw command output — tokens, stack traces, customer data — into a shared+# conversation before the agent can summarize or redact it (Codex P1). For these+# kinds the echo shows ONLY the definition's stored instruction+# (``harness_display_prompt``) and stays silent when none can be resolved; the+# Workbench transcript still renders the full prompt for the operator.+HARNESS_PROMPT_ECHO_INSTRUCTION_ONLY_KINDS = frozenset({"watch", "webhook", "hook"})+# Mention neutralizers for the echoed prompt. The echo repeats text an operator wrote+# for an agent, into a channel: quoting it does not stop a renderer from resolving a+# broadcast, a username, or an id mention, and the Discord adapter sends without+# ``allowed_mentions``, so an echoed ``@everyone`` would really ping the channel+# (Codex P2). A zero-width space after the sigil keeps the text readable while+# leaving nothing for any renderer to resolve. Deliberately platform-agnostic: every+# adapter renders the same body, so ``@`` before a word character covers the+# Slack/Discord broadcasts AND a bare Telegram ``@username`` (which+# ``TelegramFormatter.render`` HTML-escapes without defusing), and a new adapter+# inherits the guard instead of needing its own.+_HARNESS_ECHO_MENTION_SIGIL_PATTERN = re.compile(r"@(?=\w)")+_HARNESS_ECHO_ID_MENTION_PATTERN = re.compile(r"<(?=[@!#&])")+_HARNESS_ECHO_MENTION_BREAK = "\u200b"+# Cap for the definition name in the echo label. The prompt has its own cap, but the+# label is appended after it and task/watch names are never length-validated at+# creation, so an unbounded name could push the body past Discord's 2,000-char or+# Telegram's 4,096-char limit \u2014 the adapter would then reject the echo and the channel+# would see no prompt at all (Codex P2).+HARNESS_PROMPT_ECHO_MAX_NAME_CHARS = 80+_HARNESS_PROMPT_ECHO_I18N_KEYS = {+ "scheduled": "harness.promptEcho.scheduled",+ "watch": "harness.promptEcho.watch",+ "webhook": "harness.promptEcho.webhook",+ "hook": "harness.promptEcho.hook",+ "agent_run": "harness.promptEcho.agentRun",+}+++def _neutralize_mentions(text: str) -> str:+ """Make every mention in *text* inert without changing how it reads.++ Used for the Harness prompt echo, which republishes text an operator wrote for an+ agent into a shared channel. Covers every ``@`` sigil — the broadcast words+ (``@everyone`` / ``@here`` / ``@channel``) and a bare ``@username``, which Telegram+ resolves into a real notification — plus the bracketed id forms both Slack+ (``<@U…>``, ``<!here>``, ``<#C…>``) and Discord (``<@id>``, ``<@&role>``) resolve.+ """++ neutralized = _HARNESS_ECHO_MENTION_SIGIL_PATTERN.sub(+ "@" + _HARNESS_ECHO_MENTION_BREAK, text or ""+ )+ return _HARNESS_ECHO_ID_MENTION_PATTERN.sub("<" + _HARNESS_ECHO_MENTION_BREAK, neutralized)+class ActivityOutputDeliveryError(RuntimeError):"""An Activity result did not complete its local output boundary."""@@ -235,6 +300,12 @@ class ConsolidatedMessageDispatcher:# first use per turn (see ``_concise_progress_style``), dropped in# ``_drop_status_keys``.self._turn_progress_style: dict[str, str] = {}+ # Harness deliveries whose prompt has already been echoed to IM, kept as a+ # bounded FIFO (see ``emit_harness_prompt``). Per-process only: a restart+ # replay writes a new Delivery anyway, and a duplicated echo is cosmetic+ # while a missing one defeats the feature.+ self._harness_prompt_echo_keys: set[str] = set()+ self._harness_prompt_echo_order: list[str] = []# Injectable monotonic-ish clock (wall time) so tests get deterministic# elapsed/stale values without sleeping.self._now = time.time@@ -1555,6 +1626,191 @@ class ConsolidatedMessageDispatcher:return first_message_id+ async def emit_harness_prompt(+ self,+ context: MessageContext,+ text: str,+ ) -> Optional[str]:+ """Echo a Harness-originated prompt into its IM conversation.++ A scheduled task / watch / webhook / hook / ``vibe agent run`` turn writes a+ ``harness`` Message row (``mirror_harness_inbound`` and the durable Delivery+ snapshot), which the Workbench transcript renders as the turn that asked the+ question. An IM channel has no such view: it only ever received the agent's+ reply, so a scheduled result read as an answer to a question nobody could see.+ This posts that question once, at the real start of the turn (called from+ ``AgentService._begin_turn_status``, i.e. after the runtime gate is acquired).++ Deliberately NOT routed through ``emit_agent_message``: this is neither an+ agent output nor a lifecycle event. It must not consolidate into the status+ bubble, settle a turn, touch an ``agent_runs`` row, or persist a second row on+ top of the ``harness`` one that already exists. Best-effort — a failed echo+ never blocks the turn.++ Skipped for:+ * ``avibe`` — the Workbench Chat already renders the ``harness`` row.+ * ``suppress_delivery`` — a background Session delivers nothing outward.+ * a trigger kind that is not a Harness run (a human turn is the IM message).+ * ``runtime.harness_prompt_echo = false``.+ """++ spec = context.platform_specific or {}+ if context.platform == "avibe":+ return None+ if spec.get("suppress_delivery"):+ return None+ trigger_kind = str(spec.get("task_trigger_kind") or "").strip()+ if trigger_kind not in HARNESS_PROMPT_ECHO_TRIGGER_KINDS:+ return None+ # A Harness turn never passes through an IM inbound handler, so nothing else+ # has reloaded ``controller.config`` for this turn: without this mtime-guarded+ # refresh the config-only switch would be read from the process-start snapshot+ # (a true->false toggle would still send one prompt, a false->true one would+ # skip the first). Same reason as ``_refresh_status_bubble_config``.+ self._refresh_runtime_config()+ if not getattr(self.controller.config, "harness_prompt_echo", True):+ return None+ if trigger_kind in HARNESS_PROMPT_ECHO_INSTRUCTION_ONLY_KINDS:+ # Composed, agent-facing prompt: echo the stored instruction alone, never+ # the appended waiter output / failure report / webhook payload. Read+ # per-delivery, because an instruction EDITED between two firings leaves a+ # merged batch dispatching two different instructions. No resolvable+ # instruction means no echo — a run whose definition was deleted cannot+ # prove which part of its prompt a person wrote.+ prompt = self._harness_echo_merged_prompt(+ spec, "harness_display_prompts", "harness_display_prompt"+ )+ if not prompt:+ return None+ else:+ # The Delivery's display snapshots win over the dispatch text when present:+ # ``SessionTurnGate`` prepends internal instructions to ``dispatch_text``+ # (the ``[Avibe recovery: ...]`` guard on an ambiguous-start replay), and+ # the channel must see the stored prompt, not a backend-only directive.+ prompt = (+ self._harness_echo_merged_prompt(spec, "display_texts", "display_text")+ or text+ )+ body = self._harness_prompt_body(trigger_kind, spec.get("task_definition_name"), prompt)+ if not body:+ return None+ # The prompt is delivered to the SAME target as the run's result (post_to /+ # deliver_key overrides included), so the question and its answer cannot land+ # in different conversations.+ target_context = self._get_target_context(context)+ echo_key = "|".join(+ [+ str(target_context.platform or ""),+ str(target_context.channel_id or ""),+ str(target_context.thread_id or ""),+ str(spec.get("native_message_id") or context.message_id or ""),+ ]+ )+ if echo_key in self._harness_prompt_echo_keys:+ # One echo per Harness delivery. A queue flush or a fallback re-dispatch+ # can reach this turn twice in one process; the prompt text is identical,+ # so the second post would only read as the task having fired twice.+ return None+ try:+ message_id = await self._get_im_client(context).send_message(+ target_context,+ body,+ # Markdown so the ``> `` prefix renders as a real quote: Slack builds a+ # plain_text block for anything else and would show the markers+ # literally (Codex P3). Telegram is unaffected — it resolves ``None``+ # to its own HTML default anyway.+ parse_mode="markdown",+ )+ except Exception as err:+ logger.warning(+ "Failed to echo harness prompt (%s) to %s: %s",+ trigger_kind,+ target_context.channel_id,+ err,+ exc_info=True,+ )+ return None+ self._remember_harness_prompt_echo(echo_key)+ return message_id++ @staticmethod+ def _harness_echo_merged_prompt(spec: dict, batch_key: str, single_key: str) -> str:+ """Every prompt this turn is about to answer, one entry per merged Delivery.++ A busy session merges the queued Harness deliveries of one definition into a+ single Turn (``core/session_turns.py::_collect_delivery_segment``) and sends+ *all* of their prompts to the backend, so reading the singular key — the first+ Delivery only — would announce one instruction for a result answering several.+ Two ``vibe agent run`` calls merge under the shared ``agent_run`` definition id+ with different prompts; a watch/webhook/hook definition whose instruction was+ EDITED between two firings merges with different stored instructions.++ Repeat firings of an unchanged definition carry the same text, hence the+ de-dup: a merged batch reads as one echo unless the instructions really differ.+ ``batch_key`` is stamped by the durable batch hydration only, so the singular+ key still serves the legacy mirror path, which has no batch.+ """+ raw = spec.get(batch_key)+ entries = (+ [str(item or "") for item in raw] if isinstance(raw, (list, tuple)) else []+ )+ if not any(entry.strip() for entry in entries):+ entries = [str(spec.get(single_key) or "")]+ unique = dict.fromkeys(entry.strip() for entry in entries if entry.strip())+ return "\n\n".join(unique)++ def _harness_prompt_body(+ self,+ trigger_kind: str,+ definition_name: Any,+ text: str,+ ) -> Optional[str]:+ prompt = strip_silent_blocks(text or "").strip()+ if not prompt:+ return None+ truncated = self._t("harness.promptEcho.truncated")+ if len(prompt) > HARNESS_PROMPT_ECHO_MAX_CHARS:+ prompt = prompt[:HARNESS_PROMPT_ECHO_MAX_CHARS].rstrip() + truncated+ label = self._t(+ _HARNESS_PROMPT_ECHO_I18N_KEYS.get(trigger_kind, "harness.promptEcho.generic")+ )+ name = str(definition_name or "").strip()+ if len(name) > HARNESS_PROMPT_ECHO_MAX_NAME_CHARS:+ # The name is appended AFTER the prompt cap and is never length-validated+ # when a task/watch is created, so leaving it unbounded could push the body+ # past a platform message limit — the adapter would reject the echo and the+ # channel would see no prompt at all.+ name = name[:HARNESS_PROMPT_ECHO_MAX_NAME_CHARS].rstrip() + truncated+ if name:+ label = self._t("harness.promptEcho.named", label=label, name=name)+ # Quoted body: plain-text platforms still read it as a quote, and the+ # markdown platforms render it de-emphasized, so the echo never competes+ # with the agent's own reply.+ quoted = "\n".join(f"> {line}" for line in prompt.splitlines())+ # Both halves are neutralized: the label carries the definition NAME, which a+ # user typed too and can hold a mention just as easily as the prompt.+ return _neutralize_mentions(f"{label}\n{quoted}")++ def _refresh_runtime_config(self) -> None:+ """Best-effort, mtime-guarded reload of ``controller.config`` from disk.++ Resolved through ``getattr`` so the lightweight controller stubs used by the+ dispatcher tests simply skip it instead of raising.+ """+ refresh = getattr(self.controller, "_refresh_config_from_disk", None)+ if not callable(refresh):+ return+ try:+ refresh()+ except Exception:+ logger.debug("runtime config refresh failed; using cached config", exc_info=True)++ def _remember_harness_prompt_echo(self, echo_key: str) -> None:+ self._harness_prompt_echo_keys.add(echo_key)+ self._harness_prompt_echo_order.append(echo_key)+ while len(self._harness_prompt_echo_order) > HARNESS_PROMPT_ECHO_MEMORY:+ self._harness_prompt_echo_keys.discard(self._harness_prompt_echo_order.pop(0))+async def emit_agent_message(self,context: MessageContext,diff --git a/core/message_output.py b/core/message_output.pyindex 030e438b3..e5c754811 100644--- a/core/message_output.py+++ b/core/message_output.py@@ -28,6 +28,19 @@ HARNESS_TRIGGER_KINDS: frozenset[str] = frozenset(# id addresses a write to a row that cannot exist.HARNESS_RUN_ID_TRIGGER_KINDS: frozenset[str] = HARNESS_TRIGGER_KINDS - {"activity_recovery"}+# ``platform_specific`` key carrying the Harness prompt that should be echoed into+# the turn's IM conversation. The turn pipeline stages it; ``AgentService`` emits it+# once the runtime turn gate is acquired, so a turn queued behind another turn cannot+# announce its prompt while that other turn is still working.+HARNESS_PROMPT_ECHO_SPEC_KEY = "harness_prompt_echo_text"++# The echo is awaited WITH the runtime turn gate held, so a slow or unreachable IM+# API would delay the Harness turn itself plus every turn queued on that gate — an+# adapter's own budget is far longer than a turn start should ever wait (Telegram+# allows 60s per request). Bounded like the status-bubble post that follows it+# (``MessageDispatcher.begin_status_bubble``); the echo is optional, the turn is not.+HARNESS_PROMPT_ECHO_TIMEOUT_SECONDS = 5.0+@dataclass(frozen=True)class MessageOutput:diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 8456a0384..6da09904e 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -6680,6 +6680,10 @@ class ScheduledTaskService:else request.request_type),agent_name=request.agent_name,+ # A composed hook / watch / webhook / escalation prompt is the one+ # case where the request itself knows which part a person wrote, so+ # its metadata must reach ``_build_context``.+ metadata=request.metadata if isinstance(request.metadata, dict) else None,_capture_dispatch_result=True,**({"agent_id": request.agent_id} if request.agent_id else {}),)@@ -8924,6 +8928,7 @@ class ScheduledTaskService:session_id: Optional[str] = None,agent_name: Optional[str] = None,agent_id: Optional[str] = None,+ metadata: Optional[dict[str, Any]] = None,_capture_dispatch_result: bool = False,) -> Optional[str] | TaskDispatchResult:target_info = resolve_session_id_target(session_id) if session_id else None@@ -8943,6 +8948,12 @@ class ScheduledTaskService:agent_name=agent_name,agent_id=agent_id,target_info=target_info,+ # Forwarded like the ``agent_run`` path already does. Without it every+ # metadata field ``_build_context`` reads — the display-prompt override, the+ # source/parent provenance — is unreachable for an enqueued hook, watch,+ # webhook, or escalation request, which are exactly the composed kinds whose+ # echo depends on being handed the user-authored instruction.+ metadata=metadata,)# A scheduled avibe turn drives the sidebar dot through the SAME two# chokepoints as any other turn — inbound AgentService.handle_message@@ -9025,6 +9036,8 @@ class ScheduledTaskService:if native_session_fork is None and target_info and not str(target_info.native_session_id or "").strip():native_session_fork = fork_metadata_from_session_metadata(getattr(target_info, "metadata", None))+ definition_name, definition_prompt = self._definition_display_fields(task_id)+return MessageContext(user_id=session_target_context["user_id"],channel_id=channel_id,@@ -9057,6 +9070,17 @@ class ScheduledTaskService:# definition id (task / watch). Carried so the message mirror can# attribute the injected prompt to its precise definition."task_definition_id": task_id,+ # Human label for the same definition, so an outward echo of the+ # injected prompt can name what fired instead of an opaque id.+ "task_definition_name": definition_name,+ # The definition's STORED instruction, i.e. the part of this run's+ # prompt a person actually wrote. A watch / hook / webhook prompt is+ # composed for the agent to read and appends machine-generated+ # evidence (waiter stdout, a failure report, a webhook payload); an+ # outward echo may show only this segment, never the composed text.+ "harness_display_prompt": (+ str((metadata or {}).get("harness_display_prompt") or "").strip() or definition_prompt+ ),"vibe_agent_name": agent_name,"vibe_agent_id": agent_id,"source_kind": (metadata or {}).get("source_kind"),@@ -9086,6 +9110,42 @@ class ScheduledTaskService:},)+ def _definition_display_fields(+ self, definition_id: Optional[str]+ ) -> tuple[Optional[str], Optional[str]]:+ """``(name, stored instruction)`` for *definition_id*, either one ``None``.++ Resolved the same way the failure notice does it (``get_task`` mirrors+ scheduled tasks only, so a watch needs the definition row), in ONE lookup+ because both fields feed the same display copy, and best-effort: a store that+ cannot answer must not break the run it is describing. ``agent_run`` has no+ definition and passes ``None``.++ The stored instruction is the definition's own prompt — a task's ``prompt``,+ a watch's ``message`` (which the row already falls back to ``prefix`` for) —+ so it is the user-authored text with none of the evidence a composed run+ prompt appends.+ """++ identifier = str(definition_id or "").strip()+ if not identifier:+ return None, None+ try:+ task = self.store.get_task(identifier)+ if task is not None:+ return (+ str(getattr(task, "name", "") or "").strip() or None,+ str(getattr(task, "prompt", "") or "").strip() or None,+ )+ watch = self.store.get_watch_definition(identifier) or {}+ except Exception:+ logger.debug("failed to resolve definition display fields for %s", identifier, exc_info=True)+ return None, None+ return (+ str(watch.get("name") or "").strip() or None,+ str(watch.get("message") or watch.get("prefix") or "").strip() or None,+ )+def _resolve_target_context(self, target: ParsedSessionKey) -> Dict[str, Any]:platform = target.platformif platform not in self.controller.platform_settings_managers:diff --git a/core/session_turns.py b/core/session_turns.pyindex 8fa8a1f0e..a6f591bfd 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -1448,6 +1448,40 @@ class SessionTurnManager:{"delivery_id": str(deliveries[0]["id"]),"delivery_ids": [str(row["id"]) for row in deliveries],+ # Every display snapshot this Turn dispatches, in FIFO order.+ # ``_hydrate_delivery_context`` set the singular ``display_text`` from+ # the FIRST Delivery only, while ``_segment_dispatch_text`` sends the+ # whole merged batch to the backend: a consumer that shows one prompt+ # (the IM prompt echo) would announce one instruction for a result that+ # answers several. Snapshots, never ``dispatch_text`` — the replay+ # guards prepended there are backend-only.+ "display_texts": [+ str(payload.get("text") or "")+ for payload in payloads+ if str(payload.get("text") or "").strip()+ ],+ # Same reason, one layer in: for the kinds whose prompt Avibe COMPOSES+ # (watch / webhook / hook) the snapshot above holds the generated+ # evidence too, so the echo shows the definition's stored instruction+ # instead — and an instruction edited between two firings leaves a+ # merged batch dispatching two different ones. Each Delivery's own+ # stamped instruction, from its captured provenance.+ "harness_display_prompts": [+ instruction+ for instruction in (+ str(+ (+ (_scheduled_provenance(payload) or {}).get(+ "platform_specific"+ )+ or {}+ ).get("harness_display_prompt")+ or ""+ ).strip()+ for payload in payloads+ )+ if instruction+ ],"message_content": {"text": "\n".join(str(payload.get("text") or "")diff --git a/docs/plans/harness-prompt-im-echo.md b/docs/plans/harness-prompt-im-echo.mdnew file mode 100644index 000000000..de9fe1d7c--- /dev/null+++ b/docs/plans/harness-prompt-im-echo.md@@ -0,0 +1,196 @@+# Harness prompt echo to IM++## Background++A Harness turn (scheduled task, watch, webhook, hook, `vibe agent run`) carries a+stored prompt. That prompt is persisted as a `harness` Message row —+`core/message_mirror.mirror_harness_inbound` on the legacy path, the+`message_deliveries.message_snapshot(...)` write on the durable Delivery path — and+Workbench Chat renders it, so the Web transcript reads *trigger → result*.++An IM conversation had no equivalent. `mirror_harness_inbound` only publishes live+for `platform == "avibe"`, and no outbound send existed for the prompt, so Slack /+Discord / Telegram / Lark / WeChat only ever received the agent's reply: an answer+to a question nobody in the channel could see. A daily digest, a watch firing, or+another agent's `vibe agent run` all arrived as unexplained messages.++## Goal++When a background task triggers an agent turn whose session is bound to an IM+conversation, post the triggering prompt to that same conversation, once, just+before the turn starts — so the channel reads *trigger → work → result*.++Non-goals:++- changing which message the scheduled thread anchors on (still the **result**, via+ `SessionHandler.finalize_scheduled_delivery`);+- persisting a second Message row (the `harness` row already exists);+- a Web UI toggle (the switch is config-only, like the other `harness_*` runtime+ knobs).++## Solution++Stage in the shared turn pipeline, send at the real turn start, gate and format in+the dispatcher.++1. `core/handlers/message_handler.py::_handle_turn` — for `source != human`, calls+ `_stage_harness_prompt_echo(context, control_message)`, which stamps+ `HARNESS_PROMPT_ECHO_SPEC_KEY` (`core/message_output.py`) into+ `platform_specific`. Placement is the design:+ - **after** every `suppress_delivery` resolution (the `agent_run_target` and the+ `find_session_for_anchor` branches, both settled only after+ `get_session_info`), so a backgrounded session stays silent;+ - **before** `_prepend_message_metadata`, so the staged text is the prompt, not the+ decorated backend dispatch text;+ - staging `control_message`, the pre-routing prompt: subagent routing rewrites+ `message` to the prefix-stripped body, and the echo must match what the+ Workbench row shows, prefix included;+ - outside the mirror `if`, so the durable Delivery path is covered too.+2. `modules/agents/service.py::_begin_turn_status` — `_emit_staged_harness_prompt`+ pops the staged key and sends it, next to the existing turn-start hooks. The send+ belongs *here*, not in the pipeline: `AgentService.handle_message` blocks on the+ runtime turn gate first, so a pipeline-side send would show a queued task's prompt+ while another turn is still working — or leave a prompt behind for a turn that was+ cancelled on the gate. Emitted before `begin_status_bubble` so the channel still+ reads trigger -> work -> result. Best-effort, `getattr`-guarded, and bounded at+ `HARNESS_PROMPT_ECHO_TIMEOUT_SECONDS = 5`: this await holds the runtime gate, and an+ adapter's own request budget is much longer than a turn start may wait (Telegram+ allows 60s), so an unbounded send would let a degraded transport delay the+ background task itself plus every turn queued behind it. Same bound, same reason as+ the `begin_status_bubble` post right after. The staged text is popped first, so a+ timeout drops that one echo instead of deferring it.+3. `core/message_dispatcher.py::emit_harness_prompt` — owns the gates and the send.+ Deliberately **not** routed through `emit_agent_message`: this is neither agent+ output nor a lifecycle event, and must not consolidate into the status bubble,+ settle a turn, touch an `agent_runs` row, or persist a row.+ - skipped for `avibe` (Workbench renders the row), `suppress_delivery`, a+ trigger kind outside `HARNESS_PROMPT_ECHO_TRIGGER_KINDS`+ (`HARNESS_TRIGGER_KINDS` minus `activity_recovery`, which is a runtime+ re-injection, not a user instruction), and `harness_prompt_echo = false`;+ - target is `_get_target_context(context)`, so the question lands where the+ answer lands (`post_to` / deliver-key overrides included);+ - text depends on who wrote the prompt:+ - `watch` / `webhook` / `hook` compose it **for the agent** — a watch appends the+ waiter's raw stdout (`core/watches.py::_build_prompt`), an `--on-failure agent`+ escalation appends the generated failure report+ (`core/scheduled_tasks.py::_escalation_prompt`, "read by an AGENT, not shown to+ a user"), a webhook its payload. Publishing that into a shared channel would+ leak command output (tokens, stack traces) before the agent can redact it, so+ for `HARNESS_PROMPT_ECHO_INSTRUCTION_ONLY_KINDS` the echo shows **only** the+ definition's stored instruction (`harness_display_prompt`) and stays silent+ when none resolves. The Workbench transcript still renders the full prompt for+ the operator. Read per-Delivery like the snapshots below+ (`harness_display_prompts`), because an instruction *edited* between two firings+ leaves a merged batch dispatching two different ones;+ - otherwise the Delivery display snapshots when present, else the staged prompt:+ `SessionTurnGate` prepends internal instructions to `dispatch_text` (the+ `[Avibe recovery: ...]` guard on an ambiguous-start replay) that must stay+ backend-only. *All* snapshots, de-duplicated: a busy session merges the queued+ deliveries of one definition into a single Turn+ (`_collect_delivery_segment`) and dispatches every prompt+ (`_segment_dispatch_text`), so the singular first snapshot would announce one+ instruction for a result answering several — two `vibe agent run` calls merge+ under the shared `agent_run` definition id. Repeat firings of one scheduled task+ carry the same stored prompt, hence the de-dup. Both branches share+ `_harness_echo_merged_prompt(spec, batch_key, single_key)`;+ - mentions are neutralized in the whole body, label included: quoting does not stop+ a renderer from resolving `@everyone` / a bare Telegram `@username` (which+ `TelegramFormatter.render` HTML-escapes without defusing) / `<@U…>` / `<@&role>` /+ `<!channel>`, and the Discord adapter sends without `allowed_mentions`, so an+ echoed broadcast would really ping the channel. The `@` guard is every sigil+ followed by a word character, deliberately platform-agnostic — one body is+ rendered by every adapter, so a new adapter inherits it. A zero-width space after+ the sigil keeps the text reading the same;+ - sent with `parse_mode="markdown"` so the `> ` quote renders: Slack builds a+ `plain_text` block for anything else and would show the markers literally;+ Telegram resolves either value to its own HTML default;+ - body: an i18n label per trigger kind, optionally `label · name`, then the+ prompt with every line `> `-quoted (readable on plain-text platforms too),+ truncated at `HARNESS_PROMPT_ECHO_MAX_CHARS = 800`. The name is capped too+ (`HARNESS_PROMPT_ECHO_MAX_NAME_CHARS = 80`): it is appended *after* the prompt cap+ and task/watch names are never length-validated at creation, so an unbounded one+ could push the body past Discord's 2,000-char limit and the adapter would reject+ the echo, leaving the channel with no prompt at all;+ - dedupe: bounded per-process FIFO keyed on target + native/delivery id+ (`HARNESS_PROMPT_ECHO_MEMORY = 256`), so an in-process re-dispatch of one+ delivery cannot read as the task having fired twice. A cross-restart replay is+ not covered on purpose: it writes a new Delivery anyway, a duplicate echo is+ cosmetic, and a missing echo defeats the feature.+4. `core/session_turns.py::_hydrate_delivery_batch_context` stamps `display_texts` and+ `harness_display_prompts`, one entry per merged Delivery in FIFO order, next to the+ existing `delivery_ids` — `_hydrate_delivery_context` set only the singular+ `display_text`, from the first Delivery. Snapshots are read from the stored text,+ never `dispatch_text`, so the replay guards prepended there stay internal;+ instructions come from each Delivery's own captured provenance+ (`_scheduled_provenance(payload)["platform_specific"]["harness_display_prompt"]`).+5. `core/scheduled_tasks.py::_build_context` stamps `task_definition_name` and+ `harness_display_prompt` next to the existing `task_definition_id`, both resolved+ in one best-effort lookup (`_definition_display_fields`: task row, else watch+ definition), so the label names the task instead of an id and the echo has the+ user-authored instruction to fall back on. A producer that composed the prompt+ itself can override the instruction through `metadata["harness_display_prompt"]`,+ which `_execute_request` forwards from `TaskExecutionRequest.metadata` — the+ `agent_run` path already did, so without that forward the override was unreachable+ for exactly the enqueued hook / watch / webhook / escalation requests whose echo+ depends on it. The two scheduled call sites stay unchanged on purpose: a definition's+ `session_fork` metadata must not be re-applied on every fire.+ `agent_run` has no definition. Both survive a cross-restart replay: the flush+ restores every provenance key that is not execution routing+ (`_EXECUTION_ROUTING_KEYS` is a blocklist).+6. Config: `V2Config.runtime.harness_prompt_echo` (default `true`), mirrored onto+ `AppCompatConfig` + `to_app_config` (the turn path reads `controller.config`,+ which is the compat object) and hot-reloaded in+ `Controller._refresh_config_from_disk`. The gate calls that mtime-guarded reload+ itself (`_refresh_runtime_config`), because a Harness turn passes through no IM+ inbound handler and would otherwise read the process-start snapshot. No UI,+ matching `harness_run_*` — but it *is* projected in+ `vibe/api.py::config_to_payload`, which is the deep-merge base of every+ `/api/config` save: a runtime key missing there is rebuilt from the dataclass+ default, so an opt-out would silently revert on any unrelated settings save. The+ four `harness_run_*` knobs are projected for the same reason (same latent bug,+ fixed here rather than left next to the new field).+7. Copy: `harness.promptEcho.*` in `vibe/i18n/en.json` and `zh.json`.++## Evidence++- unit — `tests/test_message_dispatcher_scheduled.py::HarnessPromptEchoTests`+ (per-kind coverage, every gate, delivery override, dedupe, memory bound,+ truncation/quoting, silent-only prompt, send failure, hot-toggle reload, a failing+ reload, display-snapshot precedence over internal dispatch text, instruction-only+ echo for the composed kinds — with the waiter output absent from the body and no+ echo at all when no instruction resolves — mention neutralization for the broadcast,+ id, and bare-`@username` forms, markdown parse mode, a merged batch echoing every+ distinct prompt while repeat firings of one task collapse to one, the same for a+ merged batch of edited instructions, blank snapshots falling back to the singular+ key, a long definition name bounded before the send);+ `tests/test_internal_server.py::test_flush_suppressed_segment_claims_each_delivery_id_in_one_turn`+ (the merged context carries both snapshots and both stamped instructions);+ `tests/test_api_save_config_merge.py::test_save_config_preserves_harness_runtime_knobs_on_partial_save`;+ `tests/test_message_handler_harness_echo.py` (pipeline staging: raw prompt,+ subagent-prefixed prompt staged unstripped, human turn stages nothing, blank prompt+ stages nothing, backgrounded thread resolution visible to the echo, and no send from+ the pipeline);+ `tests/test_agent_service.py` (turn-start emission: a queued turn stays quiet until+ it owns the runtime gate, the key is popped, no staged prompt echoes nothing, a+ failing echo never breaks turn start, a hanging echo cannot hold the gate);+ `tests/test_scheduled_tasks.py::test_build_context_carries_the_definition_name_for_display`,+ `::test_build_context_prefers_an_explicit_display_prompt_from_the_request`,+ `::test_build_context_survives_a_store_that_cannot_name_the_definition`,+ `::test_execute_request_forwards_request_metadata_into_the_context` and+ `::test_claimed_request_hands_its_metadata_to_the_execution` (the metadata reaches+ the context through both hops of the enqueued-request lane).+- scenario — `MESSAGE-DELIVERY-018` (prompt precedes result; the result still owns+ the anchor) and `MESSAGE-DELIVERY-019` (background-visibility turn echoes nothing)+ in `tests/scenarios/message_delivery/`.+- manual — a real scheduled task in one IM channel per platform, plus a+ `vibe agent run` callback, to confirm ordering and formatting against live+ renderers (WeChat has no markdown).++## Todo++- [x] turn-pipeline call site and dispatcher helper+- [x] definition name in the harness context+- [x] runtime switch through V2 config, compat config, and hot reload+- [x] en/zh copy+- [x] unit + scenario coverage, catalog entries+- [ ] manual IM pass in the Incus regression environmentdiff --git a/modules/agents/service.py b/modules/agents/service.pyindex f6bff2cda..f169c27b3 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -6,7 +6,12 @@ from dataclasses import dataclass, fieldfrom typing import Any, Callable, Dict, Optionalfrom core.session_activities import SessionActivityRegistry-from core.message_output import terminal_output_for, terminal_turn_output+from core.message_output import (+ HARNESS_PROMPT_ECHO_SPEC_KEY,+ HARNESS_PROMPT_ECHO_TIMEOUT_SECONDS,+ terminal_output_for,+ terminal_turn_output,+)from core.runtime_activation import (RuntimeActivationIdentity,RuntimeActivationRegistry,@@ -1031,6 +1036,7 @@ class AgentService:update_thread_message_id(context)except Exception:logger.debug("update_thread_message_id failed at turn start", exc_info=True)+ await self._emit_staged_harness_prompt(context)dispatcher = getattr(self.controller, "message_dispatcher", None)begin_status_bubble = getattr(dispatcher, "begin_status_bubble", None) if dispatcher else Noneif callable(begin_status_bubble):@@ -1039,6 +1045,42 @@ class AgentService:except Exception:logger.debug("begin_status_bubble failed at turn start", exc_info=True)+ async def _emit_staged_harness_prompt(self, context: Any) -> None:+ """Echo a staged Harness prompt into its IM conversation at turn start.++ The turn pipeline stages the prompt (``HARNESS_PROMPT_ECHO_SPEC_KEY``); it is+ sent from here so the channel sees it only once this turn owns the runtime+ gate — never while it is still queued behind another turn, and never for a+ turn cancelled before it ran. Popped so a retry cannot post it twice, and+ emitted before the status bubble so the order stays trigger -> work -> result.+ Best-effort and time-bounded: the dispatcher owns the gates, and neither a+ failed nor a slow echo may break or stall the turn.+ """+ spec = getattr(context, "platform_specific", None)+ if not isinstance(spec, dict):+ return+ text = spec.pop(HARNESS_PROMPT_ECHO_SPEC_KEY, None)+ if not text:+ return+ dispatcher = getattr(self.controller, "message_dispatcher", None)+ emit = getattr(dispatcher, "emit_harness_prompt", None)+ if not callable(emit):+ return+ try:+ # This await holds the runtime gate (see ``_begin_turn_status``), so an+ # unbounded send would let a degraded IM transport delay the background+ # task itself and every turn queued behind it for the adapter's full+ # request budget. The staged text is already popped, so a timeout drops+ # this one echo rather than deferring it into a later turn.+ await asyncio.wait_for(+ emit(context, text),+ timeout=HARNESS_PROMPT_ECHO_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ logger.debug("harness prompt echo timed out at turn start; turn continues")+ except Exception:+ logger.debug("harness prompt echo failed at turn start", exc_info=True)+def _track_processing_indicator_turn(self, request: AgentRequest) -> None:handle = getattr(request, "processing_indicator", None)if handle is None:diff --git a/tests/scenario_harness/message_delivery.py b/tests/scenario_harness/message_delivery.pyindex a42e98ad0..9e4b49c60 100644--- a/tests/scenario_harness/message_delivery.py+++ b/tests/scenario_harness/message_delivery.py@@ -72,6 +72,9 @@ class MessageDeliveryHarness(BaseScenarioHarness):self.context.platform = platformself.dispatcher = ConsolidatedMessageDispatcher(self.controller)+ async def emit_harness_prompt(self, text: str):+ return await self.dispatcher.emit_harness_prompt(self.context, text)+async def emit_result(self, text: str):return await self.dispatcher.emit_agent_message(self.context, "result", text)diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 724ae0759..c6bf4443f 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -116,6 +116,18 @@ scenarios:kind: recoverylayer: contracttest: tests/test_session_delivery_fsm.py::test_start_write_ambiguity_replays_once_after_restart+ - id: MESSAGE-DELIVERY-018+ name: Harness turn echoes its prompt to IM before the result+ status: covered+ kind: happy_path+ layer: scenario+ test: tests/scenarios/message_delivery/test_message_delivery_scenarios.py::test_scheduled_turn_scenario_shows_its_prompt_before_the_result+ - id: MESSAGE-DELIVERY-019+ name: Background-visibility Harness turn echoes nothing outward+ status: covered+ kind: lifecycle+ layer: scenario+ test: tests/scenarios/message_delivery/test_message_delivery_scenarios.py::test_background_session_scenario_stays_silent_including_its_prompt- id: MESSAGE-DELIVERY-101name: Unresolved fallback-capable delivery fences only later FIFO submissionsstatus: covereddiff --git a/tests/scenarios/message_delivery/test_message_delivery_scenarios.py b/tests/scenarios/message_delivery/test_message_delivery_scenarios.pyindex 7d06050c8..56685f748 100644--- a/tests/scenarios/message_delivery/test_message_delivery_scenarios.py+++ b/tests/scenarios/message_delivery/test_message_delivery_scenarios.py@@ -135,6 +135,56 @@ class MessageDeliveryScenarioTests(unittest.IsolatedAsyncioTestCase):ScenarioExpect.text_contains(harness, "hello")self.assertEqual(harness.finalized_calls, [("C123", "171717.123", "msg-1")])+ async def test_scheduled_turn_scenario_shows_its_prompt_before_the_result(self):+ """Scenario: MESSAGE-DELIVERY-018"""+ harness = MessageDeliveryHarness(platform="slack")+ harness.context.message_id = "scheduled:run-18"+ harness.context.platform_specific = {+ "turn_source": "scheduled",+ "turn_base_session_id": "slack_scheduled-18",+ "task_trigger_kind": "scheduled",+ "task_execution_id": "run-18",+ "task_definition_id": "task-18",+ "task_definition_name": "Morning digest",+ "scheduled_anchor_required": True,+ }+ runner = ScenarioRunner(harness)++ await runner.run(+ ScenarioStep("echo_harness_prompt", lambda h: h.emit_harness_prompt("summarize open PRs")),+ ScenarioStep("emit_result", lambda h: h.emit_result("3 open PRs")),+ )++ ScenarioExpect.step_history(runner, ["echo_harness_prompt", "emit_result"])+ # The channel reads trigger -> result, so the reply is no longer an answer to+ # a question only the Workbench transcript could show.+ texts = harness.rendered_texts()+ self.assertEqual(len(texts), 2)+ self.assertIn("Morning digest", texts[0])+ self.assertIn("> summarize open PRs", texts[0])+ self.assertEqual(texts[1], "3 open PRs")+ # The echo must not consume the scheduled anchor: the RESULT is still what a+ # follow-up threads under.+ self.assertEqual(harness.finalized_calls, [("C123", None, "msg-2")])++ async def test_background_session_scenario_stays_silent_including_its_prompt(self):+ """Scenario: MESSAGE-DELIVERY-019"""+ harness = MessageDeliveryHarness(platform="slack")+ harness.context.message_id = "agent_run:run-19"+ harness.context.platform_specific = {+ "turn_source": "scheduled",+ "task_trigger_kind": "agent_run",+ "task_execution_id": "run-19",+ "suppress_delivery": True,+ }+ runner = ScenarioRunner(harness)++ await runner.run(+ ScenarioStep("echo_harness_prompt", lambda h: h.emit_harness_prompt("investigate the flake")),+ )++ self.assertEqual(harness.rendered_texts(), [])+if __name__ == "__main__":unittest.main()diff --git a/tests/test_agent_service.py b/tests/test_agent_service.pyindex e0776eb33..ed12915ec 100644--- a/tests/test_agent_service.py+++ b/tests/test_agent_service.py@@ -4,17 +4,18 @@ import asyncioimport sysfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import AsyncMock, Mock+from unittest.mock import AsyncMock, Mock, patchimport pytest-from core.message_output import terminal_turn_output+from core.message_output import HARNESS_PROMPT_ECHO_SPEC_KEY, terminal_turn_outputfrom core.native_dispatch_phase import (DISPATCH_PHASE_PREWRITE,backend_dispatch_attempted,set_dispatch_phase,)from core.session_activities import SessionActivityRegistry+from modules.agents import service as service_modulefrom modules.agents.service import AgentServicefrom modules.agents.codex.transport import CodexTransportfrom storage.db import create_sqlite_engine@@ -115,6 +116,10 @@ class _OrderRecordingDispatcher:async def begin_status_bubble(self, _context):self._log.append("begin_status_bubble")+ async def emit_harness_prompt(self, _context, text):+ self._log.append(f"echo:{text}")+ return "echo-msg"+class _TurnStartController:"""Records the relative order of the turn-start hooks vs the agent run."""@@ -165,6 +170,132 @@ def test_agent_service_runs_turn_start_hooks_after_gate_before_agent() -> None:asyncio.run(_run())+def test_agent_service_defers_staged_harness_prompt_until_the_gate_is_held() -> None:+ """A queued Harness turn must not announce its prompt in the channel yet.++ The turn pipeline stages the prompt, but the turn may sit behind another turn on+ the runtime gate (or be cancelled there). Echoing at turn start keeps the channel+ reading trigger -> work -> result instead of showing the second task's prompt+ while the first task is still working (Codex P2).+ """++ async def _run():+ log: list[str] = []+ controller = _TurnStartController(log)+ service = AgentService(controller=controller)+ controller.agent_service = service+ release_first = asyncio.Event()+ agent = _RuntimeAgent(release_first)+ service.register(agent)++ first_request = _request("first")+ first = asyncio.create_task(service.handle_message("claude", first_request))+ await asyncio.sleep(0)+ assert agent.started == ["first"]++ second_request = _request("second")+ second_request.context.platform_specific = {+ HARNESS_PROMPT_ECHO_SPEC_KEY: "summarize open PRs"+ }+ second = asyncio.create_task(service.handle_message("claude", second_request))+ await asyncio.sleep(0.05)+ assert "echo:summarize open PRs" not in log++ service.release_runtime_turn(first_request.context)+ release_first.set()+ await asyncio.wait_for(first, timeout=3)+ await asyncio.wait_for(second, timeout=3)++ # Echoed only once its OWN turn started (after the first turn's hooks), and+ # immediately ahead of that turn's status bubble.+ echo_at = log.index("echo:summarize open PRs")+ assert log[echo_at - 1] == "update_thread_message_id"+ assert log[echo_at + 1] == "begin_status_bubble"+ assert agent.started == ["first", "second"]+ # Popped, so a retry of the same request cannot post the prompt twice.+ assert HARNESS_PROMPT_ECHO_SPEC_KEY not in second_request.context.platform_specific++ asyncio.run(_run())+++def test_agent_service_turn_start_without_a_staged_prompt_echoes_nothing() -> None:+ async def _run():+ log: list[str] = []+ controller = _TurnStartController(log)+ service = AgentService(controller=controller)+ controller.agent_service = service+ service.register(_OrderRecordingAgent(log))++ await service.handle_message("claude", _request("hi"))++ assert not any(entry.startswith("echo:") for entry in log)++ asyncio.run(_run())+++def test_agent_service_failed_harness_prompt_echo_never_breaks_the_turn() -> None:+ async def _run():+ class _FailingEchoController:+ session_turns = None+ message_dispatcher = SimpleNamespace(+ emit_harness_prompt=AsyncMock(side_effect=RuntimeError("send failed")),+ begin_status_bubble=AsyncMock(),+ )++ controller = _FailingEchoController()+ service = AgentService(controller=controller)+ agent = _RuntimeAgent()+ service.register(agent)++ request = _request("hi")+ request.context.platform_specific = {HARNESS_PROMPT_ECHO_SPEC_KEY: "do the thing"}+ await service.handle_message("claude", request)++ assert agent.started == ["hi"]+ controller.message_dispatcher.begin_status_bubble.assert_awaited_once()++ asyncio.run(_run())+++def test_agent_service_slow_harness_prompt_echo_does_not_hold_the_gate() -> None:+ """A degraded IM transport must not stall the turn it is announcing (Codex P2).++ The echo is awaited with the runtime gate held, and an adapter's own request+ budget is far longer than a turn start should ever wait (Telegram allows 60s), so+ the wait is bounded like the status-bubble post that follows it.+ """++ async def _run():+ started = asyncio.Event()++ async def _hanging_echo(_context, _text):+ started.set()+ await asyncio.sleep(30)++ class _SlowEchoController:+ session_turns = None+ message_dispatcher = SimpleNamespace(+ emit_harness_prompt=_hanging_echo,+ begin_status_bubble=AsyncMock(),+ )++ controller = _SlowEchoController()+ service = AgentService(controller=controller)+ agent = _RuntimeAgent()+ service.register(agent)++ request = _request("hi")+ request.context.platform_specific = {HARNESS_PROMPT_ECHO_SPEC_KEY: "do the thing"}+ with patch.object(service_module, "HARNESS_PROMPT_ECHO_TIMEOUT_SECONDS", 0.05):+ await asyncio.wait_for(service.handle_message("claude", request), timeout=3)++ assert started.is_set()+ assert agent.started == ["hi"]+ controller.message_dispatcher.begin_status_bubble.assert_awaited_once()++ asyncio.run(_run())++def test_agent_service_turn_start_hooks_optional_and_guarded() -> None:async def _run():# A controller WITHOUT the turn-start hooks (and a dispatcher whosediff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex dcdd88511..41d0688e5 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -309,6 +309,33 @@ def test_save_config_preserves_status_bubble_settings_on_partial_save(monkeypatcassert payload["agent_status_heartbeat_ms"] == 12000+def test_save_config_preserves_harness_runtime_knobs_on_partial_save(monkeypatch, tmp_path):+ """The config-only Harness knobs must survive an unrelated UI save (Codex P1).++ ``config_to_payload`` is the deep-merge base for every ``/api/config`` save, so a+ ``runtime`` key it omits is absent from the merged payload and ``from_payload``+ rebuilds it from the dataclass default: a ``harness_prompt_echo: false`` opt-out+ came back enabled after any unrelated settings change. Same shape as the+ status-bubble regression above.+ """+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))++ full = _full_config_payload()+ full["runtime"]["harness_prompt_echo"] = False+ full["runtime"]["harness_run_queued_ttl_seconds"] = 4242+ created = api.save_config(full)+ assert created.runtime.harness_prompt_echo is False+ assert created.runtime.harness_run_queued_ttl_seconds == 4242++ updated = api.save_config({"show_duration": False})+ payload = api.config_to_payload(updated)++ assert updated.runtime.harness_prompt_echo is False+ assert updated.runtime.harness_run_queued_ttl_seconds == 4242+ assert payload["runtime"]["harness_prompt_echo"] is False+ assert payload["runtime"]["harness_run_queued_ttl_seconds"] == 4242++def test_config_load_defaults_missing_show_pages_prompt_to_enabled():payload = _full_config_payload()payload.pop("show_pages_prompt")diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex bb9de3912..d997b7e79 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -5223,21 +5223,22 @@ def test_flush_quarantines_agent_run_when_native_start_may_have_written(def test_flush_suppressed_segment_claims_each_delivery_id_in_one_turn(tmp_path, monkeypatch):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- def prov(execution_id: str) -> dict:+ def prov(execution_id: str, instruction: str) -> dict:return {"message_id": f"watch:def-watch:{execution_id}","platform_specific": {"task_execution_id": execution_id,"task_trigger_kind": "watch","task_definition_id": "def-watch",+ "harness_display_prompt": instruction,"suppress_delivery": True,},}session_id = _seed_avibe_session_with_queue([- ("first callback", prov("run-1")),- ("second callback", prov("run-2")),+ ("first callback", prov("run-1", "watch the deploy")),+ ("second callback", prov("run-2", "watch the deploy and page me")),])@@ -5249,6 +5250,20 @@ def test_flush_suppressed_segment_claims_each_delivery_id_in_one_turn(tmp_path,assert len(runs) == 1assert runs[0][2].message_id == "watch:def-watch:run-1"assert len(runs[0][2].platform_specific["delivery_ids"]) == 2+ # Every merged Delivery's display snapshot travels with the context. The dispatch+ # text carries BOTH prompts, so a consumer that reads the singular ``display_text``+ # (the IM prompt echo) would announce one instruction for a two-prompt result.+ assert runs[0][2].platform_specific["display_texts"] == [+ "first callback",+ "second callback",+ ]+ # Same for the composed kinds, whose echo shows the stored instruction instead of+ # the snapshot: an instruction edited between the two firings leaves the merged+ # batch dispatching both, so each Delivery's own stamped instruction travels too.+ assert runs[0][2].platform_specific["harness_display_prompts"] == [+ "watch the deploy",+ "watch the deploy and page me",+ ]with create_sqlite_engine().begin() as conn:assert message_deliveries.list_queued(conn, session_id) == []diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex 9fd2a0b2e..210080ed3 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -6,7 +6,7 @@ import tempfileimport unittestfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, Mock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -3754,3 +3754,485 @@ class PostSendBookkeepingDeliveryEvidenceTests(unittest.IsolatedAsyncioTestCase)self.assertEqual(client.delivered, ["bot-msg-1"])self.assertEqual(message_id, "bot-msg-1")self.assertEqual(calls, [("record", "run-bookkeeping", "delivered body", "bot-msg-1", "succeeded")])+++class HarnessPromptEchoTests(unittest.IsolatedAsyncioTestCase):+ """MESSAGE-DELIVERY-018: a Harness turn announces its prompt in the IM channel.++ Without the echo an IM conversation only ever received the agent's reply, so a+ scheduled/watch/webhook/hook/``agent run`` result read as an answer to a question+ nobody in the channel could see.+ """++ def _context(self, **spec):+ payload = {+ "task_trigger_kind": "scheduled",+ "task_execution_id": "run-echo-1",+ "task_definition_id": "task-echo-1",+ }+ payload.update(spec)+ return MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform=payload.pop("platform", "slack"),+ thread_id=payload.pop("thread_id", None),+ message_id=payload.pop("message_id", "scheduled:run-echo-1"),+ platform_specific=payload,+ )++ async def test_scheduled_prompt_is_echoed_to_the_channel(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ message_id = await dispatcher.emit_harness_prompt(+ self._context(task_definition_name="Daily digest"),+ "summarize yesterday's deploys",+ )++ self.assertEqual(message_id, "bot-msg-1")+ self.assertEqual(len(controller.im_client.sent), 1)+ channel_id, thread_id, text = controller.im_client.sent[0]+ self.assertEqual(channel_id, "C123")+ self.assertIsNone(thread_id)+ self.assertIn("Daily digest", text)+ self.assertIn("> summarize yesterday's deploys", text)++ async def test_every_harness_trigger_kind_is_echoed(self):+ for kind in ("scheduled", "watch", "webhook", "hook", "agent_run"):+ with self.subTest(kind=kind):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ await dispatcher.emit_harness_prompt(+ # ``watch`` / ``webhook`` / ``hook`` echo their definition's stored+ # instruction; the other two echo the dispatch text itself.+ self._context(task_trigger_kind=kind, harness_display_prompt="do the thing"),+ "do the thing",+ )+ self.assertEqual(len(controller.im_client.sent), 1)++ async def test_composed_prompt_echoes_the_instruction_not_the_generated_evidence(self):+ """Scenario: MESSAGE-DELIVERY-018++ A watch prompt is composed FOR THE AGENT: the stored instruction plus the+ waiter's raw stdout (``core/watches.py::_build_prompt``); an+ ``--on-failure agent`` escalation appends a generated failure report the same+ way. Echoing that verbatim would publish raw command output — tokens+ included — into a shared channel before the agent can redact it (Codex P1).+ """+ for kind in ("watch", "webhook", "hook"):+ with self.subTest(kind=kind):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ composed = "check the deploy and report\n\ntoken=ghp_SECRET\nrows=42"++ await dispatcher.emit_harness_prompt(+ self._context(+ task_trigger_kind=kind,+ harness_display_prompt="check the deploy and report",+ display_text=composed,+ ),+ composed,+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ self.assertIn("> check the deploy and report", text)+ self.assertNotIn("ghp_SECRET", text)+ self.assertNotIn("rows=42", text)++ async def test_composed_prompt_without_a_stored_instruction_echoes_nothing(self):+ # A deleted / unresolvable definition means nothing here can tell the+ # user-authored instruction from the generated evidence, so the echo stays+ # silent rather than guessing (the Workbench row still has the full prompt).+ for kind in ("watch", "webhook", "hook"):+ with self.subTest(kind=kind):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(+ self._context(task_trigger_kind=kind),+ "waiter said: token=ghp_SECRET",+ )++ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])++ async def test_echoed_mentions_cannot_ping_the_channel(self):+ """Quoting does not stop a renderer from resolving a mention (Codex P2).++ Discord sends without ``allowed_mentions``, so an echoed ``@everyone`` would+ really broadcast; Slack resolves ``<@U…>`` / ``<!channel>`` the same way.+ """+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(task_definition_name="@here nightly"),+ "ping @everyone plus <@U123>, <@&456> and <!channel>",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ for mention in ("@everyone", "@here", "<@U123>", "<@&456>", "<!channel>"):+ self.assertNotIn(mention, text)+ # Only a zero-width break was inserted, so the prompt still reads the same.+ self.assertIn("ping @everyone plus <@U123>, <@&456> and <!channel>", text.replace("\u200b", ""))++ async def test_echoed_username_mention_cannot_notify_on_telegram(self):+ """A bare ``@username`` is a real mention on Telegram (Codex P2).++ ``TelegramFormatter.render`` HTML-escapes the body but leaves the sigil intact,+ so an echoed handle would notify that account. Neutralized for every adapter+ rather than in the Telegram formatter: one body is rendered by all of them, and+ a new adapter inherits the guard.+ """+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(platform="telegram", task_definition_name="@release_bot nightly"),+ "ask @alice_dev to review, cc @team_lead",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ for mention in ("@alice_dev", "@team_lead", "@release_bot"):+ self.assertNotIn(mention, text)+ self.assertIn("ask @alice_dev to review, cc @team_lead", text.replace("\u200b", ""))++ async def test_echo_is_sent_as_markdown_so_the_quote_renders(self):+ # Slack builds a plain_text block for anything but markdown and would show+ # the ``> `` markers literally (Codex P3). Telegram resolves either value to+ # its own HTML default, so this changes nothing there.+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ recorded: dict = {}++ async def _send(context, text, parse_mode=None, reply_to=None):+ recorded["parse_mode"] = parse_mode+ return "bot-msg-1"++ controller.im_client.send_message = _send++ await dispatcher.emit_harness_prompt(self._context(), "do the thing")++ self.assertEqual(recorded["parse_mode"], "markdown")++ async def test_activity_recovery_and_human_turns_are_not_echoed(self):+ # ``activity_recovery`` is a runtime re-injection, not a user-authored+ # instruction; a human turn's prompt IS the IM message already on screen.+ for kind in ("activity_recovery", "", "human"):+ with self.subTest(kind=kind):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ result = await dispatcher.emit_harness_prompt(+ self._context(task_trigger_kind=kind),+ "do the thing",+ )+ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])++ async def test_workbench_platform_is_not_echoed(self):+ # Workbench Chat renders the ``harness`` Message row itself.+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(+ self._context(platform="avibe"),+ "do the thing",+ )++ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])++ async def test_background_session_is_not_echoed(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(+ self._context(suppress_delivery=True),+ "do the thing",+ )++ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])++ async def test_disabled_runtime_switch_keeps_result_only_behavior(self):+ controller = _StubController()+ controller.config.harness_prompt_echo = False+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(self._context(), "do the thing")++ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])++ async def test_display_snapshot_wins_over_internal_dispatch_text(self):+ """A replayed durable turn carries an internal recovery guard in its dispatch+ text; the channel must see the stored prompt instead (Codex P2)."""+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(display_text="summarize open PRs"),+ "[Avibe recovery: this request may have been delivered before restart.]"+ "\n\nsummarize open PRs",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ self.assertIn("> summarize open PRs", text)+ self.assertNotIn("Avibe recovery", text)++ async def test_merged_batch_echoes_every_distinct_prompt_it_dispatched(self):+ """Scenario: MESSAGE-DELIVERY-018++ Two ``vibe agent run`` deliveries queued for one busy session merge into a+ single Turn (``_collect_delivery_segment``) and BOTH prompts reach the backend+ (``_segment_dispatch_text``). Echoing the first snapshot alone would announce+ one instruction for a result that answers two (Codex P2).+ """+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(+ task_trigger_kind="agent_run",+ display_text="summarize open PRs",+ display_texts=["summarize open PRs", "then close the stale ones"],+ ),+ "summarize open PRs\n\n---\n\nthen close the stale ones",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ self.assertIn("> summarize open PRs", text)+ self.assertIn("> then close the stale ones", text)++ async def test_merged_repeat_firings_of_one_task_echo_the_prompt_once(self):+ # Two firings of the same scheduled task carry the SAME stored prompt, so the+ # merged batch must not read as the instruction having been given twice.+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(+ display_text="summarize open PRs",+ display_texts=["summarize open PRs", "summarize open PRs"],+ ),+ "summarize open PRs\n\n---\n\nsummarize open PRs",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ self.assertEqual(text.count("> summarize open PRs"), 1)++ async def test_empty_batch_snapshots_fall_back_to_the_single_snapshot(self):+ # The legacy mirror path stages no batch, and a batch of blank snapshots must+ # not silence an echo the singular key can still serve.+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(display_text="summarize open PRs", display_texts=["", " "]),+ "summarize open PRs",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ self.assertIn("> summarize open PRs", text)++ async def test_merged_composed_batch_echoes_each_stored_instruction(self):+ """Scenario: MESSAGE-DELIVERY-018++ The composed kinds echo the definition's stored instruction, and that+ instruction can be EDITED between two firings — so a merged batch dispatches+ two different ones and the singular key would announce only the first+ (Codex P2). Each Delivery's own stamped instruction, and still none of the+ generated evidence.+ """+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(+ task_trigger_kind="watch",+ harness_display_prompt="check the deploy",+ harness_display_prompts=["check the deploy", "check the deploy and page me"],+ ),+ "check the deploy\n\ntoken=ghp_SECRET",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ self.assertIn("> check the deploy", text)+ self.assertIn("> check the deploy and page me", text)+ self.assertNotIn("ghp_SECRET", text)++ async def test_merged_composed_batch_of_one_instruction_echoes_it_once(self):+ # Repeat firings of an UNCHANGED watch carry the same stored instruction; the+ # merged batch must not read as it having been given twice.+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(+ task_trigger_kind="watch",+ harness_display_prompt="check the deploy",+ harness_display_prompts=["check the deploy", "check the deploy"],+ ),+ "check the deploy\n\ntoken=ghp_SECRET",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ self.assertEqual(text.count("> check the deploy"), 1)++ async def test_merged_composed_batch_without_instructions_stays_silent(self):+ # An empty batch falls back to the singular key, and when that is absent too+ # the composed kinds still refuse to publish the generated evidence.+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(+ self._context(task_trigger_kind="watch", harness_display_prompts=["", " "]),+ "waiter said: token=ghp_SECRET",+ )++ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])++ async def test_long_definition_name_is_bounded_before_sending(self):+ """A task/watch name is never length-validated at creation (Codex P2).++ The label is appended AFTER the prompt cap, so an unbounded name could push the+ body past Discord's 2,000-char limit — the adapter would reject the echo and the+ channel would see no prompt at all.+ """+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ limit = message_dispatcher_module.HARNESS_PROMPT_ECHO_MAX_NAME_CHARS++ await dispatcher.emit_harness_prompt(+ self._context(task_definition_name="n" * (limit * 40)),+ "do the thing",+ )++ _channel_id, _thread_id, text = controller.im_client.sent[0]+ self.assertNotIn("n" * (limit + 1), text)+ self.assertIn("n" * limit, text)+ self.assertIn("truncated", text)+ self.assertIn("> do the thing", text)++ async def test_runtime_switch_is_reloaded_before_the_gate(self):+ """A Harness turn reaches no IM inbound handler, so nothing else reloads+ ``controller.config``: the config-only toggle must be re-read here, or a+ true->false change would still send one more prompt (Codex P2)."""+ controller = _StubController()+ refreshed = []++ def _refresh_config_from_disk():+ refreshed.append(True)+ controller.config.harness_prompt_echo = False++ controller._refresh_config_from_disk = _refresh_config_from_disk+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(self._context(), "do the thing")++ self.assertTrue(refreshed)+ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])++ async def test_failed_config_reload_still_echoes(self):+ controller = _StubController()+ controller._refresh_config_from_disk = Mock(side_effect=RuntimeError("disk gone"))+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(self._context(), "do the thing")++ self.assertEqual(result, "bot-msg-1")+ self.assertEqual(len(controller.im_client.sent), 1)++ async def test_echo_follows_the_delivery_override_target(self):+ # The question must land where the answer lands (``post_to`` / deliver key).+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(+ self._context(+ delivery_override={+ "user_id": "U9",+ "channel_id": "C999",+ "thread_id": "T9",+ "platform": "slack",+ "is_dm": False,+ }+ ),+ "do the thing",+ )++ self.assertEqual(controller.im_client.sent[0][0], "C999")+ self.assertEqual(controller.im_client.sent[0][1], "T9")++ async def test_repeat_dispatch_of_one_delivery_echoes_once(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = self._context()++ first = await dispatcher.emit_harness_prompt(context, "do the thing")+ second = await dispatcher.emit_harness_prompt(context, "do the thing")++ self.assertEqual(first, "bot-msg-1")+ self.assertIsNone(second)+ self.assertEqual(len(controller.im_client.sent), 1)++ async def test_distinct_runs_in_one_channel_each_echo(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ await dispatcher.emit_harness_prompt(self._context(message_id="scheduled:run-a"), "first")+ await dispatcher.emit_harness_prompt(self._context(message_id="scheduled:run-b"), "second")++ self.assertEqual(len(controller.im_client.sent), 2)++ async def test_echo_memory_stays_bounded(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ limit = message_dispatcher_module.HARNESS_PROMPT_ECHO_MEMORY++ for index in range(limit + 5):+ await dispatcher.emit_harness_prompt(+ self._context(message_id=f"scheduled:run-{index}"),+ "do the thing",+ )++ self.assertEqual(len(dispatcher._harness_prompt_echo_keys), limit)+ self.assertEqual(len(dispatcher._harness_prompt_echo_order), limit)++ async def test_long_prompt_is_truncated_and_every_line_quoted(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ limit = message_dispatcher_module.HARNESS_PROMPT_ECHO_MAX_CHARS++ await dispatcher.emit_harness_prompt(self._context(), "line one\nline two\n" + "x" * (limit * 2))++ text = controller.im_client.sent[0][2]+ body = text.split("\n", 1)[1]+ self.assertTrue(all(line.startswith("> ") for line in body.splitlines()))+ self.assertIn("truncated", text)+ self.assertLess(len(text), limit * 2)++ async def test_silent_only_prompt_sends_nothing(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(+ self._context(),+ "<silent>internal bookkeeping</silent>",+ )++ self.assertIsNone(result)+ self.assertEqual(controller.im_client.sent, [])++ async def test_send_failure_never_blocks_the_turn(self):+ controller = _StubController()+ controller.im_client = _FailingIMClient()+ dispatcher = ConsolidatedMessageDispatcher(controller)++ result = await dispatcher.emit_harness_prompt(self._context(), "do the thing")++ self.assertIsNone(result)+ # Not remembered, so a later healthy attempt for the same run can still echo.+ self.assertEqual(dispatcher._harness_prompt_echo_keys, set())diff --git a/tests/test_message_handler_harness_echo.py b/tests/test_message_handler_harness_echo.pynew file mode 100644index 000000000..d3c86919d--- /dev/null+++ b/tests/test_message_handler_harness_echo.py@@ -0,0 +1,159 @@+"""Turn-pipeline wiring for the Harness prompt echo (MESSAGE-DELIVERY-018).++The dispatcher decides WHETHER to echo and ``AgentService`` decides WHEN (at the+real turn start, once the runtime gate is held). These tests pin down WHAT the turn+pipeline stages: the stored prompt, past every ``suppress_delivery`` resolution, and+never for a human turn whose prompt is already the IM message on screen.+"""++import sys+import tempfile+import types+import unittest+from pathlib import Path+from unittest.mock import AsyncMock, Mock++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))++from core.message_output import HARNESS_PROMPT_ECHO_SPEC_KEY+from modules.im import MessageContext++# Reuses the isolated module loader (and controller/session stubs) from the+# typing test rather than a second copy of that 80-line import dance.+from tests.test_message_handler_typing import (+ MessageHandler,+ _StubController,+ _StubSessionHandler,+)+++def _build_handler():+ controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ controller.message_dispatcher = types.SimpleNamespace(emit_harness_prompt=AsyncMock(return_value="echo-1"))+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._admit_human_delivery = AsyncMock(return_value=False)+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(side_effect=lambda context, message, **_kw: message)+ return controller, handler+++def _scheduled_context(**spec):+ payload = {+ "task_trigger_kind": "scheduled",+ "task_execution_id": "run-echo",+ "task_definition_id": "task-echo",+ }+ payload.update(spec)+ return MessageContext(+ user_id="scheduled",+ channel_id="C1",+ message_id="scheduled:run-echo",+ platform="slack",+ platform_specific=payload,+ )+++def _staged_prompt(controller):+ _agent_name, request = controller.agent_service.requests[0]+ return (request.context.platform_specific or {}).get(HARNESS_PROMPT_ECHO_SPEC_KEY)+++class MessageHandlerHarnessEchoTests(unittest.IsolatedAsyncioTestCase):+ async def test_scheduled_turn_stages_the_raw_prompt_for_turn_start(self):+ """Scenario: MESSAGE-DELIVERY-018"""+ controller, handler = _build_handler()++ await handler.handle_scheduled_message(_scheduled_context(), "summarize open PRs")++ # The staged text is the RAW prompt: staging runs before+ # ``_prepend_message_metadata`` decorates the text sent to the backend.+ self.assertEqual(_staged_prompt(controller), "summarize open PRs")+ # And nothing is posted from here: the send waits for the runtime gate in+ # ``AgentService._begin_turn_status``, so a queued turn stays quiet.+ controller.message_dispatcher.emit_harness_prompt.assert_not_awaited()++ async def test_subagent_prefixed_prompt_is_staged_unstripped(self):+ """Scenario: MESSAGE-DELIVERY-018++ Subagent routing rewrites ``message`` to the prefix-stripped body before+ dispatch. The echo must still show the stored prompt — the prefix names which+ subagent was asked, and dropping it makes the visible trigger differ from the+ Workbench row (Codex P2).+ """+ controller, handler = _build_handler()+ with tempfile.TemporaryDirectory() as tmp:+ project = Path(tmp)+ agents_dir = project / ".codex" / "agents"+ agents_dir.mkdir(parents=True)+ (agents_dir / "echo-probe.toml").write_text(+ "\n".join(+ [+ 'name = "echo-probe"',+ 'description = "probe agent"',+ 'developer_instructions = "probe"',+ ]+ ),+ encoding="utf-8",+ )+ handler.session_handler.get_session_info = (+ lambda context, source="human": ("base-session", str(project), f"base-session:{project}")+ )++ await handler.handle_scheduled_message(+ _scheduled_context(), "echo-probe: audit the queue"+ )++ self.assertEqual(_staged_prompt(controller), "echo-probe: audit the queue")+ _agent_name, request = controller.agent_service.requests[0]+ self.assertEqual(request.subagent_name, "echo-probe")+ self.assertEqual(request.message, "audit the queue")++ async def test_human_turn_never_stages_a_prompt(self):+ controller, handler = _build_handler()++ await handler.handle_user_message(+ MessageContext(user_id="U1", channel_id="C1", message_id="m1", platform="slack"),+ "hello",+ )++ self.assertIsNone(_staged_prompt(controller))+ controller.message_dispatcher.emit_harness_prompt.assert_not_awaited()++ async def test_backgrounded_thread_resolution_is_visible_to_the_echo(self):+ """A session backgrounded via CLI must silence the echo too.++ ``suppress_delivery`` for an IM thread is resolved inside the turn pipeline+ from the thread's own session row, not by the caller that built the context,+ so staging earlier would hand the dispatcher a context that still looks+ deliverable.+ """+ controller, handler = _build_handler()+ controller.sessions = types.SimpleNamespace(+ find_session_for_anchor=lambda session_key, base_session_id: {"visibility": "background"}+ )+ handler.sessions = controller.sessions+ controller.resolve_vibe_agent_for_context = Mock(return_value=None)++ await handler.handle_scheduled_message(_scheduled_context(), "investigate the flake")++ _agent_name, request = controller.agent_service.requests[0]+ spec = request.context.platform_specific or {}+ self.assertEqual(spec.get(HARNESS_PROMPT_ECHO_SPEC_KEY), "investigate the flake")+ self.assertTrue(spec.get("suppress_delivery"))++ async def test_blank_prompt_stages_nothing(self):+ # A whitespace-only prompt never dispatches a turn, and it must not leave a+ # staged key behind for a later turn on the same context either.+ _controller, handler = _build_handler()+ context = _scheduled_context()++ handler._stage_harness_prompt_echo(context, " ")++ self.assertNotIn(HARNESS_PROMPT_ECHO_SPEC_KEY, context.platform_specific or {})+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex a1fe83ea6..3034d4b09 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -1010,6 +1010,113 @@ def test_build_context_assigns_hook_message_id() -> None:assert context.platform_specific["task_trigger_kind"] == "hook"+def test_build_context_carries_the_definition_name_for_display() -> None:+ """The prompt echo names what fired, so the label cannot be an opaque id."""++ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ )+ store = ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json"))+ service = ScheduledTaskService(controller=controller, store=store)+ target = parse_session_key("slack::channel::C123")++ store.get_task = (+ lambda task_id: SimpleNamespace(name="Daily digest", prompt="summarize open PRs")+ if task_id == "task-1"+ else None+ )+ store.get_watch_definition = (+ lambda definition_id: {"name": "Deploy watch", "message": "check the deploy"}+ if definition_id == "watch-1"+ else None+ )++ task_context = asyncio.run(service._build_context(target, execution_id="exec-1", task_id="task-1"))+ watch_context = asyncio.run(+ service._build_context(target, execution_id="exec-2", task_id="watch-1", trigger_kind="watch")+ )+ unknown_context = asyncio.run(service._build_context(target, execution_id="exec-3", task_id="gone"))+ anonymous_context = asyncio.run(service._build_context(target, execution_id="exec-4", trigger_kind="agent_run"))++ assert task_context.platform_specific["task_definition_name"] == "Daily digest"+ assert watch_context.platform_specific["task_definition_name"] == "Deploy watch"+ assert unknown_context.platform_specific["task_definition_name"] is None+ assert anonymous_context.platform_specific["task_definition_name"] is None++ # The definition's STORED instruction travels next to the name: a watch / hook /+ # webhook prompt appends machine-generated evidence (waiter stdout, a failure+ # report) that the outward echo must never publish, so it echoes this instead.+ assert task_context.platform_specific["harness_display_prompt"] == "summarize open PRs"+ assert watch_context.platform_specific["harness_display_prompt"] == "check the deploy"+ assert unknown_context.platform_specific["harness_display_prompt"] is None+ assert anonymous_context.platform_specific["harness_display_prompt"] is None+++def test_build_context_prefers_an_explicit_display_prompt_from_the_request() -> None:+ """A producer that composes the prompt itself can stamp the user-authored part.++ The definition lookup covers task/watch rows; a request whose prompt was composed+ somewhere else (a hook send with no definition row) can pass the instruction+ through its metadata instead, and that wins over the stored value.+ """++ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ )+ store = ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json"))+ service = ScheduledTaskService(controller=controller, store=store)+ store.get_task = lambda task_id: SimpleNamespace(name="Deploy watch", prompt="stored instruction")+ target = parse_session_key("slack::channel::C123")++ context = asyncio.run(+ service._build_context(+ target,+ execution_id="exec-1",+ task_id="task-1",+ trigger_kind="hook",+ metadata={"harness_display_prompt": "explicit instruction"},+ )+ )++ assert context.platform_specific["harness_display_prompt"] == "explicit instruction"+++def test_build_context_survives_a_store_that_cannot_name_the_definition() -> None:+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ )+ store = ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json"))+ service = ScheduledTaskService(controller=controller, store=store)++ def _boom(_identifier):+ raise RuntimeError("store unavailable")++ store.get_task = _boom+ target = parse_session_key("slack::channel::C123")++ context = asyncio.run(service._build_context(target, execution_id="exec-1", task_id="task-1"))++ # Display copy must never be able to fail the run it describes.+ assert context.platform_specific["task_definition_name"] is None+ assert context.platform_specific["harness_display_prompt"] is None+ assert context.platform_specific["task_definition_id"] == "task-1"++def test_build_context_separates_delivery_target_from_session_target() -> None:settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))controller = SimpleNamespace(@@ -8272,6 +8379,7 @@ def test_drain_requests_reserves_watch_create_per_run_before_session_validation("task_id": "watch-1","trigger_kind": "watch","agent_name": "release-reviewer",+ "metadata": {},"_capture_dispatch_result": True,}]@@ -8495,6 +8603,7 @@ def test_claimed_request_keeps_agent_identity_when_archive_lands_after_refresh("task_id": None,"trigger_kind": "hook","agent_name": "pm",+ "metadata": {},"_capture_dispatch_result": True,"agent_id": agent.id,}@@ -9434,6 +9543,88 @@ def test_execute_request_im_watch_steers_through_delivery_owner(assert handler_calls == []+def test_execute_request_forwards_request_metadata_into_the_context(+ monkeypatch,+ tmp_path,+) -> None:+ """A composed hook/watch/webhook/escalation prompt carries its user-authored part+ in the request metadata, and ``_build_context`` is the only reader — so+ ``_execute_request`` has to hand it over, exactly as the ``agent_run`` path already+ does. Without the forward the IM echo has no instruction to show and stays silent+ for every enqueued composed request (Codex P2)."""+ session_id = _make_avibe_session(+ monkeypatch,+ tmp_path,+ platform="slack",+ scope_type="channel",+ scope_native_id="C123",+ )+ contexts: list = []++ async def _submit_scheduled(sid, ctx, text, *, delivery_intent="steer"):+ contexts.append(ctx)++ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_a, **_k: None))+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ get_im_client_for_context=lambda _context: SimpleNamespace(+ should_use_thread_for_reply=lambda: True,+ should_use_thread_for_dm_session=lambda: False,+ ),+ session_turn_gate=SimpleNamespace(submit_scheduled=_submit_scheduled, in_flight={}),+ message_handler=SimpleNamespace(),+ )+ service = ScheduledTaskService(+ controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json"))+ )++ error = asyncio.run(+ service._execute_request(+ session_key="slack::channel::C123",+ post_to=None,+ deliver_key=None,+ prompt="check the deploy\n\nwaiter said: token=ghp_SECRET",+ execution_id="exec-metadata-1",+ trigger_kind="watch",+ session_id=session_id,+ metadata={"harness_display_prompt": "check the deploy"},+ )+ )++ assert error is None+ assert contexts[0].platform_specific["harness_display_prompt"] == "check the deploy"+++def test_claimed_request_hands_its_metadata_to_the_execution(monkeypatch, tmp_path: Path) -> None:+ """The enqueued-request lane is where hook / watch / webhook / escalation runs are+ executed, so the request's own metadata must reach ``_execute_request`` there."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ request_store = TaskExecutionStore()+ request = request_store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="check the deploy\n\nwaiter said: rows=42",+ metadata={"harness_display_prompt": "check the deploy"},+ )+ calls: list[dict[str, Any]] = []+ service = ScheduledTaskService(+ controller=SimpleNamespace(),+ store=ScheduledTaskStore(),+ request_store=request_store,+ )+ claimed = request_store.claim(request.id)+ assert claimed is not None++ async def _execute_request(**kwargs):+ calls.append(kwargs)+ return None++ service._execute_request = _execute_request # type: ignore[method-assign]+ asyncio.run(service._execute_claimed_request(claimed))++ assert len(calls) == 1+ assert calls[0]["metadata"] == {"harness_display_prompt": "check the deploy"}++def test_execute_request_avibe_falls_back_when_no_gate(monkeypatch, tmp_path) -> None:"""When the internal server hasn't published the gate yet(``session_turn_gate is None``), an avibe scheduled run falls back to thediff --git a/vibe/api.py b/vibe/api.pyindex 603a7a9a7..de4aa5555 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1016,6 +1016,17 @@ def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dic"default_cwd": config.runtime.default_cwd,"log_level": config.runtime.log_level,"resource_governance": config.runtime.resource_governance,+ # The config-only Harness knobs have no UI, but this payload IS the+ # deep-merge base every ``/api/config`` save builds on: a key omitted here+ # is absent from the merged payload, so ``from_payload`` rebuilds+ # ``RuntimeConfig`` with the dataclass default and silently reverts the+ # on-disk value (a ``harness_prompt_echo: false`` opt-out would come back+ # enabled after any unrelated settings save — Codex P1).+ "harness_prompt_echo": config.runtime.harness_prompt_echo,+ "harness_run_sweep_interval_seconds": config.runtime.harness_run_sweep_interval_seconds,+ "harness_run_orphan_grace_seconds": config.runtime.harness_run_orphan_grace_seconds,+ "harness_run_queued_ttl_seconds": config.runtime.harness_run_queued_ttl_seconds,+ "harness_run_hold_ttl_seconds": config.runtime.harness_run_hold_ttl_seconds,},"agents": {"opencode": config.agents.opencode.__dict__,diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 8d19fed02..e75cc2dbd 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -21,6 +21,16 @@},"harness": {"agentInitiatedContinuation": "Agent-initiated continuation",+ "promptEcho": {+ "scheduled": "⏰ Scheduled task",+ "watch": "👀 Watch",+ "webhook": "🔗 Webhook",+ "hook": "🪝 Hook",+ "agentRun": "🤖 Agent run",+ "generic": "⚙️ Background task",+ "named": "{label} · {name}",+ "truncated": "… (truncated)"+ },"watch": {"supervisorFailed": "Watch worker supervisor failed: {detail}","supervisorExitedDuringStartup": "Watch worker supervisor exited during startup.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex af20589c5..4ddcf6763 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -21,6 +21,16 @@},"harness": {"agentInitiatedContinuation": "Agent 主动发起的续接",+ "promptEcho": {+ "scheduled": "⏰ 定时任务",+ "watch": "👀 监听",+ "webhook": "🔗 Webhook",+ "hook": "🪝 Hook",+ "agentRun": "🤖 Agent 运行",+ "generic": "⚙️ 后台任务",+ "named": "{label} · {name}",+ "truncated": "…(已截断)"+ },"watch": {"supervisorFailed": "Watch 监控进程失败:{detail}","supervisorExitedDuringStartup": "Watch 监控进程在启动期间退出。",