diff --git a/cloudflare_app.py b/cloudflare_app.py index aad00bd..d9e0b85 100644 --- a/cloudflare_app.py +++ b/cloudflare_app.py @@ -353,6 +353,18 @@ async def repository_access(repo, request, identity, allow_private): return token if metadata['private'] else None, metadata['private'] +async def web_repository_access(repo, request, identity, allow_private): + token = identity.token if identity else getattr(environment(request), 'GITHUB_TOKEN', None) + metadata = await public_repo_exists(repo, token, allow_private=allow_private) + if metadata['private'] and not identity: + raise HTTPException(401, 'Connect your GitHub identity or supply its bearer credential for private analysis.') + raw_id = metadata.get('id') + repository_id = raw_id if (identity and type(raw_id) is int and raw_id >= 1) else None + canonical_repo = parse_repo(metadata.get('full_name') or repo) if repository_id is not None else repo + # Anonymous content reads cannot cross a later public-to-private transition. + return canonical_repo, (token if metadata['private'] else None), metadata['private'], repository_id + + async def mcp_repository_access(repo, token, allow_private): metadata = await public_repo_exists(repo, token, allow_private=allow_private) repository_id = metadata.get('id') @@ -452,7 +464,8 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False): repo, private, repository_id = await mcp_repository_access(repo, identity.token, req.allow_private) token = identity.token if private else None else: - token, private = await repository_access(repo, request, identity, req.allow_private) + repo, token, private, repository_id = await web_repository_access(repo, request, identity, req.allow_private) + use_graphql = full_dashboard or (identity is not None and repository_id is not None) gemini_override = None if full_dashboard else request.headers.get("X-Gemini-Api-Key") jev_override = None if full_dashboard else request.headers.get("X-TypeSafe-Api-Key") linear_override = None if full_dashboard else (request.headers.get("X-Linear-Api-Key") or "").strip() or None @@ -493,14 +506,15 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False): getattr(env, "ANALYTICS_CACHE", None) if env and not caller_keys and not private and not is_linear and not connected_linear else None ) - cache_key = public_analysis_key(repo, full_dashboard) + cache_key = public_analysis_key(repo, full_dashboard, graphql=use_graphql) if cache and not req.force_refresh: saved = await cache.get(cache_key) if saved: cached = json.loads(saved) if not full_dashboard: - return cached - if cached.get('repository_id') == repository_id and cached.get('analysis_id'): + if not use_graphql or cached.get('repository_id') == repository_id: + return cached + elif cached.get('repository_id') == repository_id and cached.get('analysis_id'): snapshot = await cache.get(public_dashboard_snapshot_key(repo, cached['analysis_id'])) if snapshot: return json.loads(snapshot) @@ -509,7 +523,7 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False): if is_linear: github_coro = ( collect_dashboard_data(repo, identity.token, private, repository_id, include_issues=False) - if full_dashboard else collect_public_data(repo, token, include_issues=False) + if use_graphql else collect_public_data(repo, token, include_issues=False) ) gh_task = asyncio.create_task(github_coro) lin_task = asyncio.create_task(collect_linear_issues(linear_team_url, linear_key, repo=repo)) @@ -523,7 +537,7 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False): raw["issues"] = linear_issues else: raw = (await collect_dashboard_data(repo, identity.token, private, repository_id) - if full_dashboard else await collect_public_data(repo, token)) + if use_graphql else await collect_public_data(repo, token)) pr_bodies = [ pr.get("body") for group in ("recent_prs", "open_prs") @@ -576,11 +590,12 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False): jev_key = jev_override or getattr(env, "TYPESAFE_API_KEY", None) metrics['repository_visibility'] = 'private' if private else 'public' options = {'allow_private': True} if private else {} + if use_graphql: + metrics['dashboard_source'] = 'github_graphql' + metrics['repository_id'] = repository_id if full_dashboard: if not private: options['load_sources'] = partial(public_value_sources, repo, identity.token, repository_id) - metrics['dashboard_source'] = 'github_graphql' - metrics['repository_id'] = repository_id metrics['analysis_id'] = secrets.token_urlsafe(24) if not metrics.get('recent_stats', {}).get('total'): metrics['p50_sle'] = metrics['p85_sle'] = None @@ -621,8 +636,8 @@ def public_dashboard_snapshot_key(repo, analysis_id): return f'{public_analysis_key(repo, True)}:{analysis_id}' -def public_analysis_key(repo, full_dashboard): - namespace = 'dashboard:v1:' if full_dashboard else '' +def public_analysis_key(repo, full_dashboard, *, graphql=False): + namespace = 'dashboard:v1:' if full_dashboard else ('graphql:v1:' if graphql else '') return f'{METRICS_CACHE_PREFIX}{namespace}{repo.lower()}' @@ -751,8 +766,11 @@ async def chat_for_identity(req, request, identity, *, full_dashboard=False): saved = await cache.get(private_analysis_key(repo, identity, req.analysis_id, True)) else: cache_key = (private_analysis_key(repo, identity, req.analysis_id) if identity and req.analysis_id - else session_analysis_key(repo, request, req.analysis_id) if req.analysis_id else public_analysis_key(repo, False)) + else session_analysis_key(repo, request, req.analysis_id) if req.analysis_id + else public_analysis_key(repo, False, graphql=bool(identity))) saved = await cache.get(cache_key) + if not saved and identity and not req.analysis_id: + saved = await cache.get(public_analysis_key(repo, False)) if not saved and identity and req.analysis_id and request.cookies.get(SESSION_COOKIE): try: await signed_in_user(request) diff --git a/index.html b/index.html index 6123324..9aba0bf 100644 --- a/index.html +++ b/index.html @@ -1090,7 +1090,11 @@

