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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(costs): the coding-CLI index is a ledger, not a cache — and it counts every subagent
rubenluetke10-beepa063da6ddfda
diff --git a/jarvis/costs/cli_usage_index.py b/jarvis/costs/cli_usage_index.pyindex b19ddc470a..b78bc0fb9e 100644--- a/jarvis/costs/cli_usage_index.py+++ b/jarvis/costs/cli_usage_index.py@@ -15,9 +15,16 @@ answers *how many tokens, when, by which agent and model*.What each source looks like — MEASURED on a live install, not taken fromdocumentation:-**Claude Code** — ``<config>/projects/<slug>/<session>.jsonl``. The records-that carry usage have ``type == "assistant"`` and hold it at-``message.usage``, with the thinking count nested one level deeper in+**Claude Code** — ``<config>/projects/<slug>/<session>.jsonl``, and the+subagents that session spawned under+``<config>/projects/<slug>/<session>/subagents/**/*.jsonl`` (a plain+``agent-<id>.jsonl`` for the Agent tool, ``workflows/<run>/agent-<id>.jsonl``+for a workflow). A subagent file is the same record shape, stamped with the+PARENT's ``sessionId``, so its spend files under the conversation that asked+for it. Those files were never read until 2026-08-27 — on the machine this was+measured on they held 14 466 of 68 937 responses, one fifth of every Claude+Code call. The records that carry usage have ``type == "assistant"`` and hold+it at ``message.usage``, with the thinking count nested one level deeper in``usage.output_tokens_details``.*The identity of such a record is NOT its ``uuid``.* One API response is@@ -84,6 +91,17 @@ Design rules this module holds itself to:* **Incremental.** A file is re-opened at its stored offset when it grew, andre-read from zero only when it SHRANK (rotated or rewritten), whose rows aredropped first. An offset is only ever stored at a line boundary.+* **Durable.** The index is a ledger, not a cache of the transcripts. A turn+ that was indexed stays indexed when its transcript is deleted — Claude Code+ removes sessions after ``cleanupPeriodDays`` (25 on the machine this was+ found on), and the money those sessions cost did not come back with them.+ Until 2026-08-27 a vanished file took its rows with it and the lifetime+ total shrank a little every night. Likewise a reader whose accounting rule+ changes never drops the table: every transcript still on disk is re-read+ and its rows are corrected in place, so the section never shows a half-+ built index as if it were the whole bill (the previous rebuild dropped+ everything first and reported $8 000 of a $13 600 month for the hours it+ took to catch up).* **Bounded.** :func:`refresh` stops when its deadline is spent, commits whatit has and says ``complete=False``. Files are taken newest-modified first andno single file may take more than :data:`_FILE_BYTE_BUDGET` per run, so one@@ -239,17 +257,24 @@ _FILE_BYTE_BUDGET = 48 * 1024 * 1024_ROLLOUT_ID = re.compile(r"([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})$")# Bumped whenever a reader's accounting changes so rows already indexed under-# the old rule would be wrong. An older index is dropped and rebuilt from the-# transcripts, which are the source of truth; nothing is lost but time.+# the old rule would be wrong. Nothing is ever dropped on a bump: the file+# bookkeeping is reset so every transcript still on disk is read again, and+# a row re-read from its own file overwrites the old one in place+# (``_INSERT_TURN``). Rows whose transcript is gone keep their old values —+# an old number beats no number, and the section names the index as still+# catching up while the re-read runs.# 2 — Codex: cached input subtracted from input; lineage-based dedup.-# 3 — cost_usd column (OpenCode records its own price). Additive: migrated-# in place, no rebuild.+# 3 — cost_usd column (OpenCode records its own price). Additive.# 4 — kimi wire logs were stored as ``agy-cli``; Antigravity (the Google-# ``agy`` binary) has its own conversation DBs. Rebuild so the two no-# longer share a Spend row.-_SCHEMA_VERSION = 4-#: Versions whose rows are still right and only need columns added.-_MIGRATE_IN_PLACE_FROM = 4+# ``agy`` binary) has its own conversation DBs. Renamed in place.+# 5 — the index became a ledger: vanished transcripts keep their rows, a+# bump re-reads instead of rebuilding, and a path index was added.+# Nothing about a row changed.+_SCHEMA_VERSION = 5+#: Rows written under a version below this were counted under a rule that has+#: since changed and are re-read from their transcripts where those still+#: exist. Rows from this version on are right as they are.+_REREAD_BELOW = 4_SCHEMA = """CREATE TABLE IF NOT EXISTS indexed_files (@@ -281,18 +306,43 @@ CREATE TABLE IF NOT EXISTS cli_turns ();CREATE INDEX IF NOT EXISTS idx_cli_turns_ts ON cli_turns (ts_ms);CREATE INDEX IF NOT EXISTS idx_cli_turns_session ON cli_turns (agent, session_id);+CREATE INDEX IF NOT EXISTS idx_cli_turns_path ON cli_turns (path);"""-# A duplicate is ignored except for one field: a row indexed without a model-# (a Codex replay ahead of its ``turn_context``) takes the model from the copy-# that knows it. Nothing else may change — the first sighting is the record.+# A turn seen again is one of two things. Read again FROM ITS OWN FILE — a+# re-read after a rule change, or Claude Code's one-line-per-content-block+# repeat of the same response — it is the same record and the fresh values+# win; that is how a rebuild corrects rows without deleting them first. Seen+# in ANOTHER file (a Codex fork replaying its parent, a resumed Claude+# session) it is a copy: the first sighting stays the record, and the one+# field a copy may fill in is a model the original did not know._INSERT_TURN = ("INSERT INTO cli_turns ""(agent, dedup_key, path, session_id, ts_ms, model, "" tokens_in, tokens_out, tokens_cached, cwd, label, cost_usd) ""VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "- "ON CONFLICT(agent, dedup_key) DO UPDATE SET model=excluded.model "- "WHERE cli_turns.model = '' AND excluded.model <> ''"+ "ON CONFLICT(agent, dedup_key) DO UPDATE SET "+ " session_id = CASE WHEN cli_turns.path = excluded.path"+ " THEN excluded.session_id ELSE cli_turns.session_id END,"+ " ts_ms = CASE WHEN cli_turns.path = excluded.path"+ " THEN excluded.ts_ms ELSE cli_turns.ts_ms END,"+ " tokens_in = CASE WHEN cli_turns.path = excluded.path"+ " THEN excluded.tokens_in ELSE cli_turns.tokens_in END,"+ " tokens_out = CASE WHEN cli_turns.path = excluded.path"+ " THEN excluded.tokens_out ELSE cli_turns.tokens_out END,"+ " tokens_cached = CASE WHEN cli_turns.path = excluded.path"+ " THEN excluded.tokens_cached ELSE cli_turns.tokens_cached END,"+ " cwd = CASE WHEN cli_turns.path = excluded.path"+ " THEN excluded.cwd ELSE cli_turns.cwd END,"+ " label = CASE WHEN cli_turns.path = excluded.path"+ " THEN excluded.label ELSE cli_turns.label END,"+ " cost_usd = CASE WHEN cli_turns.path = excluded.path"+ " THEN excluded.cost_usd ELSE cli_turns.cost_usd END,"+ " model = CASE WHEN excluded.model <> ''"+ " AND (cli_turns.path = excluded.path OR cli_turns.model = '')"+ " THEN excluded.model ELSE cli_turns.model END "+ "WHERE cli_turns.path = excluded.path"+ " OR (cli_turns.model = '' AND excluded.model <> '')")_UPSERT_FILE = (@@ -622,6 +672,10 @@ def _grok_roots(home: Path | None) -> list[Path]:#: that can hold transcripts._LAYOUTS: tuple[tuple[str, str], ...] = ((AGENT_CLAUDE, "projects/*/*.jsonl"),+ # The subagents a session spawned: ``<session>/subagents/agent-<id>.jsonl``+ # for the Agent tool, one level deeper under ``workflows/<run>/`` for a+ # workflow. ``**`` covers both and whatever depth a later CLI adds.+ (AGENT_CLAUDE, "projects/*/*/subagents/**/*.jsonl"),(AGENT_CODEX, "sessions/*/*/*/rollout-*.jsonl"),# Older Codex builds filed rollouts flat.(AGENT_CODEX, "sessions/rollout-*.jsonl"),@@ -1358,7 +1412,7 @@ def _scan_antigravity(cand: _Candidate, start: int) -> _FileScan:finally:conn.close()return _FileScan(- rows=rows,+ rows=list(rows), # type: ignore[arg-type]offset=0 if failed else cand.size,cursor=_Cursor(session_id=session_id,@@ -1441,7 +1495,7 @@ def _scan_opencode(cand: _Candidate, start: int) -> _FileScan:finally:conn.close()return _FileScan(- rows=list(rows), # type: ignore[arg-type]+ rows=rows,offset=max(newest, cand.size),cursor=_Cursor(),bytes_read=cand.size,@@ -1553,27 +1607,11 @@ def _open_rw(path: Path) -> sqlite3.Connection | None:# fsyncs. A lost tail after a crash costs a re-read, never a wrong sum.conn.execute("PRAGMA journal_mode=WAL")conn.execute("PRAGMA synchronous=NORMAL")+ conn.executescript(_SCHEMA)version = _int(conn.execute("PRAGMA user_version").fetchone()[0])- if _MIGRATE_IN_PLACE_FROM <= version < _SCHEMA_VERSION:- # Rows counted under this version are right; only the shape grew.- columns = {r[1] for r in conn.execute("PRAGMA table_info(cli_turns)")}- if "cost_usd" not in columns:- conn.execute("ALTER TABLE cli_turns ADD COLUMN cost_usd REAL NOT NULL DEFAULT 0")- conn.execute(f"PRAGMA user_version={_SCHEMA_VERSION}")- version = _SCHEMA_VERSIONif version < _SCHEMA_VERSION:- # Rows counted under an older rule are wrong, not stale. Rebuild.- if _has_rows(conn):- log.info(- "cli usage index: schema %d < %d, rebuilding from the transcripts",- version,- _SCHEMA_VERSION,- )- conn.executescript(- "DROP TABLE IF EXISTS cli_turns; DROP TABLE IF EXISTS indexed_files;"- )+ _migrate(conn, version)conn.execute(f"PRAGMA user_version={_SCHEMA_VERSION}")- conn.executescript(_SCHEMA)conn.commit()return connexcept (OSError, sqlite3.Error) as exc:@@ -1581,6 +1619,46 @@ def _open_rw(path: Path) -> sqlite3.Connection | None:return None+def _migrate(conn: sqlite3.Connection, version: int) -> None:+ """Bring an older index up to date WITHOUT losing a row.++ Every step is in place. Where a reader's rule changed, the file+ bookkeeping is cleared so each transcript still on disk is read again+ and its rows are overwritten from their own file (``_INSERT_TURN``); the+ rows of a transcript that has since been deleted are kept under the old+ rule rather than thrown away. An index that is brand new (version 0 and+ no rows) has nothing to migrate.+ """+ if version == 0 and not _has_rows(conn):+ return+ columns = {r[1] for r in conn.execute("PRAGMA table_info(cli_turns)")}+ if "cost_usd" not in columns:+ # 3: OpenCode writes its own price. Additive.+ conn.execute("ALTER TABLE cli_turns ADD COLUMN cost_usd REAL NOT NULL DEFAULT 0")+ if version < 4:+ # 4: kimi wire logs were filed under Antigravity's name. The path+ # says which reader wrote the row, so the rename needs no re-read.+ conn.execute(+ "UPDATE cli_turns SET agent = ? WHERE agent = ? AND path LIKE '%wire.jsonl'",+ (AGENT_KIMI, AGENT_AGY),+ )+ conn.execute(+ "UPDATE indexed_files SET agent = ? WHERE agent = ? AND path LIKE '%wire.jsonl'",+ (AGENT_KIMI, AGENT_AGY),+ )+ if version < _REREAD_BELOW:+ # Rows counted under an older accounting rule are wrong, not stale.+ # Forgetting every file makes the next runs read them all again from+ # byte zero; each row is then corrected from its own transcript. The+ # table stays readable — and complete — the whole time.+ log.info(+ "cli usage index: schema %d < %d, re-reading every transcript in place",+ version,+ _SCHEMA_VERSION,+ )+ conn.execute("DELETE FROM indexed_files")++def _has_rows(conn: sqlite3.Connection) -> bool:"""Whether an index holds any turn at all (decides if a rebuild is news)."""try:@@ -1632,18 +1710,23 @@ def _backfill_models(conn: sqlite3.Connection, keys: list[str]) -> None:conn.executemany(sql, [(key,) for key in keys])-def _prune_vanished(+def _forget_vanished(conn: sqlite3.Connection,candidates: list[_Candidate],known: dict[str, sqlite3.Row],home: Path | None,) -> None:- """Drop the rows of transcripts that no longer exist.-- ``_drop_rows`` only fires when a file SHRANK; a deleted file kept its rows- forever (446 rows / 88M tokens from six vanished transcripts,- 2026-08-25). Pruning is limited to roots that are readable right now, so- an unmounted drive or a transient permission error never wipes history.+ """Drop the BOOKKEEPING of transcripts that no longer exist — never their+ turns.++ The turns stay: the calls were made and billed, and the CLI deleting its+ own log afterwards (Claude Code's ``cleanupPeriodDays``, a user tidying+ ``~/.codex``) does not refund them. Until 2026-08-27 this function took+ the rows too, and the lifetime total went DOWN every night as the oldest+ day's transcripts aged out. Only the resume row goes, so a file that+ comes back (a remounted drive) is read from zero and overwrites its own+ rows in place. Limited to roots that are readable right now, so a+ transient permission error never touches the bookkeeping either."""live: list[str] = []for agent, _pattern in _LAYOUTS:@@ -1659,7 +1742,6 @@ def _prune_vanished(for key in list(known):if key in fresh or not any(key.startswith(r) for r in live):continue- _drop_rows(conn, key)conn.execute("DELETE FROM indexed_files WHERE path = ?", (key,))known.pop(key, None)@@ -1723,7 +1805,7 @@ def refresh(scanned_keys: list[str] = []try:known = _resume_rows(conn)- _prune_vanished(conn, candidates, known, home)+ _forget_vanished(conn, candidates, known, home)pending = _pending(candidates, known, since_ms)# Newest first: the file a user just closed is the one whose numbers# they are looking at, and it is the one most likely to be small.@@ -1958,20 +2040,33 @@ def _resume_point(cand: _Candidate, row: sqlite3.Row | None) -> tuple[int, _Cursdef _drop_rows(conn: sqlite3.Connection, key: str) -> None:+ """Forget the turns of ONE file — only ever because that file shrank and+ is about to be read again. A file that disappeared keeps its rows."""try:conn.execute("DELETE FROM cli_turns WHERE path = ?", (key,))except sqlite3.Error as exc:log.warning("cli usage index: could not drop rows of %s (%s)", key, exc)+def _rows_of(conn: sqlite3.Connection, key: str) -> int:+ row = conn.execute("SELECT COUNT(*) FROM cli_turns WHERE path = ?", (key,)).fetchone()+ return _int(row[0]) if row is not None else 0++def _commit_file(conn: sqlite3.Connection, cand: _Candidate, scan: _FileScan) -> int:- """Write a file's turns and its resume point as one transaction."""- before = conn.total_changes+ """Write a file's turns and its resume point as one transaction.++ ``added`` counts rows this file now owns that it did not own before. A+ row overwritten in place (a re-read, a repeated content-block line) and+ a row another file already owns are not additions — ``total_changes``+ would count both, and the section would report turns nobody made.+ """try:+ before = _rows_of(conn, cand.key)if scan.rows:priced = [r if len(r) == 12 else (*r, 0.0) for r in scan.rows]conn.executemany(_INSERT_TURN, priced)- added = conn.total_changes - before+ added = _rows_of(conn, cand.key) - beforeif scan.cursor.model:# A replayed prefix lands before the file's ``turn_context``; the# context that follows is authoritative for every row in thediff --git a/jarvis/ui/web/costs_routes.py b/jarvis/ui/web/costs_routes.pyindex 021388cdc3..996fe34069 100644--- a/jarvis/ui/web/costs_routes.py+++ b/jarvis/ui/web/costs_routes.py@@ -125,6 +125,26 @@ class Currency(BaseModel):"""``config`` when jarvis.toml set a rate, ``default`` otherwise."""+class IndexStatus(BaseModel):+ """How far the coding-CLI index has read the transcripts on disk.++ The section renders from the index, and the index fills in over many+ background runs — on a first start, after an account is added, after a+ reader's rule changes. While ``complete`` is false the coding-CLI share+ of every number on the page is still rising, and the page has to say so:+ two screenshots taken a minute apart during such a catch-up showed+ $8 000 and $12 300 for the same month and read as money gone missing+ (2026-08-27).+ """++ files_known: int+ files_indexed: int+ files_pending: int+ bytes_pending: int+ turns: int+ complete: bool++class CostSummary(BaseModel):since_ms: intuntil_ms: int@@ -142,6 +162,8 @@ class CostSummary(BaseModel):currency: Currencysources_present: list[str]"""Which stores actually existed — an empty section is explainable."""+ index: IndexStatus+ """Whether the coding-CLI numbers are final yet, and how far they are."""class DayRow(BaseModel):@@ -267,25 +289,36 @@ class _IndexRefresher:Reading a vendor transcript is seconds of I/O on gigabytes, so it cannever happen while a request waits. Instead every summary request asks- this to run, and it does so at most once a minute, one thread at a time,- reporting whatever it managed. The section always renders from what the- index already has; a first run on a busy machine simply fills in over the- next few refreshes rather than blocking the page (AP-26: nothing here- starts at import or at boot either — the first request arms it).+ this to run, and it does so one thread at a time, reporting whatever it+ managed. The section always renders from what the index already has; a+ first run on a busy machine simply fills in over the next few refreshes+ rather than blocking the page (AP-26: nothing here starts at import or+ at boot either — the first request arms it).++ Cadence: once a minute when the last run reached the end of every+ transcript, every few seconds while it did not. A catch-up — a first+ start, a new account, a re-read after a rule change — is nine gigabytes+ on the reference machine; at one twenty-second run per minute that is a+ third of the wall clock spent reading and hours of a page that says less+ than the truth. Running back to back while there is tail to read cuts+ that to the read time itself, and the summary names the state meanwhile."""_MIN_GAP_S = 60.0+ _CATCH_UP_GAP_S = 3.0_BUDGET_S = 20.0def __init__(self) -> None:self._lock = threading.Lock()self._running = Falseself._last = 0.0+ self._complete = Falsedef nudge(self, data_dir: Path | None) -> None:now = time.monotonic()with self._lock:- if self._running or (self._last and now - self._last < self._MIN_GAP_S):+ gap = self._MIN_GAP_S if self._complete else self._CATCH_UP_GAP_S+ if self._running or (self._last and now - self._last < gap):returnself._running = Truethreading.Thread(@@ -293,10 +326,12 @@ class _IndexRefresher:).start()def _run(self, data_dir: Path | None) -> None:+ complete = Falsetry:from jarvis.costs.cli_usage_index import refreshresult = refresh(data_dir=data_dir, deadline_s=self._BUDGET_S)+ complete = result.completeif result.turns_added:log.debug("cli usage index: +%d turns from %d files",@@ -311,11 +346,63 @@ class _IndexRefresher:with self._lock:self._running = Falseself._last = time.monotonic()+ self._complete = complete_refresher = _IndexRefresher()+class _IndexStatusCache:+ """``index_state`` walks the transcript folders (a few thousand ``stat``+ calls); the summary is polled every 30 s and re-requested on every filter+ click, so the walk is shared for a short while rather than repeated."""++ _TTL_S = 10.0++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._key: str | None = None+ self._value: IndexStatus | None = None+ self._at = 0.0++ def get(self, data_dir: Path | None) -> IndexStatus:+ key = str(data_dir)+ now = time.monotonic()+ with self._lock:+ if self._value is not None and self._key == key and (now - self._at) < self._TTL_S:+ return self._value+ value = _index_status(data_dir)+ with self._lock:+ self._key = key+ self._value = value+ self._at = now+ return value+++def _index_status(data_dir: Path | None) -> IndexStatus:+ try:+ from jarvis.costs.cli_usage_index import index_state++ state = index_state(data_dir=data_dir)+ except Exception as exc: # noqa: BLE001 — a status badge must never 500 the page+ log.warning("cli usage index: state unavailable (%s)", exc)+ return IndexStatus(+ files_known=0, files_indexed=0, files_pending=0, bytes_pending=0, turns=0,+ complete=True,+ )+ return IndexStatus(+ files_known=state.files_known,+ files_indexed=state.files_indexed,+ files_pending=state.files_pending,+ bytes_pending=state.bytes_pending,+ turns=state.turns,+ complete=state.complete,+ )+++_index_status_cache = _IndexStatusCache()++# ---------------------------------------------------------------------------@@ -427,6 +514,7 @@ async def get_summary(payload["facets"] = _facets(entries).model_dump()payload["currency"] = _currency().model_dump()payload["sources_present"] = [p.name for p in sources.existing()]+ payload["index"] = _index_status_cache.get(sources.cli_index_dir).model_dump()return CostSummary.model_validate(payload)diff --git a/jarvis/ui/web/frontend/src/hooks/useCosts.ts b/jarvis/ui/web/frontend/src/hooks/useCosts.tsindex 7c345fc1e8..96ffd17d9a 100644--- a/jarvis/ui/web/frontend/src/hooks/useCosts.ts+++ b/jarvis/ui/web/frontend/src/hooks/useCosts.ts@@ -125,6 +125,23 @@ export interface CostSummary {facets: CostFacets;currency: CostCurrency;sources_present: string[];+ /** Whether the coding-CLI numbers are final yet, and how far they are. */+ index: CostIndexStatus;+}++/**+ * How far the coding-CLI index has read the transcripts on disk. While+ * `complete` is false the coding-CLI share of every number on the page is+ * still rising — the page says so rather than presenting a fraction as the+ * whole bill.+ */+export interface CostIndexStatus {+ files_known: number;+ files_indexed: number;+ files_pending: number;+ bytes_pending: number;+ turns: number;+ complete: boolean;}/**diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 6044a5eb65..476a716dde 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5502,6 +5502,7 @@"refresh": "Aktualisieren","clear_filters": "Filter zurücksetzen","load_error": "Die Kosten konnten nicht gelesen werden. Dieser Bereich liest die eigenen Datenbanken der App — wenn das bleibt, ist der Datenordner nicht erreichbar.",+ "index_catching_up": "Die Coding-CLIs werden noch gezählt: {indexed} von {known} Transkripten gelesen, {pendingMb} MB offen. Jede Zahl auf dieser Seite steigt noch, bis das durch ist.","stat_total": "Gesamtkosten","stat_total_hint": "{perDay} pro Tag im Schnitt","stat_total_hint_seat": "{billed} über API-Keys abgerechnet · {seat} durch Abos gedeckt",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex a2bea797d6..a52bae9c86 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5502,6 +5502,7 @@"refresh": "Refresh","clear_filters": "Clear filters","load_error": "Spend could not be read. This section reads the app's own databases — if it keeps failing, the data folder is unreachable.",+ "index_catching_up": "Still counting the coding CLIs: {indexed} of {known} transcripts read, {pendingMb} MB to go. Every number on this page keeps rising until that is done.","stat_total": "Total spend","stat_total_hint": "{perDay} per day on average","stat_total_hint_seat": "{billed} billed to API keys · {seat} covered by subscriptions",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 9e71a43d35..28d5c6304a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5502,6 +5502,7 @@"refresh": "Actualizar","clear_filters": "Quitar filtros","load_error": "No se pudieron leer los gastos. Esta sección lee las bases de datos de la propia app; si sigue fallando, la carpeta de datos no es accesible.",+ "index_catching_up": "Las CLIs de código aún se están contando: {indexed} de {known} transcripciones leídas, {pendingMb} MB pendientes. Cada cifra de esta página sigue subiendo hasta que termine.","stat_total": "Gasto total","stat_total_hint": "{perDay} al día de media","stat_total_hint_seat": "{billed} facturado a claves API · {seat} cubierto por suscripciones",diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsxindex bfa07cda40..4db3c89ed7 100644--- a/jarvis/ui/web/frontend/src/views/CostsView.tsx+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx@@ -293,6 +293,23 @@ export function CostsView() {<EmptyRow>{t("costs_view.load_error")}</EmptyRow>) : null}+ {/*+ The coding-CLI numbers come from an index that fills in over+ background runs — a first start, a new account, a re-read after a+ rule change. A page that shows a half-read index as the month's+ total reads as money gone missing ($8 000 next to yesterday's+ $12 300, 2026-08-27). Say it is still counting, and how far it is.+ */}+ {data && !data.index.complete ? (+ <EmptyRow>+ {fill(t("costs_view.index_catching_up"), {+ indexed: formatExact(data.index.files_indexed),+ known: formatExact(data.index.files_known),+ pendingMb: formatExact(Math.round(data.index.bytes_pending / 1_000_000)),+ })}+ </EmptyRow>+ ) : null}+{/*An empty report under a row filter is indistinguishable from"nothing was spent" — the tab looked broken for a day because adiff --git a/tests/unit/costs/test_cli_usage_index.py b/tests/unit/costs/test_cli_usage_index.pyindex 3c576a47ee..3ed367df36 100644--- a/tests/unit/costs/test_cli_usage_index.py+++ b/tests/unit/costs/test_cli_usage_index.py@@ -381,6 +381,36 @@ def test_a_corrupt_line_does_not_cost_the_file(tmp_path: Path) -> None:assert len(_all(data)) == 2+def test_subagent_transcripts_are_indexed_under_their_parent_session(tmp_path: Path) -> None:+ """The Agent tool and workflows write their own files beside the session:+ ``<session>/subagents/agent-<id>.jsonl`` and+ ``<session>/subagents/workflows/<run>/agent-<id>.jsonl``. They carry the+ parent's ``sessionId``, so their spend lands on that conversation. One+ fifth of every Claude Code call on the reference machine lived there,+ unread, until 2026-08-27.+ """+ data = tmp_path / "data"+ session_dir = _claude_path(tmp_path, "sess-1").with_suffix("")+ _write(_claude_path(tmp_path, "sess-1"), [_claude_line(uuid="u1", msg_id="msg_main")])+ _write(+ session_dir / "subagents" / "agent-a1b2c3.jsonl",+ [_claude_line(uuid="u2", msg_id="msg_agent", input_tokens=100)],+ )+ _write(+ session_dir / "subagents" / "workflows" / "wf_1234" / "agent-d4e5f6.jsonl",+ [_claude_line(uuid="u3", msg_id="msg_workflow", input_tokens=1000)],+ )++ result = refresh(data_dir=data, home=tmp_path)++ assert result.files_seen == 3+ assert result.turns_added == 3+ turns = _all(data)+ assert {t.session_id for t in turns} == {"sess-1"}+ assert sum(t.tokens_in for t in turns) == 15 + 105 + 1005+ assert all(t.agent == AGENT_CLAUDE for t in turns)++# ---------------------------------------------------------------------------# Codex# ---------------------------------------------------------------------------@@ -505,8 +535,9 @@ def test_codex_fork_replays_its_parent_but_is_counted_once(tmp_path: Path) -> Noassert {t.model for t in turns} == {"gpt-5.6-terra"}-def test_an_index_built_under_an_older_rule_is_rebuilt(tmp_path: Path) -> None:- """A schema bump throws the old rows away rather than mixing two rules."""+def test_an_index_built_under_an_older_rule_is_reread(tmp_path: Path) -> None:+ """A schema bump re-reads every transcript and corrects its rows in place —+ the table never empties, so a report taken mid-way is never a fraction."""import sqlite3from jarvis.costs.cli_usage_index import index_db_path@@ -1098,7 +1129,13 @@ def test_grok_replayed_turn_counts_once(tmp_path: Path) -> None:# ----------------------------------------------------------------------------def test_a_transcript_that_disappeared_loses_its_rows(tmp_path: Path) -> None:+def test_a_transcript_that_disappeared_keeps_its_rows(tmp_path: Path) -> None:+ """The index is a ledger: a deleted log does not refund the calls in it.++ Claude Code deletes sessions after ``cleanupPeriodDays``; the total for+ the month must not sink with them. Only the file's resume row goes, so+ the state report stops counting it as pending.+ """import sqlite3from jarvis.costs.cli_usage_index import index_db_path@@ -1112,10 +1149,110 @@ def test_a_transcript_that_disappeared_loses_its_rows(tmp_path: Path) -> None:path.unlink()refresh(data_dir=data, home=tmp_path)+ refresh(data_dir=data, home=tmp_path)- assert _all(data) == []+ turns = _all(data)+ assert len(turns) == 1+ assert turns[0].tokens_in == 65with sqlite3.connect(index_db_path(data)) as conn:assert conn.execute("SELECT COUNT(*) FROM indexed_files").fetchone()[0] == 0+ state = index_state(data_dir=data, home=tmp_path)+ assert state.files_known == 0 and state.turns == 1 and state.complete+++def test_a_transcript_that_comes_back_overwrites_its_own_rows(tmp_path: Path) -> None:+ """A remounted drive: the file is read from zero and lands on the same+ rows, so the ledger neither doubles nor loses what it kept meanwhile."""+ data = tmp_path / "data"+ session = "019ffba8-3748-7652-bf9d-f3b54697b10a"+ path = _codex_path(tmp_path, session)+ lines = [*_codex_prelude(session), _codex_token_line()]+ _write(path, lines)+ refresh(data_dir=data, home=tmp_path)++ path.unlink()+ refresh(data_dir=data, home=tmp_path)+ _write(path, lines)+ result = refresh(data_dir=data, home=tmp_path)++ assert result.turns_added == 0+ assert len(_all(data)) == 1+++def test_a_schema_bump_keeps_the_rows_of_a_transcript_that_is_gone(tmp_path: Path) -> None:+ """A rebuild re-reads what is still on disk; what is not stays as it was.++ The alternative — drop everything, read it back — showed $8 000 of a+ $13 600 month for the hours the re-read took and lost every deleted+ transcript for good (2026-08-27).+ """+ import sqlite3++ from jarvis.costs.cli_usage_index import index_db_path++ data = tmp_path / "data"+ kept = _claude_path(tmp_path, "kept")+ gone = _claude_path(tmp_path, "gone")+ _write(kept, [_claude_line(uuid="u1", msg_id="msg_kept", input_tokens=10)])+ _write(gone, [_claude_line(uuid="u2", msg_id="msg_gone", input_tokens=10)])+ refresh(data_dir=data, home=tmp_path)+ assert len(_all(data)) == 2++ gone.unlink()+ with sqlite3.connect(index_db_path(data)) as conn:+ # Numbers an older rule produced, for both rows.+ conn.execute("UPDATE cli_turns SET tokens_in = 999999")+ conn.execute("PRAGMA user_version=1")++ refresh(data_dir=data, home=tmp_path)++ by_session = {t.session_id: t for t in _all(data)}+ assert set(by_session) == {"sess-1"} or len(_all(data)) == 2+ turns = sorted(_all(data), key=lambda t: t.tokens_in)+ assert len(turns) == 2+ # The file still on disk was re-read and corrected in place …+ assert turns[0].tokens_in == 15+ # … the one that is gone kept its old value rather than vanishing.+ assert turns[1].tokens_in == 999999+++def test_a_reread_corrects_a_row_but_a_copy_in_another_file_does_not(tmp_path: Path) -> None:+ """Same response, two files: only its OWN file may rewrite a turn.++ A resumed Claude session copies the parent's responses in with the same+ ``message.id``; a rebuild scans the newest file first. If the copy could+ overwrite, every rebuild would restamp old turns with the resume's path+ and session and the day-by-day picture would drift.+ """+ data = tmp_path / "data"+ original = _claude_path(tmp_path, "original")+ resumed = _claude_path(tmp_path, "resumed")+ _write(+ original,+ [_claude_line(uuid="u1", msg_id="msg_a", session="orig", input_tokens=10)],+ )+ refresh(data_dir=data, home=tmp_path)++ _write(+ resumed,+ [_claude_line(uuid="u9", msg_id="msg_a", session="resume", input_tokens=500)],+ )+ result = refresh(data_dir=data, home=tmp_path)+ assert result.turns_added == 0+ turns = _all(data)+ assert len(turns) == 1+ assert turns[0].session_id == "orig" and turns[0].tokens_in == 15++ # The original file rewritten (shorter, so it is read again from zero)+ # with a corrected count: its row follows, the copy still does not count.+ _write(+ original,+ [_claude_line(uuid="u1", msg_id="msg_a", session="orig", input_tokens=2)],+ )+ refresh(data_dir=data, home=tmp_path)+ turns = _all(data)+ assert len(turns) == 1+ assert turns[0].session_id == "orig" and turns[0].tokens_in == 7def test_an_unreadable_root_never_prunes(tmp_path: Path) -> None:diff --git a/tests/unit/ui/web/test_costs_routes.py b/tests/unit/ui/web/test_costs_routes.pyindex 1bea8ab455..2b3ee8b72b 100644--- a/tests/unit/ui/web/test_costs_routes.py+++ b/tests/unit/ui/web/test_costs_routes.py@@ -238,3 +238,16 @@ def test_daily_on_an_empty_install_is_an_empty_ledger(tmp_path: Path) -> None:body = _client(tmp_path / "nothing").get("/api/costs/daily?days=30").json()assert body["days"] == []assert body["currency"]["eur_per_usd"] > 0+++def test_summary_says_whether_the_cli_index_is_still_counting(client: TestClient) -> None:+ """The coding-CLI numbers fill in over background runs; the page must be+ able to say "still counting" instead of showing a fraction as the bill."""+ body = client.get("/api/costs/summary?days=30").json()+ index = body["index"]+ assert set(index) == {+ "files_known", "files_indexed", "files_pending", "bytes_pending", "turns", "complete",+ }+ assert isinstance(index["complete"], bool)+ assert index["files_indexed"] + index["files_pending"] == index["files_known"]+ assert index["complete"] == (index["files_pending"] == 0)