Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(harness): separate async callback ownership (#1107)

Call White4eb4420eed37
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 3e9670dbf..bdc94100a 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -1566,28 +1566,6 @@ class TaskExecutionStore:
return run
return None
- def find_explicit_session_delivery(
- self,
- *,
- parent_run_id: str,
- session_id: str,
- ) -> Optional[dict[str, Any]]:
- if self._sqlite is not None:
- return self._sqlite.find_explicit_session_delivery(
- parent_run_id=parent_run_id,
- session_id=session_id,
- )
- for run in self._list_file_runs():
- if (
- run.get("request_type") == "agent_run"
- and run.get("source_kind") == "agent"
- and run.get("parent_run_id") == parent_run_id
- and run.get("session_id") == session_id
- and str(run.get("message") or "").strip()
- ):
- return run
- return None
-
def settle_deferred_run(
self,
run_id: str,
@@ -2962,15 +2940,6 @@ class ScheduledTaskService:
if not callback_session_id:
return None
run_id = str(run.get("id") or "")
- explicit_delivery = self.request_store.find_explicit_session_delivery(
- parent_run_id=run_id,
- session_id=callback_session_id,
- )
- if explicit_delivery is not None:
- # A lane may explicitly report to its callback Session before its
- # terminal result. That accepted child Run is the callback delivery;
- # do not echo the same final through the automatic fallback too.
- return TaskExecutionRequest.from_dict(explicit_delivery)
status = _normalize_requested_run_status(run.get("status")) or str(
run.get("status") or ""
)
diff --git a/core/services/agent_graph.py b/core/services/agent_graph.py
index c1e01c082..61fcfc88d 100644
--- a/core/services/agent_graph.py
+++ b/core/services/agent_graph.py
@@ -21,7 +21,8 @@ Graph semantics (all from existing columns):
- **Spawn edge** (caller → callee): runs with ``source_kind='agent'`` and
``source_actor`` set, aggregated per (caller session, callee session).
- **Callback edge** (callee → report target): runs with ``callback_session_id``
- set; status from ``callback_status``.
+ set; status from ``callback_status``. Its delivery child has
+ ``source_kind='callback'`` and never suppresses an agent-authored spawn.
- **Trigger edge** (definition → carrying session): runs with
``run_type in ('scheduled','watch')`` grouped by ``definition_id``.
@@ -487,26 +488,13 @@ def _build_edges(
prev = _parse_iso(existing)
return prev is None or prev < cand
- # Callback target per run id — an explicit callback-delivery run
- # (source_kind='agent', parent_run_id → the delegated run) reports INTO the
- # delegated run's callback session. Such a report row must NOT be counted as
- # a spawn (it would draw a misleading callee→caller edge and make the caller
- # look "started by" the callee). Detect it: the run's session equals its
- # parent run's callback target.
- callback_target_by_run: dict[str, str] = {}
- for runs in runs_by_session.values():
- for run in runs:
- if run.get("callback_session_id"):
- callback_target_by_run[run["id"]] = run["callback_session_id"]
-
for session_id, runs in runs_by_session.items():
for run in runs:
created = run.get("created_at")
- parent = run.get("parent_run_id")
- is_callback_delivery = bool(parent) and callback_target_by_run.get(parent) == session_id
- # spawn: caller (source_actor) → this session (excluding callback-
- # delivery reports, which run in the caller's session by design)
- if run.get("source_kind") == "agent" and run.get("source_actor") and not is_callback_delivery:
+ # Callback deliveries use source_kind='callback'. Every agent child
+ # remains independent delegation, even when it targets the parent
+ # run's callback session.
+ if run.get("source_kind") == "agent" and run.get("source_actor"):
key = (run["source_actor"], session_id)
agg = spawn.setdefault(key, {"run_count": 0, "last_run_id": None, "last_at": None})
agg["run_count"] += 1
diff --git a/docs/plans/agents-run-graph-contract.md b/docs/plans/agents-run-graph-contract.md
index 494504a41..c8e23be4d 100644
--- a/docs/plans/agents-run-graph-contract.md
+++ b/docs/plans/agents-run-graph-contract.md
@@ -72,6 +72,11 @@ Amendments (orchestrator-approved):
(together with their trigger edges); a "show disabled" switch in the canvas
LEGEND reveals them (dimmed + disabled marker per A10). Client-side only;
payload unchanged.
+- **A12 (2026-07-30, callback ownership correction)**: only child Runs with
+ `source_kind='callback'` are callback deliveries. An agent-authored child
+ remains an independent spawn even when it targets the parent Run's callback
+ Session; parent/target coincidence never erases that lineage. This is
+ read-only classification: historical rows are never reset or replayed.
- **A7 (2026-07-23, PR #956 review)**: graph endpoint path renamed
`/api/agents/graph` → **`/api/agents-graph`**. Rationale: `/api/agents/…`
is the agent-resource namespace and agent names are user-creatable slugs —
@@ -185,7 +190,8 @@ Semantics:
- Edge node references: sessions by `session_id`; trigger chips by
`def:<definition_id>`.
- `spawn` edges: aggregated per (caller session → callee session) from runs
- with `source_kind='agent'` and `source_actor` set.
+ with `source_kind='agent'` and `source_actor` set. Callback deliveries use
+ `source_kind='callback'` and never enter spawn aggregation.
- `callback` edges: emitted when `callback_session_id` is set **and**
`callback_status` is non-null (amendment A4 — sync runs that only record a
return route draw nothing). Target may equal the spawn caller; the client
diff --git a/docs/plans/full-duplex-sessions.md b/docs/plans/full-duplex-sessions.md
index 7e9bc9dc1..91b2ed8de 100644
--- a/docs/plans/full-duplex-sessions.md
+++ b/docs/plans/full-duplex-sessions.md
@@ -102,10 +102,11 @@ No visible wrapper text is added. Intermediate output remains in the ledger and
the originating Session; it does not enqueue callback work. After the parent Run
reaches its one idempotent terminal transition, callback policy enqueues exactly
one turn containing the terminal `result_text`. Callback turns are deduplicated
-by Run lineage. An explicit child Agent Run delivered to the callback Session
-satisfies that policy, so the automatic fallback does not echo the same report.
-Parent `callback_status` stays pending while the parent Run is active and settles
-once against that single delivery.
+by Run lineage. An explicit child Agent Run delivered to the callback Session is
+a separate durable object with its own queue position, lineage, and callback
+policy; it never satisfies or inherits the parent's automatic callback. Parent
+`callback_status` stays pending while the parent Run is active and settles once
+against the callback Run created only from the parent's terminal result.
If a Run fails or is canceled after recording partial outputs, its callback
Session receives one terminal failure/cancellation Message. A successful Run
diff --git a/docs/plans/harness-callback-separation.md b/docs/plans/harness-callback-separation.md
new file mode 100644
index 000000000..4f19c4baf
--- /dev/null
+++ b/docs/plans/harness-callback-separation.md
@@ -0,0 +1,113 @@
+# Harness Callback Ownership and Separation
+
+## Background
+
+Issues #918 and #922, fixed by PRs #919 and #923, established two contracts:
+
+1. one terminal callback per asynchronous Agent Run; and
+2. terminal callback text comes from the turn-final assistant result, never an
+ Activity label or tool description.
+
+Two incidents on 2026-07-30 exposed one remaining ownership error. A target
+turn explicitly queued a separate Agent Run back to its caller while finishing
+with an intentional silent terminal. The callback drainer treated that queued
+child as if it were the parent's already-delivered callback.
+
+## Live Evidence
+
+The affected runtime roles were a Claude-backed coordinator Session and a
+Codex-backed implementation-lane Session. The exact local Session, Run,
+Message, and backend-native identifiers were verified during diagnosis but are
+intentionally omitted from this public plan.
+
+### Incident A
+
+- The parent escalation Run targeted the coordinator, finished `succeeded`
+ with `result_text=""`, and recorded an intentional silent terminal Message.
+- The intermediate coordinator Message remained correctly stored as
+ `author=agent`, `type=assistant`, `source=agent`.
+- The coordinator explicitly queued a full ruling Run to the lane. It had
+ `started_at=NULL`, but the parent was marked `callback_status=sent` with that
+ directed Run as its `callback_run_id`.
+- The lane did not receive that intermediate Message through callback
+ delivery. Its native Codex transcript shows it querying the PM Session at
+ `2026-07-30T02:04:41Z`, then querying the exact intermediate Message at
+ `02:04:47Z`; only afterwards did it report a truncated ruling.
+
+### Incident B
+
+- The parent escalation Run was created with `--no-callback`, so both
+ `callback_session_id` and `callback_run_id` are null.
+- The intermediate coordinator Message remained in its target Session,
+ followed by an intentional silent terminal Message.
+- The full directed ruling Run remained queued with `started_at=NULL`.
+- The lane's native transcript shows direct `vibe data query` calls at
+ `2026-07-30T03:49:32Z` and `03:49:36Z` reading the PM Session and the exact
+ intermediate row before it described the ruling as truncated.
+
+The incidents therefore do not prove intermediate callback delivery. They do
+prove that the callback ledger falsely identifies a separate queued child as a
+sent callback, which makes later inspection and automation unable to distinguish
+callback ownership from an independent directed Run.
+
+## Root Cause
+
+`ScheduledTaskService._enqueue_callback_run()` calls
+`find_explicit_session_delivery()` before building the terminal callback. Any
+agent-authored child Run with the parent id and callback target Session is
+returned as the parent's callback, regardless of whether it has started,
+completed, or was intended as a separate message.
+
+The callback drainer then writes that child's id into the parent
+`callback_run_id` and marks the callback `sent`. This conflates two durable
+objects and lets an unstarted queue entry satisfy callback delivery.
+
+## Required Behavior
+
+- Only a callback Run created from the parent's turn-final `result_text` may
+ satisfy the parent's callback policy.
+- A successful empty terminal result produces no visible callback Run. Earlier
+ assistant progress remains in the target Session only.
+- An explicitly directed Agent Run remains independent, retaining its own id,
+ source, parent lineage, queue position, callback policy, and exact message.
+- A busy callback target may queue the terminal callback, but its body and
+ provenance must still come only from the parent terminal result.
+- No Harness-generated content is persisted as human-authored input, and no
+ duplicate callback is created.
+
+## Implementation
+
+1. Remove explicit child-delivery substitution from the shared callback
+ drainer and its store API.
+2. Keep the change forward-only. Historical `callback_status=sent` rows remain
+ inert and are never reset, replayed, or used to create a new callback Run.
+3. Keep the existing terminal-result selection and exactly-once callback
+ identity from #919 and #923.
+4. Add consuming SQLite-backed tests through the real message dispatcher and
+ callback drainer for:
+ - intermediate preamble, tool boundary, intentional silent terminal;
+ - intermediate preamble followed by a full terminal result;
+ - separately directed full message while the callback target is busy; and
+ - callback idempotency and non-user Harness identity.
+5. Allocate `MESSAGE-DELIVERY-008` as contract-level partial coverage. PR
+ #1104 currently owns `MESSAGE-DELIVERY-007`; `HFR-430` is already allocated
+ on master.
+
+## Historical Compatibility
+
+The incidents predate this forward contract, but their stored delivery state is
+not replayed. An old parent row already marked `callback_status=sent` remains
+sent across upgrade and startup, even when its `callback_run_id` names a
+directed `source_kind=agent` child. No migration re-arms it and no startup path
+creates a replacement callback from its historical terminal text.
+
+Read-only consumers distinguish the two child types from persisted
+`source_kind`: `callback` identifies an automatic callback Run, while `agent`
+retains directed-Run provenance and graph lineage. This classification never
+mutates historical rows and never causes delivery.
+
+## Scope
+
+This change does not alter queue supersede, cancellation recovery, #1098,
+#1072, authentication, authorization, ACL behavior, #1074, or the Markdown
+silent-literal parser owned by PR #1104.
diff --git a/storage/background.py b/storage/background.py
index add7a19b5..4431fa0d1 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -2762,28 +2762,6 @@ class SQLiteBackgroundTaskStore:
).mappings().first()
return self._run_from_row(row) if row else None
- def find_explicit_session_delivery(
- self,
- *,
- parent_run_id: str,
- session_id: str,
- ) -> Optional[dict[str, Any]]:
- """Return a child Agent Run explicitly delivered to the callback Session."""
-
- with self.engine.connect() as conn:
- row = conn.execute(
- select(agent_runs)
- .where(agent_runs.c.run_type == "agent_run")
- .where(agent_runs.c.source_kind == "agent")
- .where(agent_runs.c.parent_run_id == parent_run_id)
- .where(agent_runs.c.session_id == session_id)
- .where(agent_runs.c.message.is_not(None))
- .where(func.length(func.trim(agent_runs.c.message)) > 0)
- .order_by(agent_runs.c.created_at, agent_runs.c.id)
- .limit(1)
- ).mappings().first()
- return self._run_from_row(row) if row else None
-
def recover_processing_runs(self) -> None:
with run_update_event_transaction(self.engine) as conn:
now = _utc_now_iso()
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index bacacfdc0..7fbbad787 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -49,6 +49,12 @@ scenarios:
kind: lifecycle
layer: contract
test: tests/test_show_git_turn_entrypoints.py::test_all_turn_entrypoints_reach_checkpoint_subscriber
+ - id: MESSAGE-DELIVERY-008
+ name: Run callbacks use only terminal output while directed child Runs remain independent
+ status: partial
+ kind: concurrency
+ layer: contract
+ test: tests/test_scheduled_tasks.py::test_directed_run_and_callback_remain_distinct_while_target_busy
next_priority:
- MESSAGE-DELIVERY-101
- MESSAGE-DELIVERY-102
diff --git a/tests/scenarios/message_delivery/observations.yaml b/tests/scenarios/message_delivery/observations.yaml
index 4dd5e7716..f221dbbed 100644
--- a/tests/scenarios/message_delivery/observations.yaml
+++ b/tests/scenarios/message_delivery/observations.yaml
@@ -11,5 +11,16 @@ observations:
required_updates:
- retain intermediate outputs only in the Run output ledger and originating Session
- keep result_text terminal-only and enqueue one terminal callback
- - treat an explicit child delivery to the callback Session as satisfying the automatic callback
+ - keep explicit child delivery independent from the parent's automatic callback
- persist harness-originated prompts with a non-user author and message type
+ - id: OBS-MESSAGE-DELIVERY-003
+ source: live_local_diagnosis
+ related_scenarios:
+ - MESSAGE-DELIVERY-008
+ summary: Queued directed child Runs were recorded as completed parent callbacks even though they had not started.
+ previous_assumption: Any explicit child Run targeting the callback Session could satisfy the parent callback.
+ observed_behavior: Parent callback ledgers inherited the child Run id while the child stayed queued, and direct cross-Session database inspection consumed an intermediate preamble instead.
+ required_updates:
+ - derive callback payloads only from the parent Run terminal result
+ - keep directed child Runs as separate durable queue objects with their own callback policy
+ - preserve intermediate assistant and tool activity in the target Session only
diff --git a/tests/test_agent_graph_service.py b/tests/test_agent_graph_service.py
index dd07e834c..9ebd005f5 100644
--- a/tests/test_agent_graph_service.py
+++ b/tests/test_agent_graph_service.py
@@ -98,7 +98,7 @@ def _insert_session(conn, session_id, *, scope_id, backend="claude", title=None,
def _insert_run(conn, run_id, *, session_id, status="succeeded", run_type="agent",
created=None, source_kind=None, source_actor=None, definition_id=None,
callback_session_id=None, callback_status=None, started=None, completed=None,
- parent_run_id=None) -> None:
+ parent_run_id=None, callback_run_id=None) -> None:
created = created or (NOW - timedelta(hours=1))
conn.execute(
agent_runs.insert().values(
@@ -128,7 +128,7 @@ def _insert_run(conn, run_id, *, session_id, status="succeeded", run_type="agent
callback_session_id=callback_session_id,
callback_status=callback_status,
callback_error=None,
- callback_run_id=None,
+ callback_run_id=callback_run_id,
callback_completed_at=None,
cancel_requested=0,
cancel_requested_at=None,
@@ -354,11 +354,9 @@ def test_window_includes_recently_completed_run(isolated_state):
engine.dispose()
-def test_callback_delivery_is_not_a_spawn(isolated_state):
- # A delegated run spawns callee and routes a callback to caller; the callee's
- # explicit callback-delivery run reports INTO the caller's session with
- # parent_run_id = the delegated run. That report must NOT create a backwards
- # spawn edge callee→caller (only the real spawn caller→callee + the callback).
+def test_callback_delivery_is_not_spawn_but_directed_child_is(isolated_state):
+ # A callback delivery has its own source_kind, while an agent-authored child
+ # aimed at the same target remains an independent delegation.
engine = create_sqlite_engine()
try:
with engine.begin() as conn:
@@ -366,14 +364,24 @@ def test_callback_delivery_is_not_a_spawn(isolated_state):
_insert_session(conn, "ses_callee", scope_id=None, backend="codex", title="Callee")
_insert_run(conn, "run_deleg", session_id="ses_callee", source_kind="agent",
source_actor="ses_caller", callback_session_id="ses_caller",
- callback_status="sent", created=NOW - timedelta(minutes=30))
- _insert_run(conn, "run_report", session_id="ses_caller", source_kind="agent",
+ callback_status="sent", callback_run_id="run_callback",
+ created=NOW - timedelta(minutes=30))
+ _insert_run(conn, "run_callback", session_id="ses_caller", source_kind="callback",
+ source_actor="run_deleg", parent_run_id="run_deleg",
+ created=NOW - timedelta(minutes=20))
+ _insert_run(conn, "run_directed", session_id="ses_caller", source_kind="agent",
source_actor="ses_callee", parent_run_id="run_deleg",
created=NOW - timedelta(minutes=10))
payload = agent_graph.build_graph(live_agents=[], now=NOW, engine=engine)
- assert _edge(payload, "spawn", "ses_caller", "ses_callee") is not None
- assert _edge(payload, "spawn", "ses_callee", "ses_caller") is None
- assert _edge(payload, "callback", "ses_callee", "ses_caller") is not None
+ forward = _edge(payload, "spawn", "ses_caller", "ses_callee")
+ directed = _edge(payload, "spawn", "ses_callee", "ses_caller")
+ callback = _edge(payload, "callback", "ses_callee", "ses_caller")
+ assert forward is not None
+ assert directed is not None
+ assert directed["run_count"] == 1
+ assert directed["last_run_id"] == "run_directed"
+ assert callback is not None
+ assert callback["last_run_id"] == "run_callback"
finally:
engine.dispose()
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 3135aeead..67ea517ff 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -19,7 +19,8 @@ from config import paths
from config.v2_settings import make_thread_native_id
from core.controller import Controller
from core.message_dispatcher import ConsolidatedMessageDispatcher
-from core.message_output import stop_output_for
+from core.message_mirror import mirror_harness_inbound
+from core.message_output import MessageOutput, stop_output_for
from core.run_settlement import (
SETTLED_BY_BACKEND_REFRESH,
SETTLED_BY_STOPPED,
@@ -47,7 +48,7 @@ from core.scheduled_tasks import (
from modules.im import MessageContext
from storage.db import create_sqlite_engine
from storage.background import SQLiteBackgroundTaskStore
-from storage.models import agent_runs, run_definitions
+from storage.models import agent_events, agent_runs, messages, run_definitions
from storage.pagination import PageRequest
from storage.session_activities import SQLiteSessionActivityStore
from storage.agent_session_rows import create_agent_session_row
@@ -4226,6 +4227,121 @@ def test_recovered_coalesced_agent_run_early_failure_settles_children(tmp_path:
assert stored[run_ids[1]]["error"] == "target session vanished"
+def _harness_turn_context(
+ *,
+ session_id: str,
+ run_id: str,
+ backend: str,
+) -> MessageContext:
+ return MessageContext(
+ user_id="harness",
+ channel_id=session_id,
+ platform="avibe",
+ message_id=f"agent_run:{run_id}",
+ platform_specific={
+ "agent_session_id": session_id,
+ "task_execution_id": run_id,
+ "task_trigger_kind": "agent_run",
+ "suppress_delivery": True,
+ "vibe_agent_name": "worker",
+ "vibe_agent_backend": backend,
+ },
+ )
+
+
+def _harness_dispatcher() -> ConsolidatedMessageDispatcher:
+ settings_manager = SimpleNamespace(
+ _canonicalize_message_type=lambda value: value,
+ )
+ im_client = SimpleNamespace(
+ should_use_thread_for_reply=lambda: False,
+ should_use_thread_for_dm_session=lambda: False,
+ )
+ controller = SimpleNamespace(
+ config=SimpleNamespace(
+ platform="avibe",
+ language="en",
+ reply_enhancements=False,
+ ),
+ get_settings_manager_for_context=lambda _context: settings_manager,
+ get_im_client_for_context=lambda _context: im_client,
+ _get_settings_key=lambda context: context.channel_id,
+ _get_session_key=lambda context: f"avibe::{context.channel_id}",
+ agent_service=SimpleNamespace(
+ emit_matches_runtime_turn=lambda _context: True,
+ release_runtime_turn=lambda _context: None,
+ ),
+ session_turns=SimpleNamespace(
+ on_terminal_result=lambda _context, is_error=False: None,
+ ),
+ mark_turn_complete=lambda _context, **_kwargs: None,
+ )
+ return ConsolidatedMessageDispatcher(controller)
+
+
+async def _persist_harness_turn(
+ *,
+ dispatcher: ConsolidatedMessageDispatcher,
+ context: MessageContext,
+ prompt: str,
+ preamble: str,
+ terminal: str,
+) -> tuple[MessageOutput, MessageOutput, MessageOutput]:
+ mirror_harness_inbound(context, prompt)
+ preamble_output = MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ idempotency_key="intermediate-preamble",
+ )
+ tool_output = MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ idempotency_key="tool-boundary",
+ )
+ terminal_output = MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ idempotency_key="terminal-result",
+ )
+ await dispatcher.emit_agent_message(
+ context,
+ "assistant",
+ preamble,
+ output=preamble_output,
+ )
+ await dispatcher.emit_agent_message(
+ context,
+ "toolcall",
+ "Tool: vibe data query",
+ output=tool_output,
+ )
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ terminal,
+ output=terminal_output,
+ )
+ return preamble_output, tool_output, terminal_output
+
+
+def _callback_service(
+ *,
+ tmp_path: Path,
+ request_store: TaskExecutionStore,
+) -> ScheduledTaskService:
+ return ScheduledTaskService(
+ controller=_avibe_controller_double(
+ gate=SimpleNamespace(
+ submit_scheduled=lambda *_args, **_kwargs: None,
+ in_flight={},
+ ),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ ),
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+
def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
@@ -4276,15 +4392,102 @@ def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Pat
assert callback_run["message"] == "complete delegated result"
-def test_agent_run_explicit_delivery_suppresses_automatic_callback(
+def test_historical_conflated_sent_callback_stays_inert_on_startup(
tmp_path: Path,
monkeypatch,
) -> None:
+ """Startup must not replay a historical directed child as a callback."""
+
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ parent = request_store.enqueue_agent_run(
+ session_id="historical-target",
+ message="historical delegated work",
+ agent_name="codex",
+ callback_session_id="historical-caller",
+ )
+ directed = request_store.enqueue_agent_run(
+ session_id="historical-caller",
+ message="historical directed report",
+ agent_name="codex",
+ source_kind="agent",
+ source_actor="historical-target",
+ parent_run_id=parent.id,
+ )
+ sqlite_store = SQLiteBackgroundTaskStore()
+ try:
+ sqlite_store.record_run_message(
+ parent.id,
+ text="stale automatic terminal",
+ terminal_status="succeeded",
+ )
+ finally:
+ sqlite_store.close()
+
+ engine = create_sqlite_engine()
+ try:
+ with engine.begin() as conn:
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == parent.id)
+ .values(
+ callback_status="sent",
+ callback_error="historical conflation",
+ callback_run_id=directed.id,
+ callback_completed_at="2026-07-30T00:00:00Z",
+ )
+ )
+ finally:
+ engine.dispose()
+ assert request_store.sqlite_backend is not None
+ request_store.sqlite_backend.close()
+
+ restarted_store = TaskExecutionStore()
+ service = _callback_service(
+ tmp_path=tmp_path,
+ request_store=restarted_store,
+ )
+
+ asyncio.run(service._drain_callbacks())
+ asyncio.run(service._drain_callbacks())
+
+ stored_parent = restarted_store.get_run(parent.id)
+ stored_directed = restarted_store.get_run(directed.id)
+ runs = restarted_store.list_runs()
+ assert stored_parent is not None
+ assert stored_parent["callback_status"] == "sent"
+ assert stored_parent["callback_error"] == "historical conflation"
+ assert stored_parent["callback_run_id"] == directed.id
+ assert stored_directed is not None
+ assert stored_directed["source_kind"] == "agent"
+ assert stored_directed["status"] == "queued"
+ assert len(runs) == 2
+ assert not any(run.get("source_kind") == "callback" for run in runs)
+ assert not any(run.get("message") == "stale automatic terminal" for run in runs)
+ assert restarted_store.sqlite_backend is not None
+ restarted_store.sqlite_backend.close()
+
+
+def test_directed_run_and_callback_remain_distinct_while_target_busy(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """Scenario: MESSAGE-DELIVERY-008."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ caller_session_id = _make_avibe_session(
+ monkeypatch,
+ tmp_path,
+ scope_native_id="callback-caller",
+ )
+ target_session_id = _make_avibe_session(
+ monkeypatch,
+ tmp_path,
+ scope_native_id="callback-target",
+ )
request_store = TaskExecutionStore()
request = request_store.enqueue_agent_run(
- session_id="target-session",
+ session_id=target_session_id,
message="delegated work",
agent_name="codex",
callback_session_id=caller_session_id,
@@ -4294,8 +4497,9 @@ def test_agent_run_explicit_delivery_suppresses_automatic_callback(
message="explicit final report",
agent_name="codex",
source_kind="agent",
- source_actor="target-session",
+ source_actor=target_session_id,
parent_run_id=request.id,
+ callback_session_id=target_session_id,
)
store = SQLiteBackgroundTaskStore()
try:
@@ -4306,27 +4510,330 @@ def test_agent_run_explicit_delivery_suppresses_automatic_callback(
)
finally:
store.close()
- service = ScheduledTaskService(
- controller=_avibe_controller_double(
- gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
- handle_scheduled_message=lambda *_args, **_kwargs: None,
- ),
- store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ service = _callback_service(
+ tmp_path=tmp_path,
request_store=request_store,
)
+ asyncio.run(service._drain_callbacks())
asyncio.run(service._drain_callbacks())
original = request_store.get_run(request.id)
assert original is not None
assert original["callback_status"] == "sent"
- assert original["callback_run_id"] == explicit.id
callback_runs = [
run
for run in request_store.list_runs()
if run.get("source_kind") == "callback" and run.get("parent_run_id") == request.id
]
- assert callback_runs == []
+ assert len(callback_runs) == 1
+ callback = callback_runs[0]
+ assert original["callback_run_id"] == callback["id"]
+ assert callback["id"] != explicit.id
+ assert callback["session_id"] == caller_session_id
+ assert callback["status"] == "queued"
+ assert callback["started_at"] is None
+ assert callback["message"] == "automatic terminal result"
+ assert callback["source_actor"] == request.id
+ assert callback["callback_session_id"] is None
+ assert explicit.callback_session_id == target_session_id
+ stored_explicit = request_store.get_run(explicit.id)
+ assert stored_explicit is not None
+ assert stored_explicit["status"] == "queued"
+ assert stored_explicit["started_at"] is None
+ assert stored_explicit["message"] == "explicit final report"
+ assert stored_explicit["source_kind"] == "agent"
+ assert stored_explicit["parent_run_id"] == request.id
+ assert stored_explicit["callback_status"] == "pending"
+ assert stored_explicit["created_at"] <= callback["created_at"]
+ assert [
+ run["id"]
+ for run in request_store.list_runs(status="queued")
+ if run.get("session_id") == caller_session_id
+ ] == [explicit.id, callback["id"]]
+
+
+def test_silent_terminal_skips_callback_and_keeps_directed_run(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """Scenario: MESSAGE-DELIVERY-008."""
+
+ target_session_id = _make_avibe_session(
+ monkeypatch,
+ tmp_path,
+ scope_native_id="silent-target",
+ agent_backend="claude",
+ )
+ caller_session_id = _make_avibe_session(
+ monkeypatch,
+ tmp_path,
+ scope_native_id="silent-caller",
+ agent_backend="codex",
+ )
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=target_session_id,
+ message="delegated work",
+ agent_name="worker",
+ agent_backend="claude",
+ callback_session_id=caller_session_id,
+ )
+ assert request_store.claim(request.id) is not None
+ explicit = request_store.enqueue_agent_run(
+ session_id=caller_session_id,
+ message="完整定向裁决:精确内容",
+ agent_name="worker",
+ agent_backend="codex",
+ source_kind="agent",
+ source_actor=target_session_id,
+ parent_run_id=request.id,
+ )
+ context = _harness_turn_context(
+ session_id=target_session_id,
+ run_id=request.id,
+ backend="claude",
+ )
+ preamble_output, _tool_output, _terminal_output = asyncio.run(
+ _persist_harness_turn(
+ dispatcher=_harness_dispatcher(),
+ context=context,
+ prompt="escalation prompt",
+ preamble="裁决如下:",
+ terminal="",
+ )
+ )
+ service = _callback_service(
+ tmp_path=tmp_path,
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_callbacks())
+
+ original = request_store.get_run(request.id)
+ assert original is not None
+ assert original["status"] == "succeeded"
+ assert original["result_text"] == ""
+ assert original["callback_status"] == "skipped"
+ assert original["callback_run_id"] is None
+ assert [
+ run
+ for run in request_store.list_runs()
+ if run.get("source_kind") == "callback"
+ and run.get("parent_run_id") == request.id
+ ] == []
+
+ stored_explicit = request_store.get_run(explicit.id)
+ assert stored_explicit is not None
+ assert stored_explicit["status"] == "queued"
+ assert stored_explicit["started_at"] is None
+ assert stored_explicit["message"] == "完整定向裁决:精确内容"
+ assert stored_explicit["source_kind"] == "agent"
+ assert stored_explicit["parent_run_id"] == request.id
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ target_messages = conn.execute(
+ select(
+ messages.c.author,
+ messages.c.type,
+ messages.c.source,
+ messages.c.native_message_id,
+ messages.c.content_text,
+ )
+ .where(messages.c.session_id == target_session_id)
+ .order_by(messages.c.created_at, messages.c.id)
+ ).mappings().all()
+ tool_events = conn.execute(
+ select(
+ agent_events.c.event_type,
+ agent_events.c.source,
+ agent_events.c.run_id,
+ agent_events.c.content_text,
+ ).where(agent_events.c.session_id == target_session_id)
+ ).mappings().all()
+ assert [row["author"] for row in target_messages] == [
+ "harness",
+ "agent",
+ "agent",
+ ]
+ assert [row["type"] for row in target_messages] == [
+ "harness",
+ "assistant",
+ "silent",
+ ]
+ assert [row["source"] for row in target_messages] == [
+ "harness",
+ "agent",
+ "agent",
+ ]
+ assert [row["native_message_id"] for row in target_messages] == [
+ f"agent_run:{request.id}",
+ preamble_output.native_message_id(context),
+ None,
+ ]
+ assert [row["content_text"] for row in target_messages] == [
+ "escalation prompt",
+ "裁决如下:",
+ "",
+ ]
+ assert all(row["author"] != "user" and row["type"] != "user" for row in target_messages)
+ assert tool_events == [
+ {
+ "event_type": "tool_call",
+ "source": "agent",
+ "run_id": request.id,
+ "content_text": "Tool: vibe data query",
+ }
+ ]
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_callback_consumes_only_full_terminal_once_across_backends(
+ tmp_path: Path,
+ monkeypatch,
+ backend: str,
+) -> None:
+ """Scenario: MESSAGE-DELIVERY-008."""
+
+ target_session_id = _make_avibe_session(
+ monkeypatch,
+ tmp_path,
+ scope_native_id=f"{backend}-target",
+ agent_backend=backend,
+ )
+ caller_session_id = _make_avibe_session(
+ monkeypatch,
+ tmp_path,
+ scope_native_id=f"{backend}-caller",
+ agent_backend=backend,
+ )
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=target_session_id,
+ message="delegated work",
+ agent_name="worker",
+ agent_backend=backend,
+ callback_session_id=caller_session_id,
+ )
+ assert request_store.claim(request.id) is not None
+ context = _harness_turn_context(
+ session_id=target_session_id,
+ run_id=request.id,
+ backend=backend,
+ )
+ preamble_output, _tool_output, terminal_output = asyncio.run(
+ _persist_harness_turn(
+ dispatcher=_harness_dispatcher(),
+ context=context,
+ prompt="delegated work",
+ preamble="The complete ruling follows:",
+ terminal="exact terminal body\nlocale.en=Ready\nlocale.zh=就绪",
+ )
+ )
+ service = _callback_service(
+ tmp_path=tmp_path,
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_callbacks())
+ asyncio.run(service._drain_callbacks())
+
+ original = request_store.get_run(request.id)
+ assert original is not None
+ assert original["status"] == "succeeded"
+ assert original["result_text"] == "exact terminal body\nlocale.en=Ready\nlocale.zh=就绪"
+ assert original["callback_status"] == "sent"
+ callback_runs = [
+ run
+ for run in request_store.list_runs()
+ if run.get("source_kind") == "callback"
+ and run.get("parent_run_id") == request.id
+ ]
+ assert len(callback_runs) == 1
+ callback = callback_runs[0]
+ assert callback["id"] == original["callback_run_id"]
+ assert callback["session_id"] == caller_session_id
+ assert callback["source_actor"] == request.id
+ assert callback["message"] == "exact terminal body\nlocale.en=Ready\nlocale.zh=就绪"
+ assert callback["status"] == "queued"
+ assert callback["started_at"] is None
+
+ claimed_callback = request_store.claim(callback["id"])
+ assert claimed_callback is not None
+ callback_context = _harness_turn_context(
+ session_id=caller_session_id,
+ run_id=callback["id"],
+ backend=backend,
+ )
+ mirror_harness_inbound(callback_context, claimed_callback.message)
+ mirror_harness_inbound(callback_context, claimed_callback.message)
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ target_messages = conn.execute(
+ select(
+ messages.c.author,
+ messages.c.type,
+ messages.c.source,
+ messages.c.native_message_id,
+ messages.c.content_text,
+ )
+ .where(messages.c.session_id == target_session_id)
+ .order_by(messages.c.created_at, messages.c.id)
+ ).mappings().all()
+ caller_messages = conn.execute(
+ select(
+ messages.c.author,
+ messages.c.type,
+ messages.c.source,
+ messages.c.native_message_id,
+ messages.c.content_text,
+ )
+ .where(messages.c.session_id == caller_session_id)
+ .order_by(messages.c.created_at, messages.c.id)
+ ).mappings().all()
+ target_events = conn.execute(
+ select(
+ agent_events.c.event_type,
+ agent_events.c.source,
+ agent_events.c.run_id,
+ agent_events.c.content_text,
+ ).where(agent_events.c.session_id == target_session_id)
+ ).mappings().all()
+ assert [row["type"] for row in target_messages] == [
+ "harness",
+ "assistant",
+ "result",
+ ]
+ assert [row["source"] for row in target_messages] == [
+ "harness",
+ "agent",
+ "agent",
+ ]
+ assert [row["native_message_id"] for row in target_messages] == [
+ f"agent_run:{request.id}",
+ preamble_output.native_message_id(context),
+ terminal_output.native_message_id(context),
+ ]
+ assert caller_messages == [
+ {
+ "author": "harness",
+ "type": "harness",
+ "source": "harness",
+ "native_message_id": f"agent_run:{callback['id']}",
+ "content_text": "exact terminal body\nlocale.en=Ready\nlocale.zh=就绪",
+ }
+ ]
+ assert all(row["author"] != "user" and row["type"] != "user" for row in caller_messages)
+ assert target_events == [
+ {
+ "event_type": "tool_call",
+ "source": "agent",
+ "run_id": request.id,
+ "content_text": "Tool: vibe data query",
+ }
+ ]
def test_agent_run_keeps_output_ledger_but_callbacks_only_terminal_result(
@@ -6795,6 +7302,9 @@ def _make_avibe_session(
*,
metadata: dict | None = None,
visibility: str = "foreground",
+ scope_native_id: str = "proj_gate_exec",
+ agent_backend: str = "claude",
+ agent_name: str = "worker",
) -> str:
"""Create a real avibe workbench session so ``resolve_session_id_target``
resolves it to ``platform='avibe'`` (the gate trigger)."""
@@ -6809,7 +7319,11 @@ def _make_avibe_session(
engine = create_sqlite_engine()
with engine.begin() as conn:
scope_id = upsert_scope(
- conn, platform="avibe", scope_type="project", native_id="proj_gate_exec", now="2026-05-31T00:00:00Z"
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id=scope_native_id,
+ now="2026-05-31T00:00:00Z",
)
conn.execute(
scope_settings.insert().values(
@@ -6832,8 +7346,8 @@ def _make_avibe_session(
session = sessions_service.create_session(
conn,
scope_id=scope_id,
- agent_backend="claude",
- agent_name="worker",
+ agent_backend=agent_backend,
+ agent_name=agent_name,
visibility=visibility,
metadata=metadata,
)
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index cfd0af363..d48289331 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -98,6 +98,102 @@ def test_alembic_script_directory_has_exactly_one_head() -> None:
assert heads[0] == HEAD_REVISION
+def test_upgrade_keeps_historical_conflated_callback_rows_sent(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260726_0037")
+ now = "2026-07-30T00:00:00Z"
+
+ with sqlite3.connect(db_path) as conn:
+ def insert_run(
+ run_id: str,
+ *,
+ source_kind: str,
+ parent_run_id: str | None = None,
+ session_id: str | None = None,
+ callback_session_id: str | None = None,
+ callback_status: str | None = None,
+ callback_run_id: str | None = None,
+ ) -> None:
+ conn.execute(
+ """
+ insert into agent_runs (
+ id, run_type, status, source_kind, parent_run_id, session_id,
+ callback_session_id, callback_status, callback_error,
+ callback_run_id, callback_completed_at, cancel_requested,
+ created_at, completed_at, updated_at, metadata_json
+ ) values (
+ ?, 'agent_run', 'succeeded', ?, ?, ?, ?, ?, 'legacy error',
+ ?, ?, 0, ?, ?, ?, '{}'
+ )
+ """,
+ (
+ run_id,
+ source_kind,
+ parent_run_id,
+ session_id,
+ callback_session_id,
+ callback_status,
+ callback_run_id,
+ now if callback_status else None,
+ now,
+ now if callback_status else None,
+ now,
+ ),
+ )
+
+ insert_run(
+ "historical_parent",
+ source_kind="agent",
+ callback_session_id="ses_caller",
+ callback_status="sent",
+ callback_run_id="directed_child",
+ )
+ insert_run(
+ "directed_child",
+ source_kind="agent",
+ parent_run_id="historical_parent",
+ session_id="ses_caller",
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ parent = conn.execute(
+ """
+ select callback_status, callback_error, callback_run_id,
+ callback_completed_at
+ from agent_runs
+ where id = 'historical_parent'
+ """
+ ).fetchone()
+ child = conn.execute(
+ """
+ select source_kind, parent_run_id, session_id
+ from agent_runs
+ where id = 'directed_child'
+ """
+ ).fetchone()
+ callback_count = conn.execute(
+ "select count(*) from agent_runs where source_kind = 'callback'"
+ ).fetchone()
+ version = conn.execute(
+ "select version_num from alembic_version"
+ ).fetchone()
+
+ assert parent == (
+ "sent",
+ "legacy error",
+ "directed_child",
+ now,
+ )
+ assert child == ("agent", "historical_parent", "ses_caller")
+ assert callback_count == (0,)
+ assert version == (HEAD_REVISION,)
+
+
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"