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.

feat(messages): populate provenance source at user/agent/harness persist points

cyha45489828862
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 404c108e5..d7326cc10 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -130,13 +130,20 @@ class MessageHandler(BaseHandler):
context = await self._prepare_turn_context(context, source)
- # Mirror the user's message into the workbench messages table
- # before we kick off the agent. Wrapped in try/except inside
- # the helper so a mirror failure can't take down the turn.
+ # Mirror the originating prompt into the workbench messages table
+ # before we kick off the agent, so the transcript shows the turn
+ # that produced the reply. Human turns are source='user'; harness
+ # turns (scheduled task / watch / webhook) are author='user' but
+ # source='harness' so the UI can mark who triggered them. Wrapped in
+ # try/except inside the helper so a mirror failure can't break the turn.
if source == self.TURN_SOURCE_HUMAN:
from core.message_mirror import mirror_inbound
mirror_inbound(context, control_message)
+ else:
+ from core.message_mirror import mirror_harness_inbound
+
+ mirror_harness_inbound(context, message)
base_session_id, working_path, composite_key = self.session_handler.get_session_info(context, source=source)
payload = dict(context.platform_specific or {})
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 357df1363..f417cd0c0 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -145,12 +145,19 @@ def persist_agent_message(context: MessageContext, canonical_type: str, text: st
row_session_id = None
if scope_id is None:
return
+ # Provenance: every agent reply is source='agent'; name = the
+ # session's agent (from the dispatch context). source_id (author_id)
+ # is left to the agent-id wiring later; the session already carries it.
+ spec = context.platform_specific or {}
+ agent_name = spec.get("vibe_agent_name") or (spec.get("agent_session_target") or {}).get("agent_name")
_append_quietly(
conn,
scope_id=scope_id,
session_id=row_session_id,
platform=context.platform,
author="agent",
+ source="agent",
+ author_name=agent_name,
message_type=message_type,
text=text,
parent_native_message_id=context.thread_id,
@@ -169,6 +176,59 @@ def persist_agent_message(context: MessageContext, canonical_type: str, text: st
logger.exception("persist_agent_message: failure on platform=%s", context.platform)
+def mirror_harness_inbound(context: MessageContext, text: str) -> None:
+ """Record a harness-originated prompt (scheduled task / watch / webhook).
+
+ Harness turns inject a *user-role* prompt into a session that the human
+ never typed, so the row is ``author='user'`` (the agent reads it as user
+ input) but ``source='harness'`` — the transcript can then mark it as
+ triggered by a scheduled task / watch instead of the user. ``author_name``
+ carries the trigger kind (scheduled / watch / webhook / ...) and
+ ``author_id`` the run-definition id, per the provenance spec.
+
+ Unlike :func:`mirror_inbound` this *does* cover avibe: no REST endpoint
+ writes the harness prompt, so without this the workbench transcript would
+ show an agent reply with no originating turn. Scope resolution mirrors
+ :func:`persist_agent_message` — avibe rows attach to the session's project
+ scope, IM rows to the delivery channel.
+ """
+ if not text or not text.strip():
+ return
+ if not context.platform:
+ return
+ spec = context.platform_specific or {}
+ trigger_kind = spec.get("task_trigger_kind")
+ definition_id = spec.get("task_definition_id")
+ session_id = spec.get("agent_session_id")
+ try:
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ if context.platform == "avibe":
+ scope_id = _scope_id_for_session(conn, session_id) if session_id else None
+ row_session_id = session_id
+ else:
+ scope_id = _resolve_scope_id(conn, context)
+ row_session_id = None
+ if scope_id is None:
+ return
+ _append_quietly(
+ conn,
+ scope_id=scope_id,
+ session_id=row_session_id,
+ platform=context.platform,
+ author="user",
+ source="harness",
+ author_name=trigger_kind,
+ author_id=definition_id,
+ message_type="user",
+ text=text,
+ native_message_id=context.message_id,
+ parent_native_message_id=context.thread_id,
+ )
+ except Exception:
+ logger.exception("mirror_harness_inbound: unexpected failure on platform=%s", context.platform)
+
+
def mirror_inbound(context: MessageContext, text: str) -> None:
"""Record a human-originated message into the messages table."""
@@ -192,6 +252,7 @@ def mirror_inbound(context: MessageContext, text: str) -> None:
session_id=None,
platform=context.platform,
author="user",
+ source="user",
message_type="user",
text=text,
author_id=context.user_id,
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index bca4188be..c15f767db 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -1561,6 +1561,10 @@ class ScheduledTaskService:
"scheduled_delivery_alias": delivery_strategy,
"task_execution_id": execution_id,
"task_trigger_kind": trigger_kind,
+ # Provenance source_id for harness-originated turns: the run
+ # definition id (task / watch). Carried so the message mirror can
+ # attribute the injected prompt to its precise definition.
+ "task_definition_id": task_id,
"vibe_agent_name": agent_name,
"suppress_delivery": bool(target_info.suppress_delivery) if target_info else False,
"agent_session_target": (
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 630c78f7a..bf183a698 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -25,7 +25,7 @@ from sqlalchemy import select
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from core.message_mirror import mirror_inbound, persist_agent_message
+from core.message_mirror import mirror_harness_inbound, mirror_inbound, persist_agent_message
from modules.im import MessageContext
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
@@ -274,6 +274,114 @@ def test_persist_agent_no_publish_without_result(isolated_state):
asyncio.run(scenario())
+def test_inbound_sets_source_user(isolated_state):
+ """Human IM turns carry source='user' (origin), distinct from author role."""
+ mirror_inbound(_slack_ctx(), "hello there")
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ row = conn.execute(select(messages).where(messages.c.platform == "slack")).mappings().first()
+ assert row["source"] == "user"
+
+
+def test_persist_agent_sets_source_and_agent_name(isolated_state):
+ """Agent replies carry source='agent' and author_name = the session's agent,
+ read from the dispatch context (vibe_agent_name)."""
+ ctx = MessageContext(
+ user_id="U",
+ channel_id="C_general",
+ platform="slack",
+ platform_specific={"vibe_agent_name": "Atlas"},
+ )
+ mirror_inbound(ctx, "ping")
+ persist_agent_message(ctx, "result", "pong")
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ agent_row = conn.execute(
+ select(messages).where(messages.c.author == "agent")
+ ).mappings().first()
+ assert agent_row["source"] == "agent"
+ assert agent_row["author_name"] == "Atlas"
+
+
+def test_harness_inbound_avibe_session_scoped(isolated_state):
+ """A scheduled/watch turn on an avibe session lands an author='user',
+ source='harness' row attributed to the session — with author_name = the
+ trigger kind and author_id = the run-definition id (the provenance spec).
+ No REST endpoint writes this, so the mirror must cover avibe here."""
+ engine = create_sqlite_engine()
+ now = "2026-05-30T12:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_h", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_harness",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_ses_harness",
+ native_session_id="",
+ title="Scheduled",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+ ctx = MessageContext(
+ user_id="scheduled",
+ channel_id="ses_harness",
+ platform="avibe",
+ message_id="watch:def_42:exec_1",
+ platform_specific={
+ "agent_session_id": "ses_harness",
+ "task_trigger_kind": "watch",
+ "task_definition_id": "def_42",
+ },
+ )
+ mirror_harness_inbound(ctx, "the watched condition fired")
+
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(messages).where(messages.c.session_id == "ses_harness")
+ ).mappings().first()
+ assert row is not None
+ assert row["author"] == "user" # agent reads it as user input
+ assert row["source"] == "harness" # but origin is the harness
+ assert row["author_name"] == "watch"
+ assert row["author_id"] == "def_42"
+ assert row["type"] == "user"
+ assert row["content_text"] == "the watched condition fired"
+
+
+def test_harness_inbound_im_scope_keyed(isolated_state):
+ """A harness turn delivered to an IM channel is scope-keyed (no session_id),
+ same shape as ``mirror_inbound`` — but tagged source='harness'."""
+ ctx = MessageContext(
+ user_id="scheduled",
+ channel_id="C_cron",
+ platform="slack",
+ message_id="scheduled:def_7:exec_9",
+ platform_specific={
+ "task_trigger_kind": "scheduled",
+ "task_definition_id": "def_7",
+ },
+ )
+ mirror_harness_inbound(ctx, "daily standup reminder")
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ row = conn.execute(select(messages).where(messages.c.platform == "slack")).mappings().first()
+ assert row["source"] == "harness"
+ assert row["author"] == "user"
+ assert row["author_name"] == "scheduled"
+ assert row["author_id"] == "def_7"
+ assert row["session_id"] is None
+
+
def test_avibe_inbound_is_noop(isolated_state):
"""avibe user messages are written by the workbench REST endpoint, so the
inbound mirror stays a no-op (agent output is persisted via
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 28c430a32..02b1c1248 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3076,6 +3076,7 @@ async def sessions_messages_create(session_id: str):
session_id=session_id,
platform="avibe",
author="user",
+ source="user",
message_type="user",
text=text if isinstance(text, str) else None,
content=content if isinstance(content, dict) else None,