Flowy AI Coach

if (setupHadFocus) document.getElementById('chat-input').focus(); // Welcome message in chat - addChatMessage('assistant', `🎉 **Repository loaded: \`${data.repo}\`**\n\nAsk me about cycle time, aging work, or throughput. Review timing and batch size are not yet available from this hosted data source.`); + const hasRichData = data.dashboard_source === 'github_graphql' || data.pr_size_scatter_points?.some(point => point.x > 0); + const sourceNote = hasRichData + ? 'Ask me about cycle time, PR size correlation, aging work, or throughput.' + : 'Ask me about cycle time, aging work, or throughput. Sign in with GitHub to include PR size and review timing.'; + addChatMessage('assistant', `🎉 **Repository loaded: \`${data.repo}\`**\n\n${sourceNote}`); } catch(e) { if (savedRepository && response && ![401, 403, 409].includes(response.status) && !repoInput.value) { @@ -1595,20 +1599,90 @@

Flowy AI Coach

if (hasAging) { if (ageTitle) ageTitle.textContent = 'Work Item Aging by Status'; const annotations = {}; - if (aging.p50_days != null) { - annotations.p50line = { - type:'line', yMin:aging.p50_days, yMax:aging.p50_days, - borderColor:'rgba(6,182,212,.7)', borderWidth:1.5, borderDash:[5,4], - label:{content:`P50: ${aging.p50_days.toFixed(1)}d`, display:true, position:'end', color:'#67e8f9', font:{size:11}} - }; - } - if (aging.p85_days != null) { - annotations.p85line = { - type:'line', yMin:aging.p85_days, yMax:aging.p85_days, - borderColor:'rgba(245,158,11,.8)', borderWidth:2, - label:{content:`P85: ${aging.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fcd34d', font:{size:11}} - }; + const stageStats = new Map( + (aging.stage_percentiles || []) + .filter(sp => sp && sp.stage) + .map(sp => [sp.stage, sp]) + ); + const hasStagePercentiles = Array.from(stageStats.values()).some(sp => sp.p50_days != null || sp.p85_days != null); + const maxItemY = Math.max(0, ...aging.items.map(item => Number(item.age_days) || 0)); + const maxP85 = Math.max( + 0, + aging.p85_days || 0, + ...Array.from(stageStats.values()).map(sp => Number(sp.p85_days) || 0) + ); + const chartTop = Math.ceil(Math.max(maxItemY, maxP85, 1) * 1.15); + + if (hasStagePercentiles) { + aging.stages.forEach((stage, idx) => { + const sp = stageStats.get(stage); + if (!sp || sp.p50_days == null || sp.p85_days == null) return; + const xMin = idx - 0.44; + const xMax = idx + 0.44; + annotations[`band_green_${idx}`] = { + type:'box', xMin, xMax, yMin:0, yMax:sp.p50_days, + backgroundColor:'rgba(16,185,129,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations[`band_yellow_${idx}`] = { + type:'box', xMin, xMax, yMin:sp.p50_days, yMax:sp.p85_days, + backgroundColor:'rgba(245,158,11,.18)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations[`band_red_${idx}`] = { + type:'box', xMin, xMax, yMin:sp.p85_days, yMax:chartTop, + backgroundColor:'rgba(244,63,94,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations[`p50_line_${idx}`] = { + type:'line', xMin, xMax, yMin:sp.p50_days, yMax:sp.p50_days, + borderColor:'rgba(16,185,129,.85)', borderWidth:1.5, borderDash:[4,3], + label:{content:`P50 ${sp.p50_days.toFixed(1)}d`, display:true, position:sp.p50_days === sp.p85_days ? 'start' : 'end', color:'#6ee7b7', backgroundColor:'rgba(15,23,42,.75)', font:{size:10}, padding:2} + }; + annotations[`p85_line_${idx}`] = { + type:'line', xMin, xMax, yMin:sp.p85_days, yMax:sp.p85_days, + borderColor:'rgba(244,63,94,.9)', borderWidth:2, + label:{content:`P85 ${sp.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fda4af', backgroundColor:'rgba(15,23,42,.75)', font:{size:10}, padding:2} + }; + }); + } else { + if (aging.p50_days != null) { + annotations.band_green_global = { + type:'box', yMin:0, yMax:aging.p50_days, + backgroundColor:'rgba(16,185,129,.14)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations.p50line = { + type:'line', yMin:aging.p50_days, yMax:aging.p50_days, + borderColor:'rgba(16,185,129,.85)', borderWidth:1.5, borderDash:[5,4], + label:{content:`P50: ${aging.p50_days.toFixed(1)}d`, display:true, position:'end', color:'#6ee7b7', font:{size:11}} + }; + } + if (aging.p85_days != null) { + if (aging.p50_days != null) { + annotations.band_yellow_global = { + type:'box', yMin:aging.p50_days, yMax:aging.p85_days, + backgroundColor:'rgba(245,158,11,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + } + annotations.band_red_global = { + type:'box', yMin:aging.p85_days, yMax:chartTop, + backgroundColor:'rgba(244,63,94,.14)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations.p85line = { + type:'line', yMin:aging.p85_days, yMax:aging.p85_days, + borderColor:'rgba(244,63,94,.9)', borderWidth:2, + label:{content:`P85: ${aging.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fda4af', font:{size:11}} + }; + } } + + const pointColors = aging.items.map(item => { + const sp = stageStats.get(item.stage); + const p50 = hasStagePercentiles ? sp?.p50_days : aging.p50_days; + const p85 = hasStagePercentiles ? sp?.p85_days : aging.p85_days; + if (p50 == null && p85 == null) return 'rgba(148,163,184,.95)'; + if (p85 != null && item.age_days > p85) return 'rgba(244,63,94,.95)'; + if (p50 != null && item.age_days > p50) return 'rgba(245,158,11,.95)'; + return 'rgba(16,185,129,.95)'; + }); + mkChart('chart-issue-age', { type: 'scatter', data: { @@ -1616,8 +1690,10 @@

Flowy AI Coach

datasets: [{ label: 'Open issues', data: aging.items.map(item => ({x: item.stage, y: item.age_days, identifier: item.identifier, title: item.title})), - backgroundColor: 'rgba(245,158,11,.8)', - pointRadius: 5, pointHoverRadius: 9, + backgroundColor: pointColors, + borderColor: '#f8fafc', + borderWidth: 1.25, + pointRadius: 5.5, pointHoverRadius: 9, }] }, options: { @@ -1629,14 +1705,18 @@

Flowy AI Coach

callbacks:{ label: ctx => { const d = ctx.raw; - return [`${d.identifier}: ${(d.title || '').slice(0, 50)}`, `${d.x} · ${d.y?.toFixed(1)} days`]; + const sp = stageStats.get(d.x); + const pace = sp && sp.p50_days != null && sp.p85_days != null + ? ` (stage P50 ${sp.p50_days.toFixed(1)}d · P85 ${sp.p85_days.toFixed(1)}d, n=${sp.n})` + : ''; + return [`${d.identifier}: ${(d.title || '').slice(0, 50)}`, `${d.x} · ${d.y?.toFixed(1)} days${pace}`]; } } } }, scales:{ - x:{ type:'category', labels: aging.stages, grid:{color:'rgba(255,255,255,.04)'} }, - y:{ grid:{color:'rgba(255,255,255,.04)'}, title:{display:true, text:'Age (days)', color:'#64748b'}, beginAtZero:true } + x:{ type:'category', labels: aging.stages, offset:true, grid:{color:'rgba(255,255,255,.04)'} }, + y:{ grid:{color:'rgba(255,255,255,.04)'}, title:{display:true, text:'Age since active start (days)', color:'#64748b'}, beginAtZero:true, max:chartTop } } } }); diff --git a/issues.py b/issues.py index c7e787f..ee0364f 100644 --- a/issues.py +++ b/issues.py @@ -799,6 +799,146 @@ def _linear_lifecycle_cfd(issues, issues_raw, window_start, now): } +_LINEAR_PRE_ACTIVE_TYPES = frozenset({"triage", "backlog", "unstarted"}) +_LINEAR_TERMINAL_TYPES = frozenset({"completed", "canceled"}) +_LINEAR_INACTIVE_TYPES = _LINEAR_PRE_ACTIVE_TYPES | _LINEAR_TERMINAL_TYPES + + +def _is_linear_active_stage(stage, state_types): + return bool(stage) and state_types.get(stage) not in _LINEAR_INACTIVE_TYPES + + +def _linear_state_changes(issue, state_types): + created = _parse(issue.get("createdAt")) + if created is None: + return [], False + history = issue.get("linearHistory") or {} + history_truncated = bool(history.get("hasNextPage")) + transitions = [] + for item in history.get("transitions") or []: + if not isinstance(item, dict): + continue + for state_key, type_key in (("fromState", "fromType"), ("toState", "toType")): + if item.get(state_key) and item.get(type_key): + state_types.setdefault(item[state_key], item[type_key]) + at = _parse(item.get("createdAt")) + if at and item.get("toState"): + transitions.append((at, item.get("fromState"), item["toState"])) + transitions.sort(key=lambda item: item[0]) + initial_stage = (transitions[0][1] or issue.get("linearState")) if transitions else issue.get("linearState") + changes = [(created, initial_stage)] if (initial_stage and not history_truncated) else [] + for at, _, to_state in transitions: + if at >= created and (not changes or changes[-1][1] != to_state): + changes.append((at, to_state)) + return changes, history_truncated + + +def _linear_active_start(issue, changes, state_types, *, history_truncated=False): + started_at = _parse(issue.get("startedAt")) + if history_truncated and started_at is not None: + return started_at + for at, stage in changes: + if _is_linear_active_stage(stage, state_types): + return at + return started_at + + +def _compute_linear_work_item_aging(open_issues, closed_issues, issues_raw, now, modern_stats): + state_types = {} + aging_stages = [] + for state in issues_raw.get("linear_states") or []: + if not isinstance(state, dict) or not state.get("name"): + continue + name, stype = state["name"], state.get("type") + if stype: + state_types[name] = stype + if stype not in _LINEAR_INACTIVE_TYPES and name not in aging_stages: + aging_stages.append(name) + + all_issues = open_issues + closed_issues + for issue in all_issues: + if issue.get("linearState") and issue.get("linearStateType"): + state_types.setdefault(issue["linearState"], issue["linearStateType"]) + + open_ids = {id(issue) for issue in open_issues} + aging_items = [] + stage_exit_ages = {stage: [] for stage in aging_stages} + completed_active_days = [] + + for issue in all_issues: + changes, history_truncated = _linear_state_changes(issue, state_types) + active_start = _linear_active_start(issue, changes, state_types, history_truncated=history_truncated) + if active_start is None: + continue + + if id(issue) in open_ids and _is_linear_active_stage(issue.get("linearState"), state_types): + stage = issue["linearState"] + if stage not in aging_stages: + aging_stages.append(stage) + stage_exit_ages.setdefault(stage, []) + aging_items.append({ + "identifier": issue.get("identifier") or f"#{issue.get('number')}", + "number": issue.get("number"), + "title": issue.get("title", ""), + "stage": stage, + "age_days": round(elapsed(active_start, now, 86400.0), 2), + }) + + last_exit_by_stage = {} + is_completed = issue.get("state") == "CLOSED" and state_types.get(issue.get("linearState")) != "canceled" + closed_at = _parse(issue.get("closedAt")) if is_completed else None + for idx, (_, stage) in enumerate(changes): + if not _is_linear_active_stage(stage, state_types): + continue + if idx + 1 < len(changes): + next_at, next_stage = changes[idx + 1] + next_type = state_types.get(next_stage) + if next_type == "canceled" or next_type in _LINEAR_PRE_ACTIVE_TYPES: + continue + exit_at = next_at + else: + exit_at = closed_at + if exit_at and exit_at >= active_start: + last_exit_by_stage[stage] = elapsed(active_start, exit_at, 86400.0) + + for stage, exit_days in last_exit_by_stage.items(): + if stage not in stage_exit_ages: + stage_exit_ages[stage] = [] + aging_stages.append(stage) + stage_exit_ages[stage].append(exit_days) + if closed_at and closed_at >= active_start: + completed_active_days.append(elapsed(active_start, closed_at, 86400.0)) + + if not aging_stages or not aging_items: + return None + + stage_percentiles = [] + for stage in aging_stages: + ages = stage_exit_ages.get(stage) or [] + p50, p85 = percentiles(ages, (0.5, 0.85), method="upper-index") if ages else (None, None) + stage_percentiles.append({ + "stage": stage, + "n": len(ages), + "p50_days": round(p50, 2) if p50 is not None else None, + "p85_days": round(p85, 2) if p85 is not None else None, + }) + + if completed_active_days: + overall_p50, overall_p85 = percentiles(completed_active_days, (0.5, 0.85), method="upper-index") + p50_days, p85_days = round(overall_p50, 2), round(overall_p85, 2) + else: + p50_days = p85_days = None + + return { + "start_basis": "active_work", + "stages": aging_stages, + "items": aging_items, + "stage_percentiles": stage_percentiles, + "p50_days": p50_days, + "p85_days": p85_days, + } + + def _window_start(issues_raw, weekly_bins): start = weekly_bins[0] if issues_raw.get("closed_truncated"): @@ -878,7 +1018,6 @@ def compute_issue_metrics(issues_raw, weekly_bins, now, stale_days=STALE_DAYS, * age_counts = {label: 0 for label, _, _ in AGE_BUCKETS} stale_items = [] - aging_items = [] for it, made, _ in open_rows: if not made: continue @@ -887,14 +1026,6 @@ def compute_issue_metrics(issues_raw, weekly_bins, now, stale_days=STALE_DAYS, * if age_days >= low and (high is None or age_days < high): age_counts[label] += 1 break - if is_linear and it.get("linearState"): - aging_items.append({ - "identifier": it.get("identifier") or f"#{it.get('number')}", - "number": it.get("number"), - "title": it.get("title", ""), - "stage": it["linearState"], - "age_days": round(age_days, 2), - }) last = _parse(it.get("updatedAt")) if (rest or is_linear) else _last_activity(it) idle_days = elapsed(last, now, 86400.0) if last else age_days if idle_days > stale_days: @@ -932,22 +1063,11 @@ def compute_issue_metrics(issues_raw, weekly_bins, now, stale_days=STALE_DAYS, * if (not is_linear and not project_cfd and flow_available and not _workflow_label_stages(repo) and factory_evidence_ready and _has_tessl_factory_signals(lifecycle_issues)): factory_cfd = _tessl_factory_lifecycle_cfd(lifecycle_issues, window_start, now, history_start) - work_item_aging = None - if is_linear and open_available: - aging_stages = [ - state["name"] for state in (issues_raw.get("linear_states") or []) - if isinstance(state, dict) and state.get("name") and state.get("type") not in ("completed", "canceled") - ] - for item in aging_items: - if item["stage"] not in aging_stages: - aging_stages.append(item["stage"]) - if aging_stages and aging_items: - work_item_aging = { - "stages": aging_stages, - "items": aging_items, - "p50_days": round(modern_stats["median_hours"] / 24.0, 2) if modern_stats["n"] and modern_stats["median_hours"] is not None else None, - "p85_days": round(modern_stats["p85_hours"] / 24.0, 2) if modern_stats["n"] and modern_stats["p85_hours"] is not None else None, - } + work_item_aging = ( + _compute_linear_work_item_aging(open_issues, modern_closed, issues_raw, now, modern_stats) + if (is_linear and open_available) + else None + ) return { "sample_size": len(sampled), "open_available": open_available, diff --git a/linear_issues.py b/linear_issues.py index 5e17313..e204882 100644 --- a/linear_issues.py +++ b/linear_issues.py @@ -379,6 +379,7 @@ def _normalize_linear_issue(node: dict, repo: str | None) -> dict | None: "title": node.get("title") or "", "body": node.get("description") or "", "createdAt": node["createdAt"], + "startedAt": node.get("startedAt"), "updatedAt": node.get("updatedAt") or node["createdAt"], "closedAt": closed_at, "state": "CLOSED" if is_closed else "OPEN", diff --git a/public/index.html b/public/index.html index 6123324..9aba0bf 100644 --- a/public/index.html +++ b/public/index.html @@ -1090,7 +1090,11 @@

Flowy AI Coach

if (setupHadFocus) document.getElementById('chat-input').focus(); // Welcome message in chat - addChatMessage('assistant', `🎉 **Repository loaded: \`${data.repo}\`**\n\nAsk me about cycle time, aging work, or throughput. Review timing and batch size are not yet available from this hosted data source.`); + const hasRichData = data.dashboard_source === 'github_graphql' || data.pr_size_scatter_points?.some(point => point.x > 0); + const sourceNote = hasRichData + ? 'Ask me about cycle time, PR size correlation, aging work, or throughput.' + : 'Ask me about cycle time, aging work, or throughput. Sign in with GitHub to include PR size and review timing.'; + addChatMessage('assistant', `🎉 **Repository loaded: \`${data.repo}\`**\n\n${sourceNote}`); } catch(e) { if (savedRepository && response && ![401, 403, 409].includes(response.status) && !repoInput.value) { @@ -1595,20 +1599,90 @@

Flowy AI Coach

if (hasAging) { if (ageTitle) ageTitle.textContent = 'Work Item Aging by Status'; const annotations = {}; - if (aging.p50_days != null) { - annotations.p50line = { - type:'line', yMin:aging.p50_days, yMax:aging.p50_days, - borderColor:'rgba(6,182,212,.7)', borderWidth:1.5, borderDash:[5,4], - label:{content:`P50: ${aging.p50_days.toFixed(1)}d`, display:true, position:'end', color:'#67e8f9', font:{size:11}} - }; - } - if (aging.p85_days != null) { - annotations.p85line = { - type:'line', yMin:aging.p85_days, yMax:aging.p85_days, - borderColor:'rgba(245,158,11,.8)', borderWidth:2, - label:{content:`P85: ${aging.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fcd34d', font:{size:11}} - }; + const stageStats = new Map( + (aging.stage_percentiles || []) + .filter(sp => sp && sp.stage) + .map(sp => [sp.stage, sp]) + ); + const hasStagePercentiles = Array.from(stageStats.values()).some(sp => sp.p50_days != null || sp.p85_days != null); + const maxItemY = Math.max(0, ...aging.items.map(item => Number(item.age_days) || 0)); + const maxP85 = Math.max( + 0, + aging.p85_days || 0, + ...Array.from(stageStats.values()).map(sp => Number(sp.p85_days) || 0) + ); + const chartTop = Math.ceil(Math.max(maxItemY, maxP85, 1) * 1.15); + + if (hasStagePercentiles) { + aging.stages.forEach((stage, idx) => { + const sp = stageStats.get(stage); + if (!sp || sp.p50_days == null || sp.p85_days == null) return; + const xMin = idx - 0.44; + const xMax = idx + 0.44; + annotations[`band_green_${idx}`] = { + type:'box', xMin, xMax, yMin:0, yMax:sp.p50_days, + backgroundColor:'rgba(16,185,129,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations[`band_yellow_${idx}`] = { + type:'box', xMin, xMax, yMin:sp.p50_days, yMax:sp.p85_days, + backgroundColor:'rgba(245,158,11,.18)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations[`band_red_${idx}`] = { + type:'box', xMin, xMax, yMin:sp.p85_days, yMax:chartTop, + backgroundColor:'rgba(244,63,94,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations[`p50_line_${idx}`] = { + type:'line', xMin, xMax, yMin:sp.p50_days, yMax:sp.p50_days, + borderColor:'rgba(16,185,129,.85)', borderWidth:1.5, borderDash:[4,3], + label:{content:`P50 ${sp.p50_days.toFixed(1)}d`, display:true, position:sp.p50_days === sp.p85_days ? 'start' : 'end', color:'#6ee7b7', backgroundColor:'rgba(15,23,42,.75)', font:{size:10}, padding:2} + }; + annotations[`p85_line_${idx}`] = { + type:'line', xMin, xMax, yMin:sp.p85_days, yMax:sp.p85_days, + borderColor:'rgba(244,63,94,.9)', borderWidth:2, + label:{content:`P85 ${sp.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fda4af', backgroundColor:'rgba(15,23,42,.75)', font:{size:10}, padding:2} + }; + }); + } else { + if (aging.p50_days != null) { + annotations.band_green_global = { + type:'box', yMin:0, yMax:aging.p50_days, + backgroundColor:'rgba(16,185,129,.14)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations.p50line = { + type:'line', yMin:aging.p50_days, yMax:aging.p50_days, + borderColor:'rgba(16,185,129,.85)', borderWidth:1.5, borderDash:[5,4], + label:{content:`P50: ${aging.p50_days.toFixed(1)}d`, display:true, position:'end', color:'#6ee7b7', font:{size:11}} + }; + } + if (aging.p85_days != null) { + if (aging.p50_days != null) { + annotations.band_yellow_global = { + type:'box', yMin:aging.p50_days, yMax:aging.p85_days, + backgroundColor:'rgba(245,158,11,.16)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + } + annotations.band_red_global = { + type:'box', yMin:aging.p85_days, yMax:chartTop, + backgroundColor:'rgba(244,63,94,.14)', borderWidth:0, drawTime:'beforeDatasetsDraw', + }; + annotations.p85line = { + type:'line', yMin:aging.p85_days, yMax:aging.p85_days, + borderColor:'rgba(244,63,94,.9)', borderWidth:2, + label:{content:`P85: ${aging.p85_days.toFixed(1)}d`, display:true, position:'end', color:'#fda4af', font:{size:11}} + }; + } } + + const pointColors = aging.items.map(item => { + const sp = stageStats.get(item.stage); + const p50 = hasStagePercentiles ? sp?.p50_days : aging.p50_days; + const p85 = hasStagePercentiles ? sp?.p85_days : aging.p85_days; + if (p50 == null && p85 == null) return 'rgba(148,163,184,.95)'; + if (p85 != null && item.age_days > p85) return 'rgba(244,63,94,.95)'; + if (p50 != null && item.age_days > p50) return 'rgba(245,158,11,.95)'; + return 'rgba(16,185,129,.95)'; + }); + mkChart('chart-issue-age', { type: 'scatter', data: { @@ -1616,8 +1690,10 @@

Flowy AI Coach

datasets: [{ label: 'Open issues', data: aging.items.map(item => ({x: item.stage, y: item.age_days, identifier: item.identifier, title: item.title})), - backgroundColor: 'rgba(245,158,11,.8)', - pointRadius: 5, pointHoverRadius: 9, + backgroundColor: pointColors, + borderColor: '#f8fafc', + borderWidth: 1.25, + pointRadius: 5.5, pointHoverRadius: 9, }] }, options: { @@ -1629,14 +1705,18 @@

Flowy AI Coach

callbacks:{ label: ctx => { const d = ctx.raw; - return [`${d.identifier}: ${(d.title || '').slice(0, 50)}`, `${d.x} · ${d.y?.toFixed(1)} days`]; + const sp = stageStats.get(d.x); + const pace = sp && sp.p50_days != null && sp.p85_days != null + ? ` (stage P50 ${sp.p50_days.toFixed(1)}d · P85 ${sp.p85_days.toFixed(1)}d, n=${sp.n})` + : ''; + return [`${d.identifier}: ${(d.title || '').slice(0, 50)}`, `${d.x} · ${d.y?.toFixed(1)} days${pace}`]; } } } }, scales:{ - x:{ type:'category', labels: aging.stages, grid:{color:'rgba(255,255,255,.04)'} }, - y:{ grid:{color:'rgba(255,255,255,.04)'}, title:{display:true, text:'Age (days)', color:'#64748b'}, beginAtZero:true } + x:{ type:'category', labels: aging.stages, offset:true, grid:{color:'rgba(255,255,255,.04)'} }, + y:{ grid:{color:'rgba(255,255,255,.04)'}, title:{display:true, text:'Age since active start (days)', color:'#64748b'}, beginAtZero:true, max:chartTop } } } }); diff --git a/tests/frontend/charts.test.cjs b/tests/frontend/charts.test.cjs index acd2364..21384aa 100644 --- a/tests/frontend/charts.test.cjs +++ b/tests/frontend/charts.test.cjs @@ -117,10 +117,15 @@ test('renderIssues replaces weekly arrivals with CFD and age distribution with W coverage: { issues: 5, with_workflow_signal: 5 }, }, work_item_aging: { - stages: ['Todo', 'In Progress'], - items: [{ identifier: 'MAG-1', number: 1, title: 'Open task', stage: 'In Progress', age_days: 4.2 }], - p50_days: 2.0, - p85_days: 4.0, + stages: ['Specify', 'Spec Review', 'Build'], + items: [{ identifier: 'MAG-1', number: 1, title: 'Open task', stage: 'Spec Review', age_days: 9.5 }], + stage_percentiles: [ + { stage: 'Specify', n: 4, p50_days: 3.0, p85_days: 6.0 }, + { stage: 'Spec Review', n: 3, p50_days: 5.0, p85_days: 11.0 }, + { stage: 'Build', n: 0, p50_days: null, p85_days: null }, + ], + p50_days: 5.0, + p85_days: 11.0, }, }); @@ -129,6 +134,16 @@ test('renderIssues replaces weekly arrivals with CFD and age distribution with W assert.equal(drawn['chart-issue-flow'], undefined); assert.equal(els['issue-age-title'].textContent, 'Work Item Aging by Status'); assert.equal(drawn['chart-issue-age'].type, 'scatter'); - assert.deepEqual(Array.from(drawn['chart-issue-age'].options.scales.x.labels), ['Todo', 'In Progress']); - assert.deepEqual(Array.from(drawn['chart-issue-age'].data.labels), ['Todo', 'In Progress']); + assert.deepEqual(Array.from(drawn['chart-issue-age'].options.scales.x.labels), ['Specify', 'Spec Review', 'Build']); + assert.deepEqual(Array.from(drawn['chart-issue-age'].data.labels), ['Specify', 'Spec Review', 'Build']); + const ann = drawn['chart-issue-age'].options.plugins.annotation.annotations; + assert.equal(ann.band_green_1.yMin, 0); + assert.equal(ann.band_green_1.yMax, 5.0); + assert.equal(ann.band_yellow_1.yMin, 5.0); + assert.equal(ann.band_yellow_1.yMax, 11.0); + assert.equal(ann.band_red_1.yMin, 11.0); + assert.ok(ann.band_red_1.yMax > 11.0); + assert.equal(ann.p50_line_1.yMin, 5.0); + assert.equal(ann.p85_line_1.yMin, 11.0); + assert.equal(ann.band_green_2, undefined); }); diff --git a/tests/integration/test_private_issue_api.py b/tests/integration/test_private_issue_api.py index a3b5088..cc2f8de 100644 --- a/tests/integration/test_private_issue_api.py +++ b/tests/integration/test_private_issue_api.py @@ -236,3 +236,98 @@ async def __aenter__(self): return FakeAIClient() 'repo': 'o/r', 'analysis_id': 'original', 'message': 'Next?'}) assert response.status_code == 200 assert response.json()['reply'] == 'Throughput rose.' + + +def test_signed_in_web_analyze_uses_graphql_for_pr_size_and_spearman(monkeypatch): + client, _, cache, _ = setup(monkeypatch) + seen = {} + + async def repo_metadata(url, **kwargs): + return 200, {}, {'private': True, 'id': 9001, 'full_name': 'o/r'} + + async def fake_graphql(repo, token, private, repository_id, *, include_issues=True): + seen.update(repo=repo, token=token, private=private, repository_id=repository_id, include_issues=include_issues) + return { + 'repo': repo, + 'captured_at': '2026-11-23T12:00:00Z', + 'recent_prs': [ + {'number': 1, 'title': 'Small', 'body': '', 'createdAt': '2026-11-20T00:00:00Z', + 'mergedAt': '2026-11-20T02:00:00Z', 'closedAt': '2026-11-20T02:00:00Z', + 'additions': 10, 'deletions': 5, 'isDraft': False, + 'author': {'login': 'alice', '__typename': 'User'}, + 'closingIssuesReferences': {'nodes': []}, 'commits': {'totalCount': 1, 'nodes': []}, + 'reviews': {'totalCount': 0, 'nodes': []}, 'timelineItems': {'nodes': []}}, + {'number': 2, 'title': 'Large', 'body': '', 'createdAt': '2026-11-21T00:00:00Z', + 'mergedAt': '2026-11-21T10:00:00Z', 'closedAt': '2026-11-21T10:00:00Z', + 'additions': 200, 'deletions': 50, 'isDraft': False, + 'author': {'login': 'alice', '__typename': 'User'}, + 'closingIssuesReferences': {'nodes': []}, 'commits': {'totalCount': 2, 'nodes': []}, + 'reviews': {'totalCount': 0, 'nodes': []}, 'timelineItems': {'nodes': []}}, + ], + 'open_prs': [], + 'pre_ai_prs': [], + 'issues': {'open': [], 'closed': [], 'pre_ai': []}, + } + + async def assess(*_, **__): + return {'status': 'ok', 'items': []} + + monkeypatch.setattr(hosted, 'request_json', repo_metadata) + monkeypatch.setattr(hosted, 'collect_dashboard_data', fake_graphql) + monkeypatch.setattr(hosted, 'collect_public_data', lambda *a, **k: pytest.fail('REST fallback should not run when signed in')) + monkeypatch.setattr(hosted, 'assess_product_value', assess) + + response = client.post( + '/api/analyze', + headers={'Authorization': 'Bearer caller-a'}, + json={'repo_url': 'o/r', 'allow_private': True}, + ) + assert response.status_code == 200, response.text + body = response.json() + assert seen == {'repo': 'o/r', 'token': 'caller-a', 'private': True, 'repository_id': 9001, 'include_issues': True} + assert body['dashboard_source'] == 'github_graphql' + assert [p['x'] for p in body['pr_size_scatter_points']] == [15, 250] + assert body['spearman_corr'] == pytest.approx(1.0) + assert all(':private:1:' in key for key in cache.stored) + + +def test_signed_in_public_analyze_uses_separate_graphql_cache_key(monkeypatch): + client, _, cache, _ = setup(monkeypatch) + # Pre-seed anonymous REST cache entry without PR sizes + cache.stored[hosted.public_analysis_key('o/r', False)] = json.dumps({'repo': 'o/r', 'pr_size_scatter_points': [{'x': 0, 'y': 1}]}) + + async def public_metadata(url, **kwargs): + return 200, {}, {'private': False, 'id': 42, 'full_name': 'o/r'} + + async def fake_graphql(repo, token, private, repository_id, *, include_issues=True): + assert private is False and repository_id == 42 and token == 'caller-a' + return { + 'repo': repo, + 'captured_at': '2026-11-23T12:00:00Z', + 'recent_prs': [ + {'number': 1, 'title': 'PR', 'body': '', 'createdAt': '2026-11-20T00:00:00Z', + 'mergedAt': '2026-11-20T02:00:00Z', 'closedAt': '2026-11-20T02:00:00Z', + 'additions': 30, 'deletions': 10, 'isDraft': False, + 'author': {'login': 'alice', '__typename': 'User'}, + 'closingIssuesReferences': {'nodes': []}, 'commits': {'totalCount': 1, 'nodes': []}, + 'reviews': {'totalCount': 0, 'nodes': []}, 'timelineItems': {'nodes': []}}, + ], + 'open_prs': [], + 'pre_ai_prs': [], + 'issues': {'open': [], 'closed': [], 'pre_ai': []}, + } + + async def assess(*_, **__): + return {'status': 'ok', 'items': []} + + monkeypatch.setattr(hosted, 'request_json', public_metadata) + monkeypatch.setattr(hosted, 'collect_dashboard_data', fake_graphql) + monkeypatch.setattr(hosted, 'collect_public_data', lambda *a, **k: pytest.fail('REST fallback should not run')) + monkeypatch.setattr(hosted, 'assess_product_value', assess) + + response = client.post('/api/analyze', headers={'Authorization': 'Bearer caller-a'}, json={'repo_url': 'o/r'}) + assert response.status_code == 200, response.text + body = response.json() + assert body['dashboard_source'] == 'github_graphql' + assert body['pr_size_scatter_points'][0]['x'] == 40 + assert hosted.public_analysis_key('o/r', False, graphql=True) in cache.stored diff --git a/tests/unit/test_linear_issues.py b/tests/unit/test_linear_issues.py index 87493ba..57dbaed 100644 --- a/tests/unit/test_linear_issues.py +++ b/tests/unit/test_linear_issues.py @@ -546,4 +546,132 @@ def fake_gh(cmd, **kwargs): assert sync_found["team_key"] == "MAG" +@pytest.mark.unit +def test_work_item_aging_uses_active_start_and_cumulative_stage_exit_percentiles(): + now = datetime.datetime(2026, 11, 23, 0, 0) + weekly_bins = [now - datetime.timedelta(weeks=w) for w in range(8, -1, -1)] + linear_states = [ + {"name": "Backlog", "type": "backlog", "position": 0}, + {"name": "Next", "type": "unstarted", "position": 1}, + {"name": "Specify", "type": "started", "position": 2}, + {"name": "Spec Review", "type": "started", "position": 3}, + {"name": "Build", "type": "started", "position": 4}, + {"name": "Verify", "type": "started", "position": 5}, + {"name": "Done", "type": "completed", "position": 6}, + {"name": "Canceled", "type": "canceled", "position": 7}, + ] + + # Item A: 5d in Backlog, enters Specify on Nov 1 (active day 0), Spec Review on Nov 11 (day 10), + # finishes Spec Review -> Build on Nov 12 (day 11), Done on Nov 15 (day 14). + item_a = { + "number": 1, + "identifier": "MAG-1", + "title": "Item A", + "createdAt": "2026-10-27T00:00:00Z", + "startedAt": "2026-11-01T00:00:00Z", + "updatedAt": "2026-11-15T00:00:00Z", + "closedAt": "2026-11-15T00:00:00Z", + "state": "CLOSED", + "linearState": "Done", + "linearStateType": "completed", + "linearHistory": { + "hasNextPage": False, + "transitions": [ + {"createdAt": "2026-11-01T00:00:00Z", "fromState": "Backlog", "toState": "Specify", "fromType": "backlog", "toType": "started"}, + {"createdAt": "2026-11-11T00:00:00Z", "fromState": "Specify", "toState": "Spec Review", "fromType": "started", "toType": "started"}, + {"createdAt": "2026-11-12T00:00:00Z", "fromState": "Spec Review", "toState": "Build", "fromType": "started", "toType": "started"}, + {"createdAt": "2026-11-15T00:00:00Z", "fromState": "Build", "toState": "Done", "fromType": "started", "toType": "completed"}, + ], + }, + } + + # Item B: enters Specify on Nov 10 (active day 0), Spec Review on Nov 13 (day 3), + # finishes Spec Review -> Build on Nov 15 (day 5), still open in Build (active age 13d on Nov 23). + item_b = { + "number": 2, + "identifier": "MAG-2", + "title": "Item B", + "createdAt": "2026-11-01T00:00:00Z", + "startedAt": "2026-11-10T00:00:00Z", + "updatedAt": "2026-11-15T00:00:00Z", + "closedAt": None, + "state": "OPEN", + "linearState": "Build", + "linearStateType": "started", + "linearHistory": { + "hasNextPage": False, + "transitions": [ + {"createdAt": "2026-11-10T00:00:00Z", "fromState": "Backlog", "toState": "Specify", "fromType": "backlog", "toType": "started"}, + {"createdAt": "2026-11-13T00:00:00Z", "fromState": "Specify", "toState": "Spec Review", "fromType": "started", "toType": "started"}, + {"createdAt": "2026-11-15T00:00:00Z", "fromState": "Spec Review", "toState": "Build", "fromType": "started", "toType": "started"}, + ], + }, + } + + # Item C: still in Backlog — must be excluded from active aging chart + item_c = { + "number": 3, + "identifier": "MAG-3", + "title": "Backlog item", + "createdAt": "2026-10-01T00:00:00Z", + "updatedAt": "2026-10-01T00:00:00Z", + "closedAt": None, + "state": "OPEN", + "linearState": "Backlog", + "linearStateType": "backlog", + "linearHistory": {"hasNextPage": False, "transitions": []}, + } + + # Item D: canceled out of Spec Review — must not count as finishing Spec Review + item_d = { + "number": 4, + "identifier": "MAG-4", + "title": "Canceled item", + "createdAt": "2026-11-10T00:00:00Z", + "startedAt": "2026-11-10T00:00:00Z", + "updatedAt": "2026-11-11T00:00:00Z", + "closedAt": "2026-11-11T00:00:00Z", + "state": "CLOSED", + "linearState": "Canceled", + "linearStateType": "canceled", + "linearHistory": { + "hasNextPage": False, + "transitions": [ + {"createdAt": "2026-11-10T12:00:00Z", "fromState": "Specify", "toState": "Spec Review", "fromType": "started", "toType": "started"}, + {"createdAt": "2026-11-11T00:00:00Z", "fromState": "Spec Review", "toState": "Canceled", "fromType": "started", "toType": "canceled"}, + ], + }, + } + + metrics = issues_mod.compute_issue_metrics( + { + "source": "linear", + "linear_states": linear_states, + "open": [item_b, item_c], + "closed": [item_a, item_d], + "pre_ai": [], + }, + weekly_bins, + now, + ) + aging = metrics["work_item_aging"] + assert aging["start_basis"] == "active_work" + assert aging["stages"] == ["Specify", "Spec Review", "Build", "Verify"] + # Only active open item MAG-2 is plotted, with age from active start (Nov 10 -> Nov 23 = 13d), not createdAt (22d) + assert len(aging["items"]) == 1 + assert aging["items"][0]["identifier"] == "MAG-2" + assert aging["items"][0]["age_days"] == 13.0 + + by_stage = {sp["stage"]: sp for sp in aging["stage_percentiles"]} + # Spec Review exits: Item A = 11.0d (from active start, NOT 1d in stage), Item B = 5.0d; Item D canceled excluded + assert by_stage["Spec Review"]["n"] == 2 + assert by_stage["Spec Review"]["p50_days"] == 11.0 # upper-index on [5.0, 11.0] + assert by_stage["Spec Review"]["p85_days"] == 11.0 + # Build exits: only Item A finished Build -> Done at 14.0d + assert by_stage["Build"] == {"stage": "Build", "n": 1, "p50_days": 14.0, "p85_days": 14.0} + # Verify has no exits yet + assert by_stage["Verify"] == {"stage": "Verify", "n": 0, "p50_days": None, "p85_days": None} + + +