Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
from analyze import collect_data, compute_flow_metrics
from linear_issues import LinearError, parse_linear_team
from product_value import assess_product_value
from jev_patterns import analyze_patterns_and_framing

# ---------------------------------------------------------------------------
# App Setup
Expand Down Expand Up @@ -137,10 +138,13 @@ def _run_analysis(repo: str, force: bool, gemini_key=None, jev_key=None, *,
metrics = compute_flow_metrics(raw)
metrics["repository_visibility"] = "private" if is_private else "public"
value_kwargs = {"allow_private": True} if is_private else {}
resolved_jev_key = jev_key or os.environ.get("TYPESAFE_API_KEY") or os.environ.get("JEV_API_KEY")
metrics["product_value"] = asyncio.run(assess_product_value(
repo, raw, gemini_key or _get_gemini_key(), os.environ.get("GITHUB_TOKEN"),
jev_key=jev_key or os.environ.get("TYPESAFE_API_KEY") or os.environ.get("JEV_API_KEY"),
jev_key=resolved_jev_key,
**value_kwargs))
metrics["pattern_insights"] = asyncio.run(analyze_patterns_and_framing(
repo, raw, metrics, jev_key=resolved_jev_key, allow_private=is_private))
return metrics


Expand Down Expand Up @@ -191,6 +195,7 @@ def _build_system_prompt(metrics: dict) -> str:
"These describe stated intent, not achieved outcomes. Keyword rules can misclassify; missing bodies limit evidence.\n"
+ value.get("scope", "") + "\n" + "\n".join(value_lines) + "\n")
issue_block = _build_issue_block(metrics.get("issues"))
pattern_block = _build_pattern_block(metrics.get("pattern_insights"))

return f"""You are **Flowy AI Coach**, an expert in software engineering flow metrics,
Value Stream Mapping, and the Theory of Constraints. You help engineering teams use data to improve
Expand Down Expand Up @@ -228,12 +233,30 @@ def _build_system_prompt(metrics: dict) -> str:
### Sample of Recent PRs
{pr_list_str or " No recent PR data available"}

{issue_block}{value_block}Answer questions about this data with specific, actionable coaching insights.
{issue_block}{value_block}{pattern_block}Answer questions about this data with specific, actionable coaching insights.
Reference specific PR numbers or metric values when relevant.
Keep answers concise but insightful. Use markdown formatting.
"""


def _build_pattern_block(patterns: Optional[dict]) -> str:
"""Prompt section for Jev-classified flow and item patterns."""
if not patterns or patterns.get("status") != "ok":
return ""
lines = []
for fp in patterns.get("flow_patterns") or []:
if fp.get("matched"):
pct = f"{fp['probability'] * 100:.0f}%" if fp.get("probability") is not None else "?"
lines.append(f"- Flow pattern [{fp['label']}] ({pct}): {fp['coaching_hint']}")
for ip in patterns.get("item_patterns") or []:
if ip.get("matched_count"):
items = ", ".join(f"#{m['number']}" for m in (ip.get("matched_items") or [])[:4])
lines.append(f"- Item pattern [{ip['label']}] ({ip['matched_count']}/{ip['sampled_count']}): {items} — {ip['coaching_hint']}")
if not lines:
return ""
return "\n### Jev-Classified Insight Patterns\n" + "\n".join(lines) + "\n"


