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(harness): expose live run anomalies (#1362)

Call Whitec1bf18961c84
diff --git a/core/controller.py b/core/controller.py
index 4ac9d0f03..246603d25 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -2620,6 +2620,11 @@ class Controller:
"controller runtime work lane shutdown failed"
) from controller_errors[0]
+ dispatcher = getattr(self, "message_dispatcher", None)
+ drain_activity = getattr(dispatcher, "drain_agent_run_activity", None)
+ if callable(drain_activity):
+ await drain_activity()
+
service_stops: list[asyncio.Task[None]] = []
for service_name in ("scheduled_task_service", "watch_service"):
service = getattr(self, service_name, None)
diff --git a/core/internal_server.py b/core/internal_server.py
index b527e946c..a3df05964 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -616,6 +616,28 @@ def create_app(
return await asyncio.to_thread(snapshot_running_agents, controller)
+ @app.post("/internal/running-agents/snapshot")
+ async def _running_agents_snapshot(request: Request) -> Any:
+ """Return live agents plus ownership for one bounded Run candidate set."""
+
+ from core.services.running_agents import (
+ HARNESS_OWNERSHIP_CANDIDATE_LIMIT,
+ snapshot_running_agents,
+ )
+
+ payload = await _safe_json(request)
+ run_ids = payload.get("run_ids") if isinstance(payload, dict) else None
+ if not isinstance(run_ids, list) or len(run_ids) > HARNESS_OWNERSHIP_CANDIDATE_LIMIT:
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": "invalid_run_candidates"},
+ )
+ return await asyncio.to_thread(
+ snapshot_running_agents,
+ controller,
+ ownership_candidate_run_ids=run_ids,
+ )
+
@app.post("/internal/running-agents/end")
async def _running_agents_end(request: Request) -> Any:
"""Terminate one running agent's live runtime (Stop turn / disconnect /
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 86e00f263..50cee776c 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -319,6 +319,12 @@ class ConsolidatedMessageDispatcher:
# while a missing one defeats the feature.
self._harness_prompt_echo_keys: set[str] = set()
self._harness_prompt_echo_order: list[str] = []
+ # Run activity is best-effort liveness evidence, never part of an
+ # individual streamed event's delivery critical path. One flush task
+ # coalesces repeated ids while a SQLite writer is busy; controller
+ # shutdown drains that exact task before stopping the shared executor.
+ self._pending_agent_run_activity_ids: set[str] = set()
+ self._agent_run_activity_flush_task: asyncio.Task[None] | None = None
# Injectable monotonic-ish clock (wall time) so tests get deterministic
# elapsed/stale values without sleeping.
self._now = time.time
@@ -1562,6 +1568,77 @@ class ConsolidatedMessageDispatcher:
if store is not None:
store.close()
+ def _schedule_agent_run_activity(
+ self,
+ context: MessageContext,
+ output_semantics: MessageOutput,
+ ) -> None:
+ """Coalesce one real non-terminal output into the liveness writer."""
+
+ if not output_semantics.records_run_output or output_semantics.settles_run:
+ return
+ run_ids = self._terminal_agent_run_ids(context, output_semantics)
+ if not run_ids:
+ return
+ scheduled_tasks = getattr(self.controller, "scheduled_task_service", None)
+ runtime_store = getattr(scheduled_tasks, "request_store", None)
+ record_activity = getattr(runtime_store, "record_run_activity", None)
+ if not callable(record_activity):
+ return
+ self._pending_agent_run_activity_ids.update(run_ids)
+ task = self._agent_run_activity_flush_task
+ if task is None or task.done():
+ self._agent_run_activity_flush_task = asyncio.create_task(
+ self._flush_agent_run_activity(),
+ name="agent-run-activity-flush",
+ )
+
+ async def _flush_agent_run_activity(self) -> None:
+ """Flush coalesced activity without delaying streamed delivery."""
+
+ try:
+ while self._pending_agent_run_activity_ids:
+ run_ids = tuple(sorted(self._pending_agent_run_activity_ids))
+ self._pending_agent_run_activity_ids.difference_update(run_ids)
+ scheduled_tasks = getattr(
+ self.controller, "scheduled_task_service", None
+ )
+ runtime_store = getattr(scheduled_tasks, "request_store", None)
+ record_activity = getattr(runtime_store, "record_run_activity", None)
+ if not callable(record_activity):
+ continue
+ try:
+ supervisor = getattr(
+ self.controller, "runtime_work_supervisor", None
+ )
+ run_sync = getattr(supervisor, "run_sync", None)
+ if callable(run_sync):
+ await run_sync(lambda: record_activity(run_ids))
+ else:
+ await asyncio.to_thread(record_activity, run_ids)
+ except Exception:
+ logger.warning(
+ "Failed to record Run activity for %s",
+ ",".join(run_ids),
+ exc_info=True,
+ )
+ finally:
+ self._agent_run_activity_flush_task = None
+ if self._pending_agent_run_activity_ids:
+ self._agent_run_activity_flush_task = asyncio.create_task(
+ self._flush_agent_run_activity(),
+ name="agent-run-activity-flush",
+ )
+
+ async def drain_agent_run_activity(self) -> None:
+ """Join all activity writes admitted before controller shutdown."""
+
+ while True:
+ task = self._agent_run_activity_flush_task
+ if task is None:
+ return
+ await asyncio.shield(task)
+
def _durable_accepted_agent_run_ids(self, context: MessageContext) -> list[str]:
turn_id = str((context.platform_specific or {}).get("turn_token") or "").strip()
if not turn_id:
@@ -2067,6 +2144,8 @@ class ConsolidatedMessageDispatcher:
self._get_session_key(context),
)
return None
+ if current_runtime_turn or output_semantics.detached:
+ self._schedule_agent_run_activity(context, output_semantics)
raw_text = text
enhanced = None
if visible_output_type and level != "silent":
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 45a1e0400..2485b6031 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -3118,6 +3118,13 @@ class TaskExecutionStore:
return item
return None
+ def record_run_activity(self, run_ids: Sequence[str]) -> list[str]:
+ """Persist activity on the shared SQLite ledger when available."""
+
+ if self._sqlite is None:
+ return []
+ return self._sqlite.record_run_activity(run_ids)
+
def cancel_run(self, run_id: str) -> bool:
if self._sqlite is not None:
return self._sqlite.cancel_run(run_id)
@@ -5178,7 +5185,12 @@ class ScheduledTaskService:
except (TypeError, ValueError):
return default
- def _owned_agent_run_ids(self) -> set[str]:
+ def _owned_agent_run_ids(
+ self,
+ *,
+ reconcile_terminal: bool = True,
+ candidate_run_ids: Optional[set[str]] = None,
+ ) -> set[str]:
"""Every run id something in THIS process is still legitimately executing.
Two lanes own a ``running`` row and neither can see the other:
@@ -5194,14 +5206,35 @@ class ScheduledTaskService:
turns own anything", which would terminalize every streaming run.
"""
+ candidates = (
+ {str(run_id) for run_id in candidate_run_ids if str(run_id or "").strip()}
+ if candidate_run_ids is not None
+ else None
+ )
owned = set(self._inflight_executions)
+ if candidates is not None:
+ owned &= candidates
session_turns = getattr(self.controller, "session_turns", None)
- provider = getattr(session_turns, "owned_agent_run_ids", None)
+ provider_name = (
+ "owned_agent_run_ids"
+ if reconcile_terminal
+ else "snapshot_owned_agent_run_ids"
+ )
+ provider = getattr(session_turns, provider_name, None)
if not callable(provider):
- raise RuntimeError("controller.session_turns.owned_agent_run_ids is unavailable")
- owned |= {str(run_id) for run_id in provider() if run_id}
+ raise RuntimeError(f"controller.session_turns.{provider_name} is unavailable")
+ provided = provider() if candidates is None else provider(candidates)
+ owned |= {str(run_id) for run_id in provided if run_id}
return owned
+ def snapshot_owned_agent_run_ids(self, candidate_run_ids: set[str]) -> set[str]:
+ """Expose the exact current ownership set to read-only operator views."""
+
+ return self._owned_agent_run_ids(
+ reconcile_terminal=False,
+ candidate_run_ids=candidate_run_ids,
+ )
+
def _deliverable_queued_run_ids(self) -> set[str]:
"""Queued runs whose transport is ready RIGHT NOW, whatever the row remembers.
diff --git a/core/services/harness_status.py b/core/services/harness_status.py
new file mode 100644
index 000000000..d308e08ee
--- /dev/null
+++ b/core/services/harness_status.py
@@ -0,0 +1,290 @@
+"""Pure projection for the bounded Harness live/anomaly operator view."""
+
+from __future__ import annotations
+
+import os
+from datetime import datetime, timezone
+from typing import Any, Iterable
+
+
+def _parse_instant(timestamp: object) -> datetime | None:
+ if not isinstance(timestamp, str) or not timestamp.strip():
+ return None
+ text = timestamp.strip()
+ if text.endswith(("Z", "z")):
+ text = f"{text[:-1]}+00:00"
+ try:
+ observed = datetime.fromisoformat(text)
+ except ValueError:
+ return None
+ if observed.tzinfo is None:
+ observed = observed.replace(tzinfo=timezone.utc)
+ return observed.astimezone(timezone.utc)
+
+
+def _seconds_since(timestamp: object, now: datetime) -> float | None:
+ observed = _parse_instant(timestamp)
+ if observed is None:
+ return None
+ return max(0.0, (now - observed).total_seconds())
+
+
+def _canonical_workdir(value: object) -> str | None:
+ cleaned = str(value or "").strip()
+ if not cleaned:
+ return None
+ return os.path.normcase(os.path.realpath(os.path.expanduser(cleaned)))
+
+
+def _runtime_identity(row: dict[str, Any]) -> str:
+ return str(
+ row.get("session_id")
+ or row.get("base_session_id")
+ or row.get("native_session_id")
+ or f"{row.get('backend')}:{row.get('pid')}"
+ )
+
+
+def _project_runtime_agent(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ key: row.get(key)
+ for key in (
+ "backend",
+ "state",
+ "base_session_id",
+ "session_id",
+ "agent_name",
+ "title",
+ "workdir",
+ "pid",
+ "model",
+ "elapsed_seconds",
+ "openable_in_chat",
+ )
+ }
+
+
+def _project_run(row: dict[str, Any], now: datetime) -> dict[str, Any]:
+ explicit_activity = row.get("last_activity_at")
+ activity_at = explicit_activity or row.get("started_at")
+ return {
+ "id": row.get("id"),
+ "run_type": row.get("run_type") or row.get("request_type"),
+ "status": row.get("status"),
+ "agent_name": row.get("agent_name"),
+ "agent_backend": row.get("agent_backend"),
+ "session_id": row.get("session_id"),
+ "definition_id": row.get("definition_id") or row.get("task_id"),
+ "created_at": row.get("created_at"),
+ "started_at": row.get("started_at"),
+ "updated_at": row.get("updated_at"),
+ "last_activity_at": activity_at,
+ "activity_basis": "output" if explicit_activity else ("start" if activity_at else None),
+ "activity_age_seconds": _seconds_since(activity_at, now),
+ "liveness": "queued" if row.get("status") == "queued" else "unknown",
+ "anomaly_codes": [],
+ }
+
+
+def _project_watch(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ key: row.get(key)
+ for key in (
+ "id",
+ "name",
+ "session_id",
+ "lifecycle_state",
+ "process_alive",
+ "health",
+ "processing_health",
+ "last_started_at",
+ "last_finished_at",
+ "last_event_at",
+ "last_exit_code",
+ "last_error",
+ )
+ }
+
+
+def _project_task(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ key: row.get(key)
+ for key in (
+ "id",
+ "name",
+ "session_id",
+ "agent_name",
+ "lifecycle_state",
+ "next_run_at",
+ "last_run_at",
+ "last_error",
+ )
+ }
+
+
+def build_harness_status(
+ *,
+ runs: Iterable[dict[str, Any]],
+ watches: Iterable[dict[str, Any]],
+ tasks: Iterable[dict[str, Any]],
+ runtime_snapshot: dict[str, Any],
+ truncated: dict[str, bool] | None = None,
+ now: datetime | None = None,
+) -> dict[str, Any]:
+ """Combine durable and controller facts without inventing lifecycle state."""
+
+ observed_now = now or datetime.now(timezone.utc)
+ if observed_now.tzinfo is None:
+ observed_now = observed_now.replace(tzinfo=timezone.utc)
+ observed_now = observed_now.astimezone(timezone.utc)
+
+ run_rows = [_project_run(dict(row), observed_now) for row in runs]
+ watch_rows = [_project_watch(dict(row)) for row in watches]
+ task_rows = [_project_task(dict(row)) for row in tasks]
+ task_rows.sort(
+ key=lambda row: (
+ (instant := _parse_instant(row.get("next_run_at"))) is None,
+ instant or datetime.max.replace(tzinfo=timezone.utc),
+ str(row.get("id") or ""),
+ )
+ )
+ runtime_rows = [
+ _project_runtime_agent(dict(row))
+ for row in runtime_snapshot.get("agents", [])
+ if isinstance(row, dict)
+ ]
+ anomalies: list[dict[str, Any]] = []
+
+ controller_available = bool(runtime_snapshot.get("available"))
+ ownership_available = bool(runtime_snapshot.get("ownership_available"))
+ owned_run_ids = {
+ str(run_id)
+ for run_id in runtime_snapshot.get("owned_run_ids", [])
+ if str(run_id or "").strip()
+ }
+ if not controller_available:
+ anomalies.append(
+ {
+ "code": "controller_unavailable",
+ "severity": "error",
+ "detail": runtime_snapshot.get("error") or "controller_unavailable",
+ }
+ )
+ elif not ownership_available:
+ anomalies.append(
+ {
+ "code": "run_ownership_unknown",
+ "severity": "error",
+ "detail": runtime_snapshot.get("ownership_error")
+ or "ownership_unavailable",
+ }
+ )
+
+ for run in run_rows:
+ if run["status"] != "running":
+ continue
+ if controller_available and ownership_available:
+ if str(run["id"]) in owned_run_ids:
+ run["liveness"] = "owned"
+ else:
+ run["liveness"] = "owner_missing"
+ run["anomaly_codes"].append("run_owner_missing")
+ anomalies.append(
+ {
+ "code": "run_owner_missing",
+ "severity": "error",
+ "run_id": run["id"],
+ "last_activity_at": run["last_activity_at"],
+ "activity_age_seconds": run["activity_age_seconds"],
+ }
+ )
+
+ for watch in watch_rows:
+ if (
+ watch.get("lifecycle_state") != "waiting"
+ or watch.get("process_alive") is not False
+ ):
+ continue
+ failed = bool(str(watch.get("last_error") or "").strip()) or watch.get("health") == "failing"
+ code = "watch_waiter_failed" if failed else "watch_waiter_missing"
+ watch["anomaly_codes"] = [code]
+ anomalies.append(
+ {
+ "code": code,
+ "severity": "error",
+ "watch_id": watch.get("id"),
+ "last_error": watch.get("last_error"),
+ "last_exit_code": watch.get("last_exit_code"),
+ }
+ )
+
+ active_by_workdir: dict[str, list[dict[str, Any]]] = {}
+ for runtime in runtime_rows:
+ if runtime.get("state") != "active":
+ continue
+ workdir = _canonical_workdir(runtime.get("workdir"))
+ if workdir:
+ active_by_workdir.setdefault(workdir, []).append(runtime)
+ for workdir, members in active_by_workdir.items():
+ identities = {_runtime_identity(member) for member in members}
+ backends = {str(member.get("backend") or "") for member in members}
+ pids = {
+ int(member["pid"])
+ for member in members
+ if isinstance(member.get("pid"), int)
+ }
+ # Several Session rows can legitimately project one shared backend process
+ # (Codex is cwd-scoped). That is one writer, not a conflict. Distinct
+ # backends or distinct process ids are the evidence this read-only view has
+ # for concurrent writers; pid-less rows remain separate runtime owners.
+ pidless_identities = {
+ _runtime_identity(member)
+ for member in members
+ if not isinstance(member.get("pid"), int)
+ }
+ writer_count = (
+ len(backends)
+ if len(backends) > 1
+ else len(pids) + len(pidless_identities)
+ )
+ if writer_count < 2:
+ continue
+ for member in members:
+ member.setdefault("anomaly_codes", []).append("active_workdir_conflict")
+ anomalies.append(
+ {
+ "code": "active_workdir_conflict",
+ "severity": "warning",
+ "workdir": workdir,
+ "session_ids": sorted(
+ {
+ str(member.get("session_id") or member.get("base_session_id"))
+ for member in members
+ }
+ ),
+ "backends": sorted({str(member.get("backend")) for member in members}),
+ }
+ )
+
+ return {
+ "generated_at": observed_now.isoformat(),
+ "controller": {
+ "available": controller_available,
+ "ownership_available": ownership_available,
+ "error": runtime_snapshot.get("error")
+ or runtime_snapshot.get("ownership_error"),
+ },
+ "runs": run_rows,
+ "watches": watch_rows,
+ "tasks": task_rows,
+ "runtime_agents": runtime_rows,
+ "anomalies": anomalies,
+ "counts": {
+ "active_runs": len(run_rows),
+ "armed_watches": len(watch_rows),
+ "enabled_tasks": len(task_rows),
+ "runtime_agents": len(runtime_rows),
+ "anomalies": len(anomalies),
+ },
+ "truncated": dict(truncated or {}),
+ }
diff --git a/core/services/running_agents.py b/core/services/running_agents.py
index ccd35ac47..f1cd123a1 100644
--- a/core/services/running_agents.py
+++ b/core/services/running_agents.py
@@ -1242,7 +1242,14 @@ async def end_running_agent(
return result
-def snapshot_running_agents(controller: "Controller") -> dict[str, Any]:
+HARNESS_OWNERSHIP_CANDIDATE_LIMIT = 101
+
+
+def snapshot_running_agents(
+ controller: "Controller",
+ *,
+ ownership_candidate_run_ids: Optional[list[str]] = None,
+) -> dict[str, Any]:
"""Return a read-only snapshot of all currently-running agent instances.
Shape::
@@ -1282,9 +1289,40 @@ def snapshot_running_agents(controller: "Controller") -> dict[str, Any]:
states[r["state"]] = states.get(r["state"], 0) + 1
by_backend[r["backend"]] = by_backend.get(r["backend"], 0) + 1
+ ownership_requested = ownership_candidate_run_ids is not None
+ candidates = {
+ str(run_id)
+ for run_id in (ownership_candidate_run_ids or [])
+ if str(run_id or "").strip()
+ }
+ ownership_available = not ownership_requested
+ ownership_error = None if not ownership_requested else "ownership_provider_unavailable"
+ owned_run_ids: list[str] = []
+ scheduled_tasks = getattr(controller, "scheduled_task_service", None)
+ ownership_provider = getattr(
+ scheduled_tasks,
+ "snapshot_owned_agent_run_ids",
+ None,
+ )
+ if ownership_requested and callable(ownership_provider):
+ try:
+ owned_run_ids = sorted(
+ str(run_id)
+ for run_id in ownership_provider(candidates)
+ if str(run_id or "").strip()
+ )
+ ownership_available = True
+ ownership_error = None
+ except Exception:
+ logger.warning("running-agents ownership snapshot failed", exc_info=True)
+ ownership_error = "ownership_probe_failed"
+
return {
"ok": True,
"agents": rows,
+ "owned_run_ids": owned_run_ids,
+ "ownership_available": ownership_available,
+ "ownership_error": ownership_error,
"counts": {
"total": len(rows),
"active": states["active"],
diff --git a/core/session_turns.py b/core/session_turns.py
index 0c8828506..42691b1e0 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -907,34 +907,79 @@ class SessionTurnManager:
if str(sink.get("turn_token") or "") == turn_id:
self._append_accepted_agent_run_ids(sink, run_ids)
- def owned_agent_run_ids(self) -> set[str]:
- """Run ids owned by a durable Delivery or a live process projection."""
+ def _project_owned_agent_run_ids(
+ self,
+ candidate_run_ids: Optional[set[str]] = None,
+ ) -> set[str]:
+ """Read Run ownership without reconciling or settling lifecycle state."""
+
+ candidates = (
+ {str(run_id) for run_id in candidate_run_ids if str(run_id or "").strip()}
+ if candidate_run_ids is not None
+ else None
+ )
+
+ def _eligible(run_ids: set[str]) -> set[str]:
+ return run_ids if candidates is None else run_ids & candidates
+
owned: set[str] = set()
for turn in list(self.in_flight.values()):
- owned |= self._agent_run_ids_from_spec(getattr(turn.context, "platform_specific", None))
+ owned |= _eligible(
+ self._agent_run_ids_from_spec(
+ getattr(turn.context, "platform_specific", None)
+ )
+ )
for sink in list(self.active_turn_sinks.values()):
- owned |= self._agent_run_ids_from_spec(sink)
- if self._durable_schema_available():
- self._reconcile_terminal_agent_runs()
+ owned |= _eligible(self._agent_run_ids_from_spec(sink))
+ if self._durable_schema_available() and candidates != set():
+ stmt = (
+ select(agent_runs.c.id)
+ .join(
+ delivery_rows,
+ delivery_rows.c.id == agent_runs.c.delivery_id,
+ )
+ .where(
+ agent_runs.c.status.in_(
+ ["queued", "pending", "running", "processing"]
+ )
+ )
+ .where(delivery_rows.c.state != "retired")
+ )
+ if candidates is not None:
+ stmt = (
+ stmt.outerjoin(
+ session_turn_rows,
+ session_turn_rows.c.id == delivery_rows.c.turn_id,
+ )
+ .where(agent_runs.c.id.in_(candidates))
+ .where(
+ or_(
+ delivery_rows.c.turn_id.is_(None),
+ session_turn_rows.c.state.in_(
+ delivery_store.TURN_OWNER_STATES
+ ),
+ )
+ )
+ )
with self._sqlite_engine().connect() as conn:
owned.update(
str(run_id)
- for run_id in conn.execute(
- select(agent_runs.c.id)
- .join(
- delivery_rows,
- delivery_rows.c.id == agent_runs.c.delivery_id,
- )
- .where(
- agent_runs.c.status.in_(
- ["queued", "pending", "running", "processing"]
- )
- )
- .where(delivery_rows.c.state != "retired")
- ).scalars()
+ for run_id in conn.execute(stmt).scalars()
)
return owned
+ def snapshot_owned_agent_run_ids(self, candidate_run_ids: set[str]) -> set[str]:
+ """Expose the side-effect-free ownership projection to operator views."""
+
+ return self._project_owned_agent_run_ids(candidate_run_ids)
+
+ def owned_agent_run_ids(self) -> set[str]:
+ """Reconcile terminal turns, then return every currently owned Run id."""
+
+ if self._durable_schema_available():
+ self._reconcile_terminal_agent_runs()
+ return self._project_owned_agent_run_ids()
+
def accepted_agent_run_ids_for_turn(self, turn_id: str) -> list[str]:
"""Read restart-stable Run attribution for one exact logical Turn."""
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index b49ebeb66..5fb972aa0 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -298,7 +298,7 @@ Relationship: Scope routes work; Agent defines who acts; Session holds continuit
- Current session id: `{default_session_id}`
### Inspecting Harness state
-Use `vibe data query` to inspect Avibe state with guarded read-only SQL before changing a Harness: confirm existing Agents, Sessions, Runs, scopes, tasks, watches, and routing facts instead of guessing.
+Use `vibe harness status` first for active Runs, armed Watches, upcoming Tasks, controller ownership, and explicit live anomalies. Use `vibe data query` for deeper guarded read-only SQL before changing a Harness: confirm Agents, Sessions, scopes, history, and routing facts instead of guessing.
Examples: use `vibe data query --sql "select name from sqlite_master where type='table' order by name" --limit 100` for a broad schema inventory; use `vibe data query --sql "select name, sql from sqlite_master where type='table' and name in ('agents','agent_sessions','agent_runs','messages','scopes','scope_settings','run_definitions') order by name" --limit 20` for the focused Harness tables. Follow `pagination.next_command` if either result has more pages.
@@ -316,6 +316,7 @@ Useful Harness queries include schema discovery, current session lookup, existin
| Remove one queued Workbench Session input | `vibe session queue remove <session-id> <message-id>` |
| Promote an existing queued Session head now | `vibe session send-now <session-id>` |
| Branch from current Session context | `vibe agent run --fork-self ...` |
+| Live/anomaly inspection | `vibe harness status` |
| State/history inspection | `vibe data query`, `vibe runs list --current-session`, `vibe runs show` |
| Recurring specialist workflow | `vibe agent create/update` plus tasks, watches, or runs |
@@ -339,7 +340,7 @@ Use `vibe session update --visible|--hidden` (`--visibility foreground|backgroun
For tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--message "..."` or `--message-file <path>` as the follow-up instruction template sent with waiter output. Prefer `--same-scope` or `--scope-id <scopes.id>` for new Session placement.
-Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`. For current-session run history, use `vibe runs list --current-session`. `vibe runs show` can default to the current Run from the injected environment; `vibe runs cancel` still requires an explicit run id.
+Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`. Use `vibe harness status` for one unified live/anomaly snapshot. For current-session run history, use `vibe runs list --current-session`. `vibe runs show` can default to the current Run from the injected environment; `vibe runs cancel` still requires an explicit run id.
The CLI exposes more options than this prompt lists. Before creating or changing Harness state, or whenever syntax/runtime effects are uncertain, read the relevant help: `vibe <command> --help` or `vibe <command> <subcommand> --help`.
diff --git a/docs/plans/harness-live-anomalies.md b/docs/plans/harness-live-anomalies.md
new file mode 100644
index 000000000..79bbcc453
--- /dev/null
+++ b/docs/plans/harness-live-anomalies.md
@@ -0,0 +1,61 @@
+# Harness Live and Anomaly View
+
+## Background
+
+Issue #1060 originally grouped several Harness reliability gaps. The merged
+implementation has since split their ownership:
+
+- #1005 reconciles abandoned queued/running Runs to terminal outcomes.
+- #1098 implements explicit send-now and queue controls from #1095.
+- #1072 and #1223 own failure delivery plus Watch waiter/processing health.
+- #1155 and #1173 own durable runtime ownership and supervised work lanes.
+- #1331 keeps cancellation scoped to the exact shared-Turn participant.
+
+The remaining operator gap is narrower: a live Run has no persisted activity
+fact between start and completion, and no command combines current Harness work
+with explicit anomalies. Concurrent active agents using one workdir are visible
+only by manually comparing runtime rows.
+
+## Goal
+
+Provide one read-only operational view while preserving the existing lifecycle,
+delivery, cancellation, and runtime ownership models.
+
+## Design
+
+1. Persist `metadata.last_activity_at` on non-terminal Run output. The write is
+ guarded to active Run states and advances both the fact and `updated_at`
+ monotonically. Existing stale-Run reconciliation therefore measures its grace
+ from the latest observed activity without gaining another timer or owner.
+2. Extend the controller's existing running-agent snapshot with the exact Run ids
+ already owned by `ScheduledTaskService` and `SessionTurnManager`. Failure to
+ read ownership is explicit and fails closed.
+3. Add `vibe harness status`. It combines active Runs, armed Watches, upcoming
+ Tasks, and the controller snapshot into one bounded-by-live-state response.
+4. Derive anomalies without persisting a parallel state machine:
+ `controller_unavailable`, `run_owner_missing`, `watch_waiter_missing`,
+ `watch_waiter_failed`, `run_ownership_unknown`, and
+ `active_workdir_conflict`.
+
+Workdir conflicts are marked, not rejected. Existing installations may
+deliberately share a checkout, and the current scheduler has no durable
+read-versus-write declaration that would make a rejection truthful. Two active
+runtime rows with the same canonical workdir are nevertheless an explicit
+operator anomaly and every affected row is flagged.
+
+## Non-goals
+
+- Reimplement send-now, cancellation, failure notices, Watch supervision, or
+ runtime ownership.
+- Add a new Run status or a second durable liveness table.
+- Infer that a long-running but owned Run is dead solely from elapsed time.
+- Change the Workbench Harness UI in this PR.
+
+## Evidence
+
+- Unit: monotonic activity writes and terminal-state guards.
+- Contract: controller ownership projection and unified anomaly derivation.
+- Scenario: HFR-480 (persisted Run activity and owner loss) and HFR-481
+ (same-workdir conflict plus Watch/Task operational inventory).
+- Residual manual: packaged CLI against a live multi-backend service remains an
+ Incus acceptance check after review.
diff --git a/storage/background.py b/storage/background.py
index 0f311f35d..5efc86606 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import heapq
import json
import logging
from contextlib import contextmanager, nullcontext
@@ -62,6 +63,7 @@ from storage.session_reclaim import (
logger = logging.getLogger(__name__)
CALLBACK_TERMINAL_TURN_ID_METADATA_KEY = "callback_terminal_turn_id"
+RUN_LAST_ACTIVITY_METADATA_KEY = "last_activity_at"
def _json_dumps(value: Any) -> str:
@@ -278,6 +280,25 @@ def compute_next_run_at(
return None
+def _scheduled_next_fire_sort_key(row: dict[str, Any]) -> tuple[bool, datetime, str]:
+ """Project and sort one enabled Task by its actual next fire instant."""
+
+ next_run_at = compute_next_run_at(
+ enabled=bool(row.get("enabled")),
+ schedule_type=row.get("schedule_type"),
+ cron=row.get("cron"),
+ run_at=row.get("run_at"),
+ timezone_name=row.get("timezone"),
+ )
+ row["next_run_at"] = next_run_at
+ instant = _parse_iso_instant(next_run_at)
+ return (
+ instant is None,
+ instant or datetime.max.replace(tzinfo=timezone.utc),
+ str(row.get("id") or ""),
+ )
+
+
RUN_STATUS_ALIASES: dict[str, str] = {
"pending": "queued",
"queued": "queued",
@@ -3810,6 +3831,110 @@ class SQLiteBackgroundTaskStore:
)
return page_result_from_limit_plus_one(rows, page_request)
+ def list_active_runs(self, *, limit: int) -> list[dict[str, Any]]:
+ """Return a bounded anomaly-first snapshot of operator-visible Runs."""
+
+ stmt = (
+ self._runs_query(exclude_run_type=(_WATCH_RUNTIME_RUN_TYPE,))
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued") + _status_query_values("running")
+ )
+ )
+ .order_by(
+ case(
+ (
+ agent_runs.c.status.in_(_status_query_values("running")),
+ 0,
+ ),
+ else_=1,
+ ),
+ agent_runs.c.updated_at.desc(),
+ agent_runs.c.id.desc(),
+ )
+ .limit(max(0, int(limit)))
+ )
+ with self.engine.connect() as conn:
+ return self._enrich_runs(
+ [self._run_from_row(row) for row in conn.execute(stmt).mappings()], conn
+ )
+
+ def active_run_ids(self, run_ids: Iterable[str]) -> set[str]:
+ """Revalidate a bounded Run snapshot without admitting newer rows."""
+
+ normalized = {str(run_id) for run_id in run_ids if str(run_id or "").strip()}
+ if not normalized:
+ return set()
+ stmt = (
+ select(agent_runs.c.id)
+ .where(agent_runs.c.id.in_(normalized))
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued") + _status_query_values("running")
+ )
+ )
+ )
+ with self.engine.connect() as conn:
+ return {str(run_id) for run_id in conn.execute(stmt).scalars()}
+
+ def list_enabled_definitions(
+ self,
+ definition_type: str,
+ *,
+ limit: int,
+ ) -> list[dict[str, Any]]:
+ """Return a bounded snapshot of armed Tasks or Watches."""
+
+ if definition_type not in {"scheduled", "watch"}:
+ raise ValueError("definition_type must be scheduled or watch")
+ row_limit = max(0, int(limit))
+ stmt = self._definitions_query(definition_type).where(
+ run_definitions.c.enabled != 0
+ )
+ converter = (
+ self._scheduled_task_from_row
+ if definition_type == "scheduled"
+ else self._watch_from_row
+ )
+ with self.engine.connect() as conn:
+ if definition_type == "scheduled":
+ # Cron next-fire instants are computed by APScheduler, so SQLite
+ # cannot order them correctly. Keep the response/enrichment bounded
+ # while selecting the true earliest rows from the enabled live set.
+ rows = heapq.nsmallest(
+ row_limit,
+ (converter(row) for row in conn.execute(stmt).mappings()),
+ key=_scheduled_next_fire_sort_key,
+ )
+ else:
+ runtime_status = (
+ select(agent_runs.c.status)
+ .where(agent_runs.c.run_type == _WATCH_RUNTIME_RUN_TYPE)
+ .where(agent_runs.c.definition_id == run_definitions.c.id)
+ .order_by(agent_runs.c.updated_at.desc(), agent_runs.c.id.desc())
+ .limit(1)
+ .scalar_subquery()
+ )
+ dead_waiter_rank = case(
+ (
+ runtime_status.is_not(None)
+ & ~runtime_status.in_(_status_query_values("running")),
+ 0,
+ ),
+ else_=1,
+ )
+ stmt = stmt.order_by(
+ dead_waiter_rank,
+ run_definitions.c.updated_at.desc(),
+ run_definitions.c.id.desc(),
+ ).limit(row_limit)
+ rows = [converter(row) for row in conn.execute(stmt).mappings()]
+ return self._enrich_definitions(
+ rows,
+ conn,
+ definition_type=definition_type,
+ )
+
def count_runs(
self,
*,
@@ -4371,6 +4496,80 @@ class SQLiteBackgroundTaskStore:
_publish_run_rows_updated([row_to_publish])
return payload
+ def record_run_activity(
+ self,
+ run_ids: Sequence[str],
+ *,
+ observed_at: Optional[str] = None,
+ ) -> list[str]:
+ """Advance the persisted activity fact for active Runs, monotonically.
+
+ Activity is output observed at the dispatcher, not a synthetic heartbeat.
+ A writer reservation keeps the read/compare/write decision atomic without
+ replacing any lifecycle or ownership state.
+ """
+
+ normalized_ids = list(
+ dict.fromkeys(
+ run_id
+ for value in run_ids
+ if (run_id := str(value or "").strip())
+ )
+ )
+ if not normalized_ids:
+ return []
+ now = observed_at or _utc_now_iso()
+ observed_instant = _parse_iso_instant(now)
+ if observed_instant is None:
+ raise ValueError("observed_at must be an ISO-8601 timestamp")
+
+ touched: list[str] = []
+ with self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ rows = conn.execute(
+ select(
+ agent_runs.c.id,
+ agent_runs.c.status,
+ agent_runs.c.updated_at,
+ agent_runs.c.metadata_json,
+ ).where(agent_runs.c.id.in_(normalized_ids))
+ ).mappings()
+ for row in rows:
+ if normalize_run_status(row["status"]) != "running":
+ continue
+ try:
+ metadata = json.loads(str(row["metadata_json"] or "{}"))
+ except (TypeError, ValueError):
+ metadata = None
+ if not isinstance(metadata, dict):
+ logger.warning(
+ "Run activity metadata is unreadable; preserving Run %s unchanged",
+ row["id"],
+ )
+ continue
+ current = str(metadata.get(RUN_LAST_ACTIVITY_METADATA_KEY) or "").strip()
+ if current:
+ current_instant = _parse_iso_instant(current)
+ if current_instant is not None:
+ if current_instant >= observed_instant:
+ continue
+ updated_at = str(row["updated_at"] or "").strip()
+ if updated_at:
+ updated_instant = _parse_iso_instant(updated_at)
+ if updated_instant is not None:
+ if updated_instant > observed_instant:
+ continue
+ metadata[RUN_LAST_ACTIVITY_METADATA_KEY] = now
+ result = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == row["id"])
+ .where(agent_runs.c.status.in_(_status_query_values("running")))
+ .values(metadata_json=_json_dumps(metadata), updated_at=now)
+ )
+ if result.rowcount:
+ touched.append(str(row["id"]))
+ return touched
+
def mark_run_execution_started(
self,
run_id: str,
@@ -6569,7 +6768,10 @@ class SQLiteBackgroundTaskStore:
# Restricted to ``agent_run`` on purpose: when ``scheduled``/``watch``
# rows settle is owned by a separate plan. Widen only alongside it.
if str(row["run_type"] or "") == "agent_run" and _older_than(
- row["started_at"] or row["created_at"], orphan_grace_seconds
+ metadata.get(RUN_LAST_ACTIVITY_METADATA_KEY)
+ or row["started_at"]
+ or row["created_at"],
+ orphan_grace_seconds,
):
reason = SWEEP_REASON_ORPHANED
elif status == "queued":
@@ -8083,6 +8285,11 @@ class SQLiteBackgroundTaskStore:
@staticmethod
def _run_from_row(row: Any) -> dict[str, Any]:
metadata = _json_loads(row["metadata_json"], {})
+ last_activity_at = (
+ metadata.get(RUN_LAST_ACTIVITY_METADATA_KEY)
+ if isinstance(metadata, dict)
+ else None
+ )
return {
"id": row["id"],
"request_type": row["run_type"],
@@ -8135,6 +8342,7 @@ class SQLiteBackgroundTaskStore:
"started_at": row["started_at"],
"completed_at": row["completed_at"],
"updated_at": row["updated_at"],
+ "last_activity_at": last_activity_at,
"metadata": metadata,
"session_fork": metadata.get("session_fork") if isinstance(metadata, dict) else None,
"ok": None if row["completed_at"] is None else normalize_run_status(row["status"]) == "succeeded",
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 9be361c77..ed23e557b 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -9,6 +9,7 @@ capability:
- tests/test_dispatcher_stream_chunk.py
- tests/test_message_dispatcher_result_fallback.py
- tests/test_agent_stop_settlement.py
+ - tests/test_harness_live_status.py
shared_harness: []
status_legend:
covered: deterministic scenario or contract coverage exists
@@ -4284,6 +4285,26 @@ scenarios:
# Turn's sole initial accepted input. Steered or coalesced participants settle
# locally, skip their callback, and leave the shared Session Turn untouched.
test: tests/test_internal_server.py::test_hfr_476_run_cancel_does_not_stop_a_shared_turn
+ - id: HFR-480
+ name: persisted Run activity exposes missing live ownership
+ status: covered
+ kind: failure_recovery
+ layer: scenario
+ backend: shared
+ # Real non-terminal output advances a monotonic durable activity fact. The
+ # unified view compares a running row with the controller's exact owner set,
+ # and reports owner loss without guessing from elapsed time.
+ test: tests/test_harness_live_status.py::test_hfr_480_persisted_activity_exposes_owner_loss
+ - id: HFR-481
+ name: unified live view marks same-workdir and Watch anomalies
+ status: covered
+ kind: observability
+ layer: scenario
+ backend: shared
+ # Active runtime rows sharing one canonical workdir are marked rather than
+ # blocked, while dead Watch supervision and upcoming Task inventory remain in
+ # the same bounded operator response.
+ test: tests/test_harness_live_status.py::test_hfr_481_unified_view_marks_workdir_conflict_and_watch_failure
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
@@ -4293,3 +4314,4 @@ plans:
- docs/plans/agent-run-zombie-settlement.md
- docs/plans/harness-watch-run-failure-boundary.md
- docs/plans/watch-follow-up-circuit-breaker.md
+ - docs/plans/harness-live-anomalies.md
diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.py
index 27b8ca889..c194fcccf 100644
--- a/tests/test_cli_agent_run_schema.py
+++ b/tests/test_cli_agent_run_schema.py
@@ -1849,6 +1849,28 @@ def test_runs_list_current_session_filters_from_caller_env(tmp_path: Path, capsy
assert [run["session_id"] for run in payload["runs"]] == ["ses-current"]
+ "activity_at",
+ (
+ "2099-01-01T00:00:00Z",
+ "2099-01-01T00:00:00z",
+ "2099-01-01T00:00:00",
+ "2099-01-01T08:00:00+08:00",
+ ),
+)
+def test_brief_run_payload_parses_supported_iso_instants(activity_at: str) -> None:
+ payload = cli._run_payload(
+ {
+ "id": "run-live",
+ "status": "running",
+ "last_activity_at": activity_at,
+ },
+ brief=True,
+ )
+
+ assert payload["activity_age_seconds"] == 0.0
+
+
def test_runs_list_current_session_conflicts_with_session_id(capsys) -> None:
parser = cli.build_parser()
args = parser.parse_args(["runs", "list", "--current-session", "--session-id", "ses-explicit"])
diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.py
index 4b1b68c34..d4e59670f 100644
--- a/tests/test_controller_dispatch_loop.py
+++ b/tests/test_controller_dispatch_loop.py
@@ -535,6 +535,43 @@ async def test_hfr_284_runtime_work_stack_joins_controller_lanes_before_service_
assert controller._runtime_work_tokens == []
+async def test_runtime_work_stack_drains_run_activity_before_executor_stop() -> None:
+ controller = Controller.__new__(Controller)
+ controller._shutdown_tainted = False
+ controller._runtime_work_tokens = []
+ stopped: list[str] = []
+
+ class _Dispatcher:
+ async def drain_agent_run_activity(self) -> None:
+ stopped.append("activity")
+
+ class _Service:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+ async def stop(self) -> None:
+ stopped.append(self.name)
+
+ class _Supervisor:
+ def quiesce(self) -> None:
+ stopped.append("quiesce")
+
+ async def stop(self) -> None:
+ stopped.append("supervisor")
+
+ controller.message_dispatcher = _Dispatcher()
+ controller.scheduled_task_service = _Service("tasks")
+ controller.watch_service = _Service("watch")
+ controller.runtime_work_supervisor = _Supervisor()
+
+ await controller._stop_runtime_work_stack()
+
+ assert stopped[0:2] == ["quiesce", "activity"]
+ assert set(stopped[2:4]) == {"tasks", "watch"}
+ assert stopped[4] == "supervisor"
+
+
def test_request_shutdown_keeps_loop_owned_supervisor_join_alive_after_grace() -> None:
controller = Controller.__new__(Controller)
loop = asyncio.new_event_loop()
diff --git a/tests/test_harness_live_status.py b/tests/test_harness_live_status.py
new file mode 100644
index 000000000..46c736135
--- /dev/null
+++ b/tests/test_harness_live_status.py
@@ -0,0 +1,555 @@
+"""Focused contracts for persisted Run activity and the unified live view."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import select, update
+
+from core.services.harness_status import build_harness_status
+from storage.background import SQLiteBackgroundTaskStore
+from storage.models import agent_runs
+from vibe import cli, internal_client
+
+
+def _enqueue_running(store: SQLiteBackgroundTaskStore, run_id: str) -> None:
+ store.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": "agent_run",
+ "status": "queued",
+ "agent_name": "codex",
+ "agent_backend": "codex",
+ "session_id": "ses-live",
+ "message": "continue",
+ "created_at": "2026-08-12T05:00:00+00:00",
+ "updated_at": "2026-08-12T05:00:00+00:00",
+ }
+ )
+ assert store.claim_pending_run(
+ run_id,
+ started_at="2026-08-12T05:01:00+00:00",
+ ) is not None
+
+
+def test_record_run_activity_is_monotonic_and_terminal_guarded(tmp_path) -> None:
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ _enqueue_running(store, "run-live")
+ claimed = store.get_run("run-live")
+ assert claimed["last_activity_at"] is None
+
+ assert store.record_run_activity(
+ ["run-live", "run-live"],
+ observed_at="2026-08-12T05:03:00+00:00",
+ ) == ["run-live"]
+ assert store.record_run_activity(
+ ["run-live"],
+ observed_at="2026-08-12T05:02:00+00:00",
+ ) == []
+ active = store.get_run("run-live")
+ assert active["last_activity_at"] == "2026-08-12T05:03:00+00:00"
+ assert active["updated_at"] == "2026-08-12T05:03:00+00:00"
+
+ store.record_run_output(
+ "run-live",
+ output_id="terminal",
+ text="done",
+ terminal_status="succeeded",
+ updated_at="2026-08-12T05:04:00+00:00",
+ )
+ assert store.record_run_activity(
+ ["run-live"],
+ observed_at="2026-08-12T05:05:00+00:00",
+ ) == []
+ settled = store.get_run("run-live")
+ assert settled["status"] == "succeeded"
+ assert settled["last_activity_at"] == "2026-08-12T05:03:00+00:00"
+ finally:
+ store.close()
+
+
+def test_record_run_activity_preserves_unreadable_metadata(tmp_path) -> None:
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ _enqueue_running(store, "run-malformed")
+ with store.engine.begin() as connection:
+ connection.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == "run-malformed")
+ .values(metadata_json="{not json")
+ )
+
+ assert store.record_run_activity(
+ ["run-malformed"],
+ observed_at="2026-08-12T05:03:00+00:00",
+ ) == []
+ with store.engine.connect() as connection:
+ stored = connection.execute(
+ select(agent_runs.c.metadata_json).where(
+ agent_runs.c.id == "run-malformed"
+ )
+ ).scalar_one()
+ assert stored == "{not json"
+ finally:
+ store.close()
+
+
+def test_hfr_480_persisted_activity_exposes_owner_loss(tmp_path) -> None:
+ """HFR-480: output activity survives while missing ownership is explicit."""
+
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ _enqueue_running(store, "run-orphan")
+ store.record_run_activity(
+ ["run-orphan"],
+ observed_at="2026-08-12T05:04:00+00:00",
+ )
+ runs = store.list_active_runs(limit=10)
+ snapshot = build_harness_status(
+ runs=runs,
+ watches=[],
+ tasks=[],
+ runtime_snapshot={
+ "available": True,
+ "ownership_available": True,
+ "owned_run_ids": [],
+ "agents": [],
+ },
+ now=datetime(2026, 8, 12, 5, 5, tzinfo=timezone.utc),
+ )
+
+ assert snapshot["runs"][0]["last_activity_at"] == "2026-08-12T05:04:00+00:00"
+ assert snapshot["runs"][0]["activity_age_seconds"] == 60
+ assert snapshot["runs"][0]["liveness"] == "owner_missing"
+ assert snapshot["runs"][0]["anomaly_codes"] == ["run_owner_missing"]
+ assert snapshot["anomalies"][0]["run_id"] == "run-orphan"
+
+ recent = store.sweep_stale_runs(
+ owned_run_ids=set(),
+ error_texts={"orphaned": "owner disappeared"},
+ now="2026-08-12T05:05:00+00:00",
+ orphan_grace_seconds=120,
+ )
+ assert recent == []
+ expired = store.sweep_stale_runs(
+ owned_run_ids=set(),
+ error_texts={"orphaned": "owner disappeared"},
+ now="2026-08-12T05:07:00+00:00",
+ orphan_grace_seconds=120,
+ )
+ assert [item.run_id for item in expired] == ["run-orphan"]
+ assert store.get_run("run-orphan")["status"] == "failed"
+ finally:
+ store.close()
+
+
+def test_hfr_481_unified_view_marks_workdir_conflict_and_watch_failure() -> None:
+ """HFR-481: one view combines work inventory with explicit anomalies."""
+
+ snapshot = build_harness_status(
+ runs=[],
+ watches=[
+ {
+ "id": "watch-ci",
+ "name": "CI",
+ "lifecycle_state": "waiting",
+ "process_alive": False,
+ "health": "failing",
+ "last_exit_code": 2,
+ "last_error": "waiter exited",
+ }
+ ],
+ tasks=[
+ {
+ "id": "task-report",
+ "name": "Report",
+ "lifecycle_state": "waiting",
+ "next_run_at": "2026-08-13T00:00:00+00:00",
+ }
+ ],
+ runtime_snapshot={
+ "available": True,
+ "ownership_available": True,
+ "owned_run_ids": [],
+ "agents": [
+ {
+ "backend": "codex",
+ "state": "active",
+ "session_id": "ses-a",
+ "base_session_id": "base-a",
+ "workdir": "/repo/project",
+ },
+ {
+ "backend": "claude",
+ "state": "active",
+ "session_id": "ses-b",
+ "base_session_id": "base-b",
+ "workdir": "/repo/project/.",
+ },
+ ],
+ },
+ now=datetime(2026, 8, 12, 5, 5, tzinfo=timezone.utc),
+ )
+
+ codes = {item["code"] for item in snapshot["anomalies"]}
+ assert codes == {"active_workdir_conflict", "watch_waiter_failed"}
+ assert snapshot["counts"] == {
+ "active_runs": 0,
+ "armed_watches": 1,
+ "enabled_tasks": 1,
+ "runtime_agents": 2,
+ "anomalies": 2,
+ }
+ assert all(
+ row["anomaly_codes"] == ["active_workdir_conflict"]
+ for row in snapshot["runtime_agents"]
+ )
+
+
+def test_same_backend_shared_process_is_not_a_workdir_conflict() -> None:
+ snapshot = build_harness_status(
+ runs=[],
+ watches=[],
+ tasks=[],
+ runtime_snapshot={
+ "available": True,
+ "ownership_available": True,
+ "owned_run_ids": [],
+ "agents": [
+ {
+ "backend": "codex",
+ "state": "active",
+ "session_id": "ses-a",
+ "base_session_id": "base-a",
+ "workdir": "/repo/project",
+ "pid": 4242,
+ },
+ {
+ "backend": "codex",
+ "state": "active",
+ "session_id": "ses-b",
+ "base_session_id": "base-b",
+ "workdir": "/repo/project",
+ "pid": 4242,
+ },
+ ],
+ },
+ )
+
+ assert snapshot["anomalies"] == []
+
+
+def test_same_backend_known_and_pidless_owners_are_a_workdir_conflict() -> None:
+ snapshot = build_harness_status(
+ runs=[],
+ watches=[],
+ tasks=[],
+ runtime_snapshot={
+ "available": True,
+ "ownership_available": True,
+ "owned_run_ids": [],
+ "agents": [
+ {
+ "backend": "codex",
+ "state": "active",
+ "session_id": "ses-known",
+ "workdir": "/repo/project",
+ "pid": 4242,
+ },
+ {
+ "backend": "codex",
+ "state": "active",
+ "session_id": "ses-pidless",
+ "workdir": "/repo/project",
+ "pid": None,
+ },
+ ],
+ },
+ )
+
+ assert [row["code"] for row in snapshot["anomalies"]] == [
+ "active_workdir_conflict"
+ ]
+
+
+def test_activity_age_accepts_utc_z_timestamps() -> None:
+ snapshot = build_harness_status(
+ runs=[
+ {
+ "id": "run-z",
+ "status": "running",
+ "last_activity_at": "2026-08-12T05:04:00Z",
+ }
+ ],
+ watches=[],
+ tasks=[],
+ runtime_snapshot={
+ "available": True,
+ "ownership_available": True,
+ "owned_run_ids": ["run-z"],
+ "agents": [],
+ },
+ now=datetime(2026, 8, 12, 5, 5, tzinfo=timezone.utc),
+ )
+
+ assert snapshot["runs"][0]["activity_age_seconds"] == 60
+
+
+def test_harness_status_cli_returns_one_unified_payload(monkeypatch, capsys) -> None:
+ sqlite_store = SimpleNamespace(
+ list_active_runs=lambda *, limit: [],
+ active_run_ids=lambda run_ids: set(run_ids),
+ list_enabled_definitions=lambda definition_type, *, limit: [],
+ )
+ monkeypatch.setattr(
+ cli,
+ "_task_request_store",
+ lambda: SimpleNamespace(sqlite_backend=sqlite_store),
+ )
+
+ async def _controller_snapshot(*, run_ids):
+ assert run_ids == []
+ return {
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "agents": [],
+ "owned_run_ids": [],
+ "ownership_available": True,
+ "ownership_error": None,
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "list_running_agents", _controller_snapshot)
+ args = cli.build_parser().parse_args(["harness", "status"])
+
+ assert cli.cmd_harness_status(args) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["kind"] == "harness_status"
+ assert payload["controller"] == {
+ "available": True,
+ "ownership_available": True,
+ "error": None,
+ }
+ assert payload["anomalies"] == []
+
+
+def test_harness_status_cli_revalidates_runs_after_ownership_snapshot(
+ monkeypatch, capsys
+) -> None:
+ run = {"id": "run-finished", "status": "running"}
+ sqlite_store = SimpleNamespace(
+ list_active_runs=lambda *, limit: [run],
+ active_run_ids=lambda run_ids: set(),
+ list_enabled_definitions=lambda definition_type, *, limit: [],
+ )
+ monkeypatch.setattr(
+ cli,
+ "_task_request_store",
+ lambda: SimpleNamespace(sqlite_backend=sqlite_store),
+ )
+
+ async def _controller_snapshot(*, run_ids):
+ assert run_ids == ["run-finished"]
+ return {
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "agents": [],
+ "owned_run_ids": [],
+ "ownership_available": True,
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "list_running_agents", _controller_snapshot)
+
+ assert cli.cmd_harness_status(SimpleNamespace()) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["runs"] == []
+ assert payload["anomalies"] == []
+
+
+def test_harness_status_cli_preserves_pre_snapshot_run_truncation(
+ monkeypatch, capsys
+) -> None:
+ runs = [{"id": f"run-{index}", "status": "running"} for index in range(101)]
+ sqlite_store = SimpleNamespace(
+ list_active_runs=lambda *, limit: runs,
+ active_run_ids=lambda run_ids: {"run-0"},
+ list_enabled_definitions=lambda definition_type, *, limit: [],
+ )
+ monkeypatch.setattr(
+ cli,
+ "_task_request_store",
+ lambda: SimpleNamespace(sqlite_backend=sqlite_store),
+ )
+
+ async def _controller_snapshot(*, run_ids):
+ return {
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "agents": [],
+ "owned_run_ids": ["run-0"],
+ "ownership_available": True,
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "list_running_agents", _controller_snapshot)
+
+ assert cli.cmd_harness_status(SimpleNamespace()) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert [row["id"] for row in payload["runs"]] == ["run-0"]
+ assert payload["truncated"]["runs"] is True
+
+
+def test_harness_status_prioritizes_running_run_before_bounded_probe(
+ tmp_path, monkeypatch, capsys
+) -> None:
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ _enqueue_running(store, "run-owner-missing")
+ for index in range(101):
+ minute, second = divmod(index, 60)
+ observed_at = f"2026-08-12T06:{minute:02d}:{second:02d}+00:00"
+ if index >= 99:
+ observed_at = "2026-08-12T06:02:00+00:00"
+ store.enqueue_run(
+ {
+ "id": f"run-queued-{index:03d}",
+ "request_type": "agent_run",
+ "status": "queued",
+ "agent_name": "codex",
+ "agent_backend": "codex",
+ "session_id": "ses-live",
+ "message": "continue",
+ "created_at": observed_at,
+ "updated_at": observed_at,
+ }
+ )
+
+ monkeypatch.setattr(
+ cli,
+ "_task_request_store",
+ lambda: SimpleNamespace(sqlite_backend=store),
+ )
+ probed_run_ids = []
+
+ async def _controller_snapshot(*, run_ids):
+ probed_run_ids.extend(run_ids)
+ return {
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "agents": [],
+ "owned_run_ids": [],
+ "ownership_available": True,
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "list_running_agents", _controller_snapshot)
+
+ assert cli.cmd_harness_status(SimpleNamespace()) == 0
+ payload = json.loads(capsys.readouterr().out)
+
+ assert probed_run_ids[:3] == [
+ "run-owner-missing",
+ "run-queued-100",
+ "run-queued-099",
+ ]
+ assert "run-owner-missing" in {row["id"] for row in payload["runs"]}
+ assert payload["truncated"]["runs"] is True
+ assert payload["anomalies"][0]["code"] == "run_owner_missing"
+ assert payload["anomalies"][0]["run_id"] == "run-owner-missing"
+ finally:
+ store.close()
+
+
+def test_harness_cli_help_uses_configured_language(monkeypatch, capsys) -> None:
+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")
+
+ with pytest.raises(SystemExit) as exc_info:
+ cli.build_parser().parse_args(["harness", "--help"])
+
+ assert exc_info.value.code == 0
+ output = capsys.readouterr().out
+ assert "检查活跃 Run、已启用 Watch、即将触发的 Task 和实时异常" in output
+ assert "显示有界的实时状态与异常快照" in output
+
+
+def test_enabled_tasks_are_bounded_after_next_fire_ordering(tmp_path) -> None:
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ for task_id, run_at, updated_at in (
+ ("task-imminent", "2099-01-01T00:00:00+00:00", "2020-01-01T00:00:00+00:00"),
+ ("task-later", "2099-02-01T00:00:00+00:00", "2026-08-12T00:00:00+00:00"),
+ ("task-latest", "2099-03-01T00:00:00+00:00", "2026-08-13T00:00:00+00:00"),
+ ):
+ store.upsert_scheduled_task(
+ {
+ "id": task_id,
+ "name": task_id,
+ "schedule_type": "at",
+ "run_at": run_at,
+ "timezone": "UTC",
+ "enabled": True,
+ "created_at": updated_at,
+ "updated_at": updated_at,
+ }
+ )
+
+ tasks = store.list_enabled_definitions("scheduled", limit=2)
+
+ assert [task["id"] for task in tasks] == ["task-imminent", "task-later"]
+ finally:
+ store.close()
+
+
+def test_unified_view_sorts_task_fire_times_as_instants() -> None:
+ snapshot = build_harness_status(
+ runs=[],
+ watches=[],
+ tasks=[
+ {"id": "later", "next_run_at": "2026-08-12T08:00:00+00:00"},
+ {"id": "earlier", "next_run_at": "2026-08-12T09:00:00+02:00"},
+ ],
+ runtime_snapshot={"available": True, "ownership_available": True},
+ )
+
+ assert [task["id"] for task in snapshot["tasks"]] == ["earlier", "later"]
+
+
+def test_enabled_watches_prioritize_dead_waiters_before_limit(tmp_path) -> None:
+ store = SQLiteBackgroundTaskStore(tmp_path / "state.sqlite")
+ try:
+ for index in range(3):
+ store.upsert_watch(
+ {
+ "id": f"watch-{index}",
+ "name": f"watch-{index}",
+ "shell_command": "true",
+ "enabled": True,
+ "created_at": f"2026-08-12T00:00:0{index}+00:00",
+ "updated_at": f"2026-08-12T00:00:0{index}+00:00",
+ }
+ )
+ store.write_watch_runtime(
+ {"watches": {"watch-0": {"running": True, "pid": 42}}},
+ updated_at="2026-08-12T00:00:03+00:00",
+ )
+ store.write_watch_runtime(
+ {"watches": {}},
+ updated_at="2026-08-12T00:00:04+00:00",
+ )
+
+ watches = store.list_enabled_definitions("watch", limit=2)
+
+ assert watches[0]["id"] == "watch-0"
+ assert watches[0]["process_alive"] is False
+ assert len(watches) == 2
+ finally:
+ store.close()
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index abf0e23d5..cf8977daa 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -175,6 +175,37 @@ def test_dispatch_async_missing_socket_raises_unavailable(tmp_path):
asyncio.run(internal_client.dispatch_async({"session_id": "s", "text": "x"}, socket_path=sock))
+def test_running_agents_ownership_snapshot_posts_bounded_candidates(socket_path):
+ app = FastAPI()
+ captured: dict = {}
+
+ @app.post("/internal/running-agents/snapshot")
+ async def _snapshot(payload: dict):
+ captured.update(payload)
+ return {
+ "ok": True,
+ "agents": [],
+ "owned_run_ids": payload["run_ids"][:1],
+ }
+
+ async def _go():
+ fake_transport = httpx.ASGITransport(app=app)
+ with patch(
+ "vibe.internal_client.httpx.AsyncHTTPTransport",
+ return_value=fake_transport,
+ ):
+ return await internal_client.list_running_agents(
+ run_ids=["run-a", "run-b"],
+ socket_path=socket_path,
+ )
+
+ result = asyncio.run(_go())
+
+ assert captured == {"run_ids": ["run-a", "run-b"]}
+ assert result["status_code"] == 200
+ assert result["body"]["owned_run_ids"] == ["run-a"]
+
+
def test_dispatch_async_read_timeout_reports_acceptance_unknown(socket_path):
sock = socket_path
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index baa2c9655..bd72e99a3 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -378,6 +378,38 @@ def test_memory_final_flush_delegates_identity_to_controller() -> None:
controller.memory_scope_for_cli_session.assert_not_called()
+def test_running_agents_snapshot_bounds_ownership_candidates(monkeypatch) -> None:
+ controller = _build_controller_double()
+ captured = []
+
+ def _snapshot(_controller, *, ownership_candidate_run_ids=None):
+ captured.append(ownership_candidate_run_ids)
+ return {"ok": True, "agents": [], "owned_run_ids": []}
+
+ monkeypatch.setattr("core.services.running_agents.snapshot_running_agents", _snapshot)
+ app = internal_server.create_app(controller)
+
+ async def _exercise():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ valid = await client.post(
+ "/internal/running-agents/snapshot",
+ json={"run_ids": ["run-a", "run-b"]},
+ )
+ oversized = await client.post(
+ "/internal/running-agents/snapshot",
+ json={"run_ids": [f"run-{index}" for index in range(102)]},
+ )
+ return valid, oversized
+
+ valid, oversized = asyncio.run(_exercise())
+
+ assert valid.status_code == 200
+ assert oversized.status_code == 400
+ assert oversized.json()["error"] == "invalid_run_candidates"
+ assert captured == [["run-a", "run-b"]]
+
+
def test_memory_archive_session_delegates_raw_identity_with_bounded_lifecycle() -> None:
controller = _build_controller_double()
controller.memory_scope_for_cli_session = Mock(
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index 62902b327..a2afbd367 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import sys
import asyncio
import tempfile
+import threading
import unittest
from pathlib import Path
from types import SimpleNamespace
@@ -90,6 +91,49 @@ class _StubController:
class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
+ async def test_nonterminal_agent_output_records_run_activity(self):
+ controller = _StubController()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-live",
+ },
+ )
+ calls = []
+ event_loop_thread = threading.get_ident()
+ entered = threading.Event()
+ release = threading.Event()
+
+ class _Store:
+ def record_run_activity(self, run_ids):
+ calls.append((list(run_ids), threading.get_ident()))
+ entered.set()
+ release.wait(timeout=2)
+
+ controller.scheduled_task_service = SimpleNamespace(request_store=_Store())
+ first_emit = asyncio.create_task(
+ dispatcher.emit_agent_message(context, "assistant", "working")
+ )
+ self.assertTrue(await asyncio.to_thread(entered.wait, 1))
+ await asyncio.wait_for(first_emit, timeout=0.5)
+ for index in range(3):
+ await asyncio.wait_for(
+ dispatcher.emit_agent_message(
+ context, "assistant", f"working {index}"
+ ),
+ timeout=0.5,
+ )
+ release.set()
+ await dispatcher.drain_agent_run_activity()
+
+ self.assertEqual(calls[0][0], ["run-live"])
+ self.assertNotEqual(calls[0][1], event_loop_thread)
+ self.assertEqual([run_ids for run_ids, _thread_id in calls], [["run-live"]] * 2)
+
async def test_detached_output_uses_explicit_run_lineage_over_receiver_context(self):
controller = _StubController()
controller.agent_service = SimpleNamespace(
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 39eb98838..4d90c4c10 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -1638,7 +1638,11 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("--session-key", prompt)
self.assertNotIn("Channel-level session key:", prompt)
self.assertIn("### Inspecting Harness state", prompt)
- self.assertIn("Use `vibe data query` to inspect Avibe state with guarded read-only SQL", prompt)
+ self.assertIn("Use `vibe harness status` first for active Runs", prompt)
+ self.assertIn(
+ "Use `vibe data query` for deeper guarded read-only SQL before changing a Harness",
+ prompt,
+ )
self.assertIn("select name from sqlite_master where type='table' order by name", prompt)
self.assertIn("schema discovery, current session lookup, existing task/watch inspection, Agent run history", prompt)
self.assertIn("### Choosing the right Harness shape", prompt)
diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.py
index fa8baca54..5d4694257 100644
--- a/tests/test_running_agents_service.py
+++ b/tests/test_running_agents_service.py
@@ -155,6 +155,72 @@ def test_safe_call_retries_runtime_error_then_falls_back():
assert running_agents._safe_call(_always, []) == []
+def test_snapshot_projects_exact_run_ownership_and_probe_failure():
+ controller = _make_controller()
+ controller.scheduled_task_service = types.SimpleNamespace(
+ snapshot_owned_agent_run_ids=lambda candidates: candidates & {"run-b", "run-a"}
+ )
+
+ snapshot = running_agents.snapshot_running_agents(
+ controller,
+ ownership_candidate_run_ids=["run-a", "run-b", "run-c"],
+ )
+
+ assert snapshot["ownership_available"] is True
+ assert snapshot["owned_run_ids"] == ["run-a", "run-b"]
+ assert snapshot["ownership_error"] is None
+
+ def _failed_probe(_candidates):
+ raise RuntimeError("turn provider unavailable")
+
+ controller.scheduled_task_service.snapshot_owned_agent_run_ids = _failed_probe
+ failed = running_agents.snapshot_running_agents(
+ controller,
+ ownership_candidate_run_ids=["run-a"],
+ )
+ assert failed["ownership_available"] is False
+ assert failed["owned_run_ids"] == []
+ assert failed["ownership_error"] == "ownership_probe_failed"
+
+
+def test_scheduled_service_ownership_snapshot_uses_pure_turn_projection():
+ from core.scheduled_tasks import ScheduledTaskService
+
+ calls = []
+ service = object.__new__(ScheduledTaskService)
+ service._inflight_executions = {"run-drain": object()}
+ service.controller = types.SimpleNamespace(
+ session_turns=types.SimpleNamespace(
+ snapshot_owned_agent_run_ids=lambda candidates: calls.append(
+ ("snapshot", candidates)
+ )
+ or {"run-turn"},
+ owned_agent_run_ids=lambda: calls.append("reconcile") or {"run-turn"},
+ )
+ )
+
+ assert service.snapshot_owned_agent_run_ids({"run-drain", "run-turn"}) == {
+ "run-drain",
+ "run-turn",
+ }
+ assert calls == [("snapshot", {"run-drain", "run-turn"})]
+
+
+def test_default_running_agents_snapshot_does_not_query_run_ownership():
+ controller = _make_controller()
+ controller.scheduled_task_service = types.SimpleNamespace(
+ snapshot_owned_agent_run_ids=lambda _candidates: pytest.fail(
+ "ordinary UI snapshot must not query Run ownership"
+ )
+ )
+
+ snapshot = running_agents.snapshot_running_agents(controller)
+
+ assert snapshot["owned_run_ids"] == []
+ assert snapshot["ownership_available"] is True
+ assert snapshot["ownership_error"] is None
+
+
def test_claude_active_and_idle_rows():
c_active = _FakeClaudeClient("slack_111", "nat-a", "opus")
c_active._fake_pid = 4242
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 2f100e28c..75d441284 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -6531,6 +6531,8 @@ def test_owned_run_sweep_retries_terminal_turn_settlement_before_orphaning(
select(agent_runs.c.status).where(agent_runs.c.id == run_id)
).scalar_one() == "running"
+ assert run_id not in manager.snapshot_owned_agent_run_ids({run_id})
+ assert settlement.calls == 1
assert run_id not in manager.owned_agent_run_ids()
assert settlement.calls == 2
with engine.connect() as conn:
@@ -6539,6 +6541,51 @@ def test_owned_run_sweep_retries_terminal_turn_settlement_before_orphaning(
).scalar_one() == "succeeded"
+def test_snapshot_retains_pre_turn_delivery_ownership(managers) -> None:
+ manager, _restarted, engine, _engine_b, _starts = managers
+ run_id = "run-queued-delivery-owner"
+ delivery_id = delivery_store.new_delivery_id()
+ now = "2026-08-01T00:00:00Z"
+ with engine.begin() as conn:
+ delivery_store.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id="ses_fsm",
+ priority="p3",
+ state="queued",
+ snapshot=delivery_store.message_snapshot(
+ scope_id=None,
+ session_id="ses_fsm",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type="harness",
+ text="queued owner",
+ ),
+ dispatch_text="queued owner",
+ now=now,
+ )
+ conn.execute(
+ agent_runs.insert().values(
+ id=run_id,
+ definition_id=None,
+ run_type="agent_run",
+ status="running",
+ cancel_requested=0,
+ session_id="ses_fsm",
+ callback_session_id="ses_callback",
+ callback_status="pending",
+ delivery_id=delivery_id,
+ created_at=now,
+ started_at=now,
+ updated_at=now,
+ metadata_json="{}",
+ )
+ )
+
+ assert manager.snapshot_owned_agent_run_ids({run_id}) == {run_id}
+
+
@pytest.mark.parametrize("sent_before_recovery", [False, True])
def test_hfr_474_startup_collapses_legacy_restart_notices_by_durable_turn(
managers,
diff --git a/vibe/cli.py b/vibe/cli.py
index b288ad299..2cf9bd1cd 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -338,7 +338,7 @@ def _print_cli_payload(kind: str, **fields) -> None:
print(json.dumps(_cli_payload(kind, **fields), indent=2))
-def _memory_cli_language() -> str:
+def _configured_cli_language() -> str:
"""Read an optional configured language without creating or migrating state."""
try:
@@ -350,6 +350,10 @@ def _memory_cli_language() -> str:
return "en"
+def _memory_cli_language() -> str:
+ return _configured_cli_language()
+
+
_MEMORY_CLI_SOURCE_STATE_I18N_KEYS = {
"available": "memory.cli.sourceState.available",
"stale": "memory.cli.sourceState.stale",
@@ -3186,6 +3190,12 @@ def _agent_payload(agent, *, brief: bool = False) -> dict:
def _run_payload(run: dict, *, brief: bool = False) -> dict:
normalized = dict(run)
normalized["status"] = normalize_run_status(normalized.get("status"))
+ activity_at = normalized.get("last_activity_at") or normalized.get("started_at")
+ activity_basis = (
+ "output"
+ if normalized.get("last_activity_at")
+ else ("start" if activity_at else None)
+ )
if brief:
return {
"id": normalized.get("id"),
@@ -3196,6 +3206,9 @@ def _run_payload(run: dict, *, brief: bool = False) -> dict:
"definition_id": normalized.get("definition_id") or normalized.get("task_id"),
"created_at": normalized.get("created_at"),
"started_at": normalized.get("started_at"),
+ "last_activity_at": activity_at,
+ "activity_basis": activity_basis,
+ "activity_age_seconds": _seconds_since_iso(activity_at),
"completed_at": normalized.get("completed_at"),
"error": normalized.get("error"),
"callback_session_id": normalized.get("callback_session_id"),
@@ -3205,11 +3218,95 @@ def _run_payload(run: dict, *, brief: bool = False) -> dict:
return normalized
+def cmd_harness_status(_args) -> int:
+ """Print one bounded operational snapshot across Harness work types."""
+
+ from core.services.harness_status import build_harness_status
+ from vibe import internal_client
+
+ try:
+ language = _configured_cli_language()
+ request_store = _task_request_store()
+ sqlite_store = request_store.sqlite_backend
+ if sqlite_store is None:
+ raise RuntimeError(i18n_t("harness.cli.error.sqliteRequired", language))
+ fetch_limit = MAX_PAGE_LIMIT + 1
+ raw_runs = sqlite_store.list_active_runs(limit=fetch_limit)
+ raw_watches = sqlite_store.list_enabled_definitions(
+ "watch",
+ limit=fetch_limit,
+ )
+ raw_tasks = sqlite_store.list_enabled_definitions(
+ "scheduled",
+ limit=fetch_limit,
+ )
+ runs_truncated = len(raw_runs) > MAX_PAGE_LIMIT
+
+ try:
+ response = asyncio.run(
+ internal_client.list_running_agents(
+ run_ids=[str(row.get("id")) for row in raw_runs if row.get("id")]
+ )
+ )
+ body = response.get("body") if isinstance(response, dict) else None
+ runtime_snapshot = dict(body) if isinstance(body, dict) else {}
+ status_code = response.get("status_code") if isinstance(response, dict) else None
+ runtime_snapshot["available"] = status_code == 200 and bool(
+ runtime_snapshot.get("ok")
+ )
+ if not runtime_snapshot["available"]:
+ runtime_snapshot["error"] = i18n_t(
+ "harness.cli.error.controllerStatus",
+ language,
+ status=status_code,
+ )
+ except internal_client.InternalServerTimeout:
+ runtime_snapshot = {
+ "available": False,
+ "error": i18n_t("harness.cli.error.controllerTimeout", language),
+ }
+ except internal_client.InternalServerUnavailable:
+ runtime_snapshot = {
+ "available": False,
+ "error": i18n_t("harness.cli.error.controllerUnavailable", language),
+ }
+
+ # Ownership is a point-in-time controller fact. Keep only Runs that were
+ # active on both sides of that snapshot so a Run completing during the
+ # request cannot be mislabeled as owner-missing.
+ active_run_ids_after = sqlite_store.active_run_ids(
+ row.get("id") for row in raw_runs
+ )
+ raw_runs = [
+ row for row in raw_runs if str(row.get("id")) in active_run_ids_after
+ ]
+
+ snapshot = build_harness_status(
+ runs=raw_runs[:MAX_PAGE_LIMIT],
+ watches=raw_watches[:MAX_PAGE_LIMIT],
+ tasks=raw_tasks[:MAX_PAGE_LIMIT],
+ runtime_snapshot=runtime_snapshot,
+ truncated={
+ "runs": runs_truncated,
+ "watches": len(raw_watches) > MAX_PAGE_LIMIT,
+ "tasks": len(raw_tasks) > MAX_PAGE_LIMIT,
+ },
+ )
+ _print_cli_payload("harness_status", **snapshot)
+ return 0
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe harness status --help")
+ return 1
+
+
def _seconds_since_iso(timestamp: object) -> float | None:
if not isinstance(timestamp, str) or not timestamp.strip():
return None
+ text = timestamp.strip()
+ if text.endswith(("Z", "z")):
+ text = f"{text[:-1]}+00:00"
try:
- started_at = datetime.fromisoformat(timestamp)
+ started_at = datetime.fromisoformat(text)
except ValueError:
return None
if started_at.tzinfo is None:
@@ -14453,6 +14550,24 @@ def build_parser():
runs_cancel_parser.add_argument("run_id")
_add_json_noop(runs_cancel_parser)
+ harness_help_language = _configured_cli_language()
+ harness_parser = subparsers.add_parser(
+ "harness",
+ help=i18n_t("harness.cli.help.command", harness_help_language),
+ description=i18n_t("harness.cli.help.description", harness_help_language),
+ error_help_command="vibe harness --help",
+ )
+ harness_subparsers = harness_parser.add_subparsers(
+ dest="harness_command",
+ metavar="{status}",
+ )
+ harness_subparsers.required = True
+ harness_status_parser = harness_subparsers.add_parser(
+ "status",
+ help=i18n_t("harness.cli.help.status", harness_help_language),
+ )
+ _add_json_noop(harness_status_parser)
+
session_parser = subparsers.add_parser(
"session",
help="Inspect, control, and update Agent sessions",
@@ -15745,6 +15860,10 @@ def main():
if args.runs_command == "cancel":
sys.exit(cmd_runs_cancel(args))
parser.error("runs command is required")
+ if args.command == "harness":
+ if args.harness_command == "status":
+ sys.exit(cmd_harness_status(args))
+ parser.error("harness command is required")
if args.command == "session":
if args.session_command == "list":
sys.exit(cmd_session_list(args))
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index ca92ceb1b..6c1e94f63 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -21,6 +21,19 @@
},
"harness": {
"agentInitiatedContinuation": "Agent-initiated continuation",
+ "cli": {
+ "help": {
+ "command": "Inspect unified Harness live state and anomalies",
+ "description": "Inspect active Runs, armed Watches, upcoming Tasks, and live anomalies.",
+ "status": "Show the bounded live/anomaly snapshot"
+ },
+ "error": {
+ "sqliteRequired": "Harness status requires the SQLite task store.",
+ "controllerStatus": "The controller returned status {status}.",
+ "controllerTimeout": "The controller request timed out.",
+ "controllerUnavailable": "The controller is unreachable."
+ }
+ },
"promptEcho": {
"scheduled": "⏰ Scheduled task",
"watch": "👀 Watch",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 9b86659fe..4bf40d393 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -21,6 +21,19 @@
},
"harness": {
"agentInitiatedContinuation": "Agent 主动发起的续接",
+ "cli": {
+ "help": {
+ "command": "检查统一的 Harness 实时状态和异常",
+ "description": "检查活跃 Run、已启用 Watch、即将触发的 Task 和实时异常。",
+ "status": "显示有界的实时状态与异常快照"
+ },
+ "error": {
+ "sqliteRequired": "Harness 状态需要 SQLite Task 存储。",
+ "controllerStatus": "控制器返回状态码 {status}。",
+ "controllerTimeout": "控制器请求超时。",
+ "controllerUnavailable": "无法连接控制器。"
+ }
+ },
"promptEcho": {
"scheduled": "⏰ 定时任务",
"watch": "👀 监听",
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 1cab05c3e..c0e6b1ba1 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -986,7 +986,11 @@ async def turn_state(session_id: str, *, socket_path: Optional[Path] = None) ->
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
-async def list_running_agents(*, socket_path: Optional[Path] = None) -> dict[str, Any]:
+async def list_running_agents(
+ *,
+ run_ids: Optional[list[str]] = None,
+ socket_path: Optional[Path] = None,
+) -> dict[str, Any]:
"""Fetch the controller's read-only running-agents snapshot.
Returns ``{status_code, body}``; raises ``InternalServerUnavailable`` on
@@ -1004,7 +1008,13 @@ async def list_running_agents(*, socket_path: Optional[Path] = None) -> dict[str
base_url="http://localhost",
timeout=httpx.Timeout(3.0, connect=0.5),
) as client:
- resp = await client.get("/internal/running-agents")
+ if run_ids is None:
+ resp = await client.get("/internal/running-agents")
+ else:
+ resp = await client.post(
+ "/internal/running-agents/snapshot",
+ json={"run_ids": run_ids},
+ )
except httpx.ReadTimeout as exc:
raise InternalServerTimeout(str(exc)) from exc
except _SOCKET_CONNECT_ERRORS as exc: