gptme-sessions

v0.2.0 Session tracking and analytics for gptme agents packages/gptme-sessions View on GitHub

gptme-sessions

Session tracking and analytics for AI coding agents: discover trajectories from gptme, Claude Code, Codex, Copilot CLI and Pi, extract productivity signals (commits, file writes, errors, token usage, cost), and keep an append-only JSONL ledger you can query, grade and audit.

Status: beta, actively developed. The SessionRecord/SessionStore API and the core CLI (sync, query, stats, post-session) are stable in practice; analysis commands evolve faster.

Why / when to use it

Once an agent runs many sessions — often across several harnesses and models — you need to answer questions like which model/backend actually ships work?, how many sessions were no-ops?, what did last week cost? or which session wrote this line? gptme-sessions normalises each harness's native trajectory format into one record schema (harness, provider, model, run type, category, outcome, duration, tokens, cost, deliverables) so those questions are one command away.

Related:

Install

Not published on PyPI. Install from the repository:

uv tool install "git+https://github.com/gptme/gptme-contrib#subdirectory=packages/gptme-sessions"
# or, from a clone of gptme-contrib:
uv pip install -e packages/gptme-sessions

Extras: shell-parse (tree-sitter-bash for more robust commit/heredoc detection) and cost (depends on gptme-usage, also not on PyPI — install it from the repo first).

Quickstart

gptme-sessions discover --since 7d    # find trajectories on this machine (read-only)
gptme-sessions sync --since 14d       # import them into the store (idempotent, deduplicates)
gptme-sessions                        # 30-day summary
gptme-sessions query --model opus --since 7d

The store lives in ~/.local/share/gptme-sessions/ (override with GPTME_SESSIONS_DIR or --sessions-dir).

PR deliverables

Gptme and Codex signal extraction emits pull_request deliverables for PR URLs returned by a matching gh pr create tool call, with gh_pr_create action evidence. This covers gptme's shell and native gh tools and Codex's exec_command and JS-wrapped exec calls. Codex shell-session polling via write_stdin retains the creation association, including a structured running-session result from custom exec. Non-empty stdin invalidates that association. Custom exec results require a parsed zero exit code before credit; Script completed alone confirms the JS wrapper finished, not that its shell command succeeded. Duplicate result URLs are counted once per session. A shell creation must stand alone or follow only a silent cd /absolute/path command; arbitrary preceding commands can print unrelated PR URLs into the same output and are conservatively excluded.

Read-only gh pr view calls, push invitations (/pull/new/branch), dry runs, unmatched results, and explicitly failed commands are not credited as PR creation. Existing records need a forced signal refresh; sync --signals alone may skip records that already have an outcome:

gptme-sessions regrade --harness gptme --outcome all --since 7d
gptme-sessions regrade --harness codex --outcome all --since 7d

regrade also refreshes other extractor-owned fields and outcomes, while preserving manual annotations and process-level failures. Back up the store before a broad historical refresh.

Native gptme child sessions

read_session_tree() and signal extraction resolve native gptme children from sibling subagent-*/conversation.jsonl directories in the parent's logs root. Each child must carry an absolute parent_logdir in subagent-meta.json that matches its parent directory. Nested children are resolved by the same identity; missing or malformed metadata is not guessed from names or modification times. This works for both retained per-run logs roots and legacy logs roots.

Child tokens, tools, duration and mutation classification feed the parent's subagent_summary; the parent's model identity remains its own. Incomplete children with retained transcripts are counted, not silently dropped. Existing Claude Code flat/workflow layouts remain supported.

Python API

from pathlib import Path
from gptme_sessions import SessionRecord, SessionStore

store = SessionStore(sessions_dir=Path("state/sessions"))  # default: GPTME_SESSIONS_DIR or ~/.local/share/gptme-sessions

store.append(SessionRecord(
    harness="pi",
    provider="openai-codex",
    model="gpt-5.6-luna",
    run_type="autonomous",
    category="code",
    outcome="productive",
    stop_reason="stop",
    cost_usd=0.0004264,
    duration_seconds=2400,
    deliverables=["abc123"],
))

recent = store.query(model="gpt-5.6-luna", since_days=7)
stats = store.stats()
print(f"Success rate: {stats['success_rate']:.0%}")

Also exported: post_session() (the full record-a-session pipeline), extract_from_path() / extract_signals*() (per-harness signal extraction), discover_*_sessions(), and normalize_model(). Build agent-specific features (journal parsing, backfills) on top of these.

CLI

Recording sessions

# Record a session at the end of an agent run: extract signals, determine outcome, append
gptme-sessions post-session --harness gptme --model opus \
  --trajectory ~/.local/share/gptme/logs/2026-03-07-foo/conversation.jsonl

# Reasoning telemetry: --reasoning-profile is the semantic intent (routine|default|deep);
# --reasoning-effort is the backend-native level (free-form; filled from the trajectory if omitted)
gptme-sessions post-session --harness claude-code --model <model> \
  --reasoning-profile deep --reasoning-effort high --trajectory ~/.claude/projects/x/id.jsonl

