v0.15.0: Metrics granularity — per-member / per-task / org + CEO scorecards (#289)

* feat(metrics): capture per-session turns + tool_calls (phase 1)

Persist LLM iterations (turns) and tool invocations per agent spawn session,
the raw signal the granular per-member performance metrics build on (real
effort/iterations vs wall-clock).

- sum_transcript_usage returns a 5-tuple adding turns = unique assistant
  message-id count; _usage_from_transcript + _resolve_active_tokens updated to
  the 5-tuple (active-tokens keeps its 4-tuple contract by slicing).
- SDK: _SessionState.turns, set by /usage/sync; /usage/status (TokenUsageStatus)
  now carries turns + tool_calls (= total_calls).
- orchestrator: new _resolve_final_turns_tools (SDK primary, transcript fallback
  for turns only; Grok -> 0/0) wired into _finalize_spawn_session, which writes
  turns + tool_calls to agent_spawn_sessions.
- migration 055 adds turns + tool_calls (BigInteger DEFAULT 0 -> historical/Grok
  rows read 0, surfaced as n/a). Verified real alembic upgrade/downgrade.

Part of metrics-granularity (v0.15.0); recon-adjusted plan on disk.

* feat(metrics): pure compute_stage_effort helper (phase 2, part 1)

Foundation-layer overlap math (no DB): split each task status window into
active (merged wall-clock overlap of spawn stints — concurrent stints counted
once, so active <= window) vs wait (queue/review idle). Distinct from summed
effort. The per-task metrics service will feed it audit-log windows + spawn
stints. 9 unit tests (disjoint/nested/partial/merged/clamped/zero/multi-window).

* feat(metrics): per-task live metrics + GET /metrics/task/{id} (phase 2)

TaskMetrics dataclass + MetricsService.get_task_metrics: summed spawn effort
(vs wall-clock), turns/tool_calls/tokens/cost, per-stage active-vs-wait
(compute_stage_effort over audit windows x spawn stints), and who-caused-rework
(revision_count + named qa/pr fail events). Open stints and the open final
stage window close at completed_at for a terminal task (else now), so stages
don't grow past completion. Exposed at GET /dashboard/metrics/task/{task_id}
(404 if absent). Real-PG tests (compose/none/in-flight) + route tests (200/404).

* feat(metrics): CEO-as-member scorecard + ceo_reject audit regression (phase 3)

The human CEO is a measured member, read purely from audit_log (agent_role='ceo'
serializes from the CEO StrEnum): approval dwell (awaiting_ceo_approval -> a CEO
decision, incl. the coordination-root reject that lands in pending), unblock
dwell (blocked -> a CEO revive), and god-mode action count (every CEO-attributed
transition). CeoScorecard + MetricsService.get_ceo_scorecard (p50/p90 via
PERCENTILE_CONT, expanding IN for the decision sets) + GET
/dashboard/metrics/member/ceo (declared before any future member/{id} route).

The ceo_reject coordination-root audit gap the plan meant to close was already
closed by the gap-sweep (routes through admin_set_status -> agent_role='ceo'
audit); locked with a regression assertion in the existing coordination-reject
test. Real-PG tests: approval/unblock/godmode, non-ceo exclusion, empty->zeros.

* feat(metrics): audit instrumentation for escalations/blocked-others/idle (phase 4a)

The three extra per-member metrics that had no data source get durable,
in-session audit events (additive; never gate the underlying action):
- apply_escalation -> task.escalated (details.escalator_slug) on both the
  normal block path and the pool-divert path -> escalations count.
- _unblock_dependents -> task.unblocked_dependents (details.count) on the
  completed BLOCKER task, captured before the dependency edges are pruned ->
  blocked-others count (sweeper attributes to the blocker's owner).
- mark_agent_idle -> agent.idle (details.agent_slug) -> idle/utilization (the
  sweeper pairs an idle mark to the member's next spawn for idle duration).
(QA pass-rate needs no new event — reuses task.awaiting_documentation[qa] +
task.qa_fail.) Real-PG tests for each; 111 transition tests still green.

* feat(metrics): member_performance_daily rollup table + migration 056 (phase 4b)

The per-member scorecard rollup: one row per (date, member_kind, agent_slug),
CEO as a first-class member_kind='ceo' row (agent_slug='' NOT NULL so the
NULL-distinct UNIQUE keeps it unique). Full column set + the four CEO-approved
extras (qa_reviews_total/passed, escalations, blocked_others, idle_seconds) plus
blocked_seconds. Overwrite-upsert on (date, member_kind, agent_slug) for an
idempotent sweep. Migration 056 verified real up/down (24 cols, 4 indexes).

* feat(metrics): _sweep_member_performance rollup sweeper (phase 4c)

The daily per-member rollup sweep (mirrors _sweep_daily_rollup): a trailing
7-day, idempotent overwrite-upsert wired into _run_sweep. One focused query per
metric merges into a (date, agent_slug) accumulator — spawn effort/turns/tokens/
cost, completed/first-pass/revisions-received, revisions-caused (qa/pr fails),
QA pass-rate (passed + total), escalations (by escalator_slug), blocked-others
(unblocked_dependents by blocker owner), idle_seconds (idle mark -> next spawn),
blocked_seconds (blocked dwell) — plus one CEO row/day (approval/unblock dwell +
god-mode). Real-PG test asserts every facet + idempotency (a 2nd sweep
overwrites, never doubles); spawn-day != completion-day split is by-design.

* feat(metrics): member/org rollup scorecards + endpoints + live overlay (phase 5)

MemberScorecard + OrgScorecard with derived rates (FPY, effort-throughput,
turns/tool-calls per task, QA pass-rate, utilization) — all division-guarded to
None. get_member_scorecard reads member_performance_daily by slug and overlays
the member's live in-flight (non-terminal) tasks' effort via get_task_metrics
(disjoint by status: completion counts stay rollup-only, overlay only enriches
effort/turns/cost; includes_live_inflight flags it). get_org_scorecard
aggregates the cell (?team=) or whole org. Routes: GET /metrics/member/{agent_id}
(404 if absent, after the ceo literal route) + GET /metrics/org?team=. Real-PG
tests (derived rates, overlay no double-count, guards, org) + route tests.

* feat(metrics): granular CEO completion notification (phase 6)

There was no CEO completion notification at all (EventType.TASK_COMPLETED was
defined but never emitted). Add notify_ceo_of_completion in
NotificationDeliveryService — a granular body (real effort vs wall-clock +
stints/turns/tool-calls/revisions[QA/PR]/cost from get_task_metrics; degrades to
wall-clock-only, turns 'n/a', when there are no spawn sessions). Reuses the
existing ALERT type (no enum migration; the notificationtype PG enum is fixed at
001). ceo_approve now emits TASK_COMPLETED + fires the notification (best-effort
via _notify_completion — never blocks completion); complete() emits
TASK_COMPLETED too (closes the dead-code gap; the WS bridge can forward it).
Pure formatter tests + real-PG notification test.

* [metrics-granularity] Phase 7: panel Scorecards tab + dashboard overview

Add the CEO-facing metrics surfaces for the granularity feature:

- New "Scorecards" tab on the Metrics page: org rollup headline, the
  CEO-as-member card (approval/unblock dwell + god-mode count), and a
  per-member table (completed, first-pass yield, active effort, turns/task,
  QA pass-rate, escalations, blocked-others, utilization). Each member row
  self-fetches its rollup scorecard; live in-flight rows carry a "live" badge.
- New dashboard overview card (ScorecardOverviewPanel): org-wide 30-day
  headline (completed, FPY, throughput/hr, active effort, cost) deep-linking
  into the Scorecards tab.
- Plumbing: TaskMetrics/MemberScorecard/OrgScorecard/CeoScorecard types,
  observability API client methods + empty fallbacks, and the four
  useCeoScorecard/useMemberScorecard/useOrgScorecard/useTaskMetrics hooks.

Panel gate green: tsc, eslint, prettier, vitest (175 tests, +6 new).

* [metrics-granularity] test: make completion-notification robust to shared-DB CEO

test_notify_ceo_of_completion_creates_alert errored in the full suite (passed
in isolation): the session-scoped test DB is shared across the run, and the
sibling real-DB board-gate test commits a role=CEO agent (slug="ceo") without
cleanup — so my env fixture's hardcoded slug="ceo" insert hit a unique-constraint
violation, and a second role=CEO row would also make _get_ceo_agent()'s
scalar_one_or_none() raise. Reuse an existing CEO when present (the singleton the
production system actually has), else create one with a unique slug. Order-
independent. Also reflow test_metrics_instrumentation.py to ruff format.

* chore(release): 0.15.0

Metrics granularity: per-member/per-task/org + CEO-as-member scorecards,
turn/tool-call capture (migration 055), member_performance_daily rollup
(migration 056) with QA pass-rate / escalations / blocked-others / utilization,
per-task active-vs-wait metrics, granular completion notification, panel
Scorecards tab + dashboard Performance card, and the ceo_reject audit fix.

Version bump across the canonical set + CHANGELOG.

* [metrics-granularity] fix pre-tag audit findings (overlay double-count + panel error states)

Adversarial review before the v0.15.0 tag surfaced two real logical gaps:

- MAJOR (backend): the live in-flight overlay re-summed ALL sessions of every
  non-terminal task via get_task_metrics, but _msweep_spawn already rolls up
  every CLOSED session regardless of task status — so a closed session on a
  still-open task was counted twice (rollup + overlay), permanently inflating a
  member's effort/turns/tokens/cost on the common reap/respawn path. The overlay
  now sums only OPEN sessions (ended_at IS NULL), which the closed-only rollup
  can never contain — disjoint by construction. A just-closed session lands in
  the rollup on the next ~60s sweep (no gap of note). Aggregated in SQL to mirror
  _msweep_spawn. Regression test reproduces the double-count (turns 10→5).

- MAJOR (panel): the four new scorecard surfaces used `isLoading || !data` with
  no isError branch, so a failed query span forever on a skeleton. They now
  surface a load error. Tests added.

Also: OrgSummary active-effort formatting no longer round-trips hours→seconds→
hours; dashboard grid uses xl:grid-cols-4 (was 2xl) so 4 panels show at 1280px;
corrected the inaccurate "NULL distinct" CEO-row uniqueness comment (agent_slug
is NOT NULL; the '' tuple is simply distinct from agent rows).

make quality GREEN (cov 95.31%); panel GREEN (vitest 178).

* [metrics-granularity] fix: decode bytes stream message-id before XCLAIM

StreamEventBus._recover_stream passed the pending message id to XCLAIM via
str() on the raw bytes the client returns (redis client has no
decode_responses), producing "b'1782066556728-0'". Redis rejects that with
"Unrecognized XCLAIM option", so pending-message recovery threw on every
reclaim tick and unacked messages from crashed/slow consumers were never
reclaimed (leaking in the PEL on every stream, spamming the error log). Decode
via the existing _to_str helper — the fix the sibling claim path already uses.

Pre-existing in v0.14.0 (unrelated to metrics granularity); folded into this
release per CEO. TDD regression test + CHANGELOG entry. make quality GREEN.

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
Renzo F
2026-07-01 05:18:45 +02:00
committed by GitHub
co-authored by Renn F
parent 1e341c766e
commit a8cb2470ba
47 changed files with 4225 additions and 40 deletions
@@ -0,0 +1,95 @@
"""sum_transcript_usage — token + turn counts from a Claude Code JSONL transcript.
The 5th return value is the LLM turn count: the number of UNIQUE assistant
``message.id``s (Claude Code logs one line per content block, all sharing the
message id, so naive line-counting would inflate both tokens and turns).
"""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from roboco.agent_sdk.transcript_usage import sum_transcript_usage
if TYPE_CHECKING:
from pathlib import Path
_EXPECTED_TUPLE_LEN = 5
def _line(msg_id: str | None, **usage: int) -> str:
msg: dict[str, object] = {"usage": usage}
if msg_id is not None:
msg["id"] = msg_id
return json.dumps({"message": msg})
def _write(path: Path, lines: list[str]) -> None:
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def test_returns_five_tuple(tmp_path: Path) -> None:
f = tmp_path / "t.jsonl"
_write(f, [_line("m1", input_tokens=10, output_tokens=5)])
result = sum_transcript_usage(f)
assert len(result) == _EXPECTED_TUPLE_LEN
def test_turns_counts_unique_message_ids(tmp_path: Path) -> None:
f = tmp_path / "t.jsonl"
_write(
f,
[
_line("m1", input_tokens=10, output_tokens=5),
_line("m2", input_tokens=20, output_tokens=7),
_line("m3", input_tokens=1, output_tokens=1),
],
)
_in, _out, _cr, _cw, turns = sum_transcript_usage(f)
expected_turns = 3
assert turns == expected_turns
def test_repeated_message_id_counts_one_turn_and_one_usage(tmp_path: Path) -> None:
# Claude Code emits one line per content block of the SAME assistant message,
# each repeating the usage — must count once for tokens AND turns.
f = tmp_path / "t.jsonl"
_write(
f,
[
_line("m1", input_tokens=10, output_tokens=5),
_line("m1", input_tokens=10, output_tokens=5),
_line("m1", input_tokens=10, output_tokens=5),
],
)
tin, tout, _cr, _cw, turns = sum_transcript_usage(f)
assert (tin, tout, turns) == (10, 5, 1)
def test_malformed_lines_skipped_without_losing_turn_count(tmp_path: Path) -> None:
f = tmp_path / "t.jsonl"
_write(
f,
[
_line("m1", input_tokens=10, output_tokens=5),
"not json at all {{{",
"",
_line("m2", input_tokens=2, output_tokens=2),
],
)
tin, _out, _cr, _cw, turns = sum_transcript_usage(f)
assert (tin, turns) == (12, 2)
def test_usage_line_without_id_sums_tokens_but_not_a_turn(tmp_path: Path) -> None:
f = tmp_path / "t.jsonl"
_write(
f,
[
_line(None, input_tokens=4, output_tokens=1),
_line("m1", input_tokens=6, output_tokens=1),
],
)
tin, _out, _cr, _cw, turns = sum_transcript_usage(f)
assert (tin, turns) == (10, 1)
+25 -3
View File
@@ -139,7 +139,11 @@ def test_missing_transcript_returns_zero_without_error(
"/usage/sync", json={"transcript_path": str(tmp_path / "nope.jsonl")}
)
assert resp.status_code == _OK
assert resp.json() == _expected([])
body = resp.json()
for key, value in _expected([]).items():
assert body[key] == value
assert body["turns"] == 0
assert body["tool_calls"] == 0
def test_malformed_lines_are_skipped(client: TestClient, tmp_path: Path) -> None:
@@ -167,7 +171,7 @@ def test_parser_handles_entries_without_message(tmp_path: Path) -> None:
json.dumps({"type": "system", "subtype": "init"}),
_assistant_line(rows[0]),
)
tin, tout, cread, cwrite = srv._sum_transcript_usage(transcript)
tin, tout, cread, cwrite, turns = srv._sum_transcript_usage(transcript)
exp = _expected(rows)
assert (tin, tout, cread, cwrite) == (
exp["tokens_input"],
@@ -175,6 +179,7 @@ def test_parser_handles_entries_without_message(tmp_path: Path) -> None:
exp["tokens_cache_read"],
exp["tokens_cache_write"],
)
assert turns == 0 # _assistant_line carries no message id
def _assistant_line_with_id(row: _UsageRow, message_id: str) -> str:
@@ -214,7 +219,7 @@ def test_parser_dedupes_repeated_message_id(tmp_path: Path) -> None:
_assistant_line_with_id(msg, "msg_aaa"), # tool_use block (same id)
_assistant_line_with_id(other, "msg_bbb"),
)
tin, tout, cread, cwrite = srv._sum_transcript_usage(transcript)
tin, tout, cread, cwrite, turns = srv._sum_transcript_usage(transcript)
# Counted once per id: msg + other, NOT msg * 3 + other.
exp = _expected([msg, other])
assert (tin, tout, cread, cwrite) == (
@@ -223,3 +228,20 @@ def test_parser_dedupes_repeated_message_id(tmp_path: Path) -> None:
exp["tokens_cache_read"],
exp["tokens_cache_write"],
)
expected_turns = 2 # two unique message ids
assert turns == expected_turns
def test_sync_response_surfaces_turns(client: TestClient, tmp_path: Path) -> None:
"""/usage/sync (and thus /usage/status) reports the LLM turn count."""
transcript = tmp_path / "session.jsonl"
_write(
transcript,
_assistant_line_with_id((10, 5, 0, 0), "msg_a"),
_assistant_line_with_id((10, 5, 0, 0), "msg_a"), # same id
_assistant_line_with_id((2, 1, 0, 0), "msg_b"),
)
body = client.post("/usage/sync", json={"transcript_path": str(transcript)}).json()
expected_turns = 2
assert body["turns"] == expected_turns
assert "tool_calls" in body
@@ -0,0 +1,60 @@
"""The member_performance_daily rollup table — schema shape."""
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from roboco.db.tables import MemberPerformanceDailyTable
from sqlalchemy import UniqueConstraint
if TYPE_CHECKING:
from sqlalchemy import Table
_TABLE = cast("Table", MemberPerformanceDailyTable.__table__)
def test_table_name() -> None:
assert MemberPerformanceDailyTable.__tablename__ == "member_performance_daily"
def test_has_all_metric_columns_including_extras() -> None:
cols = set(_TABLE.columns.keys())
assert {
# core
"date",
"member_kind",
"agent_slug",
"team",
"role",
"tasks_completed",
"tasks_first_pass",
"revisions_caused",
"revisions_received",
"active_runtime_seconds",
"turns",
"tool_calls",
"tokens",
"cost_usd",
"ceo_approval_dwell_seconds",
"ceo_unblock_dwell_seconds",
"godmode_actions",
# the 4 CEO-approved extras + blocked_seconds
"qa_reviews_total",
"qa_reviews_passed",
"escalations",
"blocked_others",
"idle_seconds",
"blocked_seconds",
} <= cols
def test_natural_key_is_unique() -> None:
uniques = [c for c in _TABLE.constraints if isinstance(c, UniqueConstraint)]
key_sets = [{col.name for col in u.columns} for u in uniques]
assert {"date", "member_kind", "agent_slug"} in key_sets
def test_agent_slug_not_nullable() -> None:
# NOT NULL DEFAULT '' — else the CEO row (agent_slug NULL) would duplicate
# under Postgres' NULL-distinct UNIQUE semantics.
assert _TABLE.columns["agent_slug"].nullable is False
+37
View File
@@ -267,6 +267,43 @@ async def test_undecodable_message_is_acked_and_dead_lettered() -> None:
assert invoked == []
class _FakeRecoverRedis:
"""Fake whose xpending_range returns the message id as BYTES (the real
client has no decode_responses), and which captures the ids XCLAIM gets."""
def __init__(self, message_id: bytes) -> None:
self._message_id = message_id
self.claimed_ids: list[object] = []
async def xpending(self, *args: object, **kwargs: object) -> dict:
del args, kwargs
return {"pending": 1}
async def xpending_range(self, *args: object, **kwargs: object) -> list:
del args, kwargs
return [{"message_id": self._message_id, "time_since_delivered": 10_000}]
async def xclaim(self, *args: object, **kwargs: object) -> list:
del args
self.claimed_ids = cast("list[object]", kwargs.get("message_ids") or [])
return [] # nothing claimed back → no handling
@pytest.mark.asyncio
async def test_recover_stream_decodes_bytes_message_id_for_xclaim() -> None:
"""xpending_range returns the message id as bytes; _recover_stream must
decode it before XCLAIM. A raw ``str(bytes)`` yields ``"b'1782..-0'"``,
which Redis rejects with "Unrecognized XCLAIM option", so pending-message
recovery silently fails every reclaim tick."""
bus = StreamEventBus()
fake = _FakeRecoverRedis(b"1782066556728-0")
bus._redis = cast("Redis", fake)
await bus._recover_stream("roboco:stream:usage", idle_time_ms=0)
assert fake.claimed_ids == ["1782066556728-0"] # decoded, not "b'...'"
# --- periodic reclaim: a runtime handler failure is retried without a restart ---
+100
View File
@@ -0,0 +1,100 @@
"""compute_stage_effort — split each stage window into active vs wait seconds.
Pure overlap math (no DB): given a stage's [start, end) window and the agent
spawn stints that ran during the task, ``active`` is the wall-clock time during
which AT LEAST ONE stint was running (overlapping stints merged, so active can
never exceed the window), and ``wait`` is the remainder. This is the wall-clock
decomposition — distinct from summed effort (Σ stint durations), which can
exceed wall-clock when stints run concurrently.
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from roboco.foundation.policy.stage_effort import StageEffort, compute_stage_effort
_BASE = datetime(2026, 7, 1, 12, 0, 0, tzinfo=UTC)
def _at(seconds: int) -> datetime:
return _BASE + timedelta(seconds=seconds)
def _window(status: str, start_s: int, end_s: int) -> tuple[str, datetime, datetime]:
return (status, _at(start_s), _at(end_s))
def _stint(start_s: int, end_s: int) -> tuple[datetime, datetime]:
return (_at(start_s), _at(end_s))
def _only(windows: list, stints: list) -> StageEffort:
result = compute_stage_effort(windows, stints)
assert len(result) == 1
return result[0]
def test_disjoint_stint_is_all_wait() -> None:
eff = _only([_window("in_progress", 0, 100)], [_stint(200, 300)])
assert (eff.active_seconds, eff.wait_seconds) == (0, 100)
def test_fully_nested_stint() -> None:
eff = _only([_window("in_progress", 0, 100)], [_stint(20, 50)])
assert (eff.active_seconds, eff.wait_seconds) == (30, 70)
def test_partial_overlap_clips_to_window() -> None:
# stint runs 80..150 but window ends at 100 -> only 20s active in-window.
eff = _only([_window("in_progress", 0, 100)], [_stint(80, 150)])
assert (eff.active_seconds, eff.wait_seconds) == (20, 80)
def test_multiple_nonoverlapping_stints_sum() -> None:
eff = _only(
[_window("in_progress", 0, 100)],
[_stint(0, 10), _stint(40, 60)],
)
assert (eff.active_seconds, eff.wait_seconds) == (30, 70)
def test_overlapping_stints_are_merged_not_double_counted() -> None:
# [10,40) and [30,60) overlap -> merged union is [10,60) = 50s, NOT 60s.
eff = _only(
[_window("in_progress", 0, 100)],
[_stint(10, 40), _stint(30, 60)],
)
# merged union [10,60) = 50s active, 50s wait (NOT 60s from double-count).
assert (eff.active_seconds, eff.wait_seconds) == (50, 50)
def test_active_never_exceeds_window_length() -> None:
eff = _only(
[_window("in_progress", 0, 100)],
[_stint(-50, 500)], # stint dwarfs the window
)
assert (eff.active_seconds, eff.wait_seconds) == (100, 0)
def test_zero_length_window() -> None:
eff = _only([_window("claimed", 50, 50)], [_stint(0, 100)])
assert (eff.active_seconds, eff.wait_seconds) == (0, 0)
def test_each_window_decomposes_independently() -> None:
windows = [_window("claimed", 0, 100), _window("in_progress", 100, 300)]
stints = [_stint(50, 250)] # spans both windows
result = compute_stage_effort(windows, stints)
by_status = {e.status: e for e in result}
claimed = by_status["claimed"]
in_progress = by_status["in_progress"]
assert (claimed.active_seconds, claimed.wait_seconds) == (50, 50)
# in_progress: stint covers 100..250 of the 100..300 window.
assert (in_progress.active_seconds, in_progress.wait_seconds) == (150, 50)
def test_to_dict_shape() -> None:
eff = _only([_window("in_progress", 0, 100)], [_stint(20, 50)])
d = eff.to_dict()
assert d == {"status": "in_progress", "active_seconds": 30, "wait_seconds": 70}
@@ -269,7 +269,7 @@ async def test_finalize_spawn_session_http_error_uses_zero_tokens() -> None:
with (
patch("roboco.runtime.orchestrator.httpx.AsyncClient", _client_cls),
patch.object(orch, "_usage_from_transcript", return_value=(0, 0, 0, 0)),
patch.object(orch, "_usage_from_transcript", return_value=(0, 0, 0, 0, 0)),
patch("roboco.db.base.get_session_factory", return_value=db_factory),
patch("roboco.billing.pricing.calculate_cost", return_value=0.0) as mock_cost,
):
@@ -303,7 +303,7 @@ async def test_finalize_spawn_session_non_200_uses_zero_tokens() -> None:
with (
patch("roboco.runtime.orchestrator.httpx.AsyncClient", _client_cls),
patch.object(orch, "_usage_from_transcript", return_value=(0, 0, 0, 0)),
patch.object(orch, "_usage_from_transcript", return_value=(0, 0, 0, 0, 0)),
patch("roboco.db.base.get_session_factory", return_value=db_factory),
patch("roboco.billing.pricing.calculate_cost", return_value=0.0) as mock_cost,
):
@@ -389,7 +389,7 @@ async def test_sweep_token_snapshots_skips_zero_token_agents() -> None:
with (
patch("roboco.runtime.orchestrator.httpx.AsyncClient", _client_cls),
patch.object(orch, "_usage_from_transcript", return_value=(0, 0, 0, 0)),
patch.object(orch, "_usage_from_transcript", return_value=(0, 0, 0, 0, 0)),
patch("roboco.db.base.get_session_factory", return_value=db_factory),
):
await orch._sweep_token_snapshots()
@@ -765,7 +765,9 @@ async def test_resolve_active_tokens_falls_back_to_transcript() -> None:
)
client = _FakeHTTPClient(_handler)
with patch.object(orch, "_usage_from_transcript", return_value=(6, 514, 100, 50)):
with patch.object(
orch, "_usage_from_transcript", return_value=(6, 514, 100, 50, 3)
):
tokens = await orch._resolve_active_tokens(
cast("httpx.AsyncClient", client), _AGENT_ID
)
@@ -790,7 +792,7 @@ async def test_resolve_active_tokens_prefers_sdk() -> None:
client = _FakeHTTPClient(_handler)
with patch.object(
orch, "_usage_from_transcript", return_value=(999, 999, 999, 999)
orch, "_usage_from_transcript", return_value=(999, 999, 999, 999, 0)
) as mock_tx:
tokens = await orch._resolve_active_tokens(
cast("httpx.AsyncClient", client), _AGENT_ID
@@ -800,6 +802,50 @@ async def test_resolve_active_tokens_prefers_sdk() -> None:
mock_tx.assert_not_called()
async def test_resolve_final_turns_tools_from_sdk() -> None:
"""turns + tool_calls come from the SDK /usage/status when present."""
orch = _make_orchestrator()
def _handler(_url: str) -> Any:
return _mock_response(200, {"turns": 7, "tool_calls": 42, "tokens_input": 1})
with patch(
"roboco.runtime.orchestrator.httpx.AsyncClient",
lambda **_kw: _FakeHTTPClient(_handler),
):
turns, tool_calls = await orch._resolve_final_turns_tools(_AGENT_ID)
assert (turns, tool_calls) == (7, 42)
async def test_resolve_final_turns_tools_transcript_fallback_for_turns() -> None:
"""When the SDK reports 0 turns, fall back to the transcript turn count.
tool_calls has no transcript equivalent and stays 0 ("n/a").
"""
orch = _make_orchestrator()
def _handler(_url: str) -> Any:
return _mock_response(200, {"turns": 0, "tool_calls": 0})
transcript_turns = 9
with (
patch(
"roboco.runtime.orchestrator.httpx.AsyncClient",
lambda **_kw: _FakeHTTPClient(_handler),
),
patch.object(
orch,
"_usage_from_transcript",
return_value=(1, 2, 3, 4, transcript_turns),
),
):
turns, tool_calls = await orch._resolve_final_turns_tools(_AGENT_ID)
assert turns == transcript_turns # recovered from the transcript
assert tool_calls == 0
# ---------------------------------------------------------------------------
# _usage_from_transcript — locate by session id across any project dir
# ---------------------------------------------------------------------------
@@ -836,7 +882,7 @@ def test_usage_from_transcript_finds_by_session_id_in_shared_app_dir(
monkeypatch.setattr(Path, "home", lambda: tmp_path)
result = AgentOrchestrator._usage_from_transcript("main-pm", sid)
assert result == (exp_in, exp_out, exp_cr, exp_cw)
assert result == (exp_in, exp_out, exp_cr, exp_cw, 1) # one message => 1 turn
def test_usage_from_transcript_without_session_id_uses_slug_glob(
@@ -859,4 +905,4 @@ def test_usage_from_transcript_without_session_id_uses_slug_glob(
monkeypatch.setattr(Path, "home", lambda: tmp_path)
result = AgentOrchestrator._usage_from_transcript("be-dev-1")
assert result == (exp_in, exp_out, 0, 0)
assert result == (exp_in, exp_out, 0, 0, 1) # one message => 1 turn