From cd7324487e2302e9922aab33bb17059b10f61543 Mon Sep 17 00:00:00 2001 From: Yuval Yeret <6516902+yyeret@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:31:28 -0500 Subject: [PATCH 1/2] feat: deterministic 80/20 context + Jev fallback, diagnostics UI, and Jev pattern catalog --- app.py | 27 +- cloudflare_app.py | 7 +- index.html | 101 ++++++- jev_patterns.py | 333 ++++++++++++++++++++++++ product_value.py | 157 +++++++++-- public/index.html | 101 ++++++- repo_research.py | 177 +++++++++---- tests/integration/test_product_value.py | 48 ++-- tests/unit/test_jev_patterns.py | 103 ++++++++ tests/unit/test_repo_research.py | 35 ++- 10 files changed, 975 insertions(+), 114 deletions(-) create mode 100644 jev_patterns.py create mode 100644 tests/unit/test_jev_patterns.py diff --git a/app.py b/app.py index 2a3e925..72e5321 100644 --- a/app.py +++ b/app.py @@ -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 @@ -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 @@ -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 @@ -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: diff --git a/cloudflare_app.py b/cloudflare_app.py index d9e0b85..910097f 100644 --- a/cloudflare_app.py +++ b/cloudflare_app.py @@ -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 @@ -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) @@ -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( diff --git a/index.html b/index.html index ef662eb..5db38d9 100644 --- a/index.html +++ b/index.html @@ -754,11 +754,24 @@

Issue Flow & Backlog Health

+ @@ -1071,7 +1084,9 @@

Flowy AI Coach

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 { @@ -1082,18 +1097,19 @@

Flowy AI Coach

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', @@ -1145,7 +1161,7 @@

Flowy AI Coach

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'); @@ -1202,6 +1218,46 @@

Flowy AI Coach

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 + ? '

Detected flow patterns:

' + : '

No system-level flow anti-patterns exceeded the detection threshold.

'; + const rows = (patterns.item_patterns || []).map(p => { + const examples = (p.matched_items || []).map(m => `#${escapeHtml(m.number)} (${(m.probability * 100).toFixed(0)}%)`).join(', ') || '—'; + return `${escapeHtml(p.label)}
${escapeHtml(p.description)}` + + `${escapeHtml(p.matched_count)} / ${escapeHtml(p.sampled_count)}` + + `${examples}${escapeHtml(p.coaching_hint)}`; + }).join(''); + table.innerHTML = 'PatternMatchedSampled itemsCoaching action' + rows + ''; } function renderProductValue(value) { @@ -1211,6 +1267,31 @@

Flowy AI Coach

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 && `Stage: ${escapeHtml(d.stage)}`, + d.context_method && `Context method: ${escapeHtml(d.context_method)}`, + d.error_code && `Error code: ${escapeHtml(d.error_code)}`, + d.fallback_used && `Fallback reason: ${escapeHtml(d.fallback_reason || 'unknown')}`, + d.http_status && `Provider HTTP: ${escapeHtml(d.http_status)}`, + d.context_elapsed_ms != null && `Context time: ${escapeHtml(d.context_elapsed_ms)}ms`, + d.total_elapsed_ms != null && `Total time: ${escapeHtml(d.total_elapsed_ms)}ms`, + Array.isArray(d.sources_loaded) && d.sources_loaded.length && `Sources loaded: ${d.sources_loaded.map(s => escapeHtml(s)).join(', ')}`, + Array.isArray(d.limitations) && d.limitations.length && `Limitations: ${d.limitations.map(l => escapeHtml(l)).join(' · ')}`, + ].filter(Boolean); + diagBody.innerHTML = parts.length ? parts.join('  |  ') : 'No additional diagnostics recorded.'; + } + } if (value.status !== 'ok') { note.textContent = `Not assessed: ${value.reason || 'unavailable.'} ${value.disclaimer}`; contextEl.innerHTML = ''; @@ -1218,9 +1299,12 @@

Flowy AI Coach

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 => `
  • ${escapeHtml(goal)}
  • `).join(''); @@ -1261,7 +1345,8 @@

    Flowy AI Coach

    const selected = filter.value; filter.innerHTML = '' + value.levels.map(level => ``).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 = 'Sample' + diff --git a/jev_patterns.py b/jev_patterns.py new file mode 100644 index 0000000..6583063 --- /dev/null +++ b/jev_patterns.py @@ -0,0 +1,333 @@ +"""Jev-backed insight pattern catalog and outcome-framing classification.""" +import asyncio +import logging +import math +import time + +from github_api import log_event, request_json +from value_classification import LEVELS, QUARTERLY_BUCKET_RE + +CATALOG_VERSION = "jev-patterns-1" +JEV_MODEL = "jev-1.14.0" +JEV_URL = "https://api.typesafe.ai/v1/systemone" +JEV_TIMEOUT = 15 +PATTERN_TIMEOUT = 25 +CONCURRENCY = 4 +MATCH_THRESHOLD = 0.6 +BODY_CHARS = 1500 + +FRAMING_LEVELS = LEVELS[:5] # Input, Activity, Output, Outcome, Impact + +ITEM_PATTERNS = { + "activity_without_outcome": { + "label": "Activity without outcome", + "description": "Work described as tasks, refactoring, or chores with no stated user or product outcome.", + "coaching_hint": "Reframe the title/body around who benefits and what observable behavior changes.", + "question": "Does this work item describe an activity, task, or technical chore without stating an observable user, product, or reliability outcome?", + }, + "vague_scope_or_ac": { + "label": "Vague scope / missing AC", + "description": "Lacks clear scope boundaries, acceptance criteria, or a verifiable definition of done.", + "coaching_hint": "Add explicit acceptance criteria or a concrete verification signal before starting work.", + "question": "Does this work item lack clear scope boundaries, acceptance criteria, or a verifiable definition of done?", + }, + "multi_concern_batch": { + "label": "Multi-concern batch", + "description": "Bundles multiple unrelated features, fixes, or concerns into a single PR or issue.", + "coaching_hint": "Split independent concerns into smaller PRs/issues to reduce review queue time and risk.", + "question": "Does this work item bundle multiple unrelated changes, features, or concerns into a single batch?", + }, + "preventive_risk_or_debt": { + "label": "Preventive risk / tech debt", + "description": "Targets reliability, security, CI stability, or technical debt reduction.", + "coaching_hint": "Track preventive work explicitly so capacity allocation is visible alongside feature delivery.", + "question": "Does this work item intend to prevent product, security, or reliability risk or pay down technical debt?", + }, + "customer_friction_fix": { + "label": "Customer friction fix", + "description": "Directly resolves a user-facing bug, UX friction, or broken workflow.", + "coaching_hint": "Verify whether recurring friction points cluster in the same component or stage.", + "question": "Does this work item directly resolve a user-facing bug, UX friction, or broken workflow?", + }, +} + +FLOW_PATTERNS = { + "review_queue_bottleneck": { + "label": "Review queue bottleneck", + "description": "PR review or approval wait time dominates overall cycle time or open WIP.", + "coaching_hint": "Lower WIP in review, set review SLAs, and shrink PR batch sizes.", + "question": "Do the supplied flow metrics show PR review or approval wait time dominating overall cycle time or open WIP?", + }, + "wip_aging_tail_risk": { + "label": "WIP aging tail risk", + "description": "Open PRs or issues are aging past P85 SLE or piling up in active stages.", + "coaching_hint": "Swarm aged items above P85 SLE before pulling new work.", + "question": "Do the supplied flow metrics show open work items aging past P85 SLE or accumulating in active stages?", + }, + "output_without_outcome_bias": { + "label": "Output/activity framing bias", + "description": "Most sampled work is framed as Input/Activity/Output rather than Outcome or Impact.", + "coaching_hint": "Shift PR and issue templates toward intended user outcomes rather than task lists.", + "question": "Do the supplied framing counts show most work framed as Input, Activity, or Output rather than Outcome or Impact?", + }, + "unlinked_work_stream": { + "label": "Unlinked work stream", + "description": "Low linkage between PRs and tracked issues or missing strategic context.", + "coaching_hint": "Link PRs to tracked issues so flow and value telemetry stay connected.", + "question": "Do the supplied flow metrics show low linkage between PRs and tracked issues or missing strategic framing?", + }, +} + +_FRAMING_CRITERIA = [ + "Input: staffing, hiring, headcount, budget, or resource allocation without a deliverable.", + "Activity: effort, meetings, spikes, refactoring, upgrades, or bug-fixing tasks without a stated deliverable or outcome.", + "Output: shipping a concrete feature, endpoint, UI component, or document without stating the user/business outcome.", + "Outcome: changing user behavior, workflow speed, reliability, or adoption metrics.", + "Impact: lagging business, revenue, retention, or strategic goal movement.", +] + +_ITEM_QUESTIONS = { + **{pid: {"type": "noul", "instructions": spec["question"]} for pid, spec in ITEM_PATTERNS.items()}, + "outcome_framing": { + "type": "score", + "instructions": "Classify the stated intent level of this work item from Input (0) to Impact (4).", + "criteria": _FRAMING_CRITERIA, + }, +} + +_FLOW_QUESTIONS = { + pid: {"type": "noul", "instructions": spec["question"]} for pid, spec in FLOW_PATTERNS.items() +} + + +def _valid_prob(answer): + if not isinstance(answer, dict) or answer.get("type") != "noul": + return None + p = answer.get("noul") + if type(p) not in (int, float) or not math.isfinite(p) or not 0 <= p <= 1: + return None + return float(p) + + +def _valid_framing(answer): + if not isinstance(answer, dict) or answer.get("type") != "score": + return None + probs = answer.get("probabilities") + if not isinstance(probs, dict) or set(probs) != {str(i) for i in range(len(FRAMING_LEVELS))}: + return None + weights = [probs.get(str(i)) for i in range(len(FRAMING_LEVELS))] + if any(type(w) not in (int, float) or not math.isfinite(w) or not 0 <= w <= 1 for w in weights): + return None + if not 0.98 <= sum(weights) <= 1.02: + return None + idx = max(range(len(weights)), key=lambda i: weights[i]) + return FRAMING_LEVELS[idx], float(weights[idx]) + + +async def _jev_call(jev_key, state, questions): + status, _, payload = await asyncio.wait_for( + request_json( + JEV_URL, + JEV_TIMEOUT, + method="POST", + headers={"Authorization": f"Bearer {jev_key}"}, + body={"model": JEV_MODEL, "state": state, "questions": questions}, + ), + JEV_TIMEOUT, + ) + if not 200 <= status < 300 or not isinstance(payload, dict): + return None + return payload.get("answers") if isinstance(payload.get("answers"), dict) else None + + +def _select_sample_items(data, max_items): + items = [] + seen = set() + for kind, key in (("pr", "recent_prs"), ("pr", "open_prs")): + for pr in data.get(key) or []: + num = pr.get("number") + title = (pr.get("title") or "").strip() + body = (pr.get("body") or "").strip() + if num is None or (kind, num) in seen or not (title or body): + continue + seen.add((kind, num)) + items.append({"kind": kind, "number": num, "title": title[:200], "body": body[:BODY_CHARS]}) + issues = data.get("issues") or {} + for key in ("open", "closed"): + for issue in issues.get(key) or []: + num = issue.get("number") or issue.get("identifier") + title = (issue.get("title") or "").strip() + body = (issue.get("body") or issue.get("description") or "").strip() + if num is None or ("issue", num) in seen or not (title or body): + continue + seen.add(("issue", num)) + items.append({"kind": "issue", "number": num, "title": title[:200], "body": body[:BODY_CHARS]}) + return items[:max_items] + + +def _flow_snapshot(metrics): + stats = metrics.get("recent_stats") or {} + issues = metrics.get("issues") or {} + vc = metrics.get("value_classification") or {} + return { + "pr_total": stats.get("total", 0), + "pr_p50_days": stats.get("p50_days"), + "pr_p85_days": stats.get("p85_days"), + "stage_percentiles": metrics.get("stage_percentiles") or {}, + "open_wip_count": len(metrics.get("open_wip") or []), + "issue_open_count": issues.get("open_count", 0), + "issue_linked_pr_count": issues.get("linked_pr_count", 0), + "framing_prs": (vc.get("prs") or {}).get("counts", {}), + "framing_issues": (vc.get("issues") or {}).get("counts", {}), + } + + +def _apply_jev_framing(metrics, item_results): + vc = metrics.get("value_classification") + if not isinstance(vc, dict): + return + by_key = {(r["kind"], r["number"]): r["framing"] for r in item_results if r.get("framing")} + if not by_key: + return + updated = False + for group_key, kind in (("prs", "pr"), ("issues", "issue")): + group = vc.get(group_key) + if not isinstance(group, dict) or not isinstance(group.get("items"), list): + continue + counts = {level: 0 for level in vc.get("levels", LEVELS)} + for item in group["items"]: + if QUARTERLY_BUCKET_RE.match(item.get("title") or ""): + counts[item["level"]] = counts.get(item["level"], 0) + 1 + continue + match = by_key.get((kind, item.get("number"))) + if match: + level, prob = match + item["level"] = level + item["rationale"] = f"Jev classification ({prob * 100:.0f}% probability)." + updated = True + counts[item["level"]] = counts.get(item["level"], 0) + 1 + group["counts"] = counts + if updated: + vc["method"] = "jev" + + +async def analyze_patterns_and_framing(repo, data, metrics, *, jev_key=None, max_items=10, allow_private=False): + """Evaluate Jev insight patterns on sampled PRs/issues + flow metrics, and upgrade framing.""" + started = time.monotonic() + log_ctx = {} if allow_private else {"repo": repo} + if not jev_key: + return { + "status": "unavailable", + "method": "rules", + "model": JEV_MODEL, + "catalog_version": CATALOG_VERSION, + "reason": "Configure TypeSafe API key to run Jev pattern classification.", + "flow_patterns": [{"id": pid, "label": spec["label"], "description": spec["description"], + "coaching_hint": spec["coaching_hint"], "matched": False, "probability": None} + for pid, spec in FLOW_PATTERNS.items()], + "item_patterns": [{"id": pid, "label": spec["label"], "description": spec["description"], + "coaching_hint": spec["coaching_hint"], "matched_count": 0, "sampled_count": 0, + "matched_items": []} + for pid, spec in ITEM_PATTERNS.items()], + "sampled_items": 0, + "assessed_items": 0, + "elapsed_ms": round((time.monotonic() - started) * 1000), + } + + samples = _select_sample_items(data, max_items) + sem = asyncio.Semaphore(CONCURRENCY) + + async def eval_item(sample): + async with sem: + state = {"work_item": {"kind": sample["kind"], "number": sample["number"], + "title": sample["title"], "description": sample["body"]}, + "scope": "Classify the supplied work item against each pattern and its stated intent framing."} + answers = await _jev_call(jev_key, state, _ITEM_QUESTIONS) + if not answers: + return None + patterns = {} + for pid in ITEM_PATTERNS: + p = _valid_prob(answers.get(pid)) + if p is not None: + patterns[pid] = p + framing = _valid_framing(answers.get("outcome_framing")) + return {"kind": sample["kind"], "number": sample["number"], "title": sample["title"], + "patterns": patterns, "framing": framing} + + async def eval_flow(): + state = {"flow_metrics": _flow_snapshot(metrics), + "scope": "Evaluate whether the supplied repository flow metrics exhibit each flow pattern."} + return await _jev_call(jev_key, state, _FLOW_QUESTIONS) + + tasks = [asyncio.create_task(eval_item(s)) for s in samples] + flow_task = asyncio.create_task(eval_flow()) + all_tasks = [*tasks, flow_task] + try: + try: + done, _ = await asyncio.wait(all_tasks, timeout=PATTERN_TIMEOUT) + finally: + pending = [t for t in all_tasks if not t.done()] + for t in pending: + t.cancel() + if pending: + await asyncio.gather(*pending, return_exceptions=True) + + flow_answers = flow_task.result() if flow_task in done and not flow_task.cancelled() and not flow_task.exception() else None + item_results = [ + t.result() for t in tasks + if t in done and not t.cancelled() and not t.exception() and t.result() is not None + ] + except Exception: + log_event(logging.WARNING, "jev_patterns_failed", **log_ctx, elapsed_ms=round((time.monotonic() - started) * 1000)) + return {"status": "failed", "method": "rules", "model": JEV_MODEL, "catalog_version": CATALOG_VERSION, + "reason": "Jev pattern classification failed.", "flow_patterns": [], "item_patterns": [], + "sampled_items": len(samples), "assessed_items": 0, + "elapsed_ms": round((time.monotonic() - started) * 1000)} + + _apply_jev_framing(metrics, item_results) + + flow_patterns = [] + for pid, spec in FLOW_PATTERNS.items(): + prob = _valid_prob((flow_answers or {}).get(pid)) + flow_patterns.append({ + "id": pid, + "label": spec["label"], + "description": spec["description"], + "coaching_hint": spec["coaching_hint"], + "probability": round(prob, 3) if prob is not None else None, + "matched": bool(prob is not None and prob >= MATCH_THRESHOLD), + }) + + item_patterns = [] + for pid, spec in ITEM_PATTERNS.items(): + matched = [] + for res in item_results: + prob = res["patterns"].get(pid) + if prob is not None and prob >= MATCH_THRESHOLD: + matched.append({"kind": res["kind"], "number": res["number"], "title": res["title"], + "probability": round(prob, 3)}) + matched.sort(key=lambda m: -m["probability"]) + item_patterns.append({ + "id": pid, + "label": spec["label"], + "description": spec["description"], + "coaching_hint": spec["coaching_hint"], + "matched_count": len(matched), + "sampled_count": len(item_results), + "matched_items": matched[:5], + }) + + elapsed_ms = round((time.monotonic() - started) * 1000) + log_event(logging.INFO, "jev_patterns_completed", **log_ctx, sampled_items=len(samples), + assessed_items=len(item_results), elapsed_ms=elapsed_ms) + return { + "status": "ok", + "method": "jev", + "model": JEV_MODEL, + "catalog_version": CATALOG_VERSION, + "flow_patterns": flow_patterns, + "item_patterns": item_patterns, + "sampled_items": len(samples), + "assessed_items": len(item_results), + "elapsed_ms": elapsed_ms, + } diff --git a/product_value.py b/product_value.py index 9bd378f..fe50702 100644 --- a/product_value.py +++ b/product_value.py @@ -452,6 +452,53 @@ async def assess_issue_value(repo, issues, key, token=None, *, jev_key=None, max load_sources=load_sources, issue=True) +def _build_fallback_context(repo, sources_list, reason_code=None): + """Build deterministic repository context from README/AGENTS.md/CLAUDE.md/metadata for Jev fallback.""" + by_id = {s["id"]: s for s in sources_list if isinstance(s, dict) and s.get("id")} + meta_desc = "" + if "metadata" in by_id: + try: + meta_obj = json.loads(by_id["metadata"].get("text") or "{}") + meta_desc = str(meta_obj.get("description") or "").strip() + except Exception: + meta_desc = "" + doc_texts = [] + for source in sources_list: + if source.get("kind") in ("readme", "document", "owner_context") and (source.get("text") or "").strip(): + doc_texts.append((source["id"], source.get("path") or source["id"], source["text"].strip())) + first_excerpt = "" + goals = [] + claims = [] + for sid, label, text in doc_texts: + lines = [ln.strip() for ln in text.splitlines() if ln.strip() and not ln.strip().startswith(" @@ -1071,7 +1084,9 @@

    Flowy AI Coach

    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 { @@ -1082,18 +1097,19 @@

    Flowy AI Coach

    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', @@ -1145,7 +1161,7 @@

    Flowy AI Coach

    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'); @@ -1202,6 +1218,46 @@

    Flowy AI Coach

    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 + ? '

    Detected flow patterns:

    ' + : '

    No system-level flow anti-patterns exceeded the detection threshold.

    '; + const rows = (patterns.item_patterns || []).map(p => { + const examples = (p.matched_items || []).map(m => `#${escapeHtml(m.number)} (${(m.probability * 100).toFixed(0)}%)`).join(', ') || '—'; + return `${escapeHtml(p.label)}
    ${escapeHtml(p.description)}` + + `${escapeHtml(p.matched_count)} / ${escapeHtml(p.sampled_count)}` + + `${examples}${escapeHtml(p.coaching_hint)}`; + }).join(''); + table.innerHTML = 'PatternMatchedSampled itemsCoaching action' + rows + ''; } function renderProductValue(value) { @@ -1211,6 +1267,31 @@

    Flowy AI Coach

    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 && `Stage: ${escapeHtml(d.stage)}`, + d.context_method && `Context method: ${escapeHtml(d.context_method)}`, + d.error_code && `Error code: ${escapeHtml(d.error_code)}`, + d.fallback_used && `Fallback reason: ${escapeHtml(d.fallback_reason || 'unknown')}`, + d.http_status && `Provider HTTP: ${escapeHtml(d.http_status)}`, + d.context_elapsed_ms != null && `Context time: ${escapeHtml(d.context_elapsed_ms)}ms`, + d.total_elapsed_ms != null && `Total time: ${escapeHtml(d.total_elapsed_ms)}ms`, + Array.isArray(d.sources_loaded) && d.sources_loaded.length && `Sources loaded: ${d.sources_loaded.map(s => escapeHtml(s)).join(', ')}`, + Array.isArray(d.limitations) && d.limitations.length && `Limitations: ${d.limitations.map(l => escapeHtml(l)).join(' · ')}`, + ].filter(Boolean); + diagBody.innerHTML = parts.length ? parts.join('  |  ') : 'No additional diagnostics recorded.'; + } + } if (value.status !== 'ok') { note.textContent = `Not assessed: ${value.reason || 'unavailable.'} ${value.disclaimer}`; contextEl.innerHTML = ''; @@ -1218,9 +1299,12 @@

    Flowy AI Coach

    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 => `
  • ${escapeHtml(goal)}
  • `).join(''); @@ -1261,7 +1345,8 @@

    Flowy AI Coach

    const selected = filter.value; filter.innerHTML = '' + value.levels.map(level => ``).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 = 'Sample' + diff --git a/repo_research.py b/repo_research.py index cfb6628..07e992b 100644 --- a/repo_research.py +++ b/repo_research.py @@ -12,6 +12,41 @@ MAX_SOURCE_CHARS = 36_000 README_CHARS = 12_000 DOCUMENT_CHARS = 4_000 +CORE_CONTEXT_PATHS = ("AGENTS.md", "CLAUDE.md", "pyproject.toml", "package.json") +INLINE_LINK_RE = re.compile(r"\[[^\]]+\]\(([^)\s]+)\)|(?:^|[\s(])@([A-Za-z0-9_./-]+\.(?:md|rst|txt|toml|json))", re.MULTILINE) +DOC_SUFFIXES = (".md", ".rst", ".txt", ".toml", ".json") + + +def _safe_repo_path(raw_path): + if not isinstance(raw_path, str): + return None + path = raw_path.split("#", 1)[0].split("?", 1)[0].strip() + if not path or "://" in path or path.startswith(("/", "~", "mailto:")): + return None + while path.startswith("./"): + path = path[2:] + parts = PurePosixPath(path).parts + if not parts or ".." in parts or len(path) > 300: + return None + if PurePosixPath(path).suffix.lower() not in DOC_SUFFIXES: + return None + if any(part.lower() in ("node_modules", "vendor", ".git", "dist", "build") for part in parts): + return None + return path + + +def _extract_inline_doc_paths(text, *, exclude=()): + found = [] + seen = {p.lower() for p in exclude} + for match in INLINE_LINK_RE.finditer(text or ""): + candidate = _safe_repo_path(match.group(1) or match.group(2)) + if not candidate or candidate.lower() in seen: + continue + seen.add(candidate.lower()) + found.append(candidate) + if len(found) >= MAX_DOCUMENTS: + break + return found SELECTION_SCHEMA = {"type": "OBJECT", "properties": { "paths": {"type": "ARRAY", "items": {"type": "STRING"}}}, "required": ["paths"]} SELECTION_PROMPT = """Choose at most five repository documents that will help a researcher understand @@ -119,23 +154,36 @@ def add(source_id, kind, text, limit, *, path=None, url=None, truncated=False): "text": bounded, "truncated": truncated or len(text) > len(bounded)}) remaining -= len(bounded) - async def fetch(suffix, label): + async def fetch(suffix, label, *, ignore_missing=False): timeout = min(REQUEST_TIMEOUT, max(0, deadline - loop.time())) if not timeout: - limitations.append(f"{label} was skipped after the research budget expired; availability is unknown.") + if not ignore_missing: + limitations.append(f"{label} was skipped after the research budget expired; availability is unknown.") return None try: status, _, payload = await asyncio.wait_for( request(f"{base}/{suffix}", timeout, headers=headers), timeout) except Exception: - limitations.append(f"{label} could not be loaded; availability is unknown.") + if not ignore_missing: + limitations.append(f"{label} could not be loaded; availability is unknown.") return None if not 200 <= status < 300: + if ignore_missing and status == 404: + return None reason = "rate limited or access refused" if status in (403, 429) else f"HTTP {status}" limitations.append(f"{label} could not be loaded ({reason}); availability is unknown.") return None return payload + def decode_doc(path, document): + try: + if not isinstance(document, dict) or document.get("encoding") != "base64": + raise ValueError + return base64.b64decode(document["content"], validate=False).decode("utf-8", "replace") + except (ValueError, KeyError, TypeError): + limitations.append(f"Document {path} did not contain readable text.") + return None + metadata = {key: metadata_sources.get(key) for key in ("description", "topics", "homepage")} metadata_text = json.dumps(metadata, ensure_ascii=False) add("metadata", "metadata", metadata_text, 2_000) @@ -152,56 +200,91 @@ async def fetch(suffix, label): add(source["id"], source["kind"], source["text"], len(source["text"]), path=source["path"], url=source["url"], truncated=source["truncated"]) - tree, releases, issues = await asyncio.gather( - fetch("git/trees/HEAD?recursive=1", "Document catalog"), - fetch("releases?per_page=5", "Recent releases"), - fetch("issues?state=open&sort=comments&direction=desc&per_page=10", "Open issue signals")) - catalog = [] - if isinstance(tree, dict) and isinstance(tree.get("tree"), list): - catalog, clipped = _catalog(tree["tree"]) - if tree.get("truncated"): - limitations.append("GitHub truncated the document tree; some documents were not discoverable.") - if clipped: - limitations.append("The document catalog was limited to 120 ranked paths.") - elif tree is not None: - limitations.append("The document catalog response was unreadable.") - - selected = [] - if catalog: - prompt = SELECTION_PROMPT.format(repo=repo, metadata=metadata_text[:2_000], readme=readme[:README_CHARS], - catalog=json.dumps(catalog, ensure_ascii=False)) - try: - selection = await asyncio.wait_for(generate(prompt, SELECTION_SCHEMA, 768, - diagnostics={**(diagnostics or {}), "stage": "repo_research_plan"}), max(0, deadline - loop.time())) - paths = selection.get("paths") if isinstance(selection, dict) else None - if not isinstance(paths, list): - limitations.append("The research planner returned an unreadable document selection.") - else: - if any(not isinstance(path, str) or path not in catalog for path in paths): - limitations.append("The research planner selected unsupported paths; those paths were ignored.") - for path in paths: - if isinstance(path, str) and path in catalog and path not in selected: - selected.append(path) - if len(selected) > MAX_DOCUMENTS: - limitations.append("The research planner selection was limited to five documents.") - selected = selected[:MAX_DOCUMENTS] - except Exception: - limitations.append("Research document planning failed; the profile uses the remaining supplied evidence.") + core_tasks = [fetch(f"contents/{quote(path, safe='/')}", f"Document {path}", ignore_missing=True) for path in CORE_CONTEXT_PATHS] + core_results = await asyncio.gather(*core_tasks, fetch("releases?per_page=5", "Recent releases"), + fetch("issues?state=open&sort=comments&direction=desc&per_page=10", "Open issue signals")) + core_docs = core_results[:len(CORE_CONTEXT_PATHS)] + releases, issues = core_results[len(CORE_CONTEXT_PATHS):] - documents = await asyncio.gather(*(fetch(f"contents/{quote(path, safe='/')}", f"Document {path}") for path in selected)) - for index, (path, document) in enumerate(zip(selected, documents), 1): + doc_index = 0 + loaded_texts = [readme] + seen_paths = {"readme.md", "readme.rst", "readme.txt"} + for path, document in zip(CORE_CONTEXT_PATHS, core_docs): if document is None: continue - try: - if not isinstance(document, dict) or document.get("encoding") != "base64": - raise ValueError - text = base64.b64decode(document["content"], validate=False).decode("utf-8", "replace") - except (ValueError, KeyError, TypeError): - limitations.append(f"Document {path} did not contain readable text.") + text = decode_doc(path, document) + if text is None: continue - add(f"document-{index}", "document", text, DOCUMENT_CHARS, path=path, + doc_index += 1 + seen_paths.add(path.lower()) + loaded_texts.append(text) + add(f"document-{doc_index}", "document", text, DOCUMENT_CHARS, path=path, url=f"{web}/blob/HEAD/{quote(path, safe='/')}") + inline_paths = [] + for text in loaded_texts: + for candidate in _extract_inline_doc_paths(text, exclude=seen_paths): + if candidate.lower() not in seen_paths and len(inline_paths) + doc_index < MAX_DOCUMENTS: + seen_paths.add(candidate.lower()) + inline_paths.append(candidate) + + if inline_paths: + inline_docs = await asyncio.gather(*(fetch(f"contents/{quote(path, safe='/')}", f"Document {path}", ignore_missing=True) for path in inline_paths)) + for path, document in zip(inline_paths, inline_docs): + if document is None: + continue + text = decode_doc(path, document) + if text is None: + continue + doc_index += 1 + add(f"document-{doc_index}", "document", text, DOCUMENT_CHARS, path=path, + url=f"{web}/blob/HEAD/{quote(path, safe='/')}") + + selected = [] + if generate is not None and doc_index == 0: + tree = await fetch("git/trees/HEAD?recursive=1", "Document catalog") + catalog = [] + if isinstance(tree, dict) and isinstance(tree.get("tree"), list): + catalog, clipped = _catalog(tree["tree"]) + if tree.get("truncated"): + limitations.append("GitHub truncated the document tree; some documents were not discoverable.") + if clipped: + limitations.append("The document catalog was limited to 120 ranked paths.") + elif tree is not None: + limitations.append("The document catalog response was unreadable.") + + if catalog: + prompt = SELECTION_PROMPT.format(repo=repo, metadata=metadata_text[:2_000], readme=readme[:README_CHARS], + catalog=json.dumps(catalog, ensure_ascii=False)) + try: + selection = await asyncio.wait_for(generate(prompt, SELECTION_SCHEMA, 768, + diagnostics={**(diagnostics or {}), "stage": "repo_research_plan"}), max(0, deadline - loop.time())) + paths = selection.get("paths") if isinstance(selection, dict) else None + if not isinstance(paths, list): + limitations.append("The research planner returned an unreadable document selection.") + else: + if any(not isinstance(path, str) or path not in catalog for path in paths): + limitations.append("The research planner selected unsupported paths; those paths were ignored.") + for path in paths: + if isinstance(path, str) and path in catalog and path not in selected: + selected.append(path) + if len(selected) > MAX_DOCUMENTS: + limitations.append("The research planner selection was limited to five documents.") + selected = selected[:MAX_DOCUMENTS] + except Exception: + limitations.append("Research document planning failed; the profile uses the remaining supplied evidence.") + + documents = await asyncio.gather(*(fetch(f"contents/{quote(path, safe='/')}", f"Document {path}") for path in selected)) + for path, document in zip(selected, documents): + if document is None: + continue + text = decode_doc(path, document) + if text is None: + continue + doc_index += 1 + add(f"document-{doc_index}", "document", text, DOCUMENT_CHARS, path=path, + url=f"{web}/blob/HEAD/{quote(path, safe='/')}") + if releases is not None and not isinstance(releases, list): limitations.append("The recent releases response was unreadable.") for index, release in enumerate((releases if isinstance(releases, list) else [])[:3], 1): diff --git a/tests/integration/test_product_value.py b/tests/integration/test_product_value.py index e262254..f1cbf16 100644 --- a/tests/integration/test_product_value.py +++ b/tests/integration/test_product_value.py @@ -170,22 +170,29 @@ def test_distribution_requires_exactly_the_supported_buckets(services, probabili def test_missing_key_sends_nothing(services): fake = services() assert run(jev_key=None)["status"] == "unavailable" - assert run(key=None)["status"] == "unavailable" assert fake.urls == [] + fallback = run(key=None) + assert fallback["status"] == "ok" and fallback["context_method"] == "evidence_fallback" + assert fallback["fallback_reason"] == "gemini_not_configured" -def test_context_failure_sends_nothing_to_jev(services): +def test_context_failure_falls_back_to_jev_with_diagnostics(services): fake = services(context_status=429) - assert run()["status"] == "failed" - assert not fake.jev_requests + result = run() + assert result["status"] == "ok" and result["context_method"] == "evidence_fallback" + assert result["fallback_reason"] == "provider_http_error" + assert result["diagnostics"]["fallback_used"] is True + assert len(fake.jev_requests) == 3 @pytest.mark.parametrize("context", [["bad"], {**CONTEXT, "strategic_goals": []}, {**CONTEXT, "value_proposition": "draft " * 500}]) def test_unusable_context_does_not_become_strategic_evidence(services, context): fake = services(context=context) - assert run()["status"] == "failed" - assert not fake.jev_requests + result = run() + assert result["status"] == "ok" and result["context_method"] == "evidence_fallback" + assert result["fallback_reason"] == "invalid_response" + assert "draft " not in json.dumps(fake.jev_requests) def test_private_repository_sends_nothing_to_models(services): @@ -220,8 +227,9 @@ def test_research_claims_cannot_cite_sources_that_were_not_loaded(services): context["repository_research"]["value_drivers"][0]["source_ids"] = ["invented-web-page"] fake = services(context=context) result = run() - assert result["status"] == "failed" and result["error_code"] == "invalid_response" - assert not fake.jev_requests + assert result["status"] == "ok" and result["context_method"] == "evidence_fallback" + assert result["fallback_reason"] == "invalid_response" + assert "invented-web-page" not in json.dumps(fake.jev_requests) def test_context_generation_constrains_references_to_loaded_source_ids(services): @@ -273,7 +281,8 @@ async def hang(url, **_): return 200, {}, {"private": False} monkeypatch.setattr(product_value, "request_json", hang) monkeypatch.setattr(product_value, "GEMINI_TIMEOUT", .01) - assert run()["status"] == "failed" + result = run() + assert result["fallback_reason"] == "timeout" and result["context_method"] == "evidence_fallback" def test_selection_is_most_recent_and_pairs_each_cohort_with_its_own_record(): @@ -462,10 +471,11 @@ async def upstream(url, **kwargs): monkeypatch.setattr(product_value, "request_json", upstream) result = run() - assert result["status"] == "failed" and result["error_code"] == "output_truncated" - assert "truncated" in result["reason"].lower() - assert result["items"] == [] and len(context_calls) == 2 - assert len([e for e in _events(caplog) if e.get("event") == "product_value_failed"]) == 1 + assert result["status"] == "ok" and result["context_method"] == "evidence_fallback" + assert result["fallback_reason"] == "output_truncated" + assert result["diagnostics"]["fallback_used"] is True + assert len(context_calls) == 2 + assert len([e for e in _events(caplog) if e.get("event") == "product_context_fallback"]) == 1 @pytest.mark.parametrize("reply,code", [ @@ -487,7 +497,8 @@ async def upstream(url, **kwargs): monkeypatch.setattr(product_value, "request_json", upstream) result = run() - assert result["status"] == "failed" and result["error_code"] == code + assert result["status"] == "ok" and result["context_method"] == "evidence_fallback" + assert result["fallback_reason"] == code assert len(calls) == 1 assert "provider-secret-sentinel" not in json.dumps(result) + caplog.text event = next(e for e in _events(caplog) if e.get("event") == "gemini_generation") @@ -527,7 +538,7 @@ async def upstream(url, **kwargs): monkeypatch.setattr(product_value, "request_json", upstream) monkeypatch.setattr(product_value, "CONTEXT_TIMEOUT", .04) result = run() - assert result["error_code"] == "timeout" and len(calls) == 2 + assert result["fallback_reason"] == "timeout" and len(calls) == 2 assert any(e.get("error_code") == "timeout" and e["stage"] == "product_context" for e in _events(caplog)) @@ -566,7 +577,8 @@ async def upstream(url, **kwargs): monkeypatch.setattr(product_value, 'request_json', upstream) result = run() - assert result['error_code'] == 'timeout' + assert result['fallback_reason'] == 'timeout' + assert result['diagnostics']['fallback_reason'] == 'timeout' assert 'exception-secret-sentinel' not in json.dumps(result) + caplog.text @@ -599,12 +611,12 @@ async def upstream(url, **kwargs): result = loop.run_until_complete(product_value.assess_product_value('o/r', DATA, 'k', jev_key='j')) finally: loop.close() - assert result['error_code'] == 'timeout' and len(calls) == 2 + assert result['fallback_reason'] == 'timeout' and len(calls) == 2 def test_unconfigured_result_exposes_the_logged_error_code(services): services() - result = run(key=None) + result = run(jev_key=None) assert result['status'] == 'unavailable' and result['error_code'] == 'not_configured' assert result['reason'] diff --git a/tests/unit/test_jev_patterns.py b/tests/unit/test_jev_patterns.py new file mode 100644 index 0000000..a867d89 --- /dev/null +++ b/tests/unit/test_jev_patterns.py @@ -0,0 +1,103 @@ +"""Unit tests for Jev insight pattern catalog and outcome-framing upgrade.""" +import asyncio + +import jev_patterns + + +def _metrics(): + return { + "recent_stats": {"total": 4, "p50_days": 2.0, "p85_days": 6.0}, + "stage_percentiles": {"coding": {"p50": 1.0, "p85": 2.0}, "review": {"p50": 3.0, "p85": 5.0}}, + "open_wip": [{"num": 10, "x": "In Review", "y": 9.0}], + "issues": {"open_count": 2, "linked_pr_count": 1}, + "value_classification": { + "levels": ["Input", "Activity", "Output", "Outcome", "Impact", "Unknown"], + "method": "rules", + "prs": { + "total": 2, + "body_available": 2, + "defaulted": 0, + "counts": {"Input": 0, "Activity": 2, "Output": 0, "Outcome": 0, "Impact": 0, "Unknown": 0}, + "items": [ + {"number": 1, "title": "FY26Q4 cleanup", "cohort": "merged", "level": "Activity", "rationale": "Quarterly bucket"}, + {"number": 2, "title": "Speed up checkout", "cohort": "open", "level": "Activity", "rationale": "Rule"}, + ], + }, + "issues": None, + }, + } + + +def _data(): + return { + "recent_prs": [{"number": 1, "title": "FY26Q4 cleanup", "body": "Refactor module"}], + "open_prs": [{"number": 2, "title": "Speed up checkout", "body": "Cuts checkout latency by 40%."}], + "issues": {"open": [{"number": 9, "title": "Fix login bug", "body": "Users cannot sign in."}], "closed": []}, + } + + +def test_patterns_unavailable_without_jev_key(): + metrics = _metrics() + result = asyncio.run(jev_patterns.analyze_patterns_and_framing("o/r", _data(), metrics, jev_key=None)) + assert result["status"] == "unavailable" + assert len(result["flow_patterns"]) == len(jev_patterns.FLOW_PATTERNS) + assert len(result["item_patterns"]) == len(jev_patterns.ITEM_PATTERNS) + assert metrics["value_classification"]["method"] == "rules" + + +def test_patterns_and_framing_upgrade_with_jev(monkeypatch): + async def fake_request(url, timeout, **kwargs): + body = kwargs["body"] + if "flow_metrics" in body["state"]: + return 200, {}, {"answers": { + "review_queue_bottleneck": {"type": "noul", "noul": 0.88}, + "wip_aging_tail_risk": {"type": "noul", "noul": 0.4}, + "output_without_outcome_bias": {"type": "noul", "noul": 0.72}, + "unlinked_work_stream": {"type": "noul", "noul": 0.2}, + }} + num = body["state"]["work_item"]["number"] + return 200, {}, {"answers": { + "activity_without_outcome": {"type": "noul", "noul": 0.9 if num == 1 else 0.1}, + "vague_scope_or_ac": {"type": "noul", "noul": 0.2}, + "multi_concern_batch": {"type": "noul", "noul": 0.1}, + "preventive_risk_or_debt": {"type": "noul", "noul": 0.75 if num == 1 else 0.1}, + "customer_friction_fix": {"type": "noul", "noul": 0.85 if num in (2, 9) else 0.1}, + "outcome_framing": {"type": "score", "probabilities": {"0": 0, "1": 0, "2": 0.1, "3": 0.85, "4": 0.05}}, + }} + + monkeypatch.setattr(jev_patterns, "request_json", fake_request) + metrics = _metrics() + result = asyncio.run(jev_patterns.analyze_patterns_and_framing("o/r", _data(), metrics, jev_key="jev")) + assert result["status"] == "ok" and result["assessed_items"] == 3 + matched_flow = {p["id"] for p in result["flow_patterns"] if p["matched"]} + assert matched_flow == {"review_queue_bottleneck", "output_without_outcome_bias"} + friction = next(p for p in result["item_patterns"] if p["id"] == "customer_friction_fix") + assert friction["matched_count"] == 2 + assert metrics["value_classification"]["method"] == "jev" + items = {i["number"]: i for i in metrics["value_classification"]["prs"]["items"]} + assert items[1]["level"] == "Activity" # QUARTERLY_BUCKET_RE guardrail preserved + assert items[2]["level"] == "Outcome" + + +def test_patterns_provider_error_degrades_gracefully(monkeypatch): + async def fail_request(url, timeout, **kwargs): + return 503, {}, {"error": "down"} + + monkeypatch.setattr(jev_patterns, "request_json", fail_request) + metrics = _metrics() + result = asyncio.run(jev_patterns.analyze_patterns_and_framing("o/r", _data(), metrics, jev_key="jev")) + assert result["status"] == "ok" and result["assessed_items"] == 0 + assert metrics["value_classification"]["method"] == "rules" + + +def test_app_pattern_prompt_block_formats_matched_patterns(): + import app + assert app._build_pattern_block(None) == "" + assert app._build_pattern_block({"status": "ok", "flow_patterns": [], "item_patterns": []}) == "" + block = app._build_pattern_block({ + "status": "ok", + "flow_patterns": [{"label": "Review queue bottleneck", "matched": True, "probability": 0.88, "coaching_hint": "Lower WIP"}], + "item_patterns": [{"label": "Activity without outcome", "matched_count": 1, "sampled_count": 2, + "matched_items": [{"number": 1}], "coaching_hint": "Reframe"}], + }) + assert "Review queue bottleneck" in block and "#1" in block diff --git a/tests/unit/test_repo_research.py b/tests/unit/test_repo_research.py index eb187c3..e6efa02 100644 --- a/tests/unit/test_repo_research.py +++ b/tests/unit/test_repo_research.py @@ -8,13 +8,14 @@ class ResearchServices: - def __init__(self, paths=None, tree=None): + def __init__(self, paths=None, tree=None, files=None): self.paths = paths if paths is not None else ["docs/strategy.md"] self.tree = tree if tree is not None else [ {"path": "docs/strategy.md", "type": "blob"}, {"path": "README.md", "type": "blob"}, {"path": "src/private.py", "type": "blob"}, ] + self.files = files if files is not None else {} self.calls, self.prompts = [], [] self.failures = {} self.document = "Users need secure, reliable exports." @@ -36,6 +37,11 @@ async def request(self, url, timeout, **kwargs): {"number": 8, "title": "Not an issue", "body": "PR body", "pull_request": {}}, ] if "/contents/" in url: + path = url.split("/contents/", 1)[1] + if path in self.files: + return 200, {}, {"encoding": "base64", "content": base64.b64encode(self.files[path].encode()).decode()} + if path in ("AGENTS.md", "CLAUDE.md", "pyproject.toml", "package.json"): + return 404, {}, {"message": "Not Found"} return 200, {}, {"encoding": "base64", "content": base64.b64encode(self.document.encode()).decode()} raise AssertionError(url) @@ -71,7 +77,7 @@ def test_model_paths_are_restricted_to_the_catalog_and_five_documents(): documents = [source for source in result["sources"] if source["kind"] == "document"] assert len(documents) == 5 assert {source["path"] for source in documents}.issubset(paths) - assert len([url for url, _, _ in service.calls if "/contents/" in url]) == 5 + assert len([url for url, _, _ in service.calls if "/contents/docs/" in url]) == 5 assert result["limitations"] @@ -169,3 +175,28 @@ def test_owner_sources_total_budget_and_duplicates(): with pytest.raises(ValueError): asyncio.run(build_research_sources('owner/public', {}, None, service.request, service.generate, owner_context=invalid)) + + +def test_deterministic_core_files_and_inline_links_skip_planner(): + service = ResearchServices(files={ + "AGENTS.md": "See @docs/arch.md and [Guide](docs/guide.md) and [Ext](https://example.com/a.md) and @../bad.md", + "docs/arch.md": "Architecture details.", + "docs/guide.md": "User guide details.", + }) + result = run(service) + paths = {s["path"] for s in result["sources"] if s["kind"] == "document"} + assert paths == {"AGENTS.md", "docs/arch.md", "docs/guide.md"} + assert not service.prompts + assert not any("/git/trees/" in url for url, _, _ in service.calls) + + +def test_safe_repo_path_and_inline_extraction_filters(): + from repo_research import _extract_inline_doc_paths, _safe_repo_path + assert _safe_repo_path(None) is None + assert _safe_repo_path("https://example.com/a.md") is None + assert _safe_repo_path("/etc/passwd.md") is None + assert _safe_repo_path("node_modules/pkg/README.md") is None + assert _safe_repo_path("src/app.py") is None + assert _safe_repo_path("./docs/guide.md#section") == "docs/guide.md" + links = " ".join(f"[d{i}](docs/d{i}.md)" for i in range(8)) + assert len(_extract_inline_doc_paths(links)) == 5 From 6fe88ac5e028b2fa4db4a30029bcbb8e022d1b83 Mon Sep 17 00:00:00 2001 From: Yuval Yeret <6516902+yyeret@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:36:29 -0500 Subject: [PATCH 2/2] fix: include jev_patterns.py in Cloudflare Worker bundle and coverage --- pyproject.toml | 2 +- scripts/prepare-cloudflare-build.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 752c674..bbfeb7f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,7 +32,7 @@ markers = [ ] [tool.coverage.run] -source = ["analyze", "app", "github_auth", "issue_candidates", "issues", "linear_auth", "linear_issues", "local_private_api", "product_value", "repo_research", "value_classification"] +source = ["analyze", "app", "github_auth", "issue_candidates", "issues", "jev_patterns", "linear_auth", "linear_issues", "local_private_api", "product_value", "repo_research", "value_classification"] branch = true [tool.coverage.report] diff --git a/scripts/prepare-cloudflare-build.py b/scripts/prepare-cloudflare-build.py index e605c10..30ba8bf 100644 --- a/scripts/prepare-cloudflare-build.py +++ b/scripts/prepare-cloudflare-build.py @@ -33,7 +33,7 @@ def main(): bundle.mkdir(parents=True, exist_ok=True) for name in ['cloudflare_worker.py', 'cloudflare_app.py', 'mcp_oauth.py', 'mcp_server.py', 'mcp_analytics.py', 'analyze.py', 'issues.py', 'linear_auth.py', 'linear_issues.py', 'flow_metrics_core.py', - 'github_api.py', 'github_auth.py', 'github_projects.py', 'google_auth.py', 'issue_candidates.py', 'product_value.py', 'repo_research.py', 'value_classification.py']: + 'github_api.py', 'github_auth.py', 'github_projects.py', 'google_auth.py', 'issue_candidates.py', 'jev_patterns.py', 'product_value.py', 'repo_research.py', 'value_classification.py']: shutil.copy2(ROOT / name, bundle / name) (ROOT / 'public').mkdir(exist_ok=True) for name in ['index.html', 'privacy.html']: