Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(board): one insights endpoint built from every usage store

rubenluetke10-beep3353a32a9baf
diff --git a/jarvis/board/insights.py b/jarvis/board/insights.py
new file mode 100644
index 0000000000..8736494487
--- /dev/null
+++ b/jarvis/board/insights.py
@@ -0,0 +1,415 @@
+"""Board insights — one read-only picture of how someone works with Jarvis.
+
+The Board's numbers come from the stores the app already keeps. Nothing new is
+recorded for the Board and no text leaves this module: only counts,
+timestamps and totals are read.
+
+Sources, each optional (a missing or unreadable store reads as "nothing yet"):
+
+* ``dictation_stats.json`` — lifetime dictation counters (words, seconds,
+ dictations per local day). Never pruned, holds no text.
+* ``personal.db`` — the Board ledger: per-day voice words, voice
+ sessions and talk time, aggregated from ``sessions.db``.
+* ``sessions.db`` — voice turn start times, for the hour-of-day map.
+* ``agent_chat.db`` — chats with Jarvis and the agents: sessions per
+ provider and the user's own messages (timestamps only).
+* ``cli_usage_index.db`` — coding-agent turns (Claude Code, Codex, ...)
+ indexed from the CLIs' own transcripts on this computer.
+
+Days are LOCAL calendar days, like every other streak in the app.
+"""
+from __future__ import annotations
+
+import contextlib
+import logging
+import sqlite3
+import threading
+import time
+from collections import defaultdict
+from collections.abc import Iterator
+from dataclasses import dataclass
+from datetime import date as _date
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+log = logging.getLogger(__name__)
+
+#: Average typing speed the "time saved" figure compares dictation against.
+#: Sent to the UI with the numbers so the comparison is stated, never implied.
+TYPING_WPM_REFERENCE = 40
+
+#: Length of an average novel, for the "that is N books" line.
+NOVEL_WORDS_REFERENCE = 90_000
+
+#: How many days the daily series covers (53 weeks fill the calendar grid).
+SERIES_DAYS = 371
+
+#: Seconds a computed picture is reused before the stores are read again.
+CACHE_TTL_S = 30.0
+
+
+@dataclass(frozen=True, slots=True)
+class InsightSources:
+ """Where each store lives. ``None`` switches a source off."""
+
+ dictation_stats: Path | None = None
+ board_db: Path | None = None
+ sessions_db: Path | None = None
+ agent_chat_db: Path | None = None
+ cli_index_db: Path | None = None
+
+
+def _read_only(path: Path | None) -> Iterator[sqlite3.Connection | None]:
+ """A read-only connection, or ``None`` when the store is absent/unreadable."""
+ if path is None or not Path(path).is_file():
+ yield None
+ return
+ try:
+ conn = sqlite3.connect(f"file:{Path(path).as_posix()}?mode=ro", uri=True, timeout=2.0)
+ except sqlite3.Error:
+ log.warning("Board insights: %s is not readable", path)
+ yield None
+ return
+ try:
+ yield conn
+ finally:
+ with contextlib.suppress(sqlite3.Error):
+ conn.close()
+
+
+def _local_day(ms: int) -> str:
+ return datetime.fromtimestamp(ms / 1000.0).astimezone().date().isoformat()
+
+
+def _local_slot(ms: int) -> tuple[int, int]:
+ """(weekday Mon=0, hour) of an epoch-ms instant in local time."""
+ moment = datetime.fromtimestamp(ms / 1000.0).astimezone()
+ return moment.weekday(), moment.hour
+
+
+def _today() -> _date:
+ return datetime.now().astimezone().date()
+
+
+def current_streak(active_days: set[str], today: _date | None = None) -> int:
+ """Consecutive active days up to today; a quiet today does not break it."""
+ cursor = today or _today()
+ if cursor.isoformat() not in active_days:
+ cursor -= timedelta(days=1)
+ streak = 0
+ while cursor.isoformat() in active_days:
+ streak += 1
+ cursor -= timedelta(days=1)
+ return streak
+
+
+def longest_streak(active_days: set[str]) -> int:
+ parsed = sorted(_date.fromisoformat(d) for d in active_days)
+ best = run = 0
+ previous: _date | None = None
+ for day in parsed:
+ run = run + 1 if previous is not None and (day - previous).days == 1 else 1
+ best = max(best, run)
+ previous = day
+ return best
+
+
+class _Day:
+ __slots__ = (
+ "agent_sessions",
+ "agent_turns",
+ "chat_messages",
+ "dictation_words",
+ "dictations",
+ "voice_words",
+ )
+
+ def __init__(self) -> None:
+ self.dictation_words = 0
+ self.dictations = 0
+ self.voice_words = 0
+ self.chat_messages = 0
+ self.agent_sessions = 0
+ self.agent_turns = 0
+
+ def active(self) -> bool:
+ return bool(
+ self.dictations or self.voice_words or self.chat_messages
+ or self.agent_sessions or self.agent_turns
+ )
+
+
+class BoardInsights:
+ """Builds the Board's picture from the stores in ``sources``. Thread-safe."""
+
+ def __init__(self, sources: InsightSources) -> None:
+ self._sources = sources
+ self._lock = threading.Lock()
+ self._cached: dict[str, Any] | None = None
+ self._cached_at = 0.0
+
+ def get(self, *, max_age_s: float = CACHE_TTL_S) -> dict[str, Any]:
+ with self._lock:
+ now = time.monotonic()
+ if self._cached is not None and now - self._cached_at < max_age_s:
+ return self._cached
+ picture = self.build()
+ self._cached, self._cached_at = picture, now
+ return picture
+
+ # ------------------------------------------------------------------
+
+ def build(self, today: _date | None = None) -> dict[str, Any]:
+ today = today or _today()
+ days: dict[str, _Day] = defaultdict(_Day)
+ punch = [[0] * 24 for _ in range(7)]
+
+ dictation = self._read_dictation(days)
+ voice = self._read_voice(days, punch)
+ chats = self._read_chats(days, punch)
+ agents = self._read_agents(days, punch, today)
+
+ active = {d for d, v in days.items() if v.active()}
+ series_start = today - timedelta(days=SERIES_DAYS - 1)
+ series = []
+ for offset in range(SERIES_DAYS):
+ key = (series_start + timedelta(days=offset)).isoformat()
+ day = days.get(key)
+ series.append({
+ "date": key,
+ "dictation_words": day.dictation_words if day else 0,
+ "voice_words": day.voice_words if day else 0,
+ "chat_messages": day.chat_messages if day else 0,
+ "agent_sessions": day.agent_sessions if day else 0,
+ "agent_turns": day.agent_turns if day else 0,
+ })
+
+ def words_between(start: _date, end: _date) -> int:
+ total = 0
+ for key, day in days.items():
+ if start.isoformat() <= key <= end.isoformat():
+ total += day.dictation_words + day.voice_words
+ return total
+
+ best_words = max(
+ days.items(),
+ key=lambda kv: (kv[1].dictation_words + kv[1].voice_words, kv[0]),
+ default=None,
+ )
+ best_agents = max(
+ days.items(), key=lambda kv: (kv[1].agent_sessions, kv[0]), default=None,
+ )
+
+ return {
+ "generated_at": datetime.now().astimezone().isoformat(timespec="seconds"),
+ "reference": {
+ "typing_wpm": TYPING_WPM_REFERENCE,
+ "novel_words": NOVEL_WORDS_REFERENCE,
+ },
+ "dictation": dictation,
+ "voice": voice,
+ "chats": chats,
+ "agents": agents,
+ "days": series,
+ "punch_card": punch,
+ "trend": {
+ "words_30d": words_between(today - timedelta(days=29), today),
+ "words_prev_30d": words_between(
+ today - timedelta(days=59), today - timedelta(days=30)
+ ),
+ },
+ "streak": {
+ "current_days": current_streak(active, today),
+ "longest_days": longest_streak(active),
+ "active_days": len(active),
+ "first_day": min(active) if active else None,
+ },
+ "records": {
+ "best_words_day": (
+ {"date": best_words[0],
+ "value": best_words[1].dictation_words + best_words[1].voice_words}
+ if best_words and (best_words[1].dictation_words + best_words[1].voice_words)
+ else None
+ ),
+ "best_agent_day": (
+ {"date": best_agents[0], "value": best_agents[1].agent_sessions}
+ if best_agents and best_agents[1].agent_sessions else None
+ ),
+ },
+ }
+
+ # ------------------------------------------------------------------
+ # Sources
+ # ------------------------------------------------------------------
+
+ def _read_dictation(self, days: dict[str, _Day]) -> dict[str, Any]:
+ out: dict[str, Any] = {"available": False, "words": 0, "dictations": 0, "seconds": 0.0}
+ path = self._sources.dictation_stats
+ if path is None or not Path(path).is_file():
+ return out
+ from jarvis.dictation.stats import DictationStats
+
+ totals, by_day = DictationStats(path).load()
+ for key, stat in by_day.items():
+ day = days[key]
+ day.dictation_words += stat.words
+ day.dictations += stat.dictations
+ out.update(
+ available=True,
+ words=int(totals.get("words", 0)),
+ dictations=int(totals.get("dictations", 0)),
+ seconds=round(float(totals.get("seconds", 0.0)), 1),
+ )
+ return out
+
+ def _read_voice(self, days: dict[str, _Day], punch: list[list[int]]) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "available": False, "sessions": 0, "turns": 0,
+ "user_words": 0, "jarvis_words": 0, "seconds": 0.0,
+ }
+ with _read_only(self._sources.board_db) as conn:
+ if conn is not None:
+ try:
+ for date, user_words, jarvis_words, sessions, seconds in conn.execute(
+ "SELECT date, user_words_count, jarvis_words_count, "
+ "session_count, conversation_seconds_estimate FROM daily_stats"
+ ):
+ days[date].voice_words += int(user_words or 0)
+ out["user_words"] += int(user_words or 0)
+ out["jarvis_words"] += int(jarvis_words or 0)
+ out["sessions"] += int(sessions or 0)
+ out["seconds"] += float(seconds or 0.0)
+ out["available"] = True
+ except sqlite3.Error:
+ log.warning("Board insights: board ledger unreadable", exc_info=True)
+ with _read_only(self._sources.sessions_db) as conn:
+ if conn is not None:
+ try:
+ for (started_ms,) in conn.execute("SELECT started_ms FROM voice_turns"):
+ if started_ms:
+ out["turns"] += 1
+ weekday, hour = _local_slot(int(started_ms))
+ punch[weekday][hour] += 1
+ out["available"] = True
+ except sqlite3.Error:
+ log.warning("Board insights: sessions.db unreadable", exc_info=True)
+ out["seconds"] = round(out["seconds"], 1)
+ return out
+
+ def _read_chats(self, days: dict[str, _Day], punch: list[list[int]]) -> dict[str, Any]:
+ out: dict[str, Any] = {"available": False, "sessions": 0, "messages": 0, "providers": []}
+ with _read_only(self._sources.agent_chat_db) as conn:
+ if conn is None:
+ return out
+ try:
+ providers: dict[str, dict[str, int]] = {}
+ for provider, surface, sessions in conn.execute(
+ "SELECT provider, surface, COUNT(*) FROM agent_chat_sessions "
+ "GROUP BY provider, surface"
+ ):
+ row = providers.setdefault(
+ provider or "", {"sessions": 0, "messages": 0, "jarvis_sessions": 0}
+ )
+ row["sessions"] += int(sessions)
+ if surface == "jarvis":
+ row["jarvis_sessions"] += int(sessions)
+ out["sessions"] += int(sessions)
+ for provider, ts_ms in conn.execute(
+ "SELECT s.provider, e.ts_ms FROM agent_chat_events e "
+ "JOIN agent_chat_sessions s ON s.session_id = e.session_id "
+ "WHERE e.kind = 'user_message'"
+ ):
+ if not ts_ms:
+ continue
+ providers.setdefault(
+ provider or "", {"sessions": 0, "messages": 0, "jarvis_sessions": 0}
+ )["messages"] += 1
+ out["messages"] += 1
+ days[_local_day(int(ts_ms))].chat_messages += 1
+ weekday, hour = _local_slot(int(ts_ms))
+ punch[weekday][hour] += 1
+ out["providers"] = sorted(
+ ({"provider": k, **v} for k, v in providers.items() if k),
+ key=lambda r: (-r["messages"], -r["sessions"], r["provider"]),
+ )
+ out["available"] = True
+ except sqlite3.Error:
+ log.warning("Board insights: agent_chat.db unreadable", exc_info=True)
+ return out
+
+ def _read_agents(
+ self, days: dict[str, _Day], punch: list[list[int]], today: _date
+ ) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "available": False, "sessions": 0, "turns": 0, "tokens": 0, "items": [],
+ }
+ with _read_only(self._sources.cli_index_db) as conn:
+ if conn is None:
+ return out
+ cutoff_ms = int(
+ datetime.combine(today - timedelta(days=29), datetime.min.time())
+ .astimezone().timestamp() * 1000
+ )
+ try:
+ items: dict[str, dict[str, Any]] = {}
+ for agent, session_id, first_ms, last_ms, turns, tokens in conn.execute(
+ "SELECT agent, session_id, MIN(ts_ms), MAX(ts_ms), COUNT(*), "
+ "SUM(tokens_in + tokens_out) FROM cli_turns WHERE ts_ms > 0 "
+ "GROUP BY agent, session_id"
+ ):
+ item = items.setdefault(agent, {
+ "agent": agent, "sessions": 0, "sessions_30d": 0, "turns": 0,
+ "turns_30d": 0, "tokens": 0, "last_ms": 0,
+ })
+ item["turns"] += int(turns)
+ item["tokens"] += int(tokens or 0)
+ item["last_ms"] = max(item["last_ms"], int(last_ms))
+ if session_id:
+ item["sessions"] += 1
+ days[_local_day(int(first_ms))].agent_sessions += 1
+ if int(first_ms) >= cutoff_ms:
+ item["sessions_30d"] += 1
+ for agent, day, turns in conn.execute(
+ "SELECT agent, strftime('%Y-%m-%d', ts_ms / 1000, 'unixepoch', 'localtime'), "
+ "COUNT(*) FROM cli_turns WHERE ts_ms > 0 GROUP BY 1, 2"
+ ):
+ days[day].agent_turns += int(turns)
+ if day >= (today - timedelta(days=29)).isoformat() and agent in items:
+ items[agent]["turns_30d"] += int(turns)
+ for weekday, hour, turns in conn.execute(
+ "SELECT "
+ "CAST(strftime('%w', ts_ms / 1000, 'unixepoch', 'localtime') AS INTEGER), "
+ "CAST(strftime('%H', ts_ms / 1000, 'unixepoch', 'localtime') AS INTEGER), "
+ "COUNT(*) FROM cli_turns WHERE ts_ms > 0 GROUP BY 1, 2"
+ ):
+ # SQLite counts Sunday as 0; the punch card is Monday-first.
+ punch[(int(weekday) + 6) % 7][int(hour)] += int(turns)
+ out["items"] = sorted(
+ items.values(), key=lambda r: (-r["sessions"], -r["turns"], r["agent"])
+ )
+ out["sessions"] = sum(r["sessions"] for r in items.values())
+ out["turns"] = sum(r["turns"] for r in items.values())
+ out["tokens"] = sum(r["tokens"] for r in items.values())
+ out["available"] = True
+ except sqlite3.Error:
+ log.warning("Board insights: cli_usage_index.db unreadable", exc_info=True)
+ return out
+
+
+def default_sources(
+ *, data_dir: Path, sessions_db: Path | None, board_db: Path | None
+) -> InsightSources:
+ """The live app's store locations, resolved the way each store's owner does."""
+ from jarvis.costs.cli_usage_index import index_db_path
+ from jarvis.dictation.stats import default_stats_path
+
+ return InsightSources(
+ dictation_stats=default_stats_path(),
+ board_db=board_db,
+ sessions_db=sessions_db,
+ agent_chat_db=Path(data_dir) / "agent_chat.db",
+ cli_index_db=index_db_path(),
+ )
+
diff --git a/jarvis/ui/web/board_routes.py b/jarvis/ui/web/board_routes.py
index d1836829ae..9afef24da6 100644
--- a/jarvis/ui/web/board_routes.py
+++ b/jarvis/ui/web/board_routes.py
@@ -7,6 +7,7 @@ Endpoints:
- ``GET /api/board/personal/tools`` → tool-usage histogram
- ``GET /api/board/personal/records`` → personal records
- ``POST /api/board/personal/refresh`` → manual aggregator run
+- ``GET /api/board/insights`` → the Board page: every usage source
- ``GET /api/board/achievements`` → all specs with unlock status
- ``GET /api/board/bio`` → current AI bio + age
- ``POST /api/board/bio/regenerate`` → manually generate a new bio
@@ -258,6 +259,128 @@ async def personal_refresh(request: Request) -> RefreshResponse:
raise HTTPException(status_code=500, detail=str(exc)) from exc
+# ----------------------------------------------------------------------
+# Insights — the Board page
+# ----------------------------------------------------------------------
+
+class InsightsReference(BaseModel):
+ typing_wpm: int
+ novel_words: int
+
+
+class InsightsDictation(BaseModel):
+ available: bool
+ words: int
+ dictations: int
+ seconds: float
+
+
+class InsightsVoice(BaseModel):
+ available: bool
+ sessions: int
+ turns: int
+ user_words: int
+ jarvis_words: int
+ seconds: float
+
+
+class InsightsChatProvider(BaseModel):
+ provider: str
+ sessions: int
+ messages: int
+ jarvis_sessions: int
+
+
+class InsightsChats(BaseModel):
+ available: bool
+ sessions: int
+ messages: int
+ providers: list[InsightsChatProvider]
+
+
+class InsightsAgent(BaseModel):
+ agent: str
+ sessions: int
+ sessions_30d: int
+ turns: int
+ turns_30d: int
+ tokens: int
+ last_ms: int
+
+
+class InsightsAgents(BaseModel):
+ available: bool
+ sessions: int
+ turns: int
+ tokens: int
+ items: list[InsightsAgent]
+
+
+class InsightsDay(BaseModel):
+ date: str
+ dictation_words: int
+ voice_words: int
+ chat_messages: int
+ agent_sessions: int
+ agent_turns: int
+
+
+class InsightsTrend(BaseModel):
+ words_30d: int
+ words_prev_30d: int
+
+
+class InsightsStreak(BaseModel):
+ current_days: int
+ longest_days: int
+ active_days: int
+ first_day: str | None
+
+
+class InsightsRecord(BaseModel):
+ date: str
+ value: int
+
+
+class InsightsRecords(BaseModel):
+ best_words_day: InsightsRecord | None
+ best_agent_day: InsightsRecord | None
+
+
+class InsightsResponse(BaseModel):
+ generated_at: str
+ reference: InsightsReference
+ dictation: InsightsDictation
+ voice: InsightsVoice
+ chats: InsightsChats
+ agents: InsightsAgents
+ days: list[InsightsDay]
+ #: 7 rows (Monday first) x 24 local hours of activity counts.
+ punch_card: list[list[int]]
+ trend: InsightsTrend
+ streak: InsightsStreak
+ records: InsightsRecords
+ categories: CategoriesResponse
+
+
+@board_router.get("/insights", response_model=InsightsResponse)
+async def board_insights(request: Request) -> InsightsResponse:
+ """Everything the Board page draws, from the stores the app already keeps.
+
+ Counts and timestamps only — no text is read into the answer. Each source
+ is optional: a missing store reads as ``available: false`` with zeros, so
+ the page can say "nothing yet" instead of failing.
+ """
+ insights = getattr(request.app.state, "board_insights", None)
+ if insights is None:
+ raise HTTPException(status_code=503, detail="Board insights not available")
+ store = _require_store(request)
+ await _freshen(request)
+ picture = await asyncio.to_thread(insights.get)
+ categories = await asyncio.to_thread(store.categories, window_days=None)
+ return InsightsResponse.model_validate({**picture, "categories": categories})
+
+
# ----------------------------------------------------------------------
# Phase B — Achievements + Bio
# ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 16ffd28bb2..ddb85d531c 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -880,6 +880,8 @@ class WebServer:
from jarvis.board.aggregator import BoardAggregator
from jarvis.board.bio_brain import BIO_TIMEOUT_S, resolve_bio_brain
from jarvis.board.evaluator import AchievementEvaluator
+ from jarvis.board.insights import BoardInsights
+ from jarvis.board.insights import default_sources as insight_sources
from jarvis.board.profile import BioGenerator, BioStore
from jarvis.board.scheduler import BioScheduler
from jarvis.board.store import BoardStore
@@ -902,6 +904,13 @@ class WebServer:
sessions_db_path=sessions_db_path,
)
store = BoardStore(db_path=db_path)
+ insights = BoardInsights(
+ insight_sources(
+ data_dir=Path(self.cfg.memory.data_dir),
+ sessions_db=sessions_db_path,
+ board_db=db_path,
+ )
+ )
evaluator = AchievementEvaluator(db_path=db_path, bus=self.bus)
bio_store = BioStore(db_path=db_path)
@@ -953,6 +962,7 @@ class WebServer:
self._bio_generator = bio_generator
app.state.board_aggregator = aggregator
app.state.board_store = store
+ app.state.board_insights = insights
app.state.achievement_evaluator = evaluator
app.state.bio_generator = bio_generator
app.state.bio_store = bio_store
@@ -971,6 +981,7 @@ class WebServer:
self._bio_generator = None
app.state.board_aggregator = None
app.state.board_store = None
+ app.state.board_insights = None
app.state.achievement_evaluator = None
app.state.bio_generator = None
app.state.bio_store = None
diff --git a/tests/board/test_insights.py b/tests/board/test_insights.py
new file mode 100644
index 0000000000..d69ab2d337
--- /dev/null
+++ b/tests/board/test_insights.py
@@ -0,0 +1,186 @@
+"""Board insights: one picture built from the stores the app already keeps.
+
+Every source is a real (temporary) store written the way its owner writes it;
+the tests check the counts, the local-day bucketing, the streak across
+sources and that a missing store degrades to ``available: false``.
+"""
+from __future__ import annotations
+
+import sqlite3
+from datetime import datetime, timedelta
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.board.aggregator import BoardAggregator
+from jarvis.board.insights import (
+ SERIES_DAYS,
+ BoardInsights,
+ InsightSources,
+ current_streak,
+ longest_streak,
+)
+from jarvis.board.store import BoardStore
+from jarvis.dictation.stats import DictationStats
+from jarvis.ui.web.board_routes import board_router
+
+
+def _noon(days_ago: int) -> datetime:
+ now = datetime.now().astimezone().replace(hour=12, minute=0, second=0, microsecond=0)
+ return now - timedelta(days=days_ago)
+
+
+def _ms(moment: datetime) -> int:
+ return int(moment.timestamp() * 1000)
+
+
+def _write_dictation(path: Path) -> None:
+ stats = DictationStats(path)
+ stats.record(created_at=_noon(0).isoformat(), word_count=120, duration_s=60.0)
+ stats.record(created_at=_noon(1).isoformat(), word_count=80, duration_s=40.0)
+
+
+def _write_agent_chat(path: Path) -> None:
+ conn = sqlite3.connect(path)
+ conn.executescript(
+ """
+ CREATE TABLE agent_chat_sessions (
+ session_id TEXT PRIMARY KEY, provider TEXT, surface TEXT
+ );
+ CREATE TABLE agent_chat_events (
+ session_id TEXT, seq INTEGER, ts_ms INTEGER, kind TEXT, payload TEXT
+ );
+ """
+ )
+ conn.execute("INSERT INTO agent_chat_sessions VALUES ('s1', 'claude-api', 'jarvis')")
+ conn.execute("INSERT INTO agent_chat_sessions VALUES ('s2', 'gemini', 'society')")
+ rows = [
+ ("s1", 1, _ms(_noon(2)), "user_message", "{}"),
+ ("s1", 2, _ms(_noon(2)), "assistant_text", "{}"),
+ ("s2", 1, _ms(_noon(2)), "user_message", "{}"),
+ ]
+ conn.executemany("INSERT INTO agent_chat_events VALUES (?, ?, ?, ?, ?)", rows)
+ conn.commit()
+ conn.close()
+
+
+def _write_cli_index(path: Path) -> None:
+ conn = sqlite3.connect(path)
+ conn.execute(
+ "CREATE TABLE cli_turns (agent TEXT, session_id TEXT, ts_ms INTEGER, "
+ "tokens_in INTEGER, tokens_out INTEGER)"
+ )
+ rows = [
+ ("claude-cli", "a", _ms(_noon(3)), 10, 5),
+ ("claude-cli", "a", _ms(_noon(3)) + 60_000, 10, 5),
+ ("claude-cli", "b", _ms(_noon(40)), 1, 1),
+ ("codex-cli", "c", _ms(_noon(3)), 100, 50),
+ ]
+ conn.executemany("INSERT INTO cli_turns VALUES (?, ?, ?, ?, ?)", rows)
+ conn.commit()
+ conn.close()
+
+
+def _sources(tmp_path: Path) -> InsightSources:
+ dictation = tmp_path / "dictation_stats.json"
+ chat = tmp_path / "agent_chat.db"
+ cli = tmp_path / "cli_usage_index.db"
+ _write_dictation(dictation)
+ _write_agent_chat(chat)
+ _write_cli_index(cli)
+ board = tmp_path / "board" / "personal.db"
+ BoardAggregator(jsonl_dir=tmp_path / "fr", db_path=board).run()
+ return InsightSources(
+ dictation_stats=dictation, board_db=board, agent_chat_db=chat, cli_index_db=cli,
+ )
+
+
+def test_build_counts_every_source(tmp_path: Path) -> None:
+ picture = BoardInsights(_sources(tmp_path)).build()
+
+ assert picture["dictation"] == {
+ "available": True, "words": 200, "dictations": 2, "seconds": 100.0,
+ }
+ assert picture["chats"]["messages"] == 2
+ assert picture["chats"]["sessions"] == 2
+ assert picture["chats"]["providers"][0]["provider"] == "claude-api"
+ assert picture["chats"]["providers"][0]["jarvis_sessions"] == 1
+
+ agents = {item["agent"]: item for item in picture["agents"]["items"]}
+ assert agents["claude-cli"]["sessions"] == 2
+ assert agents["claude-cli"]["sessions_30d"] == 1
+ assert agents["claude-cli"]["turns"] == 3
+ assert agents["claude-cli"]["tokens"] == 32
+ assert picture["agents"]["sessions"] == 3
+ assert picture["agents"]["turns"] == 4
+
+ assert picture["reference"] == {"typing_wpm": 40, "novel_words": 90_000}
+ assert picture["trend"]["words_30d"] == 200
+
+
+def test_daily_series_and_streak_span_all_sources(tmp_path: Path) -> None:
+ picture = BoardInsights(_sources(tmp_path)).build()
+
+ days = picture["days"]
+ assert len(days) == SERIES_DAYS
+ by_date = {d["date"]: d for d in days}
+ assert by_date[_noon(0).date().isoformat()]["dictation_words"] == 120
+ assert by_date[_noon(2).date().isoformat()]["chat_messages"] == 2
+ assert by_date[_noon(3).date().isoformat()]["agent_sessions"] == 2
+ # Dictation today + yesterday, chat two days ago, agents three days ago:
+ # four consecutive days, each from a different store.
+ assert picture["streak"]["current_days"] == 4
+ assert picture["records"]["best_agent_day"]["value"] == 2
+
+ punch = picture["punch_card"]
+ assert len(punch) == 7 and all(len(row) == 24 for row in punch)
+ assert sum(map(sum, punch)) == 2 + 4 # chat messages + agent turns
+
+
+def test_missing_stores_read_as_unavailable(tmp_path: Path) -> None:
+ picture = BoardInsights(
+ InsightSources(
+ dictation_stats=tmp_path / "missing.json",
+ board_db=tmp_path / "missing.db",
+ sessions_db=None,
+ agent_chat_db=tmp_path / "missing_chat.db",
+ cli_index_db=None,
+ )
+ ).build()
+ assert picture["dictation"]["available"] is False
+ assert picture["voice"]["available"] is False
+ assert picture["chats"]["available"] is False
+ assert picture["agents"]["available"] is False
+ assert picture["streak"] == {
+ "current_days": 0, "longest_days": 0, "active_days": 0, "first_day": None,
+ }
+ assert picture["records"] == {"best_words_day": None, "best_agent_day": None}
+
+
+def test_streak_grace_for_a_quiet_today() -> None:
+ today = _noon(0).date()
+ days = {(today - timedelta(days=n)).isoformat() for n in (1, 2, 3, 7, 8)}
+ assert current_streak(days, today) == 3
+ assert longest_streak(days) == 3
+
+
+def test_route_returns_the_picture_with_categories(tmp_path: Path) -> None:
+ sources = _sources(tmp_path)
+ app = FastAPI()
+ app.include_router(board_router)
+ app.state.board_store = BoardStore(db_path=sources.board_db)
+ app.state.board_insights = BoardInsights(sources)
+ with TestClient(app) as client:
+ resp = client.get("/api/board/insights")
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["dictation"]["words"] == 200
+ assert [c["category"] for c in body["categories"]["categories"]][:1] == ["agents"]
+
+
+def test_route_is_503_without_insights() -> None:
+ app = FastAPI()
+ app.include_router(board_router)
+ with TestClient(app) as client:
+ assert client.get("/api/board/insights").status_code == 503