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
fix(harness): capture result_text for every harness run (#1063)
Qi Qi0478824190a9
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex ff82dd7d0..6bee7634d 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -24,7 +24,12 @@ from core.message_mirror import (persist_agent_message,persist_silent_completion_marker,)-from core.message_output import MessageOutput, output_for_message+from core.message_output import (+ HARNESS_RUN_ID_TRIGGER_KINDS,+ HARNESS_TRIGGER_KINDS,+ MessageOutput,+ output_for_message,+)from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocksfrom core.run_settlement import (SETTLED_BY_STOPPED,@@ -1146,7 +1151,7 @@ class ConsolidatedMessageDispatcher:run_id = str(value or "").strip()if run_id and run_id not in run_ids:run_ids.append(run_id)- if not run_ids and payload.get("task_trigger_kind") == "agent_run":+ if not run_ids and payload.get("task_trigger_kind") in HARNESS_RUN_ID_TRIGGER_KINDS:run_ids = _coalesced_task_execution_ids(payload)if not run_ids:return@@ -1631,10 +1636,14 @@ class ConsolidatedMessageDispatcher:f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}")terminal_status = None- if (- canonical_type == "result"- and (context.platform_specific or {}).get("task_trigger_kind") == "agent_run"- ):+ # These two branches are one rule and must be edited as a pair:+ # the ``elif`` is the negation of the ``if``. A terminal result on+ # a Harness run takes the rich recorder (output ledger + settlement+ # + ``result_text``); everything else falls back to the legacy+ # message recorder, except an intermediate message on a Harness run,+ # which belongs to no output ledger entry and is recorded by neither.+ suppressed_trigger_kind = (context.platform_specific or {}).get("task_trigger_kind")+ if canonical_type == "result" and suppressed_trigger_kind in HARNESS_TRIGGER_KINDS:self._record_suppressed_agent_run_terminal_result(context,recorded_text,@@ -1643,7 +1652,7 @@ class ConsolidatedMessageDispatcher:terminal_error=terminal_error,output_semantics=output_semantics,)- elif canonical_type == "result" or (context.platform_specific or {}).get("task_trigger_kind") != "agent_run":+ elif canonical_type == "result" or suppressed_trigger_kind not in HARNESS_TRIGGER_KINDS:self._record_suppressed_run_message(context,recorded_text,diff --git a/core/message_output.py b/core/message_output.pyindex 887ecd066..27a0a9902 100644--- a/core/message_output.py+++ b/core/message_output.py@@ -12,6 +12,22 @@ from typing import Any, Mappingfrom core.run_settlement import SETTLED_BY_STOPPED+# Every trigger kind whose dispatch created an ``agent_runs`` row. Scheduled+# tasks, watches, webhooks, hooks and recovered Activities are all Harness runs+# and must reach the same result recorders as a direct ``vibe agent run``.+# Gating those recorders on ``agent_run`` alone is why every ``scheduled`` /+# ``watch`` row carries an empty ``result_text``.+HARNESS_TRIGGER_KINDS: frozenset[str] = frozenset(+ {"agent_run", "scheduled", "watch", "webhook", "hook", "activity_recovery"}+)++# The subset whose ``task_execution_id`` *is* the run id. ``activity_recovery``+# is deliberately excluded: it builds its context with a synthetic+# ``activity:<backend>:<id>`` execution id, and its real run ids travel on the+# Activity completion output instead. Reading its ``task_execution_id`` as a run+# id addresses a write to a row that cannot exist.+HARNESS_RUN_ID_TRIGGER_KINDS: frozenset[str] = HARNESS_TRIGGER_KINDS - {"activity_recovery"}+@dataclass(frozen=True)class MessageOutput:@@ -40,7 +56,7 @@ class MessageOutput:trigger_kind = str(spec.get("task_trigger_kind") or "").strip()inferred_run_id = (str(spec.get("task_execution_id") or "").strip()- if trigger_kind == "agent_run"+ if trigger_kind in HARNESS_RUN_ID_TRIGGER_KINDSelse "")values: dict[str, Any] = {diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 4b4c89319..a6afa8f01 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -2576,8 +2576,7 @@ class ScheduledTaskService:result_text = self._fallback_callback_result(run, status=status)return result_text.strip()- @staticmethod- def _fallback_callback_result(run: dict[str, Any], *, status: str) -> str:+ def _fallback_callback_result(self, run: dict[str, Any], *, status: str) -> str:parts: list[str] = []if run.get("error"):parts.append(f"Error: {run['error']}")@@ -2588,9 +2587,9 @@ class ScheduledTaskService:if parts:return "\n\n".join(part.strip() for part in parts if part and part.strip())if status == "canceled":- return "The run was canceled before producing a result."+ return self._t("harness.run.fallbackResult.canceled")if status == "failed":- return "The run failed before producing a result."+ return self._t("harness.run.fallbackResult.failed")return ""def _execution_lock_key(self, request: TaskExecutionRequest) -> Optional[str]:diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 4b545d825..ee32e30c1 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -6,7 +6,13 @@ from typing import Callable, Optionalfrom core.agent_auth_service import classify_auth_errorfrom core.backend_failure import backend_failure_notification_output, emit_backend_failure-from core.message_output import MessageOutput, stop_output_for, terminal_output_for, terminal_turn_output+from core.message_output import (+ HARNESS_RUN_ID_TRIGGER_KINDS,+ MessageOutput,+ stop_output_for,+ terminal_output_for,+ terminal_turn_output,+)from core.reply_enhancer import strip_silent_blocksfrom core.session_activities import SessionActivity, activity_completion_outputfrom modules.claude_sdk_compat import TextBlock, ToolUseBlock, is_claude_sdk_buffer_error@@ -1702,7 +1708,7 @@ class ClaudeAgent(BaseAgent):pending = self._pending_requests.get(composite_key) or []source = getattr(pending[0], "context", None) if pending else contextspec = getattr(source, "platform_specific", None) or {}- if spec.get("task_trigger_kind") != "agent_run":+ if spec.get("task_trigger_kind") not in HARNESS_RUN_ID_TRIGGER_KINDS:return []run_ids: list[str] = []primary = str(spec.get("task_execution_id") or "").strip()diff --git a/storage/background.py b/storage/background.pyindex 5dce6d24e..05f5257f3 100644--- a/storage/background.py+++ b/storage/background.py@@ -1895,6 +1895,7 @@ class SQLiteBackgroundTaskStore:raise ValueError("output_id is required")recorded = Falseterminal_transition = False+ text_backfilled = Falserun_payload: Optional[dict[str, Any]] = Nonerow_to_publish = Nonewith self.engine.begin() as conn:@@ -1990,8 +1991,59 @@ class SQLiteBackgroundTaskStore:.values(**terminal_values))terminal_transition = bool(transition.rowcount)+ if not terminal_transition:+ # The row was already terminal, so the guarded UPDATE above+ # matched nothing and ``result_text`` -- the one terminal+ # result callbacks read -- would stay empty forever. Harness+ # rows reach this state routinely: the scheduler settles a+ # scheduled/watch run at dispatch, long before the agent's+ # result is delivered. Backfill the text (and the error where+ # none was recorded) with its own emptiness guard so a real+ # terminal transition's values are never overwritten, and+ # leave ``status`` / ``completed_at`` alone so settlement+ # timing is unchanged.+ stored_status = normalize_run_status(row["status"])+ incoming_status = normalize_run_status(effective_terminal_status)+ # Backfill only when the stored outcome and the delivered+ # outcome AGREE. This repairs the case PR1 exists for -- a row+ # the scheduler settled at dispatch, whose text never landed+ # because the terminal UPDATE is scoped to queued|running --+ # and refuses every disagreement.+ #+ # An earlier revision enumerated which pairs were unsafe+ # (refuse cancellations; allow error only onto ``failed``).+ # Review found two contradictions that enumeration missed, in+ # both directions: a late failure landing on a ``succeeded``+ # row, then a late success body landing on a swept ``failed``+ # row. The second is the more instructive one -- the callback+ # would have reported "the report, actually fine" for a run+ # recorded as failed, because ``_build_callback_message``+ # prefers ``result_text`` over the failure fallback.+ #+ # Equality is used instead of a longer list because it is+ # total: it cannot miss a pair. A genuine outcome+ # disagreement means the stored status is wrong, and settling+ # the real terminal result is PR7's job -- PR1 must not paper+ # over it by writing text that contradicts the status.+ if stored_status == incoming_status:+ if terminal_result_text.strip():+ filled = conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .where(func.coalesce(agent_runs.c.result_text, "") == "")+ .values(result_text=terminal_result_text, updated_at=now)+ )+ text_backfilled = bool(filled.rowcount)+ if effective_terminal_error is not None:+ filled_error = conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .where(func.coalesce(agent_runs.c.error, "") == "")+ .values(error=str(effective_terminal_error), updated_at=now)+ )+ text_backfilled = text_backfilled or bool(filled_error.rowcount)- if payload_changed or terminal_transition:+ if payload_changed or terminal_transition or text_backfilled:row_to_publish = dict(conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)@@ -2004,6 +2056,10 @@ class SQLiteBackgroundTaskStore:return {"recorded": recorded,"terminal_transition": terminal_transition,+ # True when an already-terminal row was given its missing terminal+ # text/error. Distinct from ``terminal_transition`` on purpose: no+ # status changed, so callers must not read it as a settlement.+ "text_backfilled": text_backfilled,"run": run_payload,}diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex a01f4c008..5c0b58f33 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -294,6 +294,62 @@ scenarios:layer: contractbackend: sharedtest: tests/test_agent_stop_settlement.py::AgentStopSettlementTests::test_no_backend_stop_uses_the_terminal_turn_default+ - id: HFR-041+ name: every Harness run records its terminal result text, not just agent_run+ status: covered+ kind: failure+ layer: contract+ backend: shared+ test: tests/test_message_dispatcher_scheduled.py::HarnessRunResultTextTests::test_scheduled_run_records_result_text_on_an_already_terminal_row+ - id: HFR-042+ name: an already-terminal run is given its missing result text without re-settling+ status: covered+ kind: safety+ layer: contract+ backend: shared+ test: tests/test_message_dispatcher_scheduled.py::HarnessRunResultTextTests::test_terminal_backfill_never_overwrites_a_real_terminal_result+ - id: HFR-043+ name: a recovered Activity in a suppressed Session records the result on its real Run+ status: covered+ kind: failure_recovery+ layer: contract+ backend: shared+ test: tests/test_message_dispatcher_scheduled.py::HarnessRunResultTextTests::test_recovered_activity_in_a_suppressed_session_records_result_on_its_run+ - id: HFR-044+ name: a Harness turn attributes its background Activity to that turn's Run+ status: covered+ kind: failure_recovery+ layer: contract+ backend: claude+ test: tests/test_claude_agent_initiated_turn.py::ActivityRunAttributionTests::test_scheduled_turn_attributes_its_activity_to_its_run+ - id: HFR-045+ name: a late result never dresses up a canceled run+ status: covered+ kind: safety+ layer: contract+ backend: shared+ test: tests/test_message_dispatcher_scheduled.py::HarnessRunResultTextTests::test_backfill_refuses_a_canceled_run+ - id: HFR-046+ name: a late failure never attaches an error to a succeeded run+ status: covered+ kind: safety+ layer: contract+ backend: shared+ test: tests/test_message_dispatcher_scheduled.py::HarnessRunResultTextTests::test_backfill_refuses_an_error_on_a_succeeded_run+ - id: HFR-047+ name: a failed harness run still receives its diagnostic result text+ status: covered+ kind: failure+ layer: contract+ backend: shared+ test: tests/test_message_dispatcher_scheduled.py::HarnessRunResultTextTests::test_backfill_still_diagnoses_a_failed_run+ - id: HFR-048+ name: a late success body never lands on a swept failed run+ status: covered+ kind: safety+ layer: contract+ backend: shared+ test: tests/test_message_dispatcher_scheduled.py::HarnessRunResultTextTests::test_backfill_refuses_success_text_on_a_failed_runmanual_evidence:- local Incus backend process death after prompt acceptance- local Incus controller restart with persisted queued successordiff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.pyindex 8ae08c359..50486a828 100644--- a/tests/test_claude_agent_initiated_turn.py+++ b/tests/test_claude_agent_initiated_turn.py@@ -2502,3 +2502,85 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):if __name__ == "__main__": # pragma: no coverunittest.main()+++class ActivityRunAttributionTests(unittest.IsolatedAsyncioTestCase):+ """HFR-044 (re-validates HFR-031 / HFR-032): the fifth trigger-kind gate.++ A background Activity started inside a Harness turn must carry that turn's+ run ids. Those ids are the ONLY route by which a later recovered-Activity+ completion can find its run — its own context carries a synthetic+ ``activity:<backend>:<id>`` execution id, not a run id.+ """++ @staticmethod+ def _pending(**platform_specific):+ return SimpleNamespace(+ context=SimpleNamespace(platform_specific=dict(platform_specific))+ )++ async def test_scheduled_turn_attributes_its_activity_to_its_run(self):+ agent, _service = _build_agent()+ composite_key = "session-scheduled-activity:/tmp/work"+ agent._pending_requests[composite_key] = [+ self._pending(+ task_trigger_kind="scheduled",+ task_execution_id="run-scheduled",+ coalesced_queue={"execution_ids": ["run-scheduled", "run-coalesced"]},+ )+ ]++ run_ids = agent._activity_run_ids(+ composite_key,+ SimpleNamespace(platform_specific={}),+ )++ self.assertEqual(run_ids, ["run-scheduled", "run-coalesced"])++ async def test_watch_turn_attributes_its_activity_to_its_run(self):+ agent, _service = _build_agent()+ composite_key = "session-watch-activity:/tmp/work"+ agent._pending_requests[composite_key] = [+ self._pending(task_trigger_kind="watch", task_execution_id="run-watch")+ ]++ run_ids = agent._activity_run_ids(+ composite_key,+ SimpleNamespace(platform_specific={}),+ )++ self.assertEqual(run_ids, ["run-watch"])++ async def test_recovered_activity_execution_id_is_not_read_as_a_run_id(self):+ """``activity_recovery`` is excluded on purpose: its execution id is a+ synthetic Activity id, so attributing it as a run id would address every+ later write to a row that cannot exist."""+ agent, _service = _build_agent()+ composite_key = "session-activity-recovery:/tmp/work"+ agent._pending_requests[composite_key] = [+ self._pending(+ task_trigger_kind="activity_recovery",+ task_execution_id="activity:claude:act-1",+ )+ ]++ run_ids = agent._activity_run_ids(+ composite_key,+ SimpleNamespace(platform_specific={}),+ )++ self.assertEqual(run_ids, [])++ async def test_ordinary_user_turn_attributes_no_run(self):+ agent, _service = _build_agent()+ composite_key = "session-user-turn:/tmp/work"+ agent._pending_requests[composite_key] = [+ self._pending(task_execution_id="not-a-run")+ ]++ run_ids = agent._activity_run_ids(+ composite_key,+ SimpleNamespace(platform_specific={}),+ )++ self.assertEqual(run_ids, [])diff --git a/tests/test_i18n_key_parity.py b/tests/test_i18n_key_parity.pynew file mode 100644index 000000000..97bc51004--- /dev/null+++ b/tests/test_i18n_key_parity.py@@ -0,0 +1,50 @@+"""Backend i18n bundles must declare the same key set in every language.++``vibe/i18n/__init__.py`` falls back to English for a missing key, so a+zh-only gap degrades silently: the user sees English mixed into an otherwise+translated message and nothing fails. Adding a key to one file only was+uncatchable before this test.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++I18N_DIR = Path(__file__).resolve().parents[1] / "vibe" / "i18n"+++def _flatten(payload: object, prefix: str = "") -> set[str]:+ if not isinstance(payload, dict):+ return {prefix}+ keys: set[str] = set()+ for key, value in payload.items():+ path = f"{prefix}.{key}" if prefix else str(key)+ keys |= _flatten(value, path)+ return keys+++def _load(lang: str) -> dict:+ with (I18N_DIR / f"{lang}.json").open(encoding="utf-8") as handle:+ return json.load(handle)+++def test_en_and_zh_declare_the_same_keys() -> None:+ en_keys = _flatten(_load("en"))+ zh_keys = _flatten(_load("zh"))++ assert sorted(en_keys - zh_keys) == [], "keys missing from zh.json"+ assert sorted(zh_keys - en_keys) == [], "keys missing from en.json"+++def test_every_shipped_language_matches_the_english_key_set() -> None:+ """Guards the same rule for any language file added later."""+ en_keys = _flatten(_load("en"))+ languages = sorted(path.stem for path in I18N_DIR.glob("*.json"))++ assert "en" in languages and "zh" in languages+ for lang in languages:+ assert _flatten(_load(lang)) == en_keys, f"{lang}.json key set diverged"diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex 1d47d4c49..ba8c493c6 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -1220,3 +1220,341 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(len(controller.im_client.sent), 3)self.assertEqual("".join(text for _, _, text in controller.im_client.sent), long_text)self.assertEqual(controller.session_handler.calls, [("C123", None, "bot-msg-1")])+++class HarnessRunResultTextTests(unittest.IsolatedAsyncioTestCase):+ """P2: every harness run must record ``result_text``, not just ``agent_run``.++ Scenario coverage: HFR-041 (result text is recorded), HFR-042 (the backfill+ is guarded), HFR-043 (recovered Activity attribution). Re-validates HFR-030+ (which recorder a terminal output lands in) and MESSAGE-DELIVERY-005 (a Run's+ output ledger vs. its one terminal result).+ """++ @staticmethod+ def _settled_scheduled_run(task_id: str = "task-daily-report"):+ """A ``scheduled`` run the scheduler already marked terminal at dispatch.++ That premature settlement is P1; it is the state every live+ ``scheduled``/``watch`` row is in by the time its result is delivered,+ so it is the state PR1 has to write ``result_text`` into.+ """+ from core.scheduled_tasks import TaskExecutionStore++ store = TaskExecutionStore()+ request = store.enqueue_task_run(task_id)+ assert store.claim(request.id) is not None+ store.complete(request, ok=True)+ return store, request++ async def test_scheduled_run_records_result_text_on_an_already_terminal_row(self):+ """HFR-041."""+ store, request = self._settled_scheduled_run()+ dispatched = store.get_run(request.id)+ self.assertEqual(dispatched["status"], "succeeded")+ self.assertFalse(dispatched["result_text"])++ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "task_trigger_kind": "scheduled",+ "task_execution_id": request.id,+ },+ )++ message_id = await dispatcher.emit_agent_message(context, "result", "daily report body")++ self.assertEqual(message_id, "bot-msg-1")+ settled = store.get_run(request.id)+ self.assertEqual(settled["result_text"], "daily report body")+ # The output ledger is the weaker assertion: it lands from the unguarded+ # payload UPDATE and would pass even with ``result_text`` still empty.+ outputs = (settled["result_payload"] or {}).get("outputs") or []+ self.assertEqual([entry["text"] for entry in outputs], ["daily report body"])+ # Settlement timing is unchanged: the backfill writes text, not status.+ self.assertEqual(settled["status"], "succeeded")+ self.assertEqual(settled["completed_at"], dispatched["completed_at"])++ async def test_watch_run_records_result_text_on_an_already_terminal_row(self):+ """HFR-041: the 67 live ``run_type='watch'`` rows are the same defect."""+ from core.scheduled_tasks import TaskExecutionStore++ store = TaskExecutionStore()+ request = store.enqueue_hook_send(+ session_key="slack::channel::C123",+ prompt="watch fired",+ run_type="watch",+ )+ self.assertIsNotNone(store.claim(request.id))+ store.complete(request, ok=True)+ self.assertFalse(store.get_run(request.id)["result_text"])++ dispatcher = ConsolidatedMessageDispatcher(_StubController())+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "task_trigger_kind": "watch",+ "task_execution_id": request.id,+ },+ )++ await dispatcher.emit_agent_message(context, "result", "watch follow-up body")++ self.assertEqual(store.get_run(request.id)["result_text"], "watch follow-up body")++ async def test_terminal_backfill_never_overwrites_a_real_terminal_result(self):+ """HFR-042. The backfill is guarded: only an empty ``result_text`` is filled."""+ from core.scheduled_tasks import TaskExecutionStore++ store = TaskExecutionStore()+ request = store.enqueue_task_run("task-guarded")+ self.assertIsNotNone(store.claim(request.id))+ sqlite_store = store._sqlite+ self.assertIsNotNone(sqlite_store)+ first = sqlite_store.record_run_output(+ request.id,+ output_id="terminal",+ text="the real terminal result",+ terminal_status="succeeded",+ )+ self.assertTrue(first["terminal_transition"])+ self.assertFalse(first["text_backfilled"])++ second = sqlite_store.record_run_output(+ request.id,+ output_id="late",+ text="a later output",+ terminal_status="succeeded",+ )++ self.assertFalse(second["terminal_transition"])+ self.assertFalse(second["text_backfilled"])+ self.assertEqual(store.get_run(request.id)["result_text"], "the real terminal result")++ async def _settled_run(self, task_id, *, terminal_status, error=None, text=""):+ """A harness run already settled by someone other than this delivery."""+ from core.scheduled_tasks import TaskExecutionStore++ store = TaskExecutionStore()+ request = store.enqueue_task_run(task_id)+ self.assertIsNotNone(store.claim(request.id))+ sqlite_store = store._sqlite+ self.assertIsNotNone(sqlite_store)+ seed = sqlite_store.record_run_output(+ request.id, output_id="seed", text=text, terminal_status=terminal_status, error=error+ )+ self.assertTrue(seed["terminal_transition"])+ return store, sqlite_store, request++ async def test_backfill_refuses_a_canceled_run(self):+ """HFR-045. A cancellation is a decision, not a missing field.++ Without this guard a late success body lands on a ``canceled`` row, and+ because ``_build_callback_message`` prefers ``result_text`` over the+ "canceled before producing a result" fallback, the user is told the run+ produced a result after they cancelled it.+ """+ store, sqlite_store, request = await self._settled_run(+ "task-canceled", terminal_status="canceled"+ )+ late = sqlite_store.record_run_output(+ request.id, output_id="late", text="daily report body", terminal_status="succeeded"+ )+ self.assertFalse(late["text_backfilled"])+ row = store.get_run(request.id)+ self.assertEqual(row["status"], "canceled")+ self.assertFalse((row["result_text"] or "").strip())++ async def test_backfill_refuses_an_error_on_a_succeeded_run(self):+ """HFR-046. ``error`` is a verdict, not description.++ A scheduled row settles ``succeeded`` at dispatch (P1). A later failing+ delivery must not produce a succeeded-with-an-error record; settling the+ real outcome is PR7's job.+ """+ store, sqlite_store, request = await self._settled_run(+ "task-succeeded", terminal_status="succeeded"+ )+ late = sqlite_store.record_run_output(+ request.id, output_id="late", text="", terminal_status="failed", error="backend blew up"+ )+ self.assertFalse(late["text_backfilled"])+ row = store.get_run(request.id)+ self.assertEqual(row["status"], "succeeded")+ self.assertFalse((row["error"] or "").strip())++ async def test_backfill_still_diagnoses_a_failed_run(self):+ """HFR-047. Agreement still repairs, so the rule does not cost PR1 its point.++ A ``failed`` row receiving a ``failed`` delivery agrees, so it still gets+ its diagnostic text and keeps the error it settled with.+ """+ store, sqlite_store, request = await self._settled_run(+ "task-failed", terminal_status="failed", error="original error"+ )+ late = sqlite_store.record_run_output(+ request.id, output_id="late", text="what the agent managed to say", terminal_status="failed"+ )+ self.assertTrue(late["text_backfilled"])+ row = store.get_run(request.id)+ self.assertEqual(row["status"], "failed")+ self.assertEqual(row["result_text"], "what the agent managed to say")+ self.assertEqual(row["error"], "original error")++ async def test_backfill_refuses_success_text_on_a_failed_run(self):+ """HFR-048. The inverse of HFR-046, and the pair enumeration missed.++ ``sweep_stale_runs`` terminalizes an orphaned run ``failed``; the agent+ is still alive and delivers a successful result afterwards. Without the+ agreement rule the row keeps ``failed`` while ``_build_callback_message``+ reports the success body, so the user is told the report is fine for a+ run recorded as failed with "owner vanished".+ """+ store, sqlite_store, request = await self._settled_run(+ "task-swept", terminal_status="failed", error="swept: owner vanished"+ )+ late = sqlite_store.record_run_output(+ request.id,+ output_id="late",+ text="the report, actually fine",+ terminal_status="succeeded",+ )+ self.assertFalse(late["text_backfilled"])+ row = store.get_run(request.id)+ self.assertEqual(row["status"], "failed")+ self.assertFalse((row["result_text"] or "").strip())+ self.assertEqual(row["error"], "swept: owner vanished")++ async def test_scheduled_result_takes_the_rich_recorder_not_the_legacy_one(self):+ """HFR-030: the widened gate moves harness results onto the output ledger.++ Delivered (visible) variant of ``test_visible_agent_run_result_marks_run_terminal``.+ """+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "task_trigger_kind": "scheduled",+ "task_execution_id": "run-scheduled",+ },+ )+ calls = []++ class _Store:+ def get_run(self, run_id):+ return {"status": "succeeded"}++ def record_run_output(self, run_id, **kwargs):+ calls.append((run_id, kwargs))++ def close(self):+ pass++ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):+ message_id = await dispatcher.emit_agent_message(context, "result", "visible scheduled result")++ self.assertEqual(message_id, "bot-msg-1")+ self.assertEqual(len(calls), 1)+ self.assertEqual(calls[0][0], "run-scheduled")+ self.assertEqual(calls[0][1]["text"], "visible scheduled result")+ self.assertEqual(calls[0][1]["terminal_status"], "succeeded")++ async def test_suppressed_scheduled_result_takes_the_rich_recorder_not_the_legacy_one(self):+ """Suppressed variant. The ``elif`` below the widened gate is its negation,+ so widening one without the other would silently reroute this result."""+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "suppress_delivery": True,+ "task_trigger_kind": "scheduled",+ "task_execution_id": "run-scheduled",+ },+ )+ calls = []++ class _Store:+ def get_run(self, run_id):+ return {"status": "succeeded"}++ def record_run_output(self, run_id, **kwargs):+ calls.append(("output", run_id, kwargs))++ def record_run_message(self, run_id, **kwargs):+ calls.append(("legacy", run_id, kwargs))++ def close(self):+ pass++ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()):+ await dispatcher.emit_agent_message(context, "result", "private scheduled result")++ self.assertEqual([call[0] for call in calls], ["output"])+ self.assertEqual(calls[0][2]["terminal_status"], "succeeded")++ async def test_recovered_activity_in_a_suppressed_session_records_result_on_its_run(self):+ """HFR-043. ``activity_recovery`` carries a synthetic ``activity:<backend>:<id>``+ execution id, not a run id. Excluded from the widened set it would fall to+ the legacy recorder, which addresses ``record_run_message`` to that synthetic+ id, finds no row, and returns — losing the result with no exception and no+ log line. Its real run ids ride on the Activity completion output instead.+ """+ from core.session_activities import SessionActivity, activity_completion_output+ from core.scheduled_tasks import TaskExecutionStore++ store = TaskExecutionStore()+ request = store.enqueue_task_run("task-with-activity")+ self.assertIsNotNone(store.claim(request.id))++ activity = SessionActivity(+ id="act-1",+ backend="claude",+ runtime_key="runtime-1",+ session_id="ses-1",+ kind="task",+ status="completed",+ run_id=request.id,+ metadata={"run_ids": [request.id]},+ )+ controller = _StubController()+ controller.agent_service = SimpleNamespace(+ activities=SimpleNamespace(has_blocking_run_activity=lambda run_id: False),+ emit_matches_runtime_turn=lambda context: False,+ release_runtime_turn=lambda context: None,+ )+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "suppress_delivery": True,+ "task_trigger_kind": "activity_recovery",+ "task_execution_id": f"activity:claude:{activity.id}",+ },+ )++ await dispatcher.emit_agent_message(+ context,+ "result",+ "recovered background result",+ output=activity_completion_output(activity, detached=True, completes_turn=False),+ )++ settled = store.get_run(request.id)+ # Asserting only "the call did not raise" passes against the broken path.+ self.assertEqual(settled["result_text"], "recovered background result")+ self.assertEqual(settled["status"], "succeeded")+ self.assertIsNone(store.get_run(f"activity:claude:{activity.id}"))diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex ef2f38704..d71488b60 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -47,6 +47,10 @@"orphaned": "[Avibe Harness] This run was left marked as running with nothing executing it, most likely because the service restarted while it was in flight. Any output it had already sent is still kept on the run. Run it again if the work still needs doing.","transportUnavailable": "[Avibe Harness] This run stayed queued because its chat platform never reconnected, so it was never delivered. Check the platform connection in Settings, then trigger it again.","queueHoldExpired": "[Avibe Harness] This run stayed queued behind its session's turn queue for too long and was never started. Check whether that session has a stuck turn, then trigger this run again."+ },+ "fallbackResult": {+ "canceled": "The run was canceled before producing a result.",+ "failed": "The run failed before producing a result."}}},diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 3a580f7e8..a7e22312f 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -47,6 +47,10 @@"orphaned": "[Avibe Harness] 本次 run 一直标记为 running,但已经没有任何执行在推进它,通常是服务在它执行途中重启导致的。它此前已经发出的输出仍会保留在这次 run 上。如果这项工作仍需完成,请重新运行。","transportUnavailable": "[Avibe Harness] 本次 run 一直排队等待,因为它对应的聊天平台始终没有重新连接,消息也就无法送达。请在设置中检查该平台连接,然后重新触发。","queueHoldExpired": "[Avibe Harness] 本次 run 在所属 session 的 turn 队列后面排队过久,始终没有开始执行。请检查该 session 是否有卡住的 turn,然后重新触发这次 run。"+ },+ "fallbackResult": {+ "canceled": "本次 run 在产出结果前被取消,因此没有结果。",+ "failed": "本次 run 在产出结果前失败,因此没有结果。"}}},