def _build_issue_block(issues: Optional[dict]) -> str:
"""Prompt section for the Issues analytics; empty string when issues are unavailable."""
if not issues:
Expand Down
7 changes: 6 additions & 1 deletion cloudflare_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from github_api import request_json
from google_auth import verify_id_token
from product_value import assess_product_value, assess_issue_value
from jev_patterns import analyze_patterns_and_framing
import github_auth
import linear_auth
from issue_candidates import collect_issue_candidates
Expand Down Expand Up @@ -603,6 +604,10 @@ async def analyze_for_identity(req, request, identity, *, full_dashboard=False):
await assess_product_value(repo, raw, gemini_key, token, jev_key=jev_key, **options)
if metrics.get("recent_stats", {}).get("total") or raw.get("open_prs") else None
)
if metrics.get("recent_stats", {}).get("total") or raw.get("open_prs") or raw.get("issues"):
metrics["pattern_insights"] = await analyze_patterns_and_framing(repo, raw, metrics, jev_key=jev_key, allow_private=private)
else:
metrics["pattern_insights"] = None
if private or ((caller_keys or is_linear) and identity):
if not full_dashboard:
metrics['analysis_id'] = secrets.token_urlsafe(24)
Expand Down Expand Up @@ -807,7 +812,7 @@ async def chat_for_identity(req, request, identity, *, full_dashboard=False):
for m in req.history if m.role in ("user", "assistant")]
contents.append({"role": "user", "parts": [{"text": req.message}]})
body = {"system_instruction": {"parts": [{"text": prompt}]}, "contents": contents,
"generationConfig": {"temperature": 0.4, "maxOutputTokens": 700}}
"generationConfig": {"temperature": 0.4, "maxOutputTokens": 700, "thinkingConfig": {"thinkingLevel": "low"}}}
try:
async with httpx.AsyncClient(timeout=25) as client:
response = await client.post(
Expand Down
101 changes: 93 additions & 8 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -754,11 +754,24 @@ <h2>Issue Flow &amp; Backlog Health</h2>
<div style="overflow-x:auto;max-height:420px"><table class="issue-table" id="value-items"></table></div>
</div>
<div class="chart-card charts-full" id="product-value-card" style="display:none">
<div class="chart-title">Expected cost of delay (PRs)</div>
<div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
<div class="chart-title" style="margin:0">Expected cost of delay (PRs)</div>
<button type="button" id="refresh-context-btn" class="secondary-btn" onclick="refreshProductContext()" style="padding:6px 12px;font-size:12px">Refresh context</button>
</div>
<p class="issue-note" id="product-value-note"></p>
<details id="product-value-diagnostics" class="issue-note" style="margin:8px 0;display:none">
<summary>Troubleshooting &amp; diagnostics</summary>
<div id="product-value-diagnostics-body" style="margin-top:6px"></div>
</details>
<div id="product-value-context"></div>
<div style="overflow-x:auto;max-height:520px"><table class="issue-table" id="product-value-items"></table></div>
</div>
<div class="chart-card charts-full" id="pattern-insights-card" style="display:none">
<div class="chart-title">Jev pattern insights</div>
<p class="issue-note" id="pattern-insights-note"></p>
<div id="pattern-insights-flow" style="margin-bottom:12px"></div>
<div style="overflow-x:auto;max-height:420px"><table class="issue-table" id="pattern-insights-items"></table></div>
</div>
</section>

</div><!-- /dashboard -->
Expand Down Expand Up @@ -1071,7 +1084,9 @@ <h3>Flowy AI Coach</h3>
btn.disabled = true;
btn.classList.add('loading');
clearStatus();
const loadingMessage = savedRepository ? 'Reopening your last repository…' : 'Fetching repository data… this may take 30–60 seconds';
const loadingMessage = savedRepository?.forceRefresh
? 'Refreshing product context and re-scoring…'
: savedRepository ? 'Reopening your last repository…' : 'Fetching repository data… this may take 30–60 seconds';
if (document.getElementById('settings-dialog').open) {
showStatus(loadingMessage);
} else {
Expand All @@ -1082,18 +1097,19 @@ <h3>Flowy AI Coach</h3>
try {
const headers = {'Content-Type':'application/json'};
if (preferenceKey) headers['X-Analysis-Account'] = preferenceKey;
if (!savedRepository) {
if (!savedRepository || savedRepository.forceRefresh) {
for (const [id, header] of [['linear-key', 'X-Linear-Api-Key'], ['typesafe-key', 'X-TypeSafe-Api-Key'], ['gemini-key', 'X-Gemini-Api-Key']]) {
const key = document.getElementById(id)?.value?.trim();
if (key) headers[header] = key;
}
}
const linearTeamInput = document.getElementById('linear-team-input');
const linearTeam = savedRepository ? undefined : (linearTeamInput?.value?.trim() || undefined);
const isSavedRestore = Boolean(savedRepository && !savedRepository.forceRefresh);
const linearTeam = isSavedRestore ? undefined : (linearTeamInput?.value?.trim() || undefined);
const consentChecked = document.getElementById('allow-private').checked;
const allowPrivate = savedRepository?.private
?? (consentChecked && (!restoredPrivateRepository || input === restoredPrivateRepository));
const payload = { repo_url: input, force_refresh: false, allow_private: allowPrivate };
const payload = { repo_url: input, force_refresh: Boolean(savedRepository?.forceRefresh), allow_private: allowPrivate };
if (linearTeam) payload.linear_team_url = linearTeam;
response = await fetch('/api/analyze', {
method: 'POST',
Expand Down Expand Up @@ -1145,7 +1161,7 @@ <h3>Flowy AI Coach</h3>
if (savedRepository && response && ![401, 403, 409].includes(response.status) && !repoInput.value) {
repoInput.value = input;
}
showStatus(savedRepository ? `Could not reopen your last repository. ${e.message}` : `Error: ${e.message}`, 'error');
showStatus(savedRepository && !savedRepository.forceRefresh ? `Could not reopen your last repository. ${e.message}` : `Error: ${e.message}`, 'error');
} finally {
btn.disabled = false;
btn.classList.remove('loading');
Expand Down Expand Up @@ -1202,6 +1218,46 @@ <h3>Flowy AI Coach</h3>
renderIssues(d.issues, d.linear_detected, activeDashboardRepo);
renderValueClassification(d.value_classification);
renderProductValue(d.product_value);
renderPatternInsights(d.pattern_insights);
}

function refreshProductContext() {
if (!currentRepo) return;
analyzeRepo({
repo: currentRepo,
private: currentMetrics?.repository_visibility === 'private',
forceRefresh: true,
});
}

function renderPatternInsights(patterns) {
const card = document.getElementById('pattern-insights-card');
if (!card) return;
card.style.display = patterns ? 'block' : 'none';
if (!patterns) return;
const note = document.getElementById('pattern-insights-note');
const flowEl = document.getElementById('pattern-insights-flow');
const table = document.getElementById('pattern-insights-items');
if (patterns.status !== 'ok') {
note.textContent = patterns.reason || 'Pattern insights unavailable.';
flowEl.innerHTML = '';
table.innerHTML = '';
return;
}
note.textContent = `Catalog ${patterns.catalog_version} via ${patterns.model}. Sampled ${patterns.assessed_items} of ${patterns.sampled_items} work items in ${patterns.elapsed_ms}ms.`;
const matchedFlow = (patterns.flow_patterns || []).filter(p => p.matched);
flowEl.innerHTML = matchedFlow.length
? '<p><strong>Detected flow patterns:</strong></p><ul>' + matchedFlow.map(p =>
`<li><strong>${escapeHtml(p.label)}</strong> (${(p.probability * 100).toFixed(0)}%) — ${escapeHtml(p.coaching_hint)}</li>`
).join('') + '</ul>'
: '<p class="issue-note">No system-level flow anti-patterns exceeded the detection threshold.</p>';
const rows = (patterns.item_patterns || []).map(p => {
const examples = (p.matched_items || []).map(m => `#${escapeHtml(m.number)} (${(m.probability * 100).toFixed(0)}%)`).join(', ') || '—';
return `<tr><td><strong>${escapeHtml(p.label)}</strong><br><span class="issue-note">${escapeHtml(p.description)}</span></td>` +
`<td>${escapeHtml(p.matched_count)} / ${escapeHtml(p.sampled_count)}</td>` +
`<td>${examples}</td><td>${escapeHtml(p.coaching_hint)}</td></tr>`;
}).join('');
table.innerHTML = '<thead><tr><th>Pattern</th><th>Matched</th><th>Sampled items</th><th>Coaching action</th></tr></thead><tbody>' + rows + '</tbody>';
}

function renderProductValue(value) {
Expand All @@ -1211,16 +1267,44 @@ <h3>Flowy AI Coach</h3>
const note = document.getElementById('product-value-note');
const contextEl = document.getElementById('product-value-context');
const table = document.getElementById('product-value-items');
const diagBox = document.getElementById('product-value-diagnostics');
const diagBody = document.getElementById('product-value-diagnostics-body');
if (diagBox && diagBody) {
const diag = value.diagnostics;
if (!diag && value.status === 'ok') {
diagBox.style.display = 'none';
diagBody.innerHTML = '';
} else {
diagBox.style.display = 'block';
diagBox.open = value.status !== 'ok' || Boolean(diag?.fallback_used);
const d = diag || {};
const parts = [
d.stage && `<strong>Stage:</strong> ${escapeHtml(d.stage)}`,
d.context_method && `<strong>Context method:</strong> ${escapeHtml(d.context_method)}`,
d.error_code && `<strong>Error code:</strong> ${escapeHtml(d.error_code)}`,
d.fallback_used && `<strong>Fallback reason:</strong> ${escapeHtml(d.fallback_reason || 'unknown')}`,
d.http_status && `<strong>Provider HTTP:</strong> ${escapeHtml(d.http_status)}`,
d.context_elapsed_ms != null && `<strong>Context time:</strong> ${escapeHtml(d.context_elapsed_ms)}ms`,
d.total_elapsed_ms != null && `<strong>Total time:</strong> ${escapeHtml(d.total_elapsed_ms)}ms`,
Array.isArray(d.sources_loaded) && d.sources_loaded.length && `<strong>Sources loaded:</strong> ${d.sources_loaded.map(s => escapeHtml(s)).join(', ')}`,
Array.isArray(d.limitations) && d.limitations.length && `<strong>Limitations:</strong> ${d.limitations.map(l => escapeHtml(l)).join(' · ')}`,
].filter(Boolean);
diagBody.innerHTML = parts.length ? parts.join(' &nbsp;|&nbsp; ') : 'No additional diagnostics recorded.';
}
}
if (value.status !== 'ok') {
note.textContent = `Not assessed: ${value.reason || 'unavailable.'} ${value.disclaimer}`;
contextEl.innerHTML = '';
table.innerHTML = '';
return;
}
const sources = value.sources || {};
const contextLabel = value.context_method === 'evidence_fallback'
? `raw repository evidence fallback (${value.fallback_reason || 'gemini_unavailable'})`
: (value.context_model || value.context_method || 'repository context');
note.textContent = `${value.disclaimer} Assessed ${value.assessed} of ${value.selected} selected PRs` +
(value.failed ? ` (${value.failed} failed)` : '') +
`. Scores: ${value.model}; product context: ${value.context_model}. ` +
`. Scores: ${value.model}; product context: ${contextLabel}. ` +
`Context from ${[sources.description && 'description', sources.readme && (sources.readme_truncated ? 'README (truncated)' : 'README')].filter(Boolean).join(' and ') || 'repository metadata'}.`;
const ctx = value.context || {};
const goals = (ctx.strategic_goals || []).map(goal => `<li>${escapeHtml(goal)}</li>`).join('');
Expand Down Expand Up @@ -1261,7 +1345,8 @@ <h3>Flowy AI Coach</h3>
const selected = filter.value;
filter.innerHTML = '<option value="">All</option>' + value.levels.map(level => `<option>${escapeHtml(level)}</option>`).join('');
filter.value = value.levels.includes(selected) ? selected : '';
document.getElementById('value-note').textContent = value.scope + ' Rule-based classification. ' +
const methodLabel = value.method === 'jev' ? 'Jev-assisted classification. ' : 'Rule-based classification. ';
document.getElementById('value-note').textContent = value.scope + ' ' + methodLabel +
groups.map(([name, group]) => group ? `${name}: ${group.total} sampled, ${group.body_available} with bodies available, ${group.defaulted} defaulted.` : `${name}: not collected.`).join(' ') +
' Older caches may contain titles only; refresh to collect bodies. Review the rationale before drawing conclusions.';
document.getElementById('value-counts').innerHTML = '<thead><tr><th>Sample</th>' +
Expand Down
Loading
Loading