# Or import whatever is on disk
gptme-sessions sync --since 14d
gptme-sessions sync --signals    # also extract productivity signals (slower)
gptme-sessions sync --dry-run

# Amend a record after the fact (ID prefix match)
gptme-sessions annotate a1b2c3d4 --outcome productive --add-deliverable pr#42
gptme-sessions annotate a1b2 --duration 3600 --token-count 50000

post-session --harness accepts gptme, claude-code, codex, copilot-cli and pi. append still exists but is deprecated in favour of post-session/sync.

Querying

gptme-sessions stats
gptme-sessions show a1b2 --json
gptme-sessions query --run-type autonomous --outcome productive --json
gptme-sessions export --format csv --category code --model opus -o sessions.csv
gptme-sessions runs --since 14d     # duration distribution, NOOP rates, trends
gptme-sessions cost --days 7 --by-model
gptme-sessions search "rate limit" --days 30

--since accepts sub-day windows and natural phrasing (30m, 2h, 7d, 2w, "2 hours ago", all).

Threads

gptme-sessions threads --since 7d --json   # each session's best predecessor + thread id
gptme-sessions thread a1b2                  # one session's ancestry and descendants

threads mines evidence links between sessions (parent ids, journal mentions, cited commits, shared tasks/PRs) and keeps each session's single strongest link to an earlier one, so each tree is a thread of work (gptme_sessions.threads). Journals named by journal_path are digested for references; relative paths resolve against --journal-root (default: the record's project dir). --agent names the agent the records belong to; --min-weight and --coherence tune link strength and the topic-coherence penalty.

All commands

Group Commands
Record post-session, sync, annotate, append (deprecated), stamp-attempt-kind
Inspect stats (also the default with no subcommand), query, show, export, runs, yield, cost, cost-attribution, search
Trajectories discover, signals PATH (productivity signals, grade, --usage), transcript PATH (normalised transcript), replay TARGET (terminal replay)
Classify & grade classify, classify-stats, auto-tag, judge, regrade, repair-grades
Maintenance dedup (merge duplicate records), rotate (archive records older than --keep-days, default 30)
Provenance blame, threads, thread ID

Run gptme-sessions <command> --help for options.

judge scores autonomous-session journal entries (journal/YYYY-MM-DD/autonomous-session-*.md) for goal alignment (0.0–1.0 plus a one-line reason) with an LLM; the default model is Claude Haiku via ANTHROPIC_API_KEY, and other provider-prefixed models route through gptme when it is installed. --update-store writes scores back to matching records.

Set GPTME_SESSIONS_JUDGE_MODEL before starting the process to override the default for the judge APIs and CLI (an explicit --model still takes precedence). For example, GPTME_SESSIONS_JUDGE_MODEL=openrouter/anthropic/claude-haiku-5.5 selects the cheaper OpenRouter route for short prompts. This route requires the optional gptme package and an OpenRouter key; it does not replace the Anthropic-direct default for other installs. The working judge resolves OPENROUTER_API_KEY_JUDGE, then OPENROUTER_API_KEY_LLM_JUDGE, then shared OPENROUTER_API_KEY, checking the process environment before gptme configuration. It never borrows an isolated OPENROUTER_API_KEY_EVAL: journal/session material is working context even when used for measurement. If no permitted key resolves, the OpenRouter judge returns no score before initialization or inference. This key-purpose boundary does not attest the provider's effective data policy; retain provider/account privacy controls separately. Non-OpenRouter routes are unchanged.

Session provenance (blame)

blame answers "which AI session produced this line / commit?" by correlating git author-dates with session time windows from the store.

gptme-sessions blame src/watchdog.py
gptme-sessions blame src/watchdog.py --line 42
gptme-sessions blame src/watchdog.py --limit 5 --json
gptme-sessions blame gptme/gptme-contrib#1252          # PR/issue ref; needs an authenticated gh CLI
gptme-sessions blame src/hello.py --records /path/to/session-records.jsonl

A runnable, self-contained demo lives in examples/sessions-blame/.

Journal path pre-allocation

Concurrent launches can share a short session label, so the journal basename is not unique on its own. journal_path reserves the file before the session is dispatched, using O_EXCL creation plus a run-owned reservation record:

python -m gptme_sessions.journal_path --journal-dir journal --run-type autonomous \
  --label ab12 --uuid "$SESSION_UUID"
# -> /path/to/journal/2026-11-07/autonomous-session-ab12.md

Allocation uses a persistent POSIX flock file per candidate to serialize threads and processes. Ownership is published atomically after exclusive journal creation. If an allocator crashes before publication, its unowned empty file is conservatively skipped on retry; after publication, the reservation is reusable. Lock files must not be removed while allocators can be running. This helper requires POSIX flock support (Linux/macOS).

