diff --git a/AGENTS.md b/AGENTS.md index d153963..a0a239e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,9 +17,11 @@ Code, Gemini, macOS, and Windows. Use the host's native skill invocation syntax. `ce-code-review`. Resolve justified findings within the authorized scope. - Capture verified, reusable, non-obvious lessons with `ce-compound` when its criteria apply. Routine changes do not need a learning document. -- Commit with `ce-commit` when requested. Use `ce-commit-push-pr` when publishing - is authorized; use `lfg` only when explicitly requested. Pushes, PR creation, - merges, deployments, and account changes require user authorization. +- Default to **LFG mode** unless the user indicates otherwise: once verification + and `ce-code-review` (or native adversarial subagent review) pass with no + unresolved blocking findings, proceed end-to-end — commit, push, open PR, + wait for CI, merge, prune the temporary worktree, and deploy. Account changes + and destructive operations still require user authorization. Keep work proportional to risk. Start with the smallest meaningful proof of behavior, implement it, then improve structure. Use existing tests and machinery diff --git a/index.html b/index.html index 9aba0bf..ef662eb 100644 --- a/index.html +++ b/index.html @@ -278,6 +278,26 @@ #value-section select { background: var(--card); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; margin: 8px 10px 8px 0; } #value-section label { white-space: nowrap; } + .item-link{color:#93c5fd;text-decoration:none;font-weight:600;} + .item-link:hover,.item-link:focus-visible{color:#c4b5fd;text-decoration:underline;} + .msg a{color:#93c5fd;text-decoration:underline;text-underline-offset:2px;} + .msg a:hover{color:#c4b5fd;} + .drilldown{margin-top:1rem;border-top:1px solid var(--border);padding-top:.75rem;} + .drilldown summary{cursor:pointer;font-size:.82rem;font-weight:600;color:#c4b5fd;user-select:none;list-style:none;display:inline-flex;align-items:center;gap:.4rem;} + html[data-theme="light"] .item-link,html[data-theme="light"] .msg a{color:#1d4ed8;} + html[data-theme="light"] .item-link:hover,html[data-theme="light"] .item-link:focus-visible,html[data-theme="light"] .msg a:hover{color:#4338ca;} + html[data-theme="light"] .drilldown summary{color:#5b21b6;} + .drilldown summary::-webkit-details-marker{display:none;} + .drilldown summary::before{content:'▸';display:inline-block;transition:transform .15s;} + .drilldown[open] summary::before{transform:rotate(90deg);} + .drilldown-controls{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin:.7rem 0 .5rem;font-size:.78rem;color:var(--text-dim);} + .drilldown-controls select{background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:4px 8px;font-size:.78rem;} + .drilldown-table-wrap{overflow-x:auto;max-height:260px;overflow-y:auto;} + .pace-pill{display:inline-block;padding:.1rem .45rem;border-radius:99px;font-size:.7rem;font-weight:600;white-space:nowrap;} + .pace-green{background:rgba(16,185,129,.16);color:#6ee7b7;} + .pace-yellow{background:rgba(245,158,11,.18);color:#fcd34d;} + .pace-red{background:rgba(244,63,94,.18);color:#fda4af;} + .pace-neutral{background:rgba(148,163,184,.16);color:#cbd5e1;} #value-section td { vertical-align: top; } #value-counts { min-width: 540px; } #value-items { min-width: 660px; } @@ -639,6 +659,15 @@

Throughput & Active WIP

Active WIP Age by Stage
+
@@ -683,6 +712,22 @@

Issue Flow & Backlog Health

Open Issue Age Distribution
+
@@ -1110,13 +1155,27 @@

Flowy AI Coach

// Shared dashboard renderer start // ── Dashboard Renderer ────────────────────────────────────────────── + let activeDashboardRepo = null; + const GITHUB_REPO_RE = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; + function renderDashboard(d) { + activeDashboardRepo = d?.repo && GITHUB_REPO_RE.test(d.repo) ? d.repo : null; document.getElementById('placeholder').style.display = 'none'; document.getElementById('dashboard').style.display = 'block'; - const linearLabel = d.linear_team?.key - ? ` + Linear: ${d.linear_team.key}${d.linear_team.name && d.linear_team.name.toLowerCase() !== d.linear_team.key.toLowerCase() ? ` (${d.linear_team.name})` : ''}` + const repoDisplay = document.getElementById('repo-name-display'); + const repoHref = activeDashboardRepo ? `https://github.com/${activeDashboardRepo}` : null; + const linearTeam = d.linear_team || d.issues?.linear_team || null; + const linearText = linearTeam?.key + ? `Linear: ${linearTeam.key}${linearTeam.name && linearTeam.name.toLowerCase() !== linearTeam.key.toLowerCase() ? ` (${linearTeam.name})` : ''}` + : ''; + const linearHref = safeExternalUrl(linearTeam?.url); + const repoHtml = repoHref + ? `${escapeHtml(d.repo)}` + : escapeHtml(d.repo || '—'); + const linearHtml = linearText + ? ` + ${linearHref ? `${escapeHtml(linearText)}` : escapeHtml(linearText)}` : ''; - document.getElementById('repo-name-display').textContent = `${d.repo}${linearLabel}`; + repoDisplay.innerHTML = repoHtml + linearHtml; for (const chart of Object.values(charts)) chart.destroy(); charts = {}; @@ -1134,13 +1193,13 @@

Flowy AI Coach

} if (hasPRs || hasOpenPRs) renderCFD(d.cfd_data); if (hasPRs) { - renderControlChart(d.recent_scatter_points, d.p50_sle, d.p85_sle); + renderControlChart(d.recent_scatter_points, d.p50_sle, d.p85_sle, activeDashboardRepo); renderThroughput(d.throughput_data); - renderCorrelation(d.pr_size_scatter_points, d.spearman_corr); - renderComet(d.comet_points); + renderCorrelation(d.pr_size_scatter_points, d.spearman_corr, activeDashboardRepo); + renderComet(d.comet_points, activeDashboardRepo); } - if (hasPRs || hasOpenPRs) renderWIP(d.active_wip_points, d.stage_percentiles); - renderIssues(d.issues, d.linear_detected); + renderWIP(d.active_wip_points, d.stage_percentiles, activeDashboardRepo); + renderIssues(d.issues, d.linear_detected, activeDashboardRepo); renderValueClassification(d.value_classification); renderProductValue(d.product_value); } @@ -1174,7 +1233,13 @@

Flowy AI Coach

