Add experimental wrapped skill (#79)

This commit is contained in:
Vaibhav Srivastav
2026-02-02 08:00:52 -08:00
committed by GitHub
parent 77963424cd
commit f617e62e40
5 changed files with 1185 additions and 0 deletions
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+40
View File
@@ -0,0 +1,40 @@
---
name: "codex-wrapped"
description: "Generate a Codex Wrapped usage recap from local Codex logs, including last 30 days, last 7 days, and an all-time focus-hours callout. Use when the user asks for a usage summary, activity recap, or Codex Wrapped report."
---
# Codex Wrapped
Use this skill whenever the user wants a Codex Wrapped report or usage insights. Render text-only output (no image generation).
The report must be year-agnostic and should highlight last 30 days and last 7 days, while still calling out all-time focus hours.
## Quick Commands (run in order)
1) **Compute stats**
```bash
python3 .codex/skills/codex-wrapped/scripts/get_codex_stats.py \
--output /tmp/wrapped_stats.json
```
(Defaults to the system timezone; override `--timezone` only if the user requests it.)
2) **Render text report**
```bash
.codex/skills/codex-wrapped/scripts/report.sh \
--stats-file /tmp/wrapped_stats.json
```
This prints the report directly to stdout.
## Files
- `scripts/get_codex_stats.py` -- computes rolling-window stats to `/tmp/wrapped_stats.json`.
- `scripts/report.sh` -- text report renderer.
## Responding to the user
- Paste the report text exactly as printed, wrapped in triple backticks (```), to preserve spacing/box drawing.
- If something fails, state what you ran and the error.
## Notes
- Keep `/tmp/wrapped_stats.json` unless sensitive; rerun stats if outdated.
- The report adapts to terminal width. Set `WRAPPED_WIDTH=120` (or similar) to force a wider layout.
- Layout options: default is `columns` (two-column). Use `--layout table` (or `WRAPPED_LAYOUT=table`) to switch back to the compact grid.
@@ -0,0 +1,4 @@
interface:
display_name: "Wrapped"
short_description: "Create a Codex activity report from local usage data"
default_prompt: "Generate a Codex Wrapped usage report from my local Codex logs."
@@ -0,0 +1,451 @@
#!/usr/bin/env python3
"""
Aggregate Codex usage metrics for the Wrapped report.
Outputs JSON with rolling windows:
- all_time
- last_30_days
- last_7_days
"""
from __future__ import annotations
import argparse
import json
import sys
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Iterable
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
CODEX_HOME = Path.home() / ".codex"
SESSION_DIRS = ["sessions", "archived_sessions"]
DEFAULT_TIMEZONE = None
DEFAULT_OUTPUT_PATH = Path(__file__).with_name("wrapped_stats.json")
WINDOW_DELTAS = {
"all_time": None,
"last_30_days": 30,
"last_7_days": 7,
}
@dataclass
class WindowAccumulator:
name: str
start: datetime | None
session_count: int = 0
total_assistant_messages: int = 0
total_user_messages: int = 0
turn_usage_seconds: float = 0.0
session_span_seconds: float = 0.0
day_tokens: dict[datetime.date, int] = field(default_factory=lambda: defaultdict(int))
active_days: set[datetime.date] = field(default_factory=set)
hour_usage: dict[int, int] = field(default_factory=lambda: defaultdict(int))
repo_usage: dict[str, int] = field(default_factory=lambda: defaultdict(int))
longest_turn_duration: float = 0.0
longest_turn_timestamp: datetime | None = None
longest_turn_session: str | None = None
def parse_timestamp(ts: str) -> datetime:
if not ts:
raise ValueError("Empty timestamp")
if ts.endswith("Z"):
ts = ts[:-1] + "+00:00"
return datetime.fromisoformat(ts)
def iter_session_files() -> Iterable[Path]:
for rel in SESSION_DIRS:
root = CODEX_HOME / rel
if not root.exists():
continue
yield from root.rglob("*.jsonl")
def format_tokens(value: int) -> str:
if value <= 0:
return "0"
if value >= 1_000_000:
scaled = value / 1_000_000
return f"{scaled:.1f}M".replace(".0M", "M")
if value >= 1_000:
scaled = value / 1_000
return f"{scaled:.1f}k".replace(".0k", "k")
return f"{value:,}"
def render_usage_hours(seconds: float) -> str:
if seconds <= 0:
return "0 minutes"
hours = seconds / 3600
if hours < 1:
minutes = int(round(seconds / 60))
minutes = max(minutes, 1)
return f"{minutes} minute{'s' if minutes != 1 else ''}"
rounded_hours = int(round(hours))
rounded_hours = max(rounded_hours, 1)
return f"{rounded_hours} hour{'s' if rounded_hours != 1 else ''}"
def build_contrib_lines(active_days: set[datetime.date]) -> list[str]:
if not active_days:
return []
day_set = set(active_days)
first_date = min(day_set)
last_date = max(day_set)
def to_sunday(dt: datetime.date) -> datetime.date:
offset = (dt.weekday() + 1) % 7
return dt - timedelta(days=offset)
def to_saturday(dt: datetime.date) -> datetime.date:
offset = 6 - ((dt.weekday() + 1) % 7)
return dt + timedelta(days=offset)
start = to_sunday(first_date)
end = to_saturday(last_date)
total_days = (end - start).days + 1
total_weeks = total_days // 7
weekday_labels = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
line_chars: list[list[str]] = [[] for _ in range(7)]
for week_index in range(total_weeks):
week_start = start + timedelta(days=week_index * 7)
for day_offset in range(7):
current_day = week_start + timedelta(days=day_offset)
char = "" if current_day in day_set else ""
line_chars[day_offset].append(char)
contrib_lines = [
f"{weekday_labels[idx]} {''.join(chars)}" for idx, chars in enumerate(line_chars) if chars
]
return contrib_lines
def local_timezone_name() -> str:
local_tz = datetime.now().astimezone().tzinfo
if hasattr(local_tz, "key") and local_tz.key:
return local_tz.key
if local_tz:
return str(local_tz)
return "UTC"
def get_timezone(tz_name: str) -> ZoneInfo:
try:
return ZoneInfo(tz_name)
except ZoneInfoNotFoundError:
fallback = local_timezone_name()
try:
return ZoneInfo(fallback)
except ZoneInfoNotFoundError:
return ZoneInfo("UTC")
def classify_hour(hour: int | None) -> str:
if hour is None:
return "unknown"
if 22 <= hour or hour <= 3:
return "owl"
if 4 <= hour <= 9:
return "bird"
if 10 <= hour <= 16:
return "day"
return "eve"
def longest_streak(active_days: set[datetime.date]) -> int:
if not active_days:
return 0
sorted_days = sorted(active_days)
longest = 1
current = 1
prev_day = sorted_days[0]
for day in sorted_days[1:]:
if day == prev_day + timedelta(days=1):
current += 1
elif day == prev_day:
pass
else:
longest = max(longest, current)
current = 1
prev_day = day
longest = max(longest, current)
return longest
def window_stats(window: WindowAccumulator, tz_abbrev: str) -> dict[str, object]:
total_tokens = sum(window.day_tokens.values())
active_days_count = len(window.active_days)
peak_hour = None
if window.hour_usage:
peak_hour = max(window.hour_usage.items(), key=lambda item: item[1])[0]
peak_hour_display = f"{peak_hour:02d}:00" if peak_hour is not None else "unknown"
peak_hour_label = classify_hour(peak_hour)
if peak_hour is not None:
peak_hour_slot = f"{peak_hour_display} {peak_hour_label}"
else:
peak_hour_slot = "unknown"
biggest_day_date = None
biggest_day_tokens = 0
if window.day_tokens:
biggest_day_date, biggest_day_tokens = max(
window.day_tokens.items(), key=lambda item: item[1]
)
if biggest_day_date:
biggest_day_display = f"{biggest_day_date.day} {biggest_day_date.strftime('%b')}"
else:
biggest_day_display = "unknown"
top_repo = None
if window.repo_usage:
top_repo = max(window.repo_usage.items(), key=lambda item: item[1])[0]
if top_repo:
repo_path = Path(top_repo)
top_repo_label = repo_path.name or str(repo_path)
else:
top_repo_label = "unknown"
usage_seconds = max(window.session_span_seconds, window.turn_usage_seconds)
usage_hours_display = render_usage_hours(usage_seconds)
streak_days = longest_streak(window.active_days)
usage_streak_display = (
f"{streak_days} day" if streak_days == 1 else f"{streak_days} days" if streak_days else "unknown"
)
longest_turn_display = "unknown"
if window.longest_turn_timestamp is not None:
minutes = int(window.longest_turn_duration // 60)
seconds = int(round(window.longest_turn_duration % 60))
longest_turn_display = f"{minutes}m {seconds}s"
return {
"sessions": window.session_count,
"sessions_display": f"{window.session_count:,}",
"assistant_messages": window.total_assistant_messages,
"assistant_messages_display": f"{window.total_assistant_messages:,}",
"user_messages": window.total_user_messages,
"user_messages_display": f"{window.total_user_messages:,}",
"active_days": active_days_count,
"active_days_display": f"{active_days_count:,}",
"total_tokens": total_tokens,
"total_tokens_display": format_tokens(total_tokens),
"usage_hours_display": usage_hours_display,
"peak_hour": peak_hour,
"peak_hour_display": peak_hour_display,
"peak_hour_label": peak_hour_label,
"peak_hour_slot": peak_hour_slot,
"timezone_abbrev": tz_abbrev,
"usage_streak_days": streak_days,
"usage_streak_display": usage_streak_display,
"biggest_day_display": biggest_day_display,
"biggest_day_tokens": biggest_day_tokens,
"top_repo_display": top_repo_label,
"longest_turn_display": longest_turn_display,
}
def gather_metrics(tz_name: str) -> dict[str, object]:
target_tz = get_timezone(tz_name)
now_local = datetime.now(target_tz)
windows: dict[str, WindowAccumulator] = {}
for name, delta in WINDOW_DELTAS.items():
start = None if delta is None else now_local - timedelta(days=delta)
windows[name] = WindowAccumulator(name=name, start=start)
joined_at: datetime | None = None
for session_path in iter_session_files():
current_turn_start: datetime | None = None
session_start: datetime | None = None
session_end: datetime | None = None
session_workspace: str | None = None
try:
with session_path.open("r", encoding="utf-8") as handle:
for raw_line in handle:
raw_line = raw_line.strip()
if not raw_line:
continue
try:
record = json.loads(raw_line)
except json.JSONDecodeError:
continue
ts_str = record.get("timestamp")
if not ts_str:
ts_str = record.get("payload", {}).get("timestamp")
if not ts_str:
continue
try:
ts = parse_timestamp(ts_str)
except ValueError:
continue
local_ts = ts.astimezone(target_tz)
if session_start is None:
session_start = local_ts
session_end = local_ts
rec_type = record.get("type")
payload = record.get("payload", {})
for window in windows.values():
if window.start is None or local_ts >= window.start:
window.active_days.add(local_ts.date())
if rec_type == "response_item" and payload.get("type") == "message":
role = payload.get("role")
for window in windows.values():
if window.start is None or local_ts >= window.start:
if role == "assistant":
window.total_assistant_messages += 1
elif role == "user":
window.total_user_messages += 1
window.hour_usage[local_ts.hour] += 1
if rec_type == "session_meta":
session_workspace = (
payload.get("workspacePath")
or payload.get("workspace_path")
or payload.get("cwd")
or session_workspace
)
if rec_type == "turn_context":
session_workspace = (
payload.get("workspacePath")
or payload.get("workspace_path")
or payload.get("cwd")
or session_workspace
)
current_turn_start = ts
continue
if rec_type == "event_msg" and payload.get("type") == "token_count":
info = payload.get("info")
if not info or current_turn_start is None:
continue
duration = (ts - current_turn_start).total_seconds()
if duration < 0:
duration = 0
usage = info.get("last_token_usage") or info.get("total_token_usage")
tokens = 0
if usage and usage.get("total_tokens"):
tokens = usage["total_tokens"]
for window in windows.values():
if window.start is None or local_ts >= window.start:
window.turn_usage_seconds += duration
if duration > window.longest_turn_duration:
window.longest_turn_duration = duration
window.longest_turn_timestamp = local_ts
window.longest_turn_session = session_path.name
if tokens:
window.day_tokens[local_ts.date()] += tokens
current_turn_start = None
except OSError:
continue
if session_start and (joined_at is None or session_start < joined_at):
joined_at = session_start
if session_start and session_end:
for window in windows.values():
if window.start is None:
window_start = session_start
else:
window_start = max(window.start, session_start)
window_end = min(session_end, now_local)
overlap = (window_end - window_start).total_seconds()
if overlap > 0:
window.session_span_seconds += overlap
window.session_count += 1
if session_workspace:
window.repo_usage[session_workspace] += 1
tz_abbrev = now_local.strftime("%Z")
if joined_at:
joined_str = joined_at.date().isoformat()
joined_label = joined_at.strftime("%b %d")
days_diff = (now_local.date() - joined_at.date()).days
days_ago = f"{days_diff} day{'s' if days_diff != 1 else ''} ago"
joined_display = f"{joined_label} ({days_ago})"
else:
joined_str = "unknown"
days_ago = "unknown"
joined_display = "unknown"
metrics: dict[str, object] = {
"timezone": tz_name,
"timezone_abbrev": tz_abbrev,
"generated_at": now_local.isoformat(),
"joined_date": joined_str,
"joined_days_ago": days_ago,
"joined_display": joined_display,
"joined_relative_display": days_ago,
"windows": {name: window_stats(win, tz_abbrev) for name, win in windows.items()},
"contrib_lines": build_contrib_lines(windows["all_time"].active_days),
}
return metrics
def print_text(metrics: dict[str, object]) -> None:
all_time = metrics.get("windows", {}).get("all_time", {})
print(f"Joined Codex: {metrics.get('joined_display', 'unknown')}")
print(f"Sessions: {all_time.get('sessions_display', '0')}")
print(f"Assistant messages: {all_time.get('assistant_messages_display', '0')}")
print(f"Prompts: {all_time.get('user_messages_display', '0')}")
print(f"Tokens: {all_time.get('total_tokens_display', '0')}")
print(f"Usage time: {all_time.get('usage_hours_display', 'unknown')}")
print(f"Peak hour: {all_time.get('peak_hour_slot', 'unknown')}")
def main() -> None:
parser = argparse.ArgumentParser(description="Compute Codex Wrapped usage metrics.")
parser.add_argument(
"--json",
action="store_true",
help="Emit metrics as JSON for scripting.",
)
parser.add_argument(
"--timezone",
default=local_timezone_name(),
help="IANA timezone name for local stats (defaults to system timezone).",
)
parser.add_argument(
"--output",
default=str(DEFAULT_OUTPUT_PATH),
help=f"Path to save metrics JSON (default: {DEFAULT_OUTPUT_PATH}).",
)
args = parser.parse_args()
metrics = gather_metrics(args.timezone)
output_path = Path(args.output).expanduser()
with output_path.open("w", encoding="utf-8") as handle:
json.dump(metrics, handle, indent=2)
handle.write("\n")
if args.json:
json.dump(metrics, fp=sys.stdout, indent=2)
print()
return
print(f"Wrote stats to {output_path}")
print_text(metrics)
if __name__ == "__main__":
main()
+488
View File
@@ -0,0 +1,488 @@
#!/usr/bin/env bash
# Config knobs
LABEL_MIN=5
LABEL_MAX=15
MIN_PANEL_WIDTH=80
DEFAULT_PANEL_WIDTH=96
FRAME_BUFFER=7
detect_term_width() {
local cols=""
if [[ -t 1 ]]; then
if [[ -n "${COLUMNS:-}" ]]; then
cols="$COLUMNS"
fi
if command -v tput >/dev/null 2>&1; then
local tcols
tcols=$(tput cols 2>/dev/null || true)
if [[ "$tcols" =~ ^[0-9]+$ ]]; then
cols="$tcols"
fi
fi
fi
if [[ "$cols" =~ ^[0-9]+$ && "$cols" -gt 0 ]]; then
echo "$cols"
fi
}
TERM_WIDTH=$(detect_term_width)
if [[ -n "${WRAPPED_WIDTH:-}" && "${WRAPPED_WIDTH}" =~ ^[0-9]+$ ]]; then
TERM_WIDTH="$WRAPPED_WIDTH"
fi
if [[ -z "$TERM_WIDTH" ]]; then
TERM_WIDTH=$DEFAULT_PANEL_WIDTH
fi
DATA_LIMIT=$((TERM_WIDTH - 2))
if (( DATA_LIMIT < MIN_PANEL_WIDTH )); then
DATA_LIMIT=$MIN_PANEL_WIDTH
fi
DECOR_CHUNK=".:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:."
TITLE="OpenAI Codex Wrapped"
SUBTITLE=""
# Defaults (overwritten by stats JSON)
joined_line="Member since unknown"
timezone_line="Local time: unknown"
table_rows=()
hero_line=""
highlight_lines=()
activity_lines=()
column_rows=()
column_head_left="Last 30 days"
column_head_right="Last 7 days"
die() { echo "$*" >&2; exit 1; }
show_help() {
cat <<'EOF'
Usage: report.sh --stats-file <path> [--layout table|columns]
--stats-file Path to the metrics JSON produced by get_codex_stats.py.
--layout Layout style (table or columns). Default: columns.
-h, --help Show this message and exit.
EOF
}
strip_ansi_len() {
local raw="$1"
local clean
clean=$(printf '%s' "$raw" | perl -pe 's/\e\[[0-9;]*[a-zA-Z]//g')
printf '%s' "${#clean}"
}
calc_panel_width() {
local max_seen=0
for entry in "$@"; do
local span
span=$(strip_ansi_len "$entry")
(( span > max_seen )) && max_seen=$span
done
max_seen=$((max_seen + FRAME_BUFFER))
if (( max_seen < MIN_PANEL_WIDTH )); then
max_seen=$MIN_PANEL_WIDTH
fi
if (( max_seen > DATA_LIMIT )); then
max_seen=$DATA_LIMIT
fi
echo "$max_seen"
}
center_line() {
local text="$1"
local width="$2"
local text_len
text_len=$(strip_ansi_len "$text")
local left_pad=$(( (width - text_len) / 2 ))
local right_pad=$(( width - text_len - left_pad ))
printf "│%*s%s%*s│\n" "$left_pad" "" "$text" "$right_pad" ""
}
divider_line() {
local width="$1"
local left="$2"
local mid="$3"
local right="$4"
local bar="$left"
for ((i=0; i<width; i++)); do bar+="─"; done
bar+="$right"
printf '%s\n' "$bar"
}
split_row() {
local label="$1"
local value="$2"
local l_width="$3"
local r_width="$4"
if [[ -z "$label" ]]; then
label=$(printf "%-${l_width}s" "")
elif (( ${#label} < LABEL_MIN )); then
label=$(printf "%-${LABEL_MIN}s" "$label")
elif (( ${#label} > l_width )); then
label=$(echo "$label" | cut -c1-$((l_width-3)))...
else
label=$(printf "%-${l_width}s" "$label")
fi
if (( ${#value} > r_width )); then
value=$(echo "$value" | cut -c1-$((r_width-3)))...
else
value=$(printf "%-${r_width}s" "$value")
fi
printf "│ %s │ %s │\n" "$label" "$value"
}
left_line() {
local text="$1"
local width="$2"
local content=" $text"
content=$(fit_cell "$content" "$width")
printf "│%s│\n" "$content"
}
fit_cell() {
local text="$1"
local width="$2"
local len
len=$(strip_ansi_len "$text")
if (( len > width )); then
if (( width > 3 )); then
text=$(echo "$text" | cut -c1-$((width-3)))...
else
text=$(echo "$text" | cut -c1-"$width")
fi
fi
printf "%-${width}s" "$text"
}
center_cell() {
local text="$1"
local width="$2"
local text_len
text_len=$(strip_ansi_len "$text")
if (( text_len >= width )); then
printf "%s" "$(fit_cell "$text" "$width")"
return
fi
local left_pad=$(( (width - text_len) / 2 ))
local right_pad=$(( width - text_len - left_pad ))
printf "%*s%s%*s" "$left_pad" "" "$text" "$right_pad" ""
}
trim_ws() {
local s="$1"
s="${s#"${s%%[![:space:]]*}"}"
s="${s%"${s##*[![:space:]]}"}"
printf "%s" "$s"
}
load_stats() {
local src="$1"
[[ -r "$src" ]] || die "Unable to read stats file: $src"
local tsv
tsv=$(python3 - "$src" <<'PY'
import json, sys
from pathlib import Path
data = json.loads(Path(sys.argv[1]).read_text())
windows = data.get("windows", {})
all_time = windows.get("all_time", {})
last_30 = windows.get("last_30_days", {})
last_7 = windows.get("last_7_days", {})
def triple(key, default="unknown"):
return (
all_time.get(key, default),
last_30.get(key, default),
last_7.get(key, default),
)
def compress_time(value: str) -> str:
if not isinstance(value, str):
return str(value)
value = value.replace(" hours", "h").replace(" hour", "h")
value = value.replace(" minutes", "m").replace(" minute", "m")
return value
def compress_days(value: str) -> str:
if not isinstance(value, str):
return str(value)
return value.replace(" days", "d").replace(" day", "d")
def compress_peak(value: str) -> str:
if not isinstance(value, str):
return str(value)
return (
value.replace(" bird", " b")
.replace(" owl", " o")
.replace(" day", " d")
.replace(" eve", " e")
)
def double_str(key, default="unknown", compress=None, collapse=False):
_, m, w = triple(key, default)
if compress:
m = compress(m)
w = compress(w)
if collapse and m == w:
return str(m)
return f"30d {m} | 7d {w}"
rows = [
("Window", "Last 30 days | Last 7 days"),
("Sessions", double_str("sessions_display", "0")),
("Assistant messages", double_str("assistant_messages_display", "0")),
("Tokens", double_str("total_tokens_display", "0")),
("Usage time", double_str("usage_hours_display", "0")),
("Biggest day", double_str("biggest_day_display", "unknown")),
("Top repo", double_str("top_repo_display", "unknown", collapse=True)),
("Longest turn", double_str("longest_turn_display", "unknown")),
]
column_metrics = [
("Sessions", "sessions_display"),
("Prompts", "user_messages_display"),
("Tokens", "total_tokens_display"),
("Usage time", "usage_hours_display"),
("Biggest day", "biggest_day_display"),
]
stack_sections = [
("Last 30 days", "last_30_days"),
("Last 7 days", "last_7_days"),
]
joined_display = data.get("joined_display", "unknown")
timezone = data.get("timezone_abbrev") or data.get("timezone", "unknown")
def compress_focus(value: str) -> str:
return str(value)
print(f"joined_line\tMember since {joined_display}")
print(f"timezone_line\tLocal time: {timezone}")
for label, value in rows:
print(f"row\t{label}\t{value}")
def format_stack(stat_key: str, value: str) -> str:
return str(value)
def bar(active: int, total: int, width: int = 10) -> str:
if total <= 0:
return "." * width
ratio = max(0.0, min(1.0, active / total))
filled = int(round(ratio * width))
return "#" * filled + "." * (width - filled)
def percent(active: int, total: int) -> str:
if total <= 0:
return "0%"
return f"{int(round(active / total * 100))}%"
all_time = windows.get("all_time", {})
last_30 = windows.get("last_30_days", {})
last_7 = windows.get("last_7_days", {})
high_30_prompts = last_30.get("user_messages_display", "0")
high_30_active = last_30.get("active_days_display", "0")
high_peak = last_30.get("peak_hour_slot", "unknown")
high_streak = last_30.get("usage_streak_display", "unknown")
high_focus = all_time.get("usage_hours_display", "unknown")
print(f"hero_line\t{high_30_prompts} prompts in 30d — peak {high_peak}")
print(f"highlight_line\t{joined_display} | {timezone}")
print(f"highlight_line\tActive days: {high_30_active} in 30d | Streak: {high_streak}")
print(f"highlight_line\tAll-time focus: {high_focus}")
act_30 = last_30.get("active_days", 0)
act_7 = last_7.get("active_days", 0)
bar_30 = bar(int(act_30), 30)
bar_7 = bar(int(act_7), 7)
print(f"activity_line\t30d activity: {bar_30} ({int(act_30)}/30)")
print(f"activity_line\t7d activity: {bar_7} ({int(act_7)}/7)")
print("column_head\tLast 30 days\tLast 7 days")
for label, stat_key in column_metrics:
left = format_stack(stat_key, last_30.get(stat_key, "unknown"))
right = format_stack(stat_key, last_7.get(stat_key, "unknown"))
print(f"column_row\t{label}\t{left}\t{right}")
for line in data.get("contrib_lines", []):
print(f"contrib_line\t{line}")
PY
) || die "Failed to parse stats JSON: $src"
while IFS=$'\t' read -r key label value extra; do
case "$key" in
joined_line) joined_line="$label" ;;
timezone_line) timezone_line="$label" ;;
focus_line) ;;
row) table_rows+=("${label}"$'\t'"${value}") ;;
stack_section) stack_rows+=("SECTION"$'\t'"${label}") ;;
stack_item) stack_rows+=("ITEM"$'\t'"${label}"$'\t'"${value}") ;;
stack_blank) stack_rows+=("BLANK") ;;
hero_line) hero_line="$label" ;;
highlight_line) highlight_lines+=("$label") ;;
activity_line) activity_lines+=("$label") ;;
column_head)
column_head_left="$label"
column_head_right="$value"
;;
column_row)
column_rows+=("${label}"$'\t'"${value}"$'\t'"${extra}") ;;
esac
done <<<"$tsv"
}
render() {
local stats_path="$1"
local layout_override="${2:-}"
load_stats "$stats_path"
if ((${#contrib_lines[@]} == 0)); then
contrib_lines=("Sun " "Mon " "Tue " "Wed " "Thu " "Fri " "Sat ")
fi
holiday_lines=()
local layout="${WRAPPED_LAYOUT:-columns}"
if [[ -n "$layout_override" ]]; then
layout="$layout_override"
elif [[ -n "${REPORT_LAYOUT:-}" ]]; then
layout="${REPORT_LAYOUT}"
fi
local width_input=("$DECOR_CHUNK" "$TITLE" "$SUBTITLE" "$hero_line")
width_input+=("${highlight_lines[@]}")
width_input+=("${activity_lines[@]}")
if [[ "$layout" == "table" ]]; then
for row in "${table_rows[@]}"; do
IFS=$'\t' read -r label value <<<"$row"
width_input+=("$label" "$value")
done
else
width_input+=("$column_head_left" "$column_head_right")
for row in "${column_rows[@]}"; do
IFS=$'\t' read -r label value_left value_right <<<"$row"
width_input+=("$label" "$value_left" "$value_right")
done
fi
PANEL_WIDTH=$(calc_panel_width "${width_input[@]}")
local max_label=0
for row in "${table_rows[@]}"; do
IFS=$'\t' read -r label value <<<"$row"
local span
span=$(strip_ansi_len "$label")
(( span > max_label )) && max_label=$span
done
local left_span=$max_label
(( left_span < LABEL_MIN )) && left_span=$LABEL_MIN
(( left_span > LABEL_MAX )) && left_span=$LABEL_MAX
local right_span=$((PANEL_WIDTH - 5 - left_span))
if (( right_span < 20 )); then
right_span=20
left_span=$((PANEL_WIDTH - 5 - right_span))
(( left_span < LABEL_MIN )) && left_span=$LABEL_MIN
fi
local stack_rows_mode=0
if (( right_span < 40 )); then
stack_rows_mode=1
fi
divider_line "$((PANEL_WIDTH))" "┌" "─" "┐"
local deco_line="$DECOR_CHUNK"
while (( $(strip_ansi_len "$deco_line") < PANEL_WIDTH )); do
deco_line+="$DECOR_CHUNK"
done
deco_line=${deco_line:0:PANEL_WIDTH}
printf "│%s│\n" "$deco_line"
center_line "$TITLE" "$PANEL_WIDTH"
if [[ -n "$SUBTITLE" ]]; then
center_line "$SUBTITLE" "$PANEL_WIDTH"
fi
if [[ -n "$hero_line" ]]; then
center_line "$hero_line" "$PANEL_WIDTH"
fi
printf "│%s│\n" "$deco_line"
divider_line "$((PANEL_WIDTH))" "├" "─" "┤"
center_line "Highlights" "$PANEL_WIDTH"
for ln in "${highlight_lines[@]}"; do
left_line "$ln" "$PANEL_WIDTH"
done
for ln in "${activity_lines[@]}"; do
left_line "$ln" "$PANEL_WIDTH"
done
center_line "" "$PANEL_WIDTH"
if [[ "$layout" == "table" ]]; then
local horiz_left="├"; local horiz_mid="┬"; local horiz_right="┤"
local lbar; printf -v lbar '%*s' $((left_span + 2)) ""; lbar=${lbar// /─}
local rbar; printf -v rbar '%*s' $((right_span + 2)) ""; rbar=${rbar// /─}
printf "%s%s%s%s%s\n" "$horiz_left" "$lbar" "$horiz_mid" "$rbar" "$horiz_right"
for row in "${table_rows[@]}"; do
IFS=$'\t' read -r label value <<<"$row"
if (( stack_rows_mode == 1 )) && [[ "$label" == "Window" ]]; then
continue
fi
if (( stack_rows_mode == 1 )) && [[ "$value" == *"|"* ]]; then
IFS='|' read -r part_a part_b part_c <<<"$value"
part_a=$(trim_ws "$part_a")
part_b=$(trim_ws "$part_b")
part_c=$(trim_ws "$part_c")
split_row "$label" "$part_a" "$left_span" "$right_span"
if [[ -n "$part_b" ]]; then
split_row "" "$part_b" "$left_span" "$right_span"
fi
if [[ -n "$part_c" ]]; then
split_row "" "$part_c" "$left_span" "$right_span"
fi
else
split_row "$label" "$value" "$left_span" "$right_span"
fi
done
local tail_left="└"; local tail_mid="┴"; local tail_right="┘"
printf "%s%s%s%s%s\n" "$tail_left" "$lbar" "$tail_mid" "$rbar" "$tail_right"
else
divider_line "$((PANEL_WIDTH))" "├" "─" "┤"
local inner_width=$((PANEL_WIDTH))
local gap=" │ "
local gap_len=3
local left_width=$(( (inner_width - gap_len) / 2 ))
local right_width=$(( inner_width - gap_len - left_width ))
local head_left
local head_right
head_left=$(center_cell "$column_head_left" "$left_width")
head_right=$(center_cell "$column_head_right" "$right_width")
printf "│%s%s%s│\n" "$head_left" "$gap" "$head_right"
for row in "${column_rows[@]}"; do
IFS=$'\t' read -r label value_left value_right <<<"$row"
local ltext=" ${label}: ${value_left}"
local rtext=" ${label}: ${value_right}"
ltext=$(fit_cell "$ltext" "$left_width")
rtext=$(fit_cell "$rtext" "$right_width")
printf "│%s%s%s│\n" "$ltext" "$gap" "$rtext"
done
divider_line "$((PANEL_WIDTH))" "└" "─" "┘"
fi
}
main() {
local stats_path=""
local layout_arg=""
while [[ $# -gt 0 ]]; do
case "$1" in
--stats-file) stats_path="$2"; shift 2 ;;
--layout) layout_arg="$2"; shift 2 ;;
-h|--help) show_help; exit 0 ;;
*) show_help; exit 1 ;;
esac
done
[[ -n "$stats_path" ]] || die "--stats-file is required."
render "$stats_path" "$layout_arg"
}
main "$@"