Reservations default to <journal-dir>/../state/session-journal-reservations/<journal-dir-name> so sibling journal trees have independent owner namespaces. Paths use the resolved journal directory name. The location can be moved with --reservation-dir; give independent journal trees distinct explicit reservation directories. Corrupt or mismatched reservation metadata fails closed (exit 1) rather than guessing. Historical lookup validates the complete owner record before skipping another run; retries find existing owned suffixes before attempting newly available canonical paths.

--date must be a valid YYYY-MM-DD calendar date. Run type, label and UUID must be non-empty filename components without path separators or NUL. Invalid inputs fail before any directories or journal files are created.

Dispatch provenance (dispatch_cause)

dispatch_cause answers "what launched this session?" — a worker spawn, an event, a scheduled slot, a task claim, or systemd — and records it before the agent runs, so a runner that dies before post_session still leaves provenance.

python -m gptme_sessions.dispatch_cause --workspace .                    # print the cause
python -m gptme_sessions.dispatch_cause --workspace . --refresh          # re-infer from this env
python -m gptme_sessions.dispatch_cause --workspace . --record-start     # also append the start ledger
python -m gptme_sessions.dispatch_cause --workspace . --trigger          # spawn|dispatch|timer|unknown

A dispatcher exports the printed JSON as AGENT_DISPATCH_CAUSE, and post_session records it with no further wiring. Inference is identifier-only — event payloads and dispatcher prompt text stay in the stores that already own them.

Variable Meaning
AGENT_DISPATCH_CAUSE Explicit JSON cause; wins unless --refresh is passed
AGENT_DISPATCH_KIND / AGENT_DISPATCH_ID Spawn kind (worker, fanout, fanout-btb) and its id
AGENT_PARENT_SESSION_ID Recorded as parent_session_id; never inferred
AGENT_SESSION_ID, AGENT_RECEIPT_SESSION_ID Session id for the start ledger

Explicit spawn kinds take precedence over event, PM and task-selection variables that a child may inherit. Fanout retains its selected task as context while its cause kind/id identify the spawn; workers clear inherited task context. Without an explicit spawn kind, event, PM, task and systemd inference keep that order.

Legacy BOB_* spellings remain read as aliases (gptme/gptme-contrib#1724). Inference also recognises dispatcher-owned protocols that are not agent-branded: CASCADE_* selection state, EVENT_ID/EVENT_URL/EVENT_TRIGGER_TYPE, PM_DISPATCH_ID with PM_WORK_FILE, and systemd's INVOCATION_ID. A systemd cause classifies as unknown rather than timer: an invocation id proves a service ran, not that a timer fired it.

Accepted-outcome yield (yield)

yield answers "which dispatch sources produce work someone else accepts?" It groups sessions by dispatch_cause.kind, extracts each session's items, and joins them to outcomes the host supplies. The package never calls GitHub or reads a task tracker: deciding acceptance is the host's job.

gptme-sessions yield --since 14d --outcomes outcomes.jsonl [--outcomes more.jsonl] [--json]

Where trajectories are discovered

Harness Default location Override
gptme ~/.local/share/gptme/logs GPTME_LOGS_DIR
Claude Code ~/.claude/projects CLAUDE_HOME (uses $CLAUDE_HOME/projects); extra roots via GPTME_CC_EXTRA_PROJECTS_DIRS
Codex ~/.codex/sessions CODEX_SESSIONS_DIR
Copilot CLI ~/.copilot/session-state COPILOT_STATE_DIR
Pi (native v3) ~/.pi/agent/sessions PI_CODING_AGENT_SESSION_DIR, else sessionDir in Pi's settings.json, else $PI_CODING_AGENT_DIR/sessions

Grok Build trajectories are parsed by the signal/transcript extractors but are not auto-discovered.

Discovery and sync never modify or delete trajectories: a record keeps the source trajectory_path but does not own the file, so keep (or back up) your trajectories. For Pi, print-mode streams and unsupported session versions are skipped with a warning rather than recorded as false no-ops, and a session Pi is still writing is read up to its last complete line.

Records and storage

Records are append-only JSONL (session-records.jsonl, one object per line); rotate moves old records into monthly archive files.

{"session_id":"a1b2c3d4","timestamp":"2026-08-31T12:00:00+00:00","harness":"pi","provider":"openai-codex","model":"gpt-5.6-luna","run_type":"autonomous","category":"code","outcome":"productive","stop_reason":"stop","cost_usd":0.0004264,"duration_seconds":2400,"deliverables":["abc123"]}

Field notes:

Development

uv run pytest packages/gptme-sessions/tests/ -v

The Pi parser is pinned to a specific upstream Pi session contract. After upgrading Pi or refreshing fixtures, run the drift check (downloads Pi's release source; network failures are errors, not passes):

cd packages/gptme-sessions && uv run python3 scripts/check_pi_compat.py