dimensions.map(([, label]) => `${escapeHtml(label)}`).join('') + 'Cost of delay' + (value.items.map(item => { - const lead = `#${escapeHtml(item.number)} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.framing)}`; + const repo = typeof activeDashboardRepo === 'string' ? activeDashboardRepo : null; + const explicit = typeof safeExternalUrl === 'function' ? safeExternalUrl(item.url) : null; + const href = explicit || (repo && item.number ? `https://github.com/${repo}/pull/${item.number}` : null); + const ref = href + ? `#${escapeHtml(item.number)}` + : `#${escapeHtml(item.number)}`; + const lead = `${ref} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.framing)}`; if (item.status !== 'assessed') return lead + `Not scored: ${escapeHtml(item.reason || 'assessment unavailable')}.`; return lead + dimensions.map(([name]) => { const d = item.dimensions[name]; @@ -1212,7 +1277,17 @@

Flowy AI Coach

const group = valueClassification[kind]; const items = (group?.items || []).filter(item => !level || item.level === level); document.getElementById('value-items').innerHTML = 'ItemStateFramingRationale' + - (items.map(item => `#${escapeHtml(item.number)} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.level)}${escapeHtml(item.rationale)}${item.body_available ? '' : ' (Title only)'}`).join('') || + (items.map(item => { + const seg = kind === 'prs' ? 'pull' : 'issues'; + const repo = typeof activeDashboardRepo === 'string' ? activeDashboardRepo : null; + const explicit = typeof safeExternalUrl === 'function' ? safeExternalUrl(item.url) : null; + const href = explicit || (repo && item.number ? `https://github.com/${repo}/${seg}/${item.number}` : null); + const label = item.identifier || `#${item.number}`; + const ref = href + ? `${escapeHtml(label)}` + : escapeHtml(label); + return `${ref} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.level)}${escapeHtml(item.rationale)}${item.body_available ? '' : ' (Title only)'}`; + }).join('') || 'No items in this selection.') + ''; } @@ -1353,11 +1428,56 @@

Flowy AI Coach

return hours.toFixed(1) + 'h'; } + // ── External Link & Chart Helpers ───────────────────────────────── + function safeExternalUrl(url) { + if (typeof url !== 'string' || !url) return null; + try { + const parsed = new URL(url); + return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? parsed.href : null; + } catch { + return null; + } + } + + function chartPointUrl(chart, elements) { + if (!elements?.length) return null; + const el = elements[0]; + const raw = chart?.data?.datasets?.[el.datasetIndex]?.data?.[el.index]; + return safeExternalUrl(raw?.url); + } + // ── Destroy + Create Chart helpers ───────────────────────────────── function mkChart(id, config) { if (charts[id]) { charts[id].destroy(); } const ctx = document.getElementById(id); if (!ctx) return; + if (ctx.style) ctx.style.cursor = ''; + const hasPointUrls = Boolean(config?.data?.datasets?.some( + ds => Array.isArray(ds.data) && ds.data.some(pt => pt && typeof pt === 'object' && pt.url) + )); + if (hasPointUrls) { + config.options = config.options || {}; + if (!config.options.onHover) { + config.options.onHover = (event, elements, chart) => { + const target = event?.native?.target || chart?.canvas; + if (target?.style) target.style.cursor = chartPointUrl(chart, elements) ? 'pointer' : ''; + }; + } + if (!config.options.onClick) { + config.options.onClick = (_event, elements, chart) => { + const url = chartPointUrl(chart, elements); + if (url) window.open(url, '_blank', 'noopener,noreferrer'); + }; + } + config.options.plugins = config.options.plugins || {}; + config.options.plugins.tooltip = config.options.plugins.tooltip || {}; + config.options.plugins.tooltip.callbacks = config.options.plugins.tooltip.callbacks || {}; + if (!config.options.plugins.tooltip.callbacks.footer) { + config.options.plugins.tooltip.callbacks.footer = items => ( + safeExternalUrl(items?.[0]?.raw?.url) ? 'Click to open ↗' : '' + ); + } + } charts[id] = new Chart(ctx, config); } @@ -1407,9 +1527,10 @@

Flowy AI Coach

} // ── Control Chart ────────────────────────────────────────────────── - function renderControlChart(pts, p50, p85) { + function renderControlChart(pts, p50, p85, repo) { if (!pts || !pts.length) return; const sorted = pts.filter(p=>p.y !== null && p.y !== undefined).sort((a,b)=>a.x-b.x); + const prUrl = p => p.url || (repo && p.num ? `https://github.com/${repo}/pull/${p.num}` : null); const colors = { Human:'rgba(139,92,246,.75)', 'AI-Assisted':'rgba(6,182,212,.75)', 'AI-Agentic':'rgba(244,63,94,.75)' }; @@ -1418,7 +1539,7 @@

Flowy AI Coach

data: { datasets: ['Human','AI-Assisted','AI-Agentic'].map(cls => ({ label: cls, - data: sorted.filter(p=>p.classification===cls).map(p=>({x:p.x, y:p.y/24, num:p.num})), + data: sorted.filter(p=>p.classification===cls).map(p=>({x:p.x, y:p.y/24, num:p.num, url:prUrl(p)})), backgroundColor: colors[cls], pointRadius: 3, pointHoverRadius:6, })) @@ -1511,7 +1632,40 @@

Flowy AI Coach

}); } - function renderIssues(iss, linearDetected) { + let agingDrilldownState = null; + + function renderAgingDrilldown() { + if (!agingDrilldownState) return; + const table = document.getElementById('issue-age-drilldown-table'); + const stageEl = document.getElementById('issue-age-stage-filter'); + const paceEl = document.getElementById('issue-age-pace-filter'); + const countEl = document.getElementById('issue-age-drilldown-count'); + if (!table || !stageEl || !paceEl) return; + const stageFilter = stageEl.value; + const paceFilter = paceEl.value; + const filtered = agingDrilldownState.items.filter(item => + (!stageFilter || item.stage === stageFilter) && (!paceFilter || item.pace === paceFilter) + ); + if (countEl) countEl.textContent = `Showing ${filtered.length} of ${agingDrilldownState.items.length}`; + const paceMeta = { + red: ['Above P85', 'pace-red'], + yellow: ['P50–P85', 'pace-yellow'], + green: ['≤ P50', 'pace-green'], + neutral: ['No baseline', 'pace-neutral'], + }; + const rows = filtered.map(item => { + const [paceLabel, paceCls] = paceMeta[item.pace] || paceMeta.neutral; + const ref = item.url + ? `${escapeHtml(item.identifier)}` + : escapeHtml(item.identifier); + return `${ref}${escapeHtml(item.title || '')}${escapeHtml(item.stage)}${(Number(item.age_days) || 0).toFixed(1)}d${paceLabel}`; + }).join(''); + table.innerHTML = rows + ? `IssueTitleStageAgePace${rows}` + : 'No matching items.'; + } + + function renderIssues(iss, linearDetected, repo) { const sec = document.getElementById('issues-section'); sec.style.display = 'block'; const note = document.getElementById('issues-note'); @@ -1591,11 +1745,29 @@

Flowy AI Coach

} }); + const safeRepo = repo && /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repo) ? repo : null; + const issueUrl = item => { + const explicit = typeof safeExternalUrl === 'function' + ? safeExternalUrl(item?.url) + : (typeof item?.url === 'string' && /^https?:\/\//i.test(item.url) ? item.url : null); + if (explicit) return explicit; + if (iss.source === 'linear') { + if (iss.linear_team?.org && item?.identifier) { + return `https://linear.app/${encodeURIComponent(iss.linear_team.org)}/issue/${encodeURIComponent(item.identifier)}`; + } + return null; + } + if (safeRepo && item?.number) return `https://github.com/${safeRepo}/issues/${item.number}`; + return null; + }; + const aging = iss.work_item_aging; const hasAging = Boolean(aging?.items?.length && aging?.stages?.length); document.getElementById('issue-age-card').hidden = !hasAging && !iss.open_now; document.getElementById('issue-stale-card').hidden = !iss.open_now; const ageTitle = document.getElementById('issue-age-title'); + const agingDrilldown = document.getElementById('issue-age-drilldown'); + if (agingDrilldown) agingDrilldown.hidden = !hasAging; if (hasAging) { if (ageTitle) ageTitle.textContent = 'Work Item Aging by Status'; const annotations = {}; @@ -1673,15 +1845,27 @@

Flowy AI Coach

} } - const pointColors = aging.items.map(item => { + const itemPace = 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)'; - }); + if (p50 == null && p85 == null) return 'neutral'; + if (p85 != null && item.age_days > p85) return 'red'; + if (p50 != null && item.age_days > p50) return 'yellow'; + return 'green'; + }; + const paceColors = { + neutral: 'rgba(148,163,184,.95)', + red: 'rgba(244,63,94,.95)', + yellow: 'rgba(245,158,11,.95)', + green: 'rgba(16,185,129,.95)', + }; + const enrichedAgingItems = aging.items.map(item => ({ + ...item, + pace: itemPace(item), + url: issueUrl(item), + })); + const pointColors = enrichedAgingItems.map(item => paceColors[item.pace]); mkChart('chart-issue-age', { type: 'scatter', @@ -1689,7 +1873,13 @@

Flowy AI Coach

labels: aging.stages, datasets: [{ label: 'Open issues', - data: aging.items.map(item => ({x: item.stage, y: item.age_days, identifier: item.identifier, title: item.title})), + data: enrichedAgingItems.map(item => ({ + x: item.stage, + y: item.age_days, + identifier: item.identifier, + title: item.title, + url: item.url, + })), backgroundColor: pointColors, borderColor: '#f8fafc', borderWidth: 1.25, @@ -1720,7 +1910,27 @@

Flowy AI Coach

} } }); + + if (agingDrilldown) { + const sortedItems = [...enrichedAgingItems].sort((a, b) => (b.age_days || 0) - (a.age_days || 0)); + agingDrilldownState = { items: sortedItems }; + const summary = document.getElementById('issue-age-drilldown-summary'); + const overP85 = sortedItems.filter(i => i.pace === 'red').length; + if (summary) { + summary.textContent = `Inspect ${sortedItems.length} active item${sortedItems.length === 1 ? '' : 's'}${overP85 ? ` (${overP85} above P85)` : ''}`; + } + const stageFilter = document.getElementById('issue-age-stage-filter'); + if (stageFilter) { + stageFilter.innerHTML = '' + + aging.stages.map(s => ``).join(''); + stageFilter.value = ''; + } + const paceFilter = document.getElementById('issue-age-pace-filter'); + if (paceFilter) paceFilter.value = ''; + renderAgingDrilldown(); + } } else if (iss.open_now) { + agingDrilldownState = null; if (ageTitle) ageTitle.textContent = 'Open Issue Age Distribution'; mkChart('chart-issue-age', { type: 'bar', @@ -1738,9 +1948,14 @@

Flowy AI Coach

const basis = iss.stale_basis === 'updated' ? 'update' : 'comment'; document.getElementById('issue-stale-title').textContent = `Stale Issues (no ${basis} for over ${iss.stale.threshold_days} days)`; - const rows = iss.stale.items.map(i => - `${escapeHtml(i.identifier || ('#' + i.number))}${escapeHtml(i.title || '')}${Math.round(i.days_since_activity)}d idle${Math.round(i.age_days)}d old` - ).join(''); + const rows = iss.stale.items.map(i => { + const label = i.identifier || ('#' + i.number); + const href = issueUrl(i); + const ref = href + ? `${escapeHtml(label)}` + : escapeHtml(label); + return `${ref}${escapeHtml(i.title || '')}${Math.round(i.days_since_activity)}d idle${Math.round(i.age_days)}d old`; + }).join(''); document.getElementById('issue-stale-table').innerHTML = rows ? `IssueTitleIdleAge${rows}` : 'No stale issues.'; @@ -1773,10 +1988,51 @@

Flowy AI Coach

} // ── Active WIP Age ───────────────────────────────────────────────── - function renderWIP(pts, stagePct) { - if (!pts || !pts.length) return; + let wipDrilldownState = null; + + function renderWIPDrilldown() { + if (!wipDrilldownState || typeof document === 'undefined') return; + const table = document.getElementById('wip-drilldown-table'); + const stageEl = document.getElementById('wip-stage-filter'); + const countEl = document.getElementById('wip-drilldown-count'); + if (!table || !stageEl) return; + const esc = text => String(text).replace(/[&<>"']/g, ch => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch])); + const stageFilter = stageEl.value; + const filtered = wipDrilldownState.items.filter(item => !stageFilter || item.stage === stageFilter); + if (countEl) countEl.textContent = `Showing ${filtered.length} of ${wipDrilldownState.items.length}`; + const rows = filtered.map(item => { + const label = `PR #${item.num}`; + const ref = item.url + ? `${esc(label)}` + : esc(label); + return `${ref}${esc(item.title || '')}${esc(item.stage)}${esc(item.classification || '')}${(Number(item.age_days) || 0).toFixed(1)}d`; + }).join(''); + table.innerHTML = rows + ? `PRTitleStageAuthorAge${rows}` + : 'No matching open PRs.'; + } + + function renderWIP(pts, stagePct, repo) { + const wipDrilldown = typeof document !== 'undefined' ? document.getElementById('wip-drilldown') : null; + if (!pts || !pts.length) { + wipDrilldownState = null; + if (wipDrilldown) wipDrilldown.hidden = true; + return; + } const legacyMap = {'1. Active Coding':'Draft', '2. Review Queue':'In Review', '3. Merge Delay':'Approved'}; - const normalized = pts.map(p => ({...p, x: legacyMap[p.x] || p.x})); + const safeRepo = repo && /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repo) ? repo : null; + const safeUrl = url => { + if (typeof safeExternalUrl === 'function') return safeExternalUrl(url); + if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) return null; + try { + const parsed = new URL(url); + return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? parsed.href : null; + } catch { + return null; + } + }; + const prUrl = p => safeUrl(p.url) || (safeRepo && p.num ? `https://github.com/${safeRepo}/pull/${p.num}` : null); + const normalized = pts.map(p => ({...p, x: legacyMap[p.x] || p.x, url: prUrl(p)})); const hasDraft = normalized.some(p => p.x === 'Draft'); const stageOrder = hasDraft ? ['Draft', 'Opened', 'In Review', 'Approved'] : ['Opened', 'In Review', 'Approved']; const colors = { Human:'rgba(139,92,246,.8)', 'AI-Assisted':'rgba(6,182,212,.8)', 'AI-Agentic':'rgba(244,63,94,.8)' }; @@ -1787,7 +2043,7 @@

Flowy AI Coach

labels: stageOrder, datasets: ['Human','AI-Assisted','AI-Agentic'].map(cls => ({ label: cls, - data: normalized.filter(p=>p.classification===cls).map(p=>({x:p.x, y:p.y, title:p.title, num:p.num})), + data: normalized.filter(p=>p.classification===cls).map(p=>({x:p.x, y:p.y, title:p.title, num:p.num, url:p.url})), backgroundColor: colors[cls], pointRadius:5, pointHoverRadius:9, })) @@ -1811,10 +2067,28 @@

Flowy AI Coach

} } }); + + if (wipDrilldown) { + const esc = text => String(text).replace(/[&<>"']/g, ch => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch])); + const sorted = normalized + .map(p => ({ num: p.num, title: p.title, stage: p.x, classification: p.classification, age_days: p.y, url: p.url })) + .sort((a, b) => (Number(b.age_days) || 0) - (Number(a.age_days) || 0)); + wipDrilldownState = { items: sorted }; + wipDrilldown.hidden = false; + const summary = document.getElementById('wip-drilldown-summary'); + if (summary) summary.textContent = `Inspect ${sorted.length} open PR${sorted.length === 1 ? '' : 's'}`; + const stageFilter = document.getElementById('wip-stage-filter'); + if (stageFilter) { + stageFilter.innerHTML = '' + + stageOrder.map(s => ``).join(''); + stageFilter.value = ''; + } + renderWIPDrilldown(); + } } // ── Correlation Scatter ──────────────────────────────────────────── - function renderCorrelation(pts, corr) { + function renderCorrelation(pts, corr, repo) { const canvas = document.getElementById('chart-correlation'); const wrap = canvas?.parentElement; const note = document.getElementById('correlation-note'); @@ -1833,13 +2107,14 @@

Flowy AI Coach

note.textContent = ''; } const colors = { Human:'rgba(139,92,246,.65)', 'AI-Assisted':'rgba(6,182,212,.65)', 'AI-Agentic':'rgba(244,63,94,.65)' }; + const prUrl = p => p.url || (repo && p.num ? `https://github.com/${repo}/pull/${p.num}` : null); mkChart('chart-correlation', { type: 'scatter', data: { datasets: ['Human','AI-Assisted','AI-Agentic'].map(cls => ({ label: cls, - data: pts.filter(p=>p.classification===cls).map(p=>({x:Math.log10(Math.max(1,p.x)), y:p.y/24, num:p.num, title:p.title})), + data: pts.filter(p=>p.classification===cls).map(p=>({x:Math.log10(Math.max(1,p.x)), y:p.y/24, num:p.num, title:p.title, url:prUrl(p)})), backgroundColor: colors[cls], pointRadius:3.5, pointHoverRadius:7, })) @@ -1868,7 +2143,7 @@

Flowy AI Coach

} // ── Comet Chart ──────────────────────────────────────────────────── - function renderComet(pts) { + function renderComet(pts, repo) { if (!pts || !pts.length) return; // Only render recent 300 items to keep it readable @@ -1876,6 +2151,7 @@

Flowy AI Coach

const maxLane = Math.max(...recent.map(p=>p.lane)); const spanDays = (Math.max(...recent.map(p=>p.end)) - Math.min(...recent.map(p=>p.start))) / 86400000; const colors = { Human:'rgba(139,92,246,.7)', 'AI-Assisted':'rgba(6,182,212,.7)', 'AI-Agentic':'rgba(244,63,94,.7)' }; + const prUrl = p => p.url || (repo && p.key ? `https://github.com/${repo}/pull/${p.key}` : null); // Transform to scatter datasets where each point is (midpoint_ts, lane) // with a custom draw to show horizontal bars @@ -1887,6 +2163,7 @@

Flowy AI Coach

start: p.start, end: p.end, key: p.key, summary: p.summary, size: p.size, cycle_time: p.cycle_time, classification: cls, + url: prUrl(p), })), backgroundColor: colors[cls], pointStyle: 'rect', @@ -1987,9 +2264,46 @@

Flowy AI Coach

else if (role === 'user') chatHistory.push({ role: 'user', content }); } + function linkifyChatRefs(html) { + const repo = currentRepo && GITHUB_REPO_RE.test(currentRepo) ? currentRepo : null; + const linearTeam = currentMetrics?.linear_team || currentMetrics?.issues?.linear_team || null; + const linearOrg = linearTeam?.org || null; + const linearKey = linearTeam?.key && /^[A-Za-z0-9]+$/.test(linearTeam.key) ? linearTeam.key : null; + const linearRegex = linearOrg && linearKey ? new RegExp(`\\b(${linearKey}-\\d+)\\b`, 'g') : null; + return html.split(/(]*>[\s\S]*?<\/a>|]*>[\s\S]*?<\/code>|<[^>]+>)/g).map((part, idx) => { + if (idx % 2 === 1) return part; + let out = part; + if (linearRegex) { + out = out.replace(linearRegex, id => { + const href = `https://linear.app/${encodeURIComponent(linearOrg)}/issue/${encodeURIComponent(id)}`; + return `${id}`; + }); + } + if (repo) { + out = out.replace(/\b(PR|pull request)\s+#(\d+)\b|(^|[\s([,:])#(\d+)\b/gi, (m, prWord, prNum, lead, issueNum) => { + if (prWord) { + const href = `https://github.com/${repo}/pull/${prNum}`; + return `${prWord} #${prNum}`; + } + const href = `https://github.com/${repo}/issues/${issueNum}`; + return `${lead}#${issueNum}`; + }); + } + return out; + }).join(''); + } + function simpleMarkdown(text) { - return text + const mdLinks = []; + const withLinkTokens = text .replace(/&/g,'&').replace(//g,'>') + .replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (_m, label, href) => { + const safe = safeExternalUrl(href.replace(/&/g, '&')); + if (!safe) return label; + const idx = mdLinks.push(`${label}`) - 1; + return `\u0000MDLINK${idx}\u0000`; + }); + const rendered = withLinkTokens .replace(/\*\*(.+?)\*\*/g,'$1') .replace(/`(.+?)`/g,'$1') .replace(/^### (.+)$/gm,'

$1

') @@ -1998,7 +2312,9 @@

Flowy AI Coach

.replace(/(
  • .*<\/li>)/gs, m => `
      ${m}
    `) .replace(/\n{2,}/g,'

    ') .replace(/\n/g,'
    ') - .replace(/^(?!<[hup])/,'

    ').replace(/(?])$/,'

    '); + .replace(/^(?!<[hup])/,'

    ').replace(/(?])$/,'

    ') + .replace(/\u0000MDLINK(\d+)\u0000/g, (_m, i) => mdLinks[Number(i)] || ''); + return linkifyChatRefs(rendered); } async function sendChat() { diff --git a/issues.py b/issues.py index ee0364f..090ee0b 100644 --- a/issues.py +++ b/issues.py @@ -876,13 +876,16 @@ def _compute_linear_work_item_aging(open_issues, closed_issues, issues_raw, now, if stage not in aging_stages: aging_stages.append(stage) stage_exit_ages.setdefault(stage, []) - aging_items.append({ + aging_item = { "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), - }) + } + if issue.get("url"): + aging_item["url"] = issue["url"] + aging_items.append(aging_item) last_exit_by_stage = {} is_completed = issue.get("state") == "CLOSED" and state_types.get(issue.get("linearState")) != "canceled" diff --git a/public/index.html b/public/index.html index 9aba0bf..ef662eb 100644 --- a/public/index.html +++ b/public/index.html @@ -278,6 +278,26 @@ #value-section select { background: var(--card); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; margin: 8px 10px 8px 0; } #value-section label { white-space: nowrap; } + .item-link{color:#93c5fd;text-decoration:none;font-weight:600;} + .item-link:hover,.item-link:focus-visible{color:#c4b5fd;text-decoration:underline;} + .msg a{color:#93c5fd;text-decoration:underline;text-underline-offset:2px;} + .msg a:hover{color:#c4b5fd;} + .drilldown{margin-top:1rem;border-top:1px solid var(--border);padding-top:.75rem;} + .drilldown summary{cursor:pointer;font-size:.82rem;font-weight:600;color:#c4b5fd;user-select:none;list-style:none;display:inline-flex;align-items:center;gap:.4rem;} + html[data-theme="light"] .item-link,html[data-theme="light"] .msg a{color:#1d4ed8;} + html[data-theme="light"] .item-link:hover,html[data-theme="light"] .item-link:focus-visible,html[data-theme="light"] .msg a:hover{color:#4338ca;} + html[data-theme="light"] .drilldown summary{color:#5b21b6;} + .drilldown summary::-webkit-details-marker{display:none;} + .drilldown summary::before{content:'▸';display:inline-block;transition:transform .15s;} + .drilldown[open] summary::before{transform:rotate(90deg);} + .drilldown-controls{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin:.7rem 0 .5rem;font-size:.78rem;color:var(--text-dim);} + .drilldown-controls select{background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:4px 8px;font-size:.78rem;} + .drilldown-table-wrap{overflow-x:auto;max-height:260px;overflow-y:auto;} + .pace-pill{display:inline-block;padding:.1rem .45rem;border-radius:99px;font-size:.7rem;font-weight:600;white-space:nowrap;} + .pace-green{background:rgba(16,185,129,.16);color:#6ee7b7;} + .pace-yellow{background:rgba(245,158,11,.18);color:#fcd34d;} + .pace-red{background:rgba(244,63,94,.18);color:#fda4af;} + .pace-neutral{background:rgba(148,163,184,.16);color:#cbd5e1;} #value-section td { vertical-align: top; } #value-counts { min-width: 540px; } #value-items { min-width: 660px; } @@ -639,6 +659,15 @@

    Throughput & Active WIP

    Active WIP Age by Stage
    +
  • @@ -683,6 +712,22 @@

    Issue Flow & Backlog Health

    Open Issue Age Distribution
    +
    @@ -1110,13 +1155,27 @@

    Flowy AI Coach

    // Shared dashboard renderer start // ── Dashboard Renderer ────────────────────────────────────────────── + let activeDashboardRepo = null; + const GITHUB_REPO_RE = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; + function renderDashboard(d) { + activeDashboardRepo = d?.repo && GITHUB_REPO_RE.test(d.repo) ? d.repo : null; document.getElementById('placeholder').style.display = 'none'; document.getElementById('dashboard').style.display = 'block'; - const linearLabel = d.linear_team?.key - ? ` + Linear: ${d.linear_team.key}${d.linear_team.name && d.linear_team.name.toLowerCase() !== d.linear_team.key.toLowerCase() ? ` (${d.linear_team.name})` : ''}` + const repoDisplay = document.getElementById('repo-name-display'); + const repoHref = activeDashboardRepo ? `https://github.com/${activeDashboardRepo}` : null; + const linearTeam = d.linear_team || d.issues?.linear_team || null; + const linearText = linearTeam?.key + ? `Linear: ${linearTeam.key}${linearTeam.name && linearTeam.name.toLowerCase() !== linearTeam.key.toLowerCase() ? ` (${linearTeam.name})` : ''}` + : ''; + const linearHref = safeExternalUrl(linearTeam?.url); + const repoHtml = repoHref + ? `${escapeHtml(d.repo)}` + : escapeHtml(d.repo || '—'); + const linearHtml = linearText + ? ` + ${linearHref ? `${escapeHtml(linearText)}` : escapeHtml(linearText)}` : ''; - document.getElementById('repo-name-display').textContent = `${d.repo}${linearLabel}`; + repoDisplay.innerHTML = repoHtml + linearHtml; for (const chart of Object.values(charts)) chart.destroy(); charts = {}; @@ -1134,13 +1193,13 @@

    Flowy AI Coach

    } if (hasPRs || hasOpenPRs) renderCFD(d.cfd_data); if (hasPRs) { - renderControlChart(d.recent_scatter_points, d.p50_sle, d.p85_sle); + renderControlChart(d.recent_scatter_points, d.p50_sle, d.p85_sle, activeDashboardRepo); renderThroughput(d.throughput_data); - renderCorrelation(d.pr_size_scatter_points, d.spearman_corr); - renderComet(d.comet_points); + renderCorrelation(d.pr_size_scatter_points, d.spearman_corr, activeDashboardRepo); + renderComet(d.comet_points, activeDashboardRepo); } - if (hasPRs || hasOpenPRs) renderWIP(d.active_wip_points, d.stage_percentiles); - renderIssues(d.issues, d.linear_detected); + renderWIP(d.active_wip_points, d.stage_percentiles, activeDashboardRepo); + renderIssues(d.issues, d.linear_detected, activeDashboardRepo); renderValueClassification(d.value_classification); renderProductValue(d.product_value); } @@ -1174,7 +1233,13 @@

    Flowy AI Coach

    dimensions.map(([, label]) => `${escapeHtml(label)}`).join('') + 'Cost of delay' + (value.items.map(item => { - const lead = `#${escapeHtml(item.number)} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.framing)}`; + const repo = typeof activeDashboardRepo === 'string' ? activeDashboardRepo : null; + const explicit = typeof safeExternalUrl === 'function' ? safeExternalUrl(item.url) : null; + const href = explicit || (repo && item.number ? `https://github.com/${repo}/pull/${item.number}` : null); + const ref = href + ? `#${escapeHtml(item.number)}` + : `#${escapeHtml(item.number)}`; + const lead = `${ref} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.framing)}`; if (item.status !== 'assessed') return lead + `Not scored: ${escapeHtml(item.reason || 'assessment unavailable')}.`; return lead + dimensions.map(([name]) => { const d = item.dimensions[name]; @@ -1212,7 +1277,17 @@

    Flowy AI Coach

    const group = valueClassification[kind]; const items = (group?.items || []).filter(item => !level || item.level === level); document.getElementById('value-items').innerHTML = 'ItemStateFramingRationale' + - (items.map(item => `#${escapeHtml(item.number)} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.level)}${escapeHtml(item.rationale)}${item.body_available ? '' : ' (Title only)'}`).join('') || + (items.map(item => { + const seg = kind === 'prs' ? 'pull' : 'issues'; + const repo = typeof activeDashboardRepo === 'string' ? activeDashboardRepo : null; + const explicit = typeof safeExternalUrl === 'function' ? safeExternalUrl(item.url) : null; + const href = explicit || (repo && item.number ? `https://github.com/${repo}/${seg}/${item.number}` : null); + const label = item.identifier || `#${item.number}`; + const ref = href + ? `${escapeHtml(label)}` + : escapeHtml(label); + return `${ref} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.level)}${escapeHtml(item.rationale)}${item.body_available ? '' : ' (Title only)'}`; + }).join('') || 'No items in this selection.') + ''; } @@ -1353,11 +1428,56 @@

    Flowy AI Coach

    return hours.toFixed(1) + 'h'; } + // ── External Link & Chart Helpers ───────────────────────────────── + function safeExternalUrl(url) { + if (typeof url !== 'string' || !url) return null; + try { + const parsed = new URL(url); + return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? parsed.href : null; + } catch { + return null; + } + } + + function chartPointUrl(chart, elements) { + if (!elements?.length) return null; + const el = elements[0]; + const raw = chart?.data?.datasets?.[el.datasetIndex]?.data?.[el.index]; + return safeExternalUrl(raw?.url); + } + // ── Destroy + Create Chart helpers ───────────────────────────────── function mkChart(id, config) { if (charts[id]) { charts[id].destroy(); } const ctx = document.getElementById(id); if (!ctx) return; + if (ctx.style) ctx.style.cursor = ''; + const hasPointUrls = Boolean(config?.data?.datasets?.some( + ds => Array.isArray(ds.data) && ds.data.some(pt => pt && typeof pt === 'object' && pt.url) + )); + if (hasPointUrls) { + config.options = config.options || {}; + if (!config.options.onHover) { + config.options.onHover = (event, elements, chart) => { + const target = event?.native?.target || chart?.canvas; + if (target?.style) target.style.cursor = chartPointUrl(chart, elements) ? 'pointer' : ''; + }; + } + if (!config.options.onClick) { + config.options.onClick = (_event, elements, chart) => { + const url = chartPointUrl(chart, elements); + if (url) window.open(url, '_blank', 'noopener,noreferrer'); + }; + } + config.options.plugins = config.options.plugins || {}; + config.options.plugins.tooltip = config.options.plugins.tooltip || {}; + config.options.plugins.tooltip.callbacks = config.options.plugins.tooltip.callbacks || {}; + if (!config.options.plugins.tooltip.callbacks.footer) { + config.options.plugins.tooltip.callbacks.footer = items => ( + safeExternalUrl(items?.[0]?.raw?.url) ? 'Click to open ↗' : '' + ); + } + } charts[id] = new Chart(ctx, config); } @@ -1407,9 +1527,10 @@

    Flowy AI Coach

    } // ── Control Chart ────────────────────────────────────────────────── - function renderControlChart(pts, p50, p85) { + function renderControlChart(pts, p50, p85, repo) { if (!pts || !pts.length) return; const sorted = pts.filter(p=>p.y !== null && p.y !== undefined).sort((a,b)=>a.x-b.x); + const prUrl = p => p.url || (repo && p.num ? `https://github.com/${repo}/pull/${p.num}` : null); const colors = { Human:'rgba(139,92,246,.75)', 'AI-Assisted':'rgba(6,182,212,.75)', 'AI-Agentic':'rgba(244,63,94,.75)' }; @@ -1418,7 +1539,7 @@

    Flowy AI Coach

    data: { datasets: ['Human','AI-Assisted','AI-Agentic'].map(cls => ({ label: cls, - data: sorted.filter(p=>p.classification===cls).map(p=>({x:p.x, y:p.y/24, num:p.num})), + data: sorted.filter(p=>p.classification===cls).map(p=>({x:p.x, y:p.y/24, num:p.num, url:prUrl(p)})), backgroundColor: colors[cls], pointRadius: 3, pointHoverRadius:6, })) @@ -1511,7 +1632,40 @@

    Flowy AI Coach

    }); } - function renderIssues(iss, linearDetected) { + let agingDrilldownState = null; + + function renderAgingDrilldown() { + if (!agingDrilldownState) return; + const table = document.getElementById('issue-age-drilldown-table'); + const stageEl = document.getElementById('issue-age-stage-filter'); + const paceEl = document.getElementById('issue-age-pace-filter'); + const countEl = document.getElementById('issue-age-drilldown-count'); + if (!table || !stageEl || !paceEl) return; + const stageFilter = stageEl.value; + const paceFilter = paceEl.value; + const filtered = agingDrilldownState.items.filter(item => + (!stageFilter || item.stage === stageFilter) && (!paceFilter || item.pace === paceFilter) + ); + if (countEl) countEl.textContent = `Showing ${filtered.length} of ${agingDrilldownState.items.length}`; + const paceMeta = { + red: ['Above P85', 'pace-red'], + yellow: ['P50–P85', 'pace-yellow'], + green: ['≤ P50', 'pace-green'], + neutral: ['No baseline', 'pace-neutral'], + }; + const rows = filtered.map(item => { + const [paceLabel, paceCls] = paceMeta[item.pace] || paceMeta.neutral; + const ref = item.url + ? `${escapeHtml(item.identifier)}` + : escapeHtml(item.identifier); + return `${ref}${escapeHtml(item.title || '')}${escapeHtml(item.stage)}${(Number(item.age_days) || 0).toFixed(1)}d${paceLabel}`; + }).join(''); + table.innerHTML = rows + ? `IssueTitleStageAgePace${rows}` + : 'No matching items.'; + } + + function renderIssues(iss, linearDetected, repo) { const sec = document.getElementById('issues-section'); sec.style.display = 'block'; const note = document.getElementById('issues-note'); @@ -1591,11 +1745,29 @@

    Flowy AI Coach

    } }); + const safeRepo = repo && /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repo) ? repo : null; + const issueUrl = item => { + const explicit = typeof safeExternalUrl === 'function' + ? safeExternalUrl(item?.url) + : (typeof item?.url === 'string' && /^https?:\/\//i.test(item.url) ? item.url : null); + if (explicit) return explicit; + if (iss.source === 'linear') { + if (iss.linear_team?.org && item?.identifier) { + return `https://linear.app/${encodeURIComponent(iss.linear_team.org)}/issue/${encodeURIComponent(item.identifier)}`; + } + return null; + } + if (safeRepo && item?.number) return `https://github.com/${safeRepo}/issues/${item.number}`; + return null; + }; + const aging = iss.work_item_aging; const hasAging = Boolean(aging?.items?.length && aging?.stages?.length); document.getElementById('issue-age-card').hidden = !hasAging && !iss.open_now; document.getElementById('issue-stale-card').hidden = !iss.open_now; const ageTitle = document.getElementById('issue-age-title'); + const agingDrilldown = document.getElementById('issue-age-drilldown'); + if (agingDrilldown) agingDrilldown.hidden = !hasAging; if (hasAging) { if (ageTitle) ageTitle.textContent = 'Work Item Aging by Status'; const annotations = {}; @@ -1673,15 +1845,27 @@

    Flowy AI Coach

    } } - const pointColors = aging.items.map(item => { + const itemPace = 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)'; - }); + if (p50 == null && p85 == null) return 'neutral'; + if (p85 != null && item.age_days > p85) return 'red'; + if (p50 != null && item.age_days > p50) return 'yellow'; + return 'green'; + }; + const paceColors = { + neutral: 'rgba(148,163,184,.95)', + red: 'rgba(244,63,94,.95)', + yellow: 'rgba(245,158,11,.95)', + green: 'rgba(16,185,129,.95)', + }; + const enrichedAgingItems = aging.items.map(item => ({ + ...item, + pace: itemPace(item), + url: issueUrl(item), + })); + const pointColors = enrichedAgingItems.map(item => paceColors[item.pace]); mkChart('chart-issue-age', { type: 'scatter', @@ -1689,7 +1873,13 @@

    Flowy AI Coach

    labels: aging.stages, datasets: [{ label: 'Open issues', - data: aging.items.map(item => ({x: item.stage, y: item.age_days, identifier: item.identifier, title: item.title})), + data: enrichedAgingItems.map(item => ({ + x: item.stage, + y: item.age_days, + identifier: item.identifier, + title: item.title, + url: item.url, + })), backgroundColor: pointColors, borderColor: '#f8fafc', borderWidth: 1.25, @@ -1720,7 +1910,27 @@

    Flowy AI Coach

    } } }); + + if (agingDrilldown) { + const sortedItems = [...enrichedAgingItems].sort((a, b) => (b.age_days || 0) - (a.age_days || 0)); + agingDrilldownState = { items: sortedItems }; + const summary = document.getElementById('issue-age-drilldown-summary'); + const overP85 = sortedItems.filter(i => i.pace === 'red').length; + if (summary) { + summary.textContent = `Inspect ${sortedItems.length} active item${sortedItems.length === 1 ? '' : 's'}${overP85 ? ` (${overP85} above P85)` : ''}`; + } + const stageFilter = document.getElementById('issue-age-stage-filter'); + if (stageFilter) { + stageFilter.innerHTML = '' + + aging.stages.map(s => ``).join(''); + stageFilter.value = ''; + } + const paceFilter = document.getElementById('issue-age-pace-filter'); + if (paceFilter) paceFilter.value = ''; + renderAgingDrilldown(); + } } else if (iss.open_now) { + agingDrilldownState = null; if (ageTitle) ageTitle.textContent = 'Open Issue Age Distribution'; mkChart('chart-issue-age', { type: 'bar', @@ -1738,9 +1948,14 @@

    Flowy AI Coach

    const basis = iss.stale_basis === 'updated' ? 'update' : 'comment'; document.getElementById('issue-stale-title').textContent = `Stale Issues (no ${basis} for over ${iss.stale.threshold_days} days)`; - const rows = iss.stale.items.map(i => - `${escapeHtml(i.identifier || ('#' + i.number))}${escapeHtml(i.title || '')}${Math.round(i.days_since_activity)}d idle${Math.round(i.age_days)}d old` - ).join(''); + const rows = iss.stale.items.map(i => { + const label = i.identifier || ('#' + i.number); + const href = issueUrl(i); + const ref = href + ? `${escapeHtml(label)}` + : escapeHtml(label); + return `${ref}${escapeHtml(i.title || '')}${Math.round(i.days_since_activity)}d idle${Math.round(i.age_days)}d old`; + }).join(''); document.getElementById('issue-stale-table').innerHTML = rows ? `IssueTitleIdleAge${rows}` : 'No stale issues.'; @@ -1773,10 +1988,51 @@

    Flowy AI Coach

    } // ── Active WIP Age ───────────────────────────────────────────────── - function renderWIP(pts, stagePct) { - if (!pts || !pts.length) return; + let wipDrilldownState = null; + + function renderWIPDrilldown() { + if (!wipDrilldownState || typeof document === 'undefined') return; + const table = document.getElementById('wip-drilldown-table'); + const stageEl = document.getElementById('wip-stage-filter'); + const countEl = document.getElementById('wip-drilldown-count'); + if (!table || !stageEl) return; + const esc = text => String(text).replace(/[&<>"']/g, ch => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch])); + const stageFilter = stageEl.value; + const filtered = wipDrilldownState.items.filter(item => !stageFilter || item.stage === stageFilter); + if (countEl) countEl.textContent = `Showing ${filtered.length} of ${wipDrilldownState.items.length}`; + const rows = filtered.map(item => { + const label = `PR #${item.num}`; + const ref = item.url + ? `${esc(label)}` + : esc(label); + return `${ref}${esc(item.title || '')}${esc(item.stage)}${esc(item.classification || '')}${(Number(item.age_days) || 0).toFixed(1)}d`; + }).join(''); + table.innerHTML = rows + ? `PRTitleStageAuthorAge${rows}` + : 'No matching open PRs.'; + } + + function renderWIP(pts, stagePct, repo) { + const wipDrilldown = typeof document !== 'undefined' ? document.getElementById('wip-drilldown') : null; + if (!pts || !pts.length) { + wipDrilldownState = null; + if (wipDrilldown) wipDrilldown.hidden = true; + return; + } const legacyMap = {'1. Active Coding':'Draft', '2. Review Queue':'In Review', '3. Merge Delay':'Approved'}; - const normalized = pts.map(p => ({...p, x: legacyMap[p.x] || p.x})); + const safeRepo = repo && /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repo) ? repo : null; + const safeUrl = url => { + if (typeof safeExternalUrl === 'function') return safeExternalUrl(url); + if (typeof url !== 'string' || !/^https?:\/\//i.test(url)) return null; + try { + const parsed = new URL(url); + return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? parsed.href : null; + } catch { + return null; + } + }; + const prUrl = p => safeUrl(p.url) || (safeRepo && p.num ? `https://github.com/${safeRepo}/pull/${p.num}` : null); + const normalized = pts.map(p => ({...p, x: legacyMap[p.x] || p.x, url: prUrl(p)})); const hasDraft = normalized.some(p => p.x === 'Draft'); const stageOrder = hasDraft ? ['Draft', 'Opened', 'In Review', 'Approved'] : ['Opened', 'In Review', 'Approved']; const colors = { Human:'rgba(139,92,246,.8)', 'AI-Assisted':'rgba(6,182,212,.8)', 'AI-Agentic':'rgba(244,63,94,.8)' }; @@ -1787,7 +2043,7 @@

    Flowy AI Coach

    labels: stageOrder, datasets: ['Human','AI-Assisted','AI-Agentic'].map(cls => ({ label: cls, - data: normalized.filter(p=>p.classification===cls).map(p=>({x:p.x, y:p.y, title:p.title, num:p.num})), + data: normalized.filter(p=>p.classification===cls).map(p=>({x:p.x, y:p.y, title:p.title, num:p.num, url:p.url})), backgroundColor: colors[cls], pointRadius:5, pointHoverRadius:9, })) @@ -1811,10 +2067,28 @@

    Flowy AI Coach

    } } }); + + if (wipDrilldown) { + const esc = text => String(text).replace(/[&<>"']/g, ch => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch])); + const sorted = normalized + .map(p => ({ num: p.num, title: p.title, stage: p.x, classification: p.classification, age_days: p.y, url: p.url })) + .sort((a, b) => (Number(b.age_days) || 0) - (Number(a.age_days) || 0)); + wipDrilldownState = { items: sorted }; + wipDrilldown.hidden = false; + const summary = document.getElementById('wip-drilldown-summary'); + if (summary) summary.textContent = `Inspect ${sorted.length} open PR${sorted.length === 1 ? '' : 's'}`; + const stageFilter = document.getElementById('wip-stage-filter'); + if (stageFilter) { + stageFilter.innerHTML = '' + + stageOrder.map(s => ``).join(''); + stageFilter.value = ''; + } + renderWIPDrilldown(); + } } // ── Correlation Scatter ──────────────────────────────────────────── - function renderCorrelation(pts, corr) { + function renderCorrelation(pts, corr, repo) { const canvas = document.getElementById('chart-correlation'); const wrap = canvas?.parentElement; const note = document.getElementById('correlation-note'); @@ -1833,13 +2107,14 @@

    Flowy AI Coach

    note.textContent = ''; } const colors = { Human:'rgba(139,92,246,.65)', 'AI-Assisted':'rgba(6,182,212,.65)', 'AI-Agentic':'rgba(244,63,94,.65)' }; + const prUrl = p => p.url || (repo && p.num ? `https://github.com/${repo}/pull/${p.num}` : null); mkChart('chart-correlation', { type: 'scatter', data: { datasets: ['Human','AI-Assisted','AI-Agentic'].map(cls => ({ label: cls, - data: pts.filter(p=>p.classification===cls).map(p=>({x:Math.log10(Math.max(1,p.x)), y:p.y/24, num:p.num, title:p.title})), + data: pts.filter(p=>p.classification===cls).map(p=>({x:Math.log10(Math.max(1,p.x)), y:p.y/24, num:p.num, title:p.title, url:prUrl(p)})), backgroundColor: colors[cls], pointRadius:3.5, pointHoverRadius:7, })) @@ -1868,7 +2143,7 @@

    Flowy AI Coach

    } // ── Comet Chart ──────────────────────────────────────────────────── - function renderComet(pts) { + function renderComet(pts, repo) { if (!pts || !pts.length) return; // Only render recent 300 items to keep it readable @@ -1876,6 +2151,7 @@

    Flowy AI Coach

    const maxLane = Math.max(...recent.map(p=>p.lane)); const spanDays = (Math.max(...recent.map(p=>p.end)) - Math.min(...recent.map(p=>p.start))) / 86400000; const colors = { Human:'rgba(139,92,246,.7)', 'AI-Assisted':'rgba(6,182,212,.7)', 'AI-Agentic':'rgba(244,63,94,.7)' }; + const prUrl = p => p.url || (repo && p.key ? `https://github.com/${repo}/pull/${p.key}` : null); // Transform to scatter datasets where each point is (midpoint_ts, lane) // with a custom draw to show horizontal bars @@ -1887,6 +2163,7 @@

    Flowy AI Coach

    start: p.start, end: p.end, key: p.key, summary: p.summary, size: p.size, cycle_time: p.cycle_time, classification: cls, + url: prUrl(p), })), backgroundColor: colors[cls], pointStyle: 'rect', @@ -1987,9 +2264,46 @@

    Flowy AI Coach

    else if (role === 'user') chatHistory.push({ role: 'user', content }); } + function linkifyChatRefs(html) { + const repo = currentRepo && GITHUB_REPO_RE.test(currentRepo) ? currentRepo : null; + const linearTeam = currentMetrics?.linear_team || currentMetrics?.issues?.linear_team || null; + const linearOrg = linearTeam?.org || null; + const linearKey = linearTeam?.key && /^[A-Za-z0-9]+$/.test(linearTeam.key) ? linearTeam.key : null; + const linearRegex = linearOrg && linearKey ? new RegExp(`\\b(${linearKey}-\\d+)\\b`, 'g') : null; + return html.split(/(]*>[\s\S]*?<\/a>|]*>[\s\S]*?<\/code>|<[^>]+>)/g).map((part, idx) => { + if (idx % 2 === 1) return part; + let out = part; + if (linearRegex) { + out = out.replace(linearRegex, id => { + const href = `https://linear.app/${encodeURIComponent(linearOrg)}/issue/${encodeURIComponent(id)}`; + return `${id}`; + }); + } + if (repo) { + out = out.replace(/\b(PR|pull request)\s+#(\d+)\b|(^|[\s([,:])#(\d+)\b/gi, (m, prWord, prNum, lead, issueNum) => { + if (prWord) { + const href = `https://github.com/${repo}/pull/${prNum}`; + return `${prWord} #${prNum}`; + } + const href = `https://github.com/${repo}/issues/${issueNum}`; + return `${lead}#${issueNum}`; + }); + } + return out; + }).join(''); + } + function simpleMarkdown(text) { - return text + const mdLinks = []; + const withLinkTokens = text .replace(/&/g,'&').replace(//g,'>') + .replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (_m, label, href) => { + const safe = safeExternalUrl(href.replace(/&/g, '&')); + if (!safe) return label; + const idx = mdLinks.push(`${label}`) - 1; + return `\u0000MDLINK${idx}\u0000`; + }); + const rendered = withLinkTokens .replace(/\*\*(.+?)\*\*/g,'$1') .replace(/`(.+?)`/g,'$1') .replace(/^### (.+)$/gm,'

    $1

    ') @@ -1998,7 +2312,9 @@

    Flowy AI Coach

    .replace(/(
  • .*<\/li>)/gs, m => `
      ${m}
    `) .replace(/\n{2,}/g,'

    ') .replace(/\n/g,'
    ') - .replace(/^(?!<[hup])/,'

    ').replace(/(?])$/,'

    '); + .replace(/^(?!<[hup])/,'

    ').replace(/(?])$/,'

    ') + .replace(/\u0000MDLINK(\d+)\u0000/g, (_m, i) => mdLinks[Number(i)] || ''); + return linkifyChatRefs(rendered); } async function sendChat() { diff --git a/tests/frontend/charts.test.cjs b/tests/frontend/charts.test.cjs index 21384aa..75b3032 100644 --- a/tests/frontend/charts.test.cjs +++ b/tests/frontend/charts.test.cjs @@ -146,4 +146,188 @@ test('renderIssues replaces weekly arrivals with CFD and age distribution with W 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); + assert.equal(drawn['chart-issue-age'].data.datasets[0].data[0].url, null); +}); + +test('mkChart wires hover cursor, click-to-open new tab, and tooltip hint for safe point URLs', () => { + const snippet = extractRenderer(' // ── External Link & Chart Helpers', ' // ── Shared Chart Defaults'); + const opened = []; + let createdConfig = null; + const ctx = { + URL, + charts: {}, + document: { getElementById: () => ({ id: 'c' }) }, + window: { open: (...args) => opened.push(args) }, + Chart: function(_el, cfg) { createdConfig = cfg; this.destroy = () => {}; }, + }; + vm.runInNewContext(`${snippet}\nthis.mkChart = mkChart;`, ctx); + + ctx.mkChart('chart-test', { + type: 'scatter', + data: { + datasets: [{ + data: [ + { x: 1, y: 2, url: 'https://linear.app/org/issue/MAG-1' }, + { x: 2, y: 3, url: 'javascript:alert(1)' }, + ], + }], + }, + options: {}, + }); + + const fakeCanvas = { style: { cursor: '' } }; + const fakeChart = { canvas: fakeCanvas, data: createdConfig.data }; + + createdConfig.options.onHover({ native: { target: fakeCanvas } }, [{ datasetIndex: 0, index: 0 }], fakeChart); + assert.equal(fakeCanvas.style.cursor, 'pointer'); + + createdConfig.options.onHover({ native: { target: fakeCanvas } }, [{ datasetIndex: 0, index: 1 }], fakeChart); + assert.equal(fakeCanvas.style.cursor, ''); + + createdConfig.options.onClick({}, [{ datasetIndex: 0, index: 0 }], fakeChart); + createdConfig.options.onClick({}, [{ datasetIndex: 0, index: 1 }], fakeChart); + assert.deepEqual(opened, [['https://linear.app/org/issue/MAG-1', '_blank', 'noopener,noreferrer']]); + + assert.equal(createdConfig.options.plugins.tooltip.callbacks.footer([{ raw: createdConfig.data.datasets[0].data[0] }]), 'Click to open ↗'); + assert.equal(createdConfig.options.plugins.tooltip.callbacks.footer([{ raw: createdConfig.data.datasets[0].data[1] }]), ''); +}); + +test('PR charts and issue tables/drilldowns attach clickable external links', () => { + const wipSnippet = extractRenderer(' // ── Active WIP Age', ' // ── Correlation Scatter'); + const wipEls = { + 'wip-drilldown': { hidden: true }, + 'wip-drilldown-summary': { textContent: '' }, + 'wip-stage-filter': { innerHTML: '', value: '' }, + 'wip-drilldown-count': { textContent: '' }, + 'wip-drilldown-table': { innerHTML: '' }, + }; + let wipCfg = null; + const wipCtx = { + URL, + document: { getElementById: id => wipEls[id] || null }, + mkChart: (_id, cfg) => { wipCfg = cfg; }, + }; + vm.runInNewContext(`${wipSnippet}\nthis.renderWIP = renderWIP; this.renderWIPDrilldown = renderWIPDrilldown;`, wipCtx); + wipCtx.renderWIP([ + { x: 'In Review', y: 4.2, num: 42, title: 'Fix flow', classification: 'Human' }, + { x: 'Opened', y: 1.0, num: 43, title: 'Add tests', classification: 'AI-Assisted', url: 'javascript:alert(1)' }, + ], null, 'acme/app'); + assert.equal(wipCfg.data.datasets[0].data[0].url, 'https://github.com/acme/app/pull/42'); + assert.equal(wipCfg.data.datasets[1].data[0].url, 'https://github.com/acme/app/pull/43'); + assert.doesNotMatch(wipEls['wip-drilldown-table'].innerHTML, /javascript:/i); + assert.equal(wipEls['wip-drilldown'].hidden, false); + assert.match(wipEls['wip-drilldown-table'].innerHTML, /href="https:\/\/github\.com\/acme\/app\/pull\/42" target="_blank" rel="noopener noreferrer">PR #42<\/a>/); + wipEls['wip-stage-filter'].value = 'Opened'; + wipCtx.renderWIPDrilldown(); + assert.equal(wipEls['wip-drilldown-count'].textContent, 'Showing 1 of 2'); + assert.doesNotMatch(wipEls['wip-drilldown-table'].innerHTML, /PR #42/); + + const issueSnippet = extractRenderer(' // ── Issues', ' // ── Throughput Chart'); + const issueEls = { + 'issues-section': { style: {} }, + 'issues-note': { textContent: '' }, + 'issue-details': { hidden: true }, + 'linear-connect-banner': { hidden: true, textContent: '' }, + 'issue-lifecycle-card': { hidden: true }, + 'issue-cfd-note': { textContent: '' }, + 'issue-flow-card': { hidden: false }, + 'issue-age-card': { hidden: true }, + 'issue-age-title': { textContent: '' }, + 'issue-age-drilldown': { hidden: true }, + 'issue-age-drilldown-summary': { textContent: '' }, + 'issue-age-stage-filter': { innerHTML: '', value: '' }, + 'issue-age-pace-filter': { value: '' }, + 'issue-age-drilldown-count': { textContent: '' }, + 'issue-age-drilldown-table': { innerHTML: '' }, + 'issue-stale-card': { hidden: true }, + 'issue-stale-title': { textContent: '' }, + 'issue-stale-table': { innerHTML: '' }, + }; + const drawn = {}; + const issueCtx = { + document: { getElementById: id => issueEls[id] || null }, + mkChart: (id, cfg) => { drawn[id] = cfg; }, + fmt_days: h => `${h}h`, + window: { parent: null }, + }; + issueCtx.window.parent = issueCtx.window; + vm.runInNewContext(`${issueSnippet}\nthis.renderIssues = renderIssues; this.renderAgingDrilldown = renderAgingDrilldown;`, issueCtx); + issueCtx.renderIssues({ + source: 'linear', + linear_team: { key: 'MAG', org: 'magnitude' }, + sample_size: 2, + open_available: true, + closed_available: true, + open_now: 2, + cycle_time: { modern: { n: 1, median_hours: 24, p85_hours: 48 } }, + weekly: [], + age_buckets: [], + stale: { + threshold_days: 14, + items: [{ identifier: 'MAG-9', number: 9, title: 'Old item', days_since_activity: 20, age_days: 30, url: 'https://linear.app/magnitude/issue/MAG-9' }], + }, + work_item_aging: { + stages: ['Spec Review'], + items: [ + { identifier: 'MAG-1', number: 1, title: 'Slow spec', stage: 'Spec Review', age_days: 14, url: 'https://linear.app/magnitude/issue/MAG-1' }, + { identifier: 'MAG-2', number: 2, title: 'Fast spec', stage: 'Spec Review', age_days: 2 }, + ], + stage_percentiles: [{ stage: 'Spec Review', n: 5, p50_days: 4, p85_days: 10 }], + p50_days: 4, + p85_days: 10, + }, + }, null, 'acme/app'); + assert.equal(drawn['chart-issue-age'].data.datasets[0].data[0].url, 'https://linear.app/magnitude/issue/MAG-1'); + assert.equal(drawn['chart-issue-age'].data.datasets[0].data[1].url, 'https://linear.app/magnitude/issue/MAG-2'); + assert.match(issueEls['issue-stale-table'].innerHTML, /href="https:\/\/linear\.app\/magnitude\/issue\/MAG-9" target="_blank" rel="noopener noreferrer">MAG-9<\/a>/); + assert.equal(issueEls['issue-age-drilldown'].hidden, false); + assert.match(issueEls['issue-age-drilldown-summary'].textContent, /1 above P85/); + issueEls['issue-age-pace-filter'].value = 'red'; + issueCtx.renderAgingDrilldown(); + assert.equal(issueEls['issue-age-drilldown-count'].textContent, 'Showing 1 of 2'); + assert.match(issueEls['issue-age-drilldown-table'].innerHTML, /MAG-1/); + assert.doesNotMatch(issueEls['issue-age-drilldown-table'].innerHTML, /MAG-2/); + + // Linear items without org or explicit url must NOT fall back to GitHub issue URLs + issueCtx.renderIssues({ + source: 'linear', + linear_team: { key: 'MAG' }, + sample_size: 1, + open_available: true, + closed_available: true, + open_now: 1, + cycle_time: { modern: { n: 0 } }, + weekly: [], + age_buckets: [], + stale: { threshold_days: 14, items: [] }, + work_item_aging: { + stages: ['Build'], + items: [{ identifier: 'MAG-5', number: 5, title: 'No org', stage: 'Build', age_days: 3 }], + stage_percentiles: [], + }, + }, null, 'acme/app'); + assert.equal(drawn['chart-issue-age'].data.datasets[0].data[0].url, null); +}); + +test('simpleMarkdown and linkifyChatRefs link PRs, issues, Linear IDs without nested anchors or code mangling', () => { + const helpers = extractRenderer(' // ── External Link & Chart Helpers', ' // ── Destroy + Create Chart helpers'); + const escSnippet = extractRenderer(' function escapeHtml(', ' function renderIssueLifecycle('); + const mdSnippet = extractRenderer(' function linkifyChatRefs(', ' async function sendChat('); + const ctx = { + URL, + GITHUB_REPO_RE: /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/, + currentRepo: 'acme/app', + currentMetrics: { linear_team: { key: 'MAG', org: 'magnitude' } }, + }; + vm.runInNewContext(`${helpers}\n${escSnippet}\n${mdSnippet}\nthis.simpleMarkdown = simpleMarkdown;`, ctx); + + const out = ctx.simpleMarkdown('Check PR #42, #12, MAG-7, `PR #99`, &#39; and [doc](https://example.com/a**b**c) and [bad](javascript:alert(1)).'); + assert.match(out, /PR #42<\/a>/); + assert.doesNotMatch(out, /]*>PR #12<\/a>/); + assert.match(out, /MAG-7<\/a>/); + assert.match(out, /PR #99<\/code>/); + assert.doesNotMatch(out, /issues\/39/); + assert.match(out, /doc<\/a>/); + assert.doesNotMatch(out, /href="javascript:/i); }); diff --git a/tests/unit/test_linear_issues.py b/tests/unit/test_linear_issues.py index 57dbaed..8613307 100644 --- a/tests/unit/test_linear_issues.py +++ b/tests/unit/test_linear_issues.py @@ -591,6 +591,7 @@ def test_work_item_aging_uses_active_start_and_cumulative_stage_exit_percentiles "number": 2, "identifier": "MAG-2", "title": "Item B", + "url": "https://linear.app/magnitude/issue/MAG-2/item-b", "createdAt": "2026-11-01T00:00:00Z", "startedAt": "2026-11-10T00:00:00Z", "updatedAt": "2026-11-15T00:00:00Z", @@ -661,6 +662,7 @@ def test_work_item_aging_uses_active_start_and_cumulative_stage_exit_percentiles assert len(aging["items"]) == 1 assert aging["items"][0]["identifier"] == "MAG-2" assert aging["items"][0]["age_days"] == 13.0 + assert aging["items"][0]["url"] == "https://linear.app/magnitude/issue/MAG-2/item-b" 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