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.

fix(board): stop hero-stat decay and phantom hours; streak grace for a quiet today

Ruben Lütke0b5d8605495d
diff --git a/jarvis/board/aggregator.py b/jarvis/board/aggregator.py
index 161bebf40c..b2c0e7b721 100644
--- a/jarvis/board/aggregator.py
+++ b/jarvis/board/aggregator.py
@@ -39,7 +39,7 @@ import time
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass, field
-from datetime import UTC, datetime
+from datetime import UTC, datetime, tzinfo
from pathlib import Path
from typing import Any
@@ -59,6 +59,40 @@ SCHEMA_FILE = Path(__file__).parent / "schema.sql"
VOICE_RETRY_WINDOW_S = 8.0
CONVERSATION_TRACE_CAP_S = 30 * 60.0
+# Daily-stats upsert, two flavours sharing one column list. The full variant
+# overwrites the day with the recompute; the insert-only variant backs a
+# FROZEN day (below the retention-prune horizon): its already-recorded ledger
+# row wins and only a first-time insert (board DB rebuilt from scratch) lands.
+_UPSERT_COLUMNS_SQL = """
+ INSERT INTO daily_stats (
+ date, tasks_completed, tasks_failed, tools_used,
+ unique_tools_count, voice_commands_count,
+ voice_first_try_rate, hours_saved_estimate,
+ active_events_count, conversation_seconds_estimate,
+ user_words_count, jarvis_words_count, session_count,
+ category_counts
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+"""
+
+_UPSERT_INSERT_ONLY_SQL = _UPSERT_COLUMNS_SQL + "ON CONFLICT(date) DO NOTHING"
+
+_UPSERT_FULL_SQL = _UPSERT_COLUMNS_SQL + """
+ ON CONFLICT(date) DO UPDATE SET
+ tasks_completed = excluded.tasks_completed,
+ tasks_failed = excluded.tasks_failed,
+ tools_used = excluded.tools_used,
+ unique_tools_count = excluded.unique_tools_count,
+ voice_commands_count = excluded.voice_commands_count,
+ voice_first_try_rate = excluded.voice_first_try_rate,
+ hours_saved_estimate = excluded.hours_saved_estimate,
+ active_events_count = excluded.active_events_count,
+ conversation_seconds_estimate = excluded.conversation_seconds_estimate,
+ user_words_count = excluded.user_words_count,
+ jarvis_words_count = excluded.jarvis_words_count,
+ session_count = excluded.session_count,
+ category_counts = excluded.category_counts
+"""
+
ACTIVE_EVENT_NAMES = {
"ActionExecuted",
"BrainTurnCompleted",
@@ -144,6 +178,7 @@ class BoardAggregator:
jsonl_dir: Path,
db_path: Path | None = None,
sessions_db_path: Path | None = None,
+ tz: tzinfo | None = None,
) -> None:
self._jsonl_dir = Path(jsonl_dir)
self._db_path = Path(db_path) if db_path is not None else (
@@ -155,6 +190,11 @@ class BoardAggregator:
self._sessions_db_path = (
Path(sessions_db_path) if sessions_db_path is not None else None
)
+ # Day-bucketing timezone. ``None`` = the host's local timezone (the
+ # meaningful granularity for a personal dashboard). Tests inject
+ # explicit zones to prove the bucketing is deterministic and that
+ # all-time totals are timezone-invariant.
+ self._tz = tz
self._db_path.parent.mkdir(parents=True, exist_ok=True)
self._db: sqlite3.Connection | None = None
# Serialises every aggregation run. The connection is shared across
@@ -221,7 +261,9 @@ class BoardAggregator:
try:
daily = self._aggregate_events()
self._aggregate_sessions(daily)
- self._upsert_daily_stats(daily.values())
+ self._upsert_daily_stats(
+ daily.values(), freeze_before_ms=self._read_prune_horizon()
+ )
self._refresh_personal_records()
self._set_meta("last_run_ns", str(time.time_ns()))
except Exception: # noqa: BLE001
@@ -354,7 +396,7 @@ class BoardAggregator:
ts_ns = int(record.get("ts_ns") or 0)
if ts_ns <= 0:
continue
- date = _iso_date_from_ns(ts_ns)
+ date = _iso_date_from_ns(ts_ns, self._tz)
stats = daily.setdefault(date, DailyStats(date=date))
event = record.get("event", "")
payload = record.get("payload") or {}
@@ -442,7 +484,7 @@ class BoardAggregator:
ms = row["started_ms"]
if not ms:
continue
- date = _iso_date_from_ms(int(ms))
+ date = _iso_date_from_ms(int(ms), self._tz)
stats = daily.setdefault(date, DailyStats(date=date))
user_words = _count_words(row["user_text"])
jarvis_words = _count_words(row["jarvis_text"])
@@ -463,7 +505,7 @@ class BoardAggregator:
ms = row["started_ms"]
if not ms:
continue
- date = _iso_date_from_ms(int(ms))
+ date = _iso_date_from_ms(int(ms), self._tz)
stats = daily.setdefault(date, DailyStats(date=date))
stats.session_count += 1
ended = row["ended_ms"]
@@ -477,40 +519,68 @@ class BoardAggregator:
with contextlib.suppress(sqlite3.Error):
conn.close()
+ def _read_prune_horizon(self) -> int | None:
+ """Retention-prune high-water mark recorded in ``sessions.db``.
+
+ Every day whose local day-start lies below this instant may have lost
+ source rows to the recorder's boot-time retention prune, so its
+ already-recorded ledger row must never be overwritten with a recompute
+ from the shrunken source. ``None`` (no sessions db, old schema, never
+ pruned) keeps the historical full-overwrite behaviour.
+ """
+ path = self._sessions_db_path
+ if path is None or not Path(path).exists():
+ return None
+ try:
+ conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ except sqlite3.Error:
+ return None
+ try:
+ row = conn.execute(
+ "SELECT value FROM store_meta WHERE key = 'prune_horizon_ms'"
+ ).fetchone()
+ return int(row[0]) if row is not None else None
+ except (sqlite3.Error, TypeError, ValueError):
+ return None
+ finally:
+ with contextlib.suppress(sqlite3.Error):
+ conn.close()
+
# ------------------------------------------------------------------
# Upsert
# ------------------------------------------------------------------
- def _upsert_daily_stats(self, rows: Iterable[DailyStats]) -> None:
+ def _day_start_ms(self, date: str) -> int:
+ """Epoch ms of the day's midnight in the bucketing timezone."""
+ day = datetime.fromisoformat(date)
+ if self._tz is not None:
+ day = day.replace(tzinfo=self._tz)
+ else:
+ day = day.astimezone() # naive -> host-local midnight
+ return int(day.timestamp() * 1000)
+
+ def _upsert_daily_stats(
+ self,
+ rows: Iterable[DailyStats],
+ *,
+ freeze_before_ms: int | None = None,
+ ) -> None:
+ """Write per-day rows. Days at or below the prune horizon are frozen:
+ their existing ledger row wins and only a first-time INSERT (board DB
+ rebuilt from scratch) is allowed — a recompute from a source that lost
+ rows to retention must never shrink an already-recorded day (this was
+ the bug that made ACTIVE TIME decay day by day).
+ """
conn = self.db
with conn:
conn.execute("BEGIN")
for stats in rows:
+ frozen = (
+ freeze_before_ms is not None
+ and self._day_start_ms(stats.date) < freeze_before_ms
+ )
conn.execute(
- """
- INSERT INTO daily_stats (
- date, tasks_completed, tasks_failed, tools_used,
- unique_tools_count, voice_commands_count,
- voice_first_try_rate, hours_saved_estimate,
- active_events_count, conversation_seconds_estimate,
- user_words_count, jarvis_words_count, session_count,
- category_counts
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT(date) DO UPDATE SET
- tasks_completed = excluded.tasks_completed,
- tasks_failed = excluded.tasks_failed,
- tools_used = excluded.tools_used,
- unique_tools_count = excluded.unique_tools_count,
- voice_commands_count = excluded.voice_commands_count,
- voice_first_try_rate = excluded.voice_first_try_rate,
- hours_saved_estimate = excluded.hours_saved_estimate,
- active_events_count = excluded.active_events_count,
- conversation_seconds_estimate = excluded.conversation_seconds_estimate,
- user_words_count = excluded.user_words_count,
- jarvis_words_count = excluded.jarvis_words_count,
- session_count = excluded.session_count,
- category_counts = excluded.category_counts
- """,
+ _UPSERT_INSERT_ONLY_SQL if frozen else _UPSERT_FULL_SQL,
(
stats.date,
stats.tasks_completed,
@@ -659,13 +729,14 @@ class BoardAggregator:
_ensure_daily_stats_columns(conn)
-def _iso_date_from_ns(ts_ns: int) -> str:
- """Converts a nanosecond timestamp to an ISO date in the local timezone.
+def _iso_date_from_ns(ts_ns: int, tz: tzinfo | None = None) -> str:
+ """Converts a nanosecond timestamp to an ISO date in the given timezone.
- Local time is the meaningful granularity for a personal dashboard — a
- commit at 00:30 belongs to the user's "today", not "yesterday in UTC".
+ ``None`` means the host's local timezone — the meaningful granularity for
+ a personal dashboard: a commit at 00:30 belongs to the user's "today",
+ not "yesterday in UTC".
"""
- dt = datetime.fromtimestamp(ts_ns / 1e9, tz=UTC).astimezone()
+ dt = datetime.fromtimestamp(ts_ns / 1e9, tz=UTC).astimezone(tz)
return dt.strftime("%Y-%m-%d")
@@ -677,9 +748,9 @@ def _is_active_event(event: str, payload: dict[str, Any]) -> bool:
return True
-def _iso_date_from_ms(ts_ms: int) -> str:
- """ISO date (local timezone) from a millisecond epoch timestamp."""
- dt = datetime.fromtimestamp(ts_ms / 1000.0, tz=UTC).astimezone()
+def _iso_date_from_ms(ts_ms: int, tz: tzinfo | None = None) -> str:
+ """ISO date from a millisecond epoch timestamp (``None`` = host-local)."""
+ dt = datetime.fromtimestamp(ts_ms / 1000.0, tz=UTC).astimezone(tz)
return dt.strftime("%Y-%m-%d")
diff --git a/jarvis/board/store.py b/jarvis/board/store.py
index 6f967a673b..fc3a822620 100644
--- a/jarvis/board/store.py
+++ b/jarvis/board/store.py
@@ -358,18 +358,25 @@ def _calc_streak(conn: sqlite3.Connection) -> int:
*Not* a streak in the Snapchat sense — no push notification, no UI nag,
no "You lost your streak!" pop-up. Plan §0 forbids breakable streaks.
- This number is rendered in the UI only as an info badge ("5-day series")
- and stays at 0 when the user skips a day.
+ This number is rendered in the UI only as an info badge ("5-day series").
+
+ A quiet *today* gets grace: before the first interaction of the day the
+ run ending yesterday is shown instead of a demoralising (and wrong) 0.
+ The streak only reads 0 once yesterday was quiet too.
"""
- cursor = _today()
- streak = 0
- while True:
+
+ def _active(day: _date) -> bool:
row = conn.execute(
"SELECT active_events_count FROM daily_stats WHERE date = ?",
- (cursor.isoformat(),),
+ (day.isoformat(),),
).fetchone()
- if row is None or int(row["active_events_count"]) <= 0:
- break
+ return row is not None and int(row["active_events_count"]) > 0
+
+ cursor = _today()
+ if not _active(cursor):
+ cursor -= timedelta(days=1)
+ streak = 0
+ while _active(cursor):
streak += 1
cursor -= timedelta(days=1)
return streak
diff --git a/jarvis/sessions/init.py b/jarvis/sessions/init.py
index 4acb90bac2..42f42170b8 100644
--- a/jarvis/sessions/init.py
+++ b/jarvis/sessions/init.py
@@ -51,14 +51,18 @@ def bootstrap_sessions(
# Crash recovery: sessions without ended_ms stem from an unclean
# shutdown of the previous process (hard kill, crash). Without
# this cleanup they would show up permanently as "running" in the UI.
- # Mark them as "shutdown" with ended_ms = startup time.
- import time as _time
+ # Seal them at their LAST RECORDED ACTIVITY — never at boot time, which
+ # could be hours later and would inflate every duration-based stat
+ # (the board once showed a 14.8 h phantom session created this way).
open_ids = store.list_open_sessions()
for sid in open_ids:
try:
+ row = store.get_session(sid)
+ started_ms = row.started_ms if row is not None else 0
+ ended_ms = max(store.last_activity_ms(sid) or 0, started_ms)
store.finalize_session(
session_id=sid,
- ended_ms=int(_time.time() * 1000),
+ ended_ms=ended_ms,
hangup_reason=HANGUP_SHUTDOWN,
turn_count=0, # conservative: we don't know the aggregates
total_cost_usd=0.0,
@@ -71,6 +75,16 @@ def bootstrap_sessions(
if open_ids:
log.info("SessionRecorder: marked %d stale session(s) as shutdown", len(open_ids))
+ # One-time-per-row repair of seals created by the old boot-time stamping.
+ # Idempotent and cheap: only 'shutdown' rows are inspected, and honest
+ # seals sit inside the tolerance.
+ try:
+ repaired = store.repair_crash_seals()
+ if repaired:
+ log.info("SessionRecorder: repaired %d inflated crash seal(s)", repaired)
+ except Exception as exc: # noqa: BLE001
+ log.warning("SessionRecorder: crash-seal repair failed: %s", exc)
+
recorder = SessionRecorder(store=store)
recorder.attach(bus)
diff --git a/jarvis/sessions/schema.sql b/jarvis/sessions/schema.sql
index b7a69e223b..86dbdd725a 100644
--- a/jarvis/sessions/schema.sql
+++ b/jarvis/sessions/schema.sql
@@ -62,6 +62,17 @@ CREATE TABLE IF NOT EXISTS voice_turns (
CREATE INDEX IF NOT EXISTS idx_turns_session ON voice_turns(session_id, idx);
+-- Store-level bookkeeping. Currently holds the retention-prune horizon
+-- (key ``prune_horizon_ms``): the highest cutoff ever used by
+-- ``prune_older_than``. Readers (the board aggregator) use it to tell
+-- "rows were deleted below this instant" from "rows never existed", so an
+-- already-recorded day is never recomputed from a half-pruned source.
+CREATE TABLE IF NOT EXISTS store_meta (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL
+);
+
+
CREATE TABLE IF NOT EXISTS voice_events (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL REFERENCES voice_sessions(id) ON DELETE CASCADE,
diff --git a/jarvis/sessions/store.py b/jarvis/sessions/store.py
index 3f9309a5ec..a7916b1e18 100644
--- a/jarvis/sessions/store.py
+++ b/jarvis/sessions/store.py
@@ -411,6 +411,11 @@ class SessionStore:
Cascade delete in schema.sql cleans up turns + events
automatically along with it. Returns the number of deleted session rows.
+
+ The cutoff is recorded as the ``prune_horizon_ms`` high-water mark in
+ ``store_meta`` (monotonically increasing) so downstream aggregators can
+ distinguish "deleted below this instant" from "never existed" and stop
+ recomputing days from a half-pruned source.
"""
if days <= 0:
return 0
@@ -420,8 +425,83 @@ class SessionStore:
"DELETE FROM voice_sessions WHERE started_ms < ?",
(cutoff_ms,),
)
+ self._c.execute(
+ """
+ INSERT INTO store_meta (key, value) VALUES ('prune_horizon_ms', ?)
+ ON CONFLICT(key) DO UPDATE SET
+ -- Cast BOTH sides: the column has TEXT affinity, and in
+ -- SQLite's cross-type ordering TEXT always sorts above
+ -- INTEGER, so MAX(text, int) would pick the text blindly.
+ value = MAX(
+ CAST(store_meta.value AS INTEGER),
+ CAST(excluded.value AS INTEGER)
+ )
+ """,
+ (cutoff_ms,),
+ )
return cur.rowcount
+ def prune_horizon_ms(self) -> int | None:
+ """Highest retention cutoff ever applied, or ``None`` if never pruned."""
+ with self._lock:
+ row = self._c.execute(
+ "SELECT value FROM store_meta WHERE key = 'prune_horizon_ms'"
+ ).fetchone()
+ if row is None:
+ return None
+ try:
+ return int(row["value"])
+ except (TypeError, ValueError):
+ return None
+
+ def last_activity_ms(self, session_id: str) -> int | None:
+ """Latest recorded timestamp of a session: raw events plus turn
+ start/end. ``None`` when the session left no trace beyond its header.
+ Used to seal crashed sessions honestly instead of stamping boot time.
+ """
+ with self._lock:
+ row = self._c.execute(
+ """
+ SELECT MAX(ts) AS ts FROM (
+ SELECT MAX(ts_ms) AS ts FROM voice_events WHERE session_id = ?
+ UNION ALL
+ SELECT MAX(MAX(started_ms), COALESCE(MAX(ended_ms), 0)) AS ts
+ FROM voice_turns WHERE session_id = ?
+ )
+ """,
+ (session_id, session_id),
+ ).fetchone()
+ ts = row["ts"] if row is not None else None
+ return int(ts) if ts else None
+
+ def repair_crash_seals(self, *, tolerance_ms: int = 3_600_000) -> int:
+ """Re-seal ``shutdown`` sessions whose recorded end drifted more than
+ ``tolerance_ms`` past their last real activity.
+
+ Crash recovery used to stamp ``ended_ms = boot time``, so a session
+ that died in the evening and was recovered the next morning carried
+ 14+ phantom hours into every duration-based stat. Idempotent: honest
+ seals are inside the tolerance and stay untouched. Returns the number
+ of repaired rows.
+ """
+ with self._lock:
+ rows = self._c.execute(
+ "SELECT id, started_ms, ended_ms FROM voice_sessions "
+ "WHERE hangup_reason = 'shutdown' AND ended_ms IS NOT NULL"
+ ).fetchall()
+ repaired = 0
+ for r in rows:
+ last = self.last_activity_ms(r["id"])
+ honest_end = max(last or 0, int(r["started_ms"]))
+ if int(r["ended_ms"]) > honest_end + tolerance_ms:
+ with self._lock:
+ self._c.execute(
+ "UPDATE voice_sessions SET ended_ms = ? WHERE id = ?",
+ (honest_end, r["id"]),
+ )
+ repaired += 1
+ return repaired
+
def wal_checkpoint(self) -> None:
with self._lock:
self._c.execute("PRAGMA wal_checkpoint(TRUNCATE)")
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index fba773aa8a..4f1d35b92c 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -456,9 +456,10 @@ class WebServer:
# The board's rich source is the durable voice-session store
# (sessions.db), not the flight-recorder JSONL (which is empty on
- # most installs). Matches the [sessions] default db path used by
- # bootstrap_sessions (cwd-relative ``data/sessions.db``).
- sessions_db_path = Path("data/sessions.db")
+ # most installs). Resolved exactly like bootstrap_sessions does —
+ # a bare CWD-relative path would silently starve the board of its
+ # source whenever the app starts from a different directory.
+ sessions_db_path = self._resolve_sessions_db_path()
aggregator = BoardAggregator(
jsonl_dir=jsonl_dir,
@@ -2330,47 +2331,61 @@ class WebServer:
db_path, recovered, len(scheduler._heap),
)
+ def _read_sessions_toml_section(self) -> dict:
+ """The raw ``[sessions]`` section from jarvis.toml (may be empty).
+
+ That section is NOT in the Pydantic tree (see assumption A-2 in the
+ Phase-7 bootstrap), hence tomllib directly.
+ """
+ toml_path = Path("jarvis.toml")
+ if not toml_path.exists():
+ return {}
+ try:
+ import tomllib
+ with toml_path.open("rb") as fh:
+ raw = tomllib.load(fh)
+ return raw.get("sessions", {}) or {}
+ except Exception as exc: # noqa: BLE001
+ logger.opt(exception=exc).warning(
+ "Could not read the [sessions] section from jarvis.toml — using defaults"
+ )
+ return {}
+
+ def _resolve_sessions_db_path(self) -> Path:
+ """Absolute path to sessions.db, shared by recorder and board.
+
+ A relative ``[sessions].db_path`` is anchored at the data-dir parent
+ (the repo root), never at the process CWD, so every consumer sees the
+ SAME database regardless of where the app was launched from.
+ """
+ section = self._read_sessions_toml_section()
+ db_path = Path(str(section.get("db_path", "data/sessions.db")))
+ if not db_path.is_absolute():
+ db_path = Path(self.cfg.memory.data_dir).parent / db_path
+ return db_path
+
def _init_session_stack(self) -> None:
"""Voice-session recorder + store for the transcription view.
Bootstrap analogous to ``_init_mission_stack``, but sync — the store
uses sqlite3 + threading.Lock (see ``jarvis/sessions/store.py``).
- Reads defaults from the ``[sessions]`` section in jarvis.toml; that
- section is NOT in the Pydantic tree (see assumption A-2 in the
- Phase-7 bootstrap), hence tomllib directly.
"""
from jarvis.sessions.init import bootstrap_sessions
# Defaults match jarvis.toml [sessions] (enabled=true,
# data/sessions.db, retention 30d). User can override via TOML.
- enabled = True
- rel_db_path = "data/sessions.db"
- retention_days = 30
-
- toml_path = Path("jarvis.toml")
- if toml_path.exists():
- try:
- import tomllib
- with toml_path.open("rb") as fh:
- raw = tomllib.load(fh)
- section = raw.get("sessions", {}) or {}
- enabled = bool(section.get("enabled", enabled))
- rel_db_path = str(section.get("db_path", rel_db_path))
- retention_days = int(section.get("retention_days", retention_days))
- except Exception as exc: # noqa: BLE001
- logger.opt(exception=exc).warning(
- "Could not read the [sessions] section from jarvis.toml — using defaults"
- )
+ section = self._read_sessions_toml_section()
+ enabled = bool(section.get("enabled", True))
+ try:
+ retention_days = int(section.get("retention_days", 30))
+ except (TypeError, ValueError):
+ retention_days = 30
if not enabled:
logger.info("Voice-session recorder disabled via [sessions].enabled=false")
return
- # rel_db_path is relative to the repo root (= cwd at start). If
- # absolute, it stays absolute. Path() handles both correctly.
- db_path = Path(rel_db_path)
- if not db_path.is_absolute():
- db_path = Path(self.cfg.memory.data_dir).parent / db_path
+ db_path = self._resolve_sessions_db_path()
db_path.parent.mkdir(parents=True, exist_ok=True)
result = bootstrap_sessions(
diff --git a/tests/board/test_stats_invariants.py b/tests/board/test_stats_invariants.py
new file mode 100644
index 0000000000..a49fb7b527
--- /dev/null
+++ b/tests/board/test_stats_invariants.py
@@ -0,0 +1,504 @@
+"""Invariant tests for the board hero stats (words, streak, active time).
+
+The board previously violated three invariants that these tests pin down:
+
+1. **Monotonic ledger** — the session recorder prunes ``sessions.db`` rows
+ older than the retention window at every boot with a millisecond-precise
+ cutoff. The aggregator then recomputed partially-pruned days from the
+ remaining rows and blindly overwrote the complete ``daily_stats`` row, so
+ ACTIVE TIME, conversation counts and word counts silently decayed day by
+ day. Once a day is in the ledger, a shrinking *source* must never shrink
+ the ledger.
+2. **Honest crash seal** — sessions left open by a crash were sealed at the
+ next boot with ``ended_ms = boot time``, inflating a day's active time by
+ many phantom hours (observed: a 14.8 h "session"). Stale sessions must be
+ sealed with their last recorded activity instead.
+3. **Streak grace** — the running streak anchored strictly at *today*, so it
+ displayed 0 every morning until the first interaction of the day. A quiet
+ today must not break yesterday's streak.
+
+Plus determinism guards: the aggregation must derive everything from stored
+timestamps — never file mtime — and per-day totals must be timezone-stable.
+"""
+from __future__ import annotations
+
+import json
+import os
+import sqlite3
+from datetime import UTC, datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+
+from jarvis.board.aggregator import BoardAggregator, _ensure_daily_stats_columns
+from jarvis.board.store import BoardStore
+from jarvis.core.bus import EventBus
+from jarvis.sessions.constants import HANGUP_SHUTDOWN
+from jarvis.sessions.init import bootstrap_sessions, shutdown_sessions
+from jarvis.sessions.store import SessionStore
+
+# ----------------------------------------------------------------------
+# Helpers
+# ----------------------------------------------------------------------
+
+
+def _ms(moment: datetime) -> int:
+ return int(moment.timestamp() * 1000)
+
+
+def _now() -> datetime:
+ return datetime.now().astimezone()
+
+
+def _add_session(
+ store: SessionStore,
+ *,
+ sid: str,
+ start: datetime,
+ duration_s: float | None,
+ turns: list[tuple[float, float, str, str]] = (),
+ hangup_reason: str = "hotkey",
+) -> None:
+ """Insert one session with optional turns via the real store API.
+
+ ``turns`` entries are ``(offset_s, turn_duration_s, user_text, jarvis_text)``
+ relative to the session start. ``duration_s=None`` leaves the session open.
+ """
+ store.upsert_session(session_id=sid, started_ms=_ms(start))
+ for i, (offset_s, dur_s, user_text, jarvis_text) in enumerate(turns):
+ turn_id = f"{sid}-t{i}"
+ t0 = _ms(start + timedelta(seconds=offset_s))
+ store.upsert_turn(turn_id=turn_id, session_id=sid, idx=i, started_ms=t0)
+ store.finalize_turn(
+ turn_id=turn_id,
+ ended_ms=t0 + int(dur_s * 1000),
+ user_text=user_text,
+ user_lang="en",
+ jarvis_text=jarvis_text,
+ jarvis_lang="en",
+ tier="fast",
+ provider="test",
+ model="test",
+ tokens_in=0,
+ tokens_out=0,
+ cost_usd=0.0,
+ latency_total_ms=0,
+ tool_calls=[],
+ )
+ if duration_s is not None:
+ store.finalize_session(
+ session_id=sid,
+ ended_ms=_ms(start + timedelta(seconds=duration_s)),
+ hangup_reason=hangup_reason,
+ turn_count=len(turns),
+ total_cost_usd=0.0,
+ total_tokens_in=0,
+ total_tokens_out=0,
+ providers_used=[],
+ )
+
+
+def _snapshot_daily(agg: BoardAggregator) -> dict[str, dict[str, Any]]:
+ rows = agg.db.execute(
+ "SELECT date, session_count, user_words_count, jarvis_words_count, "
+ "active_events_count, conversation_seconds_estimate FROM daily_stats"
+ ).fetchall()
+ return {r["date"]: dict(r) for r in rows}
+
+
+def _totals(agg: BoardAggregator) -> dict[str, float]:
+ row = agg.db.execute(
+ "SELECT COALESCE(SUM(session_count),0) s, COALESCE(SUM(user_words_count),0) uw, "
+ "COALESCE(SUM(jarvis_words_count),0) jw, "
+ "COALESCE(SUM(conversation_seconds_estimate),0) secs FROM daily_stats"
+ ).fetchone()
+ return {"sessions": row["s"], "user_words": row["uw"],
+ "jarvis_words": row["jw"], "seconds": row["secs"]}
+
+
+def _mk_board_db(db_path: Path) -> sqlite3.Connection:
+ """Create an empty board DB with the real schema for streak fixtures."""
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+ conn = sqlite3.connect(db_path, isolation_level=None)
+ conn.row_factory = sqlite3.Row
+ schema = (Path("jarvis/board/schema.sql")).read_text(encoding="utf-8")
+ conn.executescript(schema)
+ _ensure_daily_stats_columns(conn)
+ return conn
+
+
+def _insert_active_day(conn: sqlite3.Connection, day: str, events: int = 5) -> None:
+ conn.execute(
+ "INSERT INTO daily_stats (date, active_events_count) VALUES (?, ?) "
+ "ON CONFLICT(date) DO UPDATE SET active_events_count = excluded.active_events_count",
+ (day, events),
+ )
+
+
+def _tz(name: str, fallback_hours: int) -> timezone | Any:
+ """A real IANA zone when tzdata is available, else a fixed offset."""
+ try:
+ from zoneinfo import ZoneInfo
+
+ return ZoneInfo(name)
+ except Exception: # noqa: BLE001 - no tzdata on this host
+ return timezone(timedelta(hours=fallback_hours))
+
+
+# ----------------------------------------------------------------------
+# 1. Monotonic ledger under retention pruning
+# ----------------------------------------------------------------------
+
+
+def test_prune_records_a_horizon(tmp_path: Path) -> None:
+ """``prune_older_than`` must record its cutoff so readers can tell
+ "deleted" from "never existed". The horizon only ever moves forward."""
+ store = SessionStore(db_path=tmp_path / "sessions.db")
+ store.open()
+ try:
+ _add_session(store, sid="old", start=_now() - timedelta(days=40), duration_s=60)
+ before = _ms(_now() - timedelta(days=30))
+ store.prune_older_than(30)
+ after = _ms(_now() - timedelta(days=30))
+ horizon = store.prune_horizon_ms()
+ assert horizon is not None
+ assert before <= horizon <= after
+
+ # A later prune with a LARGER window must not move the horizon back.
+ store.prune_older_than(60)
+ assert store.prune_horizon_ms() == horizon
+ finally:
+ store.close()
+
+
+def test_pruned_source_never_shrinks_daily_ledger(tmp_path: Path) -> None:
+ """Core monotonicity: re-aggregating after a retention prune must leave
+ every already-recorded day (and therefore all totals) untouched — even for
+ the boundary day the ms-precise cutoff slices in half."""
+ sessions_db = tmp_path / "sessions.db"
+ store = SessionStore(db_path=sessions_db)
+ store.open()
+
+ now = _now()
+ cutoff = now - timedelta(days=30)
+ # Two sessions on the cutoff day, one on each side of the cutoff instant,
+ # both clamped into the cutoff day so the day is only PARTIALLY pruned.
+ day_start = cutoff.replace(hour=0, minute=0, second=0, microsecond=0)
+ day_end = day_start + timedelta(days=1)
+ before_cutoff = cutoff - timedelta(hours=1)
+ if before_cutoff < day_start:
+ before_cutoff = day_start + (cutoff - day_start) / 2
+ after_cutoff = cutoff + timedelta(hours=1)
+ if after_cutoff >= day_end:
+ after_cutoff = cutoff + (day_end - cutoff) / 2
+
+ _add_session(
+ store, sid="ancient", start=now - timedelta(days=40), duration_s=600,
+ turns=[(1, 5, "three words here", "four words in reply")],
+ )
+ _add_session(
+ store, sid="boundary-pruned", start=before_cutoff, duration_s=600,
+ turns=[(1, 5, "alpha beta gamma delta", "echo foxtrot")],
+ )
+ _add_session(
+ store, sid="boundary-kept", start=after_cutoff, duration_s=300,
+ turns=[(1, 5, "one two", "three")],
+ )
+ _add_session(
+ store, sid="fresh", start=now - timedelta(days=5), duration_s=120,
+ turns=[(1, 5, "hello there", "hi")],
+ )
+
+ agg = BoardAggregator(
+ jsonl_dir=tmp_path / "flight_recorder",
+ db_path=tmp_path / "board" / "personal.db",
+ sessions_db_path=sessions_db,
+ )
+ agg.run()
+ daily_before = _snapshot_daily(agg)
+ totals_before = _totals(agg)
+ assert totals_before["sessions"] == 4
+ assert totals_before["seconds"] == 600 + 600 + 300 + 120
+
+ # The recorder's boot-time retention prune removes "ancient" entirely and
+ # slices the boundary day in half.
+ pruned = store.prune_older_than(30)
+ assert pruned == 2
+ store.close()
+
+ agg.run()
+ assert _snapshot_daily(agg) == daily_before
+ assert _totals(agg) == totals_before
+ agg.close()
+
+
+def test_fresh_board_db_still_backfills_frozen_dates(tmp_path: Path) -> None:
+ """The freeze must protect existing rows, not forbid first-time inserts:
+ rebuilding a deleted board DB must still ingest whatever the sources have,
+ including dates below the prune horizon."""
+ sessions_db = tmp_path / "sessions.db"
+ store = SessionStore(db_path=sessions_db)
+ store.open()
+ now = _now()
+ _add_session(
+ store, sid="kept", start=now - timedelta(days=29, hours=1), duration_s=600,
+ turns=[(1, 5, "still here", "yes")],
+ )
+ store.prune_older_than(30) # horizon exists, nothing was actually deleted
+ store.close()
+
+ agg = BoardAggregator(
+ jsonl_dir=tmp_path / "flight_recorder",
+ db_path=tmp_path / "board" / "personal.db",
+ sessions_db_path=sessions_db,
+ )
+ agg.run()
+ totals = _totals(agg)
+ assert totals["sessions"] == 1
+ assert totals["seconds"] == 600
+ agg.close()
+
+
+# ----------------------------------------------------------------------
+# 2. Honest crash seal
+# ----------------------------------------------------------------------
+
+
+def test_crash_seal_uses_last_activity_not_boot_time(tmp_path: Path) -> None:
+ """A session left open by a crash must be sealed with its last recorded
+ activity, not with "whenever the app happened to restart"."""
+ db_path = tmp_path / "sessions.db"
+ store = SessionStore(db_path=db_path)
+ store.open()
+ start = _now() - timedelta(hours=10)
+ _add_session(
+ store, sid="crashed", start=start, duration_s=None,
+ turns=[(5, 85, "are you there", "certainly")],
+ )
+ last_activity = _ms(start + timedelta(seconds=5 + 85))
+ store.close()
+
+ result = bootstrap_sessions(bus=EventBus(), db_path=db_path, retention_days=30)
+ try:
+ row = result["store"].get_session("crashed")
+ assert row is not None
+ assert row.hangup_reason == HANGUP_SHUTDOWN
+ assert row.ended_ms == last_activity # NOT ten hours later at boot time
+ finally:
+ shutdown_sessions(result)
+
+
+def test_inflated_shutdown_seal_is_repaired_at_boot(tmp_path: Path) -> None:
+ """Sessions already sealed with a phantom boot-time end (the observed
+ 14.8 h ghost) are repaired to their last activity on the next bootstrap.
+ Honestly sealed sessions stay untouched."""
+ db_path = tmp_path / "sessions.db"
+ store = SessionStore(db_path=db_path)
+ store.open()
+ start = _now() - timedelta(days=2)
+ _add_session(
+ store, sid="ghost", start=start, duration_s=14 * 3600,
+ turns=[(5, 55, "short chat", "indeed")],
+ hangup_reason=HANGUP_SHUTDOWN,
+ )
+ honest_start = _now() - timedelta(days=1)
+ _add_session(
+ store, sid="honest", start=honest_start, duration_s=90,
+ turns=[(5, 55, "quick one", "done")],
+ hangup_reason="hotkey",
+ )
+ store.close()
+
+ result = bootstrap_sessions(bus=EventBus(), db_path=db_path, retention_days=30)
+ try:
+ ghost = result["store"].get_session("ghost")
+ assert ghost is not None
+ assert ghost.ended_ms == _ms(start + timedelta(seconds=60))
+ honest = result["store"].get_session("honest")
+ assert honest is not None
+ assert honest.ended_ms == _ms(honest_start + timedelta(seconds=90))
+ finally:
+ shutdown_sessions(result)
+
+
+# ----------------------------------------------------------------------
+# 3. Streak semantics
+# ----------------------------------------------------------------------
+
+
+def test_streak_survives_a_quiet_today(tmp_path: Path) -> None:
+ """Before the first interaction of the day the streak must show the run
+ ending yesterday — not reset to 0 every morning."""
+ db_path = tmp_path / "board" / "personal.db"
+ conn = _mk_board_db(db_path)
+ today = _now().date()
+ _insert_active_day(conn, (today - timedelta(days=1)).isoformat())
+ _insert_active_day(conn, (today - timedelta(days=2)).isoformat())
+ conn.close()
+
+ store = BoardStore(db_path=db_path)
+ assert store.summary(window_days=30)["streak_days"] == 2
+
+
+def test_streak_counts_today_and_resets_on_gap(tmp_path: Path) -> None:
+ db_path = tmp_path / "board" / "personal.db"
+ conn = _mk_board_db(db_path)
+ today = _now().date()
+ _insert_active_day(conn, today.isoformat())
+ _insert_active_day(conn, (today - timedelta(days=1)).isoformat())
+ # gap at today-2, older activity must not count into the running streak
+ _insert_active_day(conn, (today - timedelta(days=3)).isoformat())
+ conn.close()
+
+ store = BoardStore(db_path=db_path)
+ assert store.summary(window_days=30)["streak_days"] == 2
+
+
+def test_streak_zero_when_yesterday_and_today_quiet(tmp_path: Path) -> None:
+ db_path = tmp_path / "board" / "personal.db"
+ conn = _mk_board_db(db_path)
+ today = _now().date()
+ _insert_active_day(conn, (today - timedelta(days=2)).isoformat())
+ _insert_active_day(conn, (today - timedelta(days=3)).isoformat())
+ conn.close()
+
+ store = BoardStore(db_path=db_path)
+ assert store.summary(window_days=30)["streak_days"] == 0
+
+
+def test_longest_streak_spans_month_and_year_boundaries(tmp_path: Path) -> None:
+ db_path = tmp_path / "board" / "personal.db"
+ conn = _mk_board_db(db_path)
+ for day in ("2025-12-30", "2025-12-31", "2026-01-01", "2026-01-02"):
+ _insert_active_day(conn, day)
+ for day in ("2026-04-29", "2026-04-30", "2026-05-01"):
+ _insert_active_day(conn, day)
+ conn.close()
+
+ store = BoardStore(db_path=db_path)
+ assert store.summary(window_days=30)["longest_streak"] == 4
+
+
+# ----------------------------------------------------------------------
+# 4. Word counts — exact fixture
+# ----------------------------------------------------------------------
+
+
+def test_word_counts_exact_on_fixture(tmp_path: Path) -> None:
+ """YOU SAID / NICO SAID are whitespace word counts over the stored turn
+ texts — punctuation and repeated whitespace must not change the count."""
+ sessions_db = tmp_path / "sessions.db"
+ store = SessionStore(db_path=sessions_db)
+ store.open()
+ start = _now() - timedelta(days=1, hours=2)
+ _add_session(
+ store, sid="s1", start=start, duration_s=300,
+ turns=[
+ (1, 5, "Hello there, friend!", "Hi."), # 3 user / 1 jarvis
+ (10, 5, "state-of-the-art demo", "works really well"), # 2 / 3
+ (20, 5, "", "counting only real words"), # 0 / 4
+ ],
+ )
+ store.close()
+
+ agg = BoardAggregator(
+ jsonl_dir=tmp_path / "flight_recorder",
+ db_path=tmp_path / "board" / "personal.db",
+ sessions_db_path=sessions_db,
+ )
+ agg.run()
+ agg.close()
+
+ summary = BoardStore(db_path=tmp_path / "board" / "personal.db").summary()
+ assert summary["totals"]["user_words"] == 5
+ assert summary["totals"]["jarvis_words"] == 8
+ assert summary["totals"]["session_count"] == 1
+
+
+# ----------------------------------------------------------------------
+# 5. Determinism: timezones and file metadata
+# ----------------------------------------------------------------------
+
+
+def test_totals_are_timezone_invariant(tmp_path: Path) -> None:
+ """Day *bucketing* legitimately follows the configured timezone, but the
+ all-time totals must be identical whether the host thinks it is in UTC,
+ Berlin or Auckland — and repeated runs must be byte-stable."""
+ sessions_db = tmp_path / "sessions.db"
+ store = SessionStore(db_path=sessions_db)
+ store.open()
+ # 23:30 UTC — lands on different local dates in different zones.
+ utc_evening = datetime.now(tz=UTC).replace(
+ hour=23, minute=30, second=0, microsecond=0
+ ) - timedelta(days=5)
+ _add_session(
+ store, sid="s1", start=utc_evening, duration_s=600,
+ turns=[(1, 5, "spread across zones", "indeed it is")],
+ )
+ _add_session(
+ store, sid="s2", start=utc_evening - timedelta(days=1, hours=12),
+ duration_s=300, turns=[(1, 5, "second day", "yes")],
+ )
+ store.close()
+
+ zones = {
+ "utc": UTC,
+ "berlin": _tz("Europe/Berlin", 2),
+ "auckland": _tz("Pacific/Auckland", 12),
+ }
+ all_totals: dict[str, dict[str, float]] = {}
+ for name, tz in zones.items():
+ snapshots = []
+ for run in range(2):
+ agg = BoardAggregator(
+ jsonl_dir=tmp_path / "flight_recorder",
+ db_path=tmp_path / f"board-{name}-{run}" / "personal.db",
+ sessions_db_path=sessions_db,
+ tz=tz,
+ )
+ agg.run()
+ snapshots.append((_snapshot_daily(agg), _totals(agg)))
+ agg.close()
+ assert snapshots[0] == snapshots[1], f"non-deterministic in {name}"
+ all_totals[name] = snapshots[0][1]
+
+ assert all_totals["utc"] == all_totals["berlin"] == all_totals["auckland"]
+
+
+def test_results_do_not_depend_on_file_mtime(tmp_path: Path) -> None:
+ """Everything derives from timestamps stored IN the data. Touching the
+ files (backup tools, copies, git operations do this) must not move any
+ number."""
+ sessions_db = tmp_path / "sessions.db"
+ store = SessionStore(db_path=sessions_db)
+ store.open()
+ _add_session(
+ store, sid="s1", start=_now() - timedelta(days=3), duration_s=240,
+ turns=[(1, 5, "mtime must not matter", "correct")],
+ )
+ store.close()
+
+ jsonl_dir = tmp_path / "flight_recorder"
+ jsonl_dir.mkdir()
+ ts_ns = int((_now() - timedelta(days=2)).timestamp() * 1e9)
+ (jsonl_dir / "events.jsonl").write_text(
+ json.dumps({
+ "ts_ns": ts_ns, "event": "TranscriptFinal",
+ "trace_id": "t1", "payload": {},
+ }) + "\n",
+ encoding="utf-8",
+ )
+
+ db_path = tmp_path / "board" / "personal.db"
+ agg = BoardAggregator(
+ jsonl_dir=jsonl_dir, db_path=db_path, sessions_db_path=sessions_db
+ )
+ agg.run()
+ before = _snapshot_daily(agg)
+
+ ancient = 946_684_800 # 2000-01-01, far away from every stored timestamp
+ os.utime(sessions_db, (ancient, ancient))
+ os.utime(jsonl_dir / "events.jsonl", (ancient, ancient))
+
+ assert agg.run_if_stale(ttl_s=0) is True
+ assert _snapshot_daily(agg) == before
+ agg.close()