Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,9 @@ test/test_data/real_projects/index.html
# the two rules above, which predate that export mode. Use `git add -f` if an
# image ever needs to be a real fixture.
test/test_data/real_projects/*/images/
# SQLite cache the CLI drops into a projects dir when run against test data
claude-code-log-cache.db
# SQLite cache the CLI drops into a projects dir when run against test data,
# with the -wal / -shm files SQLite keeps beside it while it is open
claude-code-log-cache.db*

# >>> foldyard (managed) — do not edit inside this block >>>
# Box/host-generated files foldyard writes beside foldyard.toml; never commit.
Expand Down
23 changes: 20 additions & 3 deletions claude_code_log/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@ class CachedFileState(BaseModel):
row_fingerprints: List[bytes] = []


def _row_peak(row: sqlite3.Row) -> Optional[int]:
"""A session row's ``peak_context_tokens`` (``None`` when unknown)."""
return row["peak_context_tokens"] if "peak_context_tokens" in row.keys() else None


class SessionCacheData(BaseModel):
"""Cached session-level information."""

Expand All @@ -136,6 +141,12 @@ class SessionCacheData(BaseModel):
total_output_tokens: int = 0
total_cache_creation_tokens: int = 0
total_cache_read_tokens: int = 0
# Migration 019: the largest context one main-thread turn sent (input +

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: stale comment.

It says None covers "a row written before the migration, an archived session whose source is gone". Since 6f06a598 the migration fills both from messages, so None now means only a Codex session or a session with no usage, as application_model.md already says.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2135385: the comment now says the migration fills the column for every cached session, and that None means a session with no usage or a Codex session.

# cache creation + cache read); the migration fills it for every
# session already cached. ``None`` is unknown — a session with no
# usage, or a provider (Codex) that reports only cumulative totals —
# and is not shown, never read as a zero.
peak_context_tokens: Optional[int] = None
# Teammates feature — set when the session was active in a team.
# First non-None ``teamName`` of any entry in the session.
team_name: Optional[str] = None
Expand Down Expand Up @@ -2918,8 +2929,9 @@ def write(conn: sqlite3.Connection) -> None:
message_count, first_user_message, cwd,
total_input_tokens, total_output_tokens,
total_cache_creation_tokens, total_cache_read_tokens,
team_name, ai_title, hidden, residual_count
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
team_name, ai_title, hidden, residual_count,
peak_context_tokens
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(project_id, session_id) DO UPDATE SET
summary = excluded.summary,
first_timestamp = excluded.first_timestamp,
Expand All @@ -2934,7 +2946,8 @@ def write(conn: sqlite3.Connection) -> None:
team_name = excluded.team_name,
ai_title = excluded.ai_title,
hidden = excluded.hidden,
residual_count = excluded.residual_count
residual_count = excluded.residual_count,
peak_context_tokens = excluded.peak_context_tokens
""",
(
self._project_id,
Expand All @@ -2957,6 +2970,7 @@ def write(conn: sqlite3.Connection) -> None:
scrub_surrogates(data.ai_title),
1 if data.hidden else 0,
data.residual_count or 0,
data.peak_context_tokens,
),
)

Expand Down Expand Up @@ -3444,6 +3458,7 @@ def get_all_session_rows(self) -> Dict[str, SessionCacheData]:
total_output_tokens=row["total_output_tokens"],
total_cache_creation_tokens=row["total_cache_creation_tokens"],
total_cache_read_tokens=row["total_cache_read_tokens"],
peak_context_tokens=_row_peak(row),
team_name=row["team_name"] if "team_name" in row.keys() else None,
hidden=bool(row["hidden"]),
residual_count=row["residual_count"],
Expand Down Expand Up @@ -3711,6 +3726,7 @@ def get_cached_project_data(self) -> Optional[ProjectCache]:
total_output_tokens=row["total_output_tokens"],
total_cache_creation_tokens=row["total_cache_creation_tokens"],
total_cache_read_tokens=row["total_cache_read_tokens"],
peak_context_tokens=_row_peak(row),
team_name=row["team_name"] if "team_name" in row.keys() else None,
)

Expand Down Expand Up @@ -4182,6 +4198,7 @@ def get_archived_sessions(
total_output_tokens=row["total_output_tokens"],
total_cache_creation_tokens=row["total_cache_creation_tokens"],
total_cache_read_tokens=row["total_cache_read_tokens"],
peak_context_tokens=_row_peak(row),
team_name=row["team_name"]
if "team_name" in row.keys()
else None,
Expand Down
64 changes: 57 additions & 7 deletions claude_code_log/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
get_project_display_name,
is_agent_session,
parse_date_bounds,
turn_context_tokens,
relative_href,
resident_bytes,
resident_transcript_bytes,
Expand Down Expand Up @@ -2594,10 +2595,43 @@ def compute_session_data(
cache.total_cache_read_tokens += (
getattr(usage, "cache_read_input_tokens", 0) or 0
)
if not getattr(message, "isSidechain", False):
context = turn_context_tokens(usage)
if context > (cache.peak_context_tokens or 0):
cache.peak_context_tokens = context

return result


def session_token_fields(data: Optional[SessionCacheData]) -> Dict[str, Any]:
"""A session's token figures for an index or nav row.

The minimal theme's meta lines read these (peak · new · out); the
classic theme reads none of them.
"""
if data is None:
return {}
return {
"total_input_tokens": data.total_input_tokens,
"total_output_tokens": data.total_output_tokens,
"total_cache_creation_tokens": data.total_cache_creation_tokens,
"peak_context_tokens": data.peak_context_tokens,
}


def _provider_session_token_fields(
totals: "Optional[ProviderTokenTotals]",
) -> Dict[str, Any]:
"""``session_token_fields`` for a provider that reports only cumulative
session totals (Codex): the same keys, the peak unknown."""
return {
"total_input_tokens": totals.input_tokens if totals else 0,
"total_output_tokens": totals.output_tokens if totals else 0,
"total_cache_creation_tokens": 0,
"peak_context_tokens": None,
}


def compute_session_residuals(messages: List[TranscriptEntry]) -> Dict[str, int]:
"""Per-session count of traversed entries ``compute_session_data`` skips.

Expand Down Expand Up @@ -2741,6 +2775,7 @@ def _plan_page(
total_output_tokens = 0
total_cache_creation_tokens = 0
total_cache_read_tokens = 0
peak_context_tokens: Optional[int] = None
# The cached count must be the sessions-table sum, because
# is_page_stale() compares it against SUM(sessions.message_count)
# on the next run. len(page_messages) counts what's rendered
Expand All @@ -2766,6 +2801,10 @@ def _plan_page(
total_output_tokens += s.total_output_tokens
total_cache_creation_tokens += s.total_cache_creation_tokens
total_cache_read_tokens += s.total_cache_read_tokens
if s.peak_context_tokens is not None:
peak_context_tokens = max(
peak_context_tokens or 0, s.peak_context_tokens
)

# Build page_info for navigation
has_prev = page_num > 1
Expand Down Expand Up @@ -2796,7 +2835,7 @@ def _plan_page(
if total_output_tokens:
token_parts.append(f"Output: {total_output_tokens:,}")
if total_cache_creation_tokens:
token_parts.append(f"Cache Create: {total_cache_creation_tokens:,}")
token_parts.append(f"Cache Creation: {total_cache_creation_tokens:,}")
if total_cache_read_tokens:
token_parts.append(f"Cache Read: {total_cache_read_tokens:,}")
token_summary = " | ".join(token_parts) if token_parts else None
Expand All @@ -2805,6 +2844,12 @@ def _plan_page(
"message_count": page_message_count,
"date_range": date_range,
"token_summary": token_summary,
# The figures behind ``token_summary``, for the minimal theme's
# header (peak · new · out); the peak is the page's largest.
"total_input_tokens": total_input_tokens,
"total_output_tokens": total_output_tokens,
"total_cache_creation_tokens": total_cache_creation_tokens,
"peak_context_tokens": peak_context_tokens,
}

page_title = f"{title} - Page {page_num}" if page_num > 1 else title
Expand Down Expand Up @@ -5240,6 +5285,7 @@ def _collect_project_sessions(messages: list[TranscriptEntry]) -> list[dict[str,
"first_user_message": data.first_user_message
if data.first_user_message
else "[No user message found in session.]",
**session_token_fields(data),
}
)

Expand Down Expand Up @@ -5392,6 +5438,8 @@ def _project_window_view(
"message_count": part.message_count if part else 0,
"first_user_message": row.first_user_message,
"team_name": row.team_name,
# The window's own figures, like its message count.
**session_token_fields(part),
}
)
sessions.sort(key=lambda s: (s["first_timestamp"] or "", s["id"]))
Expand Down Expand Up @@ -6406,12 +6454,12 @@ def render_provider_wholesale(
"first_user_message": first_user
or "[No user message found in session.]",
"file": f"{rel_dest}/session-{session_key}{suffix}.{ext}",
# NOTE: no per-session token_summary key here — the Claude
# index project-card session list carries none either, and
# the drift pin (test_index_summary_dict_shape_matches_claude_path)
# locks the two session-dict shapes together. Per-session
# cumulative totals are stored on the session cache instead
# (durability); the project card shows the rolled-up total.
# The same token keys as the Claude path's session rows
# (``session_token_fields``) — the drift pin
# (test_index_summary_dict_shape_matches_claude_path)
# locks the two shapes together. From the cumulative
# session totals; no peak, which needs per-turn usage.
**_provider_session_token_fields(session_totals.get(session_key)),
}
)

Expand Down Expand Up @@ -7893,6 +7941,7 @@ def _convert_plan_inline(
"message_count": session_data.message_count,
"first_user_message": session_data.first_user_message
or "[No user message found in session.]",
**session_token_fields(session_data),
# Per-session link relative to the index
# root. Used by the index renderer when
# `combined_suppressed` is True so the
Expand Down Expand Up @@ -8124,6 +8173,7 @@ def _convert_plan_inline(
"message_count": session_data.message_count,
"first_user_message": session_data.first_user_message
or "[No user message found in session.]",
**session_token_fields(session_data),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test gap: three of the four index builders aren't tested for the token fields.

The cached, archived, fallback (_collect_project_sessions, line 5288) and date-window (_project_window_view, line 5442) builders all pass token fields now. Only the cached one is pinned, and only indirectly, through the Codex key-equality drift test. test_index_session_rows_show_peak_new_and_out gives index_sessions hand-built dicts. So removing **session_token_fields(...) from the archived, fallback or window builder fails no test.

Suggested fix: an end-to-end process_projects_hierarchy(theme="minimal") test that asserts peak / new appear in an index.html session row on each route.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6f06a59. test_every_index_builder_gives_session_rows_their_token_figures runs process_projects_hierarchy(theme="minimal") four ways: cached, use_cache=False (the _collect_project_sessions fallback), from_date (the window view), and archived. Each time it asserts that every index.html session row has peak, new and out. I mutation-checked it by blanking **session_token_fields(...) in each builder in turn, and each blank fails exactly its own case.

# `{variant}` keeps the link in step with
# `_generate_individual_session_files`'s
# filename (`session-{id}{variant}.{ext}`).
Expand Down
Loading
Loading