feat(intelligence): efficiency scoring, AI smell detection, burn rate forecasting#85
Conversation
… forecasting Rebased onto origin/main (ad7d729) — fully compatible with remote access, local power costing, CO2 footprint, billing modes and all Phase 2 features merged since June 7. ### backend/scoring.py (new) - 0–100 efficiency score per session: output_ratio × error_penalty × turn_penalty × 100 - Higher score = more output tokens per total token, fewer errors, fewer turns - score_label(): maps score to good (≥70) / fair (≥40) / poor ### backend/smells.py (new) - Rule-based detector for 5 anti-patterns: context_rot (>200 turns), loop_trap (≥8 consecutive identical tool calls), tool_thrash (≥25 reads of same file), high_error_rate (>20% errors), massive_session (>2M tokens) - Each smell carries severity warning | critical ### backend/forecast.py (new) - Daily token bucketing, linear regression, trend detection (accelerating/steady/slowing) - Projects monthly token usage and days-until-limit vs plan quotas - Plans: claude_pro 500M, claude_max 2B, codex_plus 200M, copilot 100M ### backend/main.py - Imports all three modules after existing `from pricing import` - Scoring + smell detection loop attached to every session after global sort - Three new endpoints: GET /forecast, GET /smells, GET /efficiency ### frontend/src/app/page.tsx - Smell interface + efficiency/smells fields added to Session interface - ForecastResponse interface - forecastRes useResource hook (polls /forecast every 60s) - New Score column (⚡ badge) in Recent Activity table, colour-coded green/amber/red - Smell warning icon (⚠) on session rows, critical = red, warning = amber - Burn Rate card in dashboard sidebar: daily rate, projected month, plan progress bar, urgency alert when limit ≤7 days away — all compatible with Vasi's new billing framing No new required dependencies. Zero TypeScript errors against latest codebase. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
9136b01 to
e50b008
Compare
…l detection, burn rate Adds a new Intelligence Layer section covering all three features in this branch: efficiency score formula, smell detection rules and thresholds, burn rate forecast plan limits and API response shape. Also adds three new bullet points to Features list. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Correlates structural prompt features against efficiency scores using Pearson r to surface what makes sessions good or bad. Backend - new backend/prompt_analysis.py: - extract_features: 10 structural/semantic features per prompt - classify_task: regex task type fix/build/refactor/analyze/test/deploy - _pearson: Pearson correlation, pure stdlib no scipy/numpy - analyse_prompt_dna: correlations sorted by abs(r), task-type breakdown - GET /insights/prompt-dna endpoint wired into main.py Frontend - page.tsx: - PromptDnaResponse interface + DnaCorrelation type - Prompt DNA card in right sidebar polling every 120s - Boosts/Hurts efficiency sections with r-value badges and insight tooltips - By-task-type mini bar chart coloured by score band Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds the Prompt DNA section to the Intelligence Layer docs: feature extraction table, task classification, UI description, API shape with example response. Also updates the feature list bullet and the implementation notes table to include the 4th module. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Compares efficiency scores across model names, filterable by task type.
Backend new backend/model_comparison.py:
- compare_models(sessions, task_type): groups sessions by model name
- Per model: avg/median/p75/best efficiency, total/avg tokens, task breakdown
- task_types_available list for dynamic filter pills
- GET /insights/model-comparison endpoint with optional task_type param
Frontend page.tsx:
- ModelRow + ModelComparisonResponse interfaces
- modelTaskFilter state plus useEffect for dynamic URL refetch on filter change
- Full-width Model comparison Section below main grid
- Task type filter pills with active state
- Model rows: rank badge, model name, agent colour, avg bar, p75 bar,
best/sess/avg-tok stats, task breakdown pills coloured by score band
Real data: claude-sonnet-4-6 (68.4) > claude-opus-4-7 (48.4) > gpt-5.5 (0.8)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Adds Multi-Model Comparison section to the Intelligence Layer docs: stat table, UI description, API shape with example response. Updates feature list bullet and implementation notes table to 5 modules. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Attaches git context to every session by finding the commit that was
HEAD at or before the session timestamp via subprocess git commands.
Backend - new backend/git_context.py:
- get_git_info(project, timestamp): resolves git binary with shutil.which
+ Windows fallback path, normalises POSIX-style paths like /c:/...,
handles datetime objects and ISO strings, 5-min cache per (project, date)
- git_summary(sessions): aggregates per-project stats across all sessions
- GET /insights/git-summary endpoint
Per session git_info fields:
is_git, branch, commit_sha, commit_msg, commit_author,
commit_time, files_changed, lines_added, lines_deleted
Frontend - page.tsx:
- GitInfo + GitProjectSummary + GitSummaryResponse interfaces
- git_info added to Session interface
- Branch badge under project name in Recent Activity table rows
- Full-width Repository activity Section: project cards with branch,
latest commit SHA+msg, +lines/-lines/net and files changed count
Real data: 29 git sessions, 7 repos, 5590 lines added, 440 deleted
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Time-series chart showing daily efficiency over the last 30/60 days
with a 7-day rolling average line, trend direction badge, and streak
detection — answers "am I getting better over time?"
Backend - new backend/trends.py:
- compute_trends(sessions, days): buckets sessions by calendar day,
computes avg/best/worst efficiency per day, 7-day rolling average
(calendar-based window not row-based, so gaps don't skew it),
trend direction by comparing last-7 vs prior-7 data-days,
current streak of consecutive good days (avg >= 60)
- GET /insights/trends?days=30|60
Frontend - page.tsx:
- TrendDay + TrendsResponse interfaces
- trendsDays state (30 | 60) with toggle buttons
- Full-width Section with Recharts ComposedChart: coloured Bar
(green/amber/red by efficiency band) + brand-colour rolling
average Line with connectNulls
- Stats chips: trend badge with WoW delta, overall avg, streak,
best day callout
- 60pt ReferenceLine (good threshold)
- Legend row
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Two new analytics layers that answer "when" and "how" questions
about coding sessions.
Time Intelligence (backend/time_intel.py, GET /insights/time):
- Groups sessions by UTC hour-of-day and day-of-week
- Returns per-bucket avg efficiency, session count, token totals
- Computes peak_hour, worst_hour, peak_dow, peak_period
(morning/afternoon/evening/night) via weighted period scoring
Tool Footprint (backend/tool_footprint.py, GET /insights/tool-footprint):
- Buckets sessions by toolset size: lean(1-5) / standard(6-15)
/ heavy(16-30) / bloated(31+)
- Classifies each tool as core/agent/browser/mcp/meta
- Per-category presence effect: efficiency with vs without each class
- Top-15 tools by session frequency with avg efficiency scores
Frontend (page.tsx):
- TimeIntelResponse + ToolFootprintResponse interfaces
- useResource hooks for /insights/time and /insights/tool-footprint
- Time Intelligence section: stats strip (peak hour/day, period,
avoid callout) + two side-by-side Recharts bar charts (hour + DOW),
coloured green/amber/red by efficiency band
- Tool Footprint section: horizontal efficiency bar chart by size
bucket + scrollable top-tools ranked list with category badges
and colour-coded efficiency scores
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Connects session cost to efficiency outcomes — answers which model
gives the best value and where money is being wasted.
Backend - new backend/cost_intel.py (GET /insights/cost):
- by_model: avg cost, total cost, avg efficiency, cost_per_eff_pt,
avg cache hit % per model — sorted best value first
- by_task_type: same metrics grouped by task type
- cache_tiers: sessions bucketed into 5 cache-hit bands (0-20%
through 80-100%) showing how cache hit % correlates with
efficiency and cost
- wasteful: top-5 sessions with highest waste_score = cost
percentile rank minus efficiency (expensive + low quality)
- best_value_model: lowest cost_per_eff_pt with >= 2 sessions
Frontend - page.tsx:
- CostIntelResponse + related interfaces
- useResource for /insights/cost
- Full-width Cost Intelligence section:
· Stats strip: total spend, avg/session, best value model, cache%
· By-model bars: proportional cost/eff-pt bars (green→red) with
efficiency score and formatted cost-per-point labels
· Cache tier analysis: efficiency bars per 20%-bucket + avg cost
· Expensive flops card: AlertTriangle + top wasteful sessions
with session ID, model, cost, efficiency
Real data: $579 total, gpt-5.5 worst at $11.37/pt, claude-opus-4-7
best value at $0.52/pt
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- New backend modules: anomaly detection (z-score), AI recommendations (cross-module rules), project health score (composite 0-100 A-F grade) - New endpoints: /insights/anomalies, /insights/recommendations, /insights/project-health (joined with earlier trends/time/tool/cost) - New frontend /intelligence page with all 8 intelligence sections: Recommendations, Project Health, Anomaly Detection, Session Trends, Model Comparison, Prompt DNA, Cost Intelligence, Time Intelligence, Tool Footprint, Repository Activity - Navigation.tsx: added Intelligence tab (Brain icon) between Analytics and Local Models - Dashboard (page.tsx): removed 6 full-width intelligence sections, added compact IntelligenceSnapshot widget linking to /intelligence Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…pshot only Prompt DNA detail now lives exclusively on /intelligence. Dashboard sidebar now shows Burn Rate + Model Distribution + IntelligenceSnapshot summary widget. Removed orphaned interface declarations and unused Recharts/lucide imports. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Backend: - recommendations: cost_model_switch now shows impact as efficiency gain when replacement model costs more per session (was null, now +49 pts) - anomaly: add affected_sessions field to distinguish unique anomalous sessions from total anomaly signal count (3 sessions vs 5 signals) - trends: return trend="new" instead of "steady" when no prior-period data exists — prevents false "steady" label with insufficient history Frontend (intelligence/page.tsx — TypeScript interface gaps): - TrendsResponse: add week_over_week, worst_day; TrendDay: add best, worst, total_tokens - AnomalyResponse: add affected_sessions; update description to show "X signals across Y sessions" instead of "X anomalies" - TimeIntelResponse: add worst_dow, sessions_skipped; TimeHourRow: add total_tokens - ToolFootprintResponse: add sessions_skipped - CostIntelResponse: add by_task_type, sessions_skipped, CostTaskRow - ModelComparisonResponse: add task_type_filter - GitProjectSummary: add latest_commit_time; display in repo activity - Session Trends: handle new "new" trend state with blue colour + ✦ icon - IntelligenceSnapshot: show "X sessions flagged / Y signals total" Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace every piece of technical jargon across the intelligence layer so any user can understand their AI agent data at a glance: Frontend (intelligence/page.tsx): - Add quality score legend banner (0-100 scale explained with color key) - Rename all 12 section titles to plain English - Anomaly types: cost_spike → Unusually expensive, etc. - Z-score σ notation → X× above normal - Severity: critical/warning → Serious/Watch out - Prompt DNA r=0.73 → strength labels (Very strong link, Moderate link, etc.) - Prompt DNA cards: Boosts/Hurts efficiency → What works well/What to avoid - Project health components: Smell-free/Efficiency → Consistency/Work quality - Trends: improving/steady/declining/new → plain English labels - pts WoW → pts vs last week, raw averages → X/100 quality scores - Model comparison: added /100 suffix and legend for dual bars - Cost: value-for-money framing, /quality pt label, clearer card titles - Time: Best hour/day labels, scores shown as X/100 - Tool footprint: lean/standard/heavy/bloated → human size labels - All chart tooltips updated to say Quality score Backend (anomaly.py, recommendations.py): - Anomaly detail strings: removed σ, added /100 quality scores, plain language - Recommendation titles/details: removed /eff-pt, humanized smell labels, trend messages now say quality score not efficiency Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
|
Thanks for the big effort on the Intelligence Layer! This is a substantial set of new capabilities on top of the existing session data — efficiency scoring (0-100), AI smell detection (context rot, loop traps, tool thrashing, etc.), burn rate forecasting with plan limits and trends, Prompt DNA analysis, multi-model comparison, project health grades, recommendations, anomalies, and more. The approach (pure stdlib, in-memory post-scan enrichment, no new dependencies) aligns well with the project's local-first philosophy, and the README documentation for the new layer is excellent. I reviewed this using our Key findingsPolicy blocker (hard requirement):
Compatibility & integration work needed (this is why full validation will take time):
Other observations:
Because this introduces so many new features and touches both the data model and UI, making everything properly compatible and robust is going to take some dedicated follow-up time (parser enrichment, integration fixes, tests, possibly splitting the work). Suggested next steps
I'm happy to help review pieces, pair on the enrichment work, or re-run validation once updates are in. Let me know how you'd like to move forward. (Full internal validation report with file:line details is available if needed.) |
|
Tagging you on the review of this PR (full details in the previous comment: #85 (comment)). Quick summary of what we found:
We're happy to help with the compatibility work, parser enrichment, or splitting the PR. Let us know how you'd like to proceed! |
|
Tagging you on the review of this PR (full details in the previous comment: #85 (comment)). Quick summary of what we found:
We're happy to help with the compatibility work, parser enrichment, or splitting the PR. Let us know how you'd like to proceed! |
Summary
Three new analytical capabilities built on top of the existing session data — all pure computation, no new required dependencies.
1. Agent Efficiency Score (
backend/scoring.py)A 0–100 score per session measuring how productively tokens were used:
output_ratio= output tokens / total tokens (more output = more productive)error_penalty= 1 / (1 + errors × 0.15) — penalises tool failuresturn_penalty= 1 / (1 + log(turns) × 0.18) — rewards concise promptsEvery session in
/sessionsnow includesefficiency: 73.2andefficiency_label: good | fair | poor.2. AI Smell Detection (
backend/smells.py)Rule-based detection of 5 anti-patterns:
context_rotloop_traptool_thrashhigh_error_ratemassive_sessionEvery session includes
smells: [{type, title, detail, severity}]. New endpointGET /smells?project=<path>returns only sessions with warnings.3. Burn Rate Forecasting (
backend/forecast.py)Linear projection of token usage toward monthly subscription limits:
GET /forecast?plan=claude_proFrontend (
frontend/src/app/page.tsx)⚡ Scorecolumn in the Recent Activity table — colour-coded pill (green ≥70, amber ≥40, red <40)⚠icon on session rows with smell count and critical/warning colourNo new required dependencies
All Python modules use stdlib only (
math,datetime,collections). Lucide icons used are already in the project's icon set.Test plan
/sessionsresponse includesefficiencyandsmellsfieldsGET /forecast— confirm JSON withdaily_avg_7d,trend,days_until_limitGET /smells— confirm only sessions with warnings are returnedGET /efficiency— confirm sessions sorted by efficiency score descending🤖 Generated with Claude Code