From 736c142a1c859cce6b63862ba90ddfdfefb3d72c Mon Sep 17 00:00:00 2001
From: "tessl-app[bot]" <295179765+tessl-app[bot]@users.noreply.github.com>
Date: Fri, 23 Oct 2026 14:05:44 +0000
Subject: [PATCH 1/5] feat: assess each PR's expected value to the repository's
product (#15)
One Gemini call per analysis builds product context (summary, value
proposition, lean canvas, strategic goals) from the repository description,
topics and README. One Gemini call per sampled PR then rates expected value
(High/Medium/Low/Unclear) with confidence, beneficiaries, why it matters, the
matching goal and missing context. Content framing is passed as evidence only.
Results are labelled as expectations, not realized impact, and degrade to a
status and reason when no key is configured or the context call fails.
Co-Authored-By: Claude Opus 5.5
---
README.md | 15 ++
app.py | 3 +
cloudflare_app.py | 4 +-
index.html | 45 ++++
product_value.py | 200 ++++++++++++++++++
public/index.html | 45 ++++
pyproject.toml | 2 +-
scripts/prepare-cloudflare-build.py | 2 +-
scripts/security-check.py | 2 +-
tests/integration/test_product_value.py | 161 ++++++++++++++
tests/integration/test_security_boundaries.py | 4 +-
tests/test_chat.py | 2 +-
12 files changed, 479 insertions(+), 6 deletions(-)
create mode 100644 product_value.py
create mode 100644 tests/integration/test_product_value.py
diff --git a/README.md b/README.md
index c9962ae..22f69d8 100644
--- a/README.md
+++ b/README.md
@@ -58,6 +58,21 @@ matches can misread context. Review rationales before interpreting distributions
Existing caches remain usable with title-only classification. Use `python analyze.py OWNER/REPO --refresh` to collect bodies.
`/api/analyze` exposes the additive `value_classification` field; AI contribution
classification remains in `classification`.
+
+### Expected product value
+
+When `GEMINI_API_KEY` is configured, each analysis also judges the value each sampled
+PR is expected to deliver to the repository's product (`product_value.py`). One Gemini
+call turns the repository description, topics and README into product context: a
+summary, value proposition, lean canvas, and the strategic goals the repository
+appears focused on. One Gemini call per PR, for the 30 most recent sampled PRs (up to
+10 open), then rates expected value as High, Medium, Low or Unclear with confidence,
+who benefits, why it matters, the matching goal, and missing context. Content framing
+is passed as evidence, but clear outcome language alone does not imply high value.
+These are expectations, not verified realized impact. Without a key, or if the context
+call fails, `/api/analyze` returns `product_value` with a status and reason and the
+rest of the analysis is unchanged. The dashboard shows the context and per-PR
+assessments under Content framing.
## Cloudflare deployment
This project uses Cloudflare Python Workers (FastAPI), Workers Static Assets, KV for cached public results, and native Worker rate-limit bindings.
diff --git a/app.py b/app.py
index 36ab235..385503e 100644
--- a/app.py
+++ b/app.py
@@ -29,6 +29,7 @@
import sys
sys.path.insert(0, str(Path(__file__).parent))
from analyze import collect_data, compute_flow_metrics
+from product_value import assess_product_value
# ---------------------------------------------------------------------------
# App Setup
@@ -110,6 +111,8 @@ def _run_analysis(repo: str, force: bool) -> dict:
raise HTTPException(status_code=400, detail="Only public repositories are supported.")
raw = collect_data(repo)
metrics = compute_flow_metrics(raw)
+ metrics["product_value"] = asyncio.run(assess_product_value(
+ repo, raw, _get_gemini_key(), os.environ.get("GITHUB_TOKEN")))
return metrics
diff --git a/cloudflare_app.py b/cloudflare_app.py
index 58b2352..73c369c 100644
--- a/cloudflare_app.py
+++ b/cloudflare_app.py
@@ -14,9 +14,10 @@
from analyze import collect_public_data, compute_flow_metrics
from github_api import request_json
from google_auth import verify_id_token
+from product_value import assess_product_value
app = FastAPI(title="GitHub Flow Analytics")
-METRICS_CACHE_PREFIX = "metrics:v2:"
+METRICS_CACHE_PREFIX = "metrics:v3:"
SESSION_COOKIE = "gha_session"
NONCE_COOKIE = "gha_nonce"
SESSION_SECONDS = 60 * 60 * 24 * 14
@@ -240,6 +241,7 @@ async def analyze_repo(req: AnalyzeRequest, request: Request):
raise HTTPException(status_code=502, detail="Repository analysis failed. Please try again.") from exc
if not metrics.get("recent_stats", {}).get("total"):
raise HTTPException(status_code=422, detail="No merged pull requests were found for this public repository.")
+ metrics["product_value"] = await assess_product_value(repo, raw, getattr(env, "GEMINI_API_KEY", None) if env else None, token)
if cache:
await cache.put(cache_key, json.dumps(metrics, separators=(",", ":")), expiration_ttl=21600)
return metrics
diff --git a/index.html b/index.html
index 1eca295..e6ca5e6 100644
--- a/index.html
+++ b/index.html
@@ -579,6 +579,12 @@
') + '';
}
let valueClassification = null;
diff --git a/product_value.py b/product_value.py
new file mode 100644
index 0000000..652824c
--- /dev/null
+++ b/product_value.py
@@ -0,0 +1,200 @@
+"""Expected product value of each PR, judged by Gemini against the repository's product.
+
+One call per analysis turns the README and repository description into product
+context (value proposition, lean canvas, strategic goals). One call per sampled
+PR then judges the value that PR is expected to deliver. This is an expectation
+from stated intent and changed code size, never a measurement of realized impact,
+and it is kept separate from the rule-based content framing.
+"""
+import asyncio
+import base64
+import json
+
+from github_api import request_json
+from value_classification import compute_value_classification
+
+VERSION = "gemini-product-value-1"
+MODEL = "gemini-3.5-flash-lite"
+GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL}:generateContent"
+VALUE_LEVELS = ["High", "Medium", "Low", "Unclear"]
+CONFIDENCE_LEVELS = ["High", "Medium", "Low"]
+DEFAULT_MAX_PRS = 30
+README_CHARS = 12_000
+BODY_CHARS = 4_000
+CONCURRENCY = 5
+DISCLAIMER = ("Expected value judged by Gemini from PR text and the repository's stated product. "
+ "Not verified realized impact. Clear outcome framing alone does not imply high value.")
+
+_STRING = {"type": "STRING"}
+CONTEXT_SCHEMA = {"type": "OBJECT", "properties": {
+ "product_summary": _STRING,
+ "value_proposition": _STRING,
+ "lean_canvas": {"type": "OBJECT", "properties": {key: _STRING for key in (
+ "customer_segments", "problem", "solution", "unique_value_proposition",
+ "channels", "revenue_streams", "cost_structure", "key_metrics", "unfair_advantage")}},
+ "strategic_goals": {"type": "ARRAY", "items": _STRING},
+ "missing_context": _STRING,
+}, "required": ["product_summary", "value_proposition", "lean_canvas", "strategic_goals", "missing_context"]}
+
+ASSESSMENT_SCHEMA = {"type": "OBJECT", "properties": {
+ "expected_value": {"type": "STRING", "enum": VALUE_LEVELS},
+ "value_summary": _STRING,
+ "beneficiaries": _STRING,
+ "why_it_matters": _STRING,
+ "strategic_goal": _STRING,
+ "confidence": {"type": "STRING", "enum": CONFIDENCE_LEVELS},
+ "missing_context": _STRING,
+}, "required": ["expected_value", "value_summary", "beneficiaries", "why_it_matters",
+ "strategic_goal", "confidence", "missing_context"]}
+
+CONTEXT_PROMPT = """You describe the product a GitHub repository provides, so later reviewers can judge
+which changes matter to it. Use only the evidence below. Where the evidence is silent, say "Unknown"
+rather than guessing, and list what is missing in missing_context.
+Return a short product summary, a one-sentence value proposition, a lean canvas, and the 3 to 5
+strategic goals the repository appears focused on now, most important first.
+
+Repository: {repo}
+Description: {description}
+Topics: {topics}
+Homepage: {homepage}
+
+README (may be truncated):
+{readme}"""
+
+ASSESSMENT_PROMPT = """You judge the value a pull request is expected to deliver to the product below.
+Rules:
+- Judge expected value to this product and its users, not how well the PR is written.
+- Outcome or impact language in the title is framing, not value. A clearly framed PR can be Low value,
+ and a terse maintenance PR can be High value when the product depends on it.
+- This is an expectation. Never claim the value was achieved or measured.
+- Use Unclear when the evidence cannot support a judgment, and say what is missing.
+- strategic_goal names the matching goal from the list, or "None".
+Keep each text field to one or two sentences.
+
+## Product context
+{context}
+
+## Pull request #{number} ({cohort})
+Title: {title}
+Lines changed: {size}
+Rule-based content framing: {framing} ({rationale})
+Body (may be truncated):
+{body}"""
+
+
+def _github_headers(token):
+ headers = {"Accept": "application/vnd.github+json", "User-Agent": "github-flow-analytics/0.1"}
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ return headers
+
+
+async def fetch_product_sources(repo, token=None):
+ """Repository description, topics, homepage and README text from GitHub's REST API."""
+ headers = _github_headers(token)
+ base = f"https://api.github.com/repos/{repo}"
+ (meta_status, _, meta), (readme_status, _, readme) = await asyncio.gather(
+ request_json(base, headers=headers, timeout=10),
+ request_json(f"{base}/readme", headers=headers, timeout=10))
+ meta = meta if 200 <= meta_status < 300 else {}
+ text = ""
+ if 200 <= readme_status < 300 and readme.get("encoding") == "base64":
+ text = base64.b64decode(readme.get("content", "")).decode("utf-8", "replace")
+ return {"description": meta.get("description") or "", "topics": meta.get("topics") or [],
+ "homepage": meta.get("homepage") or "", "readme": text[:README_CHARS],
+ "readme_truncated": len(text) > README_CHARS}
+
+
+async def gemini_json(key, prompt, schema, max_tokens=1200):
+ """Call Gemini for a structured JSON answer; raise ValueError on any failure."""
+ body = {"contents": [{"role": "user", "parts": [{"text": prompt}]}],
+ "generationConfig": {"temperature": 0.2, "maxOutputTokens": max_tokens,
+ "responseMimeType": "application/json", "responseSchema": schema}}
+ status, _, payload = await request_json(GEMINI_URL, method="POST", headers={"x-goog-api-key": key},
+ body=body, timeout=25)
+ if status < 200 or status >= 300:
+ raise ValueError(f"Gemini returned HTTP {status}")
+ try:
+ parts = payload["candidates"][0]["content"]["parts"]
+ return json.loads("".join(part.get("text", "") for part in parts))
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
+ raise ValueError("Gemini returned an unreadable answer") from exc
+
+
+def select_prs(data, value_classification, max_prs=DEFAULT_MAX_PRS):
+ """Most recent sampled PRs to assess: up to a third open, the rest merged."""
+ raw = {pr.get("number"): pr for key in ("recent_prs", "open_prs") for pr in data.get(key) or []}
+ items = value_classification["prs"]["items"]
+ open_items = [i for i in items if i["cohort"] == "open"][:max_prs // 3]
+ merged = [i for i in items if i["cohort"] == "merged"][:max_prs - len(open_items)]
+ return [(item, raw.get(item["number"], {})) for item in merged + open_items]
+
+
+def _context_text(context):
+ canvas = context.get("lean_canvas") or {}
+ goals = context.get("strategic_goals") or []
+ return "\n".join([f"Summary: {context.get('product_summary', '')}",
+ f"Value proposition: {context.get('value_proposition', '')}",
+ *(f"{key.replace('_', ' ').capitalize()}: {value}" for key, value in canvas.items()),
+ "Strategic goals:", *(f"{n}. {goal}" for n, goal in enumerate(goals, 1))])
+
+
+def _clean(assessment):
+ result = {key: str(assessment.get(key) or "").strip() for key in ASSESSMENT_SCHEMA["required"]}
+ if result["expected_value"] not in VALUE_LEVELS:
+ result["expected_value"] = "Unclear"
+ if result["confidence"] not in CONFIDENCE_LEVELS:
+ result["confidence"] = "Low"
+ return result
+
+
+async def assess_pr(key, context_text, item, pr):
+ prompt = ASSESSMENT_PROMPT.format(
+ context=context_text, number=item["number"], cohort=item["cohort"], title=item["title"],
+ size=(pr.get("additions") or 0) + (pr.get("deletions") or 0) or "unknown",
+ framing=item["level"], rationale=item["rationale"],
+ body=(pr.get("body") or "(no body)")[:BODY_CHARS])
+ base = {"number": item["number"], "title": item["title"], "cohort": item["cohort"], "framing": item["level"]}
+ try:
+ return {**base, "status": "assessed", **_clean(await gemini_json(key, prompt, ASSESSMENT_SCHEMA, 600))}
+ except Exception: # one failed PR must not lose the others
+ return {**base, "status": "failed"}
+
+
+async def assess_product_value(repo, data, key, token=None, max_prs=DEFAULT_MAX_PRS):
+ """Product context plus one expected-value assessment per sampled PR.
+
+ Never raises: a missing key or failed context call returns a status the
+ dashboard explains, so the rest of the analysis is unaffected.
+ """
+ value_classification = compute_value_classification(data)
+ result = {"method": "gemini", "model": MODEL, "version": VERSION, "levels": VALUE_LEVELS,
+ "disclaimer": DISCLAIMER, "context": None, "sources": None, "items": [],
+ "total_prs": value_classification["prs"]["total"]}
+ if not key:
+ return {**result, "status": "unavailable", "reason": "No Gemini API key is configured."}
+ try:
+ sources = await fetch_product_sources(repo, token)
+ context = await gemini_json(key, CONTEXT_PROMPT.format(
+ repo=repo, description=sources["description"] or "(none)",
+ topics=", ".join(sources["topics"]) or "(none)", homepage=sources["homepage"] or "(none)",
+ readme=sources["readme"] or "(no README)"), CONTEXT_SCHEMA, 1500)
+ except Exception: # httpx errors locally, JS fetch errors on Workers, bad answers
+ return {**result, "status": "failed", "reason": "Product context could not be generated."}
+ result["sources"] = {"description": bool(sources["description"]), "readme": bool(sources["readme"]),
+ "readme_truncated": sources["readme_truncated"]}
+ result["context"] = context
+ context_text = _context_text(context)
+ limit = asyncio.Semaphore(CONCURRENCY)
+
+ async def bounded(item, pr):
+ async with limit:
+ return await assess_pr(key, context_text, item, pr)
+
+ result["items"] = list(await asyncio.gather(*(bounded(item, pr) for item, pr in select_prs(data, value_classification, max_prs))))
+ counts = dict.fromkeys(VALUE_LEVELS, 0)
+ for item in result["items"]:
+ if item["status"] == "assessed":
+ counts[item["expected_value"]] += 1
+ return {**result, "status": "ok", "counts": counts,
+ "assessed": sum(counts.values()), "failed": sum(i["status"] == "failed" for i in result["items"])}
diff --git a/public/index.html b/public/index.html
index 1eca295..e6ca5e6 100644
--- a/public/index.html
+++ b/public/index.html
@@ -579,6 +579,12 @@
') + '';
}
let valueClassification = null;
diff --git a/pyproject.toml b/pyproject.toml
index 5b49dfa..f464508 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -32,7 +32,7 @@ markers = [
]
[tool.coverage.run]
-source = ["analyze", "app", "issues", "value_classification"]
+source = ["analyze", "app", "issues", "product_value", "value_classification"]
branch = true
[tool.coverage.report]
diff --git a/scripts/prepare-cloudflare-build.py b/scripts/prepare-cloudflare-build.py
index 40bc14b..acd52cf 100644
--- a/scripts/prepare-cloudflare-build.py
+++ b/scripts/prepare-cloudflare-build.py
@@ -27,7 +27,7 @@ def main():
bundle = ROOT / '.wrangler' / 'worker'
bundle.mkdir(parents=True, exist_ok=True)
for name in ['cloudflare_worker.py', 'cloudflare_app.py', 'analyze.py', 'issues.py',
- 'github_api.py', 'google_auth.py', 'value_classification.py']:
+ 'github_api.py', 'google_auth.py', 'product_value.py', 'value_classification.py']:
shutil.copy2(ROOT / name, bundle / name)
(ROOT / 'public').mkdir(exist_ok=True)
for name in ['index.html', 'privacy.html']:
diff --git a/scripts/security-check.py b/scripts/security-check.py
index 727c7b9..06ec795 100644
--- a/scripts/security-check.py
+++ b/scripts/security-check.py
@@ -79,7 +79,7 @@ def main():
f'--report-path={CACHE / "source.json"}']))
checks.append(run('Source security (medium/high severity)', [sys.executable, '-m', 'bandit', '-r',
'app.py', 'cloudflare_app.py', 'google_auth.py', 'github_api.py', 'analyze.py',
- 'issues.py', 'value_classification.py', 'scripts', '-ll', '-f', 'json', '-o', str(CACHE / 'bandit.json')]))
+ 'issues.py', 'product_value.py', 'value_classification.py', 'scripts', '-ll', '-f', 'json', '-o', str(CACHE / 'bandit.json')]))
lock_export = CACHE / 'runtime-requirements.txt'
exported = run('Export locked runtime dependencies', [sys.executable, '-m', 'uv', 'export', '--locked',
'--no-dev', '--extra', 'local', '--no-hashes', '--no-emit-project', '--output-file', str(lock_export)])
diff --git a/tests/integration/test_product_value.py b/tests/integration/test_product_value.py
new file mode 100644
index 0000000..40b3901
--- /dev/null
+++ b/tests/integration/test_product_value.py
@@ -0,0 +1,161 @@
+import asyncio
+import base64
+import json
+from types import SimpleNamespace
+
+import pytest
+
+import product_value
+from tests.integration.test_security_boundaries import hosted, hosted_client
+
+CONTEXT = {"product_summary": "Flow analytics for GitHub repositories.",
+ "value_proposition": "Coaches teams to deliver faster.",
+ "lean_canvas": {"customer_segments": "Engineering leads"},
+ "strategic_goals": ["Trustworthy flow metrics", "Hosted dashboard adoption"],
+ "missing_context": "No pricing information."}
+
+DATA = {"recent_prs": [
+ {"number": 1, "title": "Users can export reports faster", "body": "Adds CSV export.", "additions": 40, "deletions": 2},
+ {"number": 2, "title": "Bump lint config", "body": None, "additions": 1, "deletions": 1}],
+ "open_prs": [{"number": 3, "title": "Fix cycle time for draft PRs", "body": "Drafts skewed p85."}]}
+
+
+def gemini_reply(answer):
+ return 200, {}, {"candidates": [{"content": {"parts": [{"text": json.dumps(answer)}]}}]}
+
+
+class FakeServices:
+ """Answers GitHub and Gemini requests; records each Gemini prompt."""
+
+ def __init__(self, assessments=None, context_status=200, readme="# Flow analytics\nFor teams."):
+ self.assessments = assessments or {}
+ self.context_status = context_status
+ self.readme = readme
+ self.prompts = []
+
+ async def __call__(self, url, *, headers, method="GET", body=None, timeout=15):
+ if url.endswith("/readme"):
+ return 200, {}, {"encoding": "base64", "content": base64.b64encode(self.readme.encode()).decode()}
+ if url.startswith("https://api.github.com/repos/"):
+ return 200, {}, {"description": "Public flow analytics", "topics": ["dora"], "homepage": ""}
+ prompt = body["contents"][0]["parts"][0]["text"]
+ self.prompts.append(prompt)
+ if "## Pull request #" not in prompt:
+ return (self.context_status, {}, {}) if self.context_status != 200 else gemini_reply(CONTEXT)
+ number = int(prompt.split("## Pull request #")[1].split(" ")[0])
+ answer = self.assessments.get(number)
+ if answer is None:
+ return 500, {}, {"message": "boom"}
+ return gemini_reply(answer)
+
+
+def assessment(value, **extra):
+ return {"expected_value": value, "value_summary": "Faster exports.", "beneficiaries": "Engineering leads",
+ "why_it_matters": "Supports adoption.", "strategic_goal": "Hosted dashboard adoption",
+ "confidence": "Medium", "missing_context": "Usage data.", **extra}
+
+
+@pytest.fixture
+def services(monkeypatch):
+ def install(**kwargs):
+ fake = FakeServices(**kwargs)
+ monkeypatch.setattr(product_value, "request_json", fake)
+ return fake
+ return install
+
+
+def run(data=DATA, key="k", **kwargs):
+ return asyncio.run(product_value.assess_product_value("o/r", data, key, **kwargs))
+
+
+def test_assesses_each_sampled_pr_against_generated_product_context(services):
+ fake = services(assessments={1: assessment("High"), 2: assessment("Low"), 3: assessment("Medium")})
+ result = run()
+ assert result["status"] == "ok"
+ assert result["context"]["strategic_goals"][0] == "Trustworthy flow metrics"
+ assert result["counts"] == {"High": 1, "Medium": 1, "Low": 1, "Unclear": 0}
+ assert [(i["number"], i["cohort"], i["expected_value"]) for i in result["items"]] == [
+ (1, "merged", "High"), (2, "merged", "Low"), (3, "open", "Medium")]
+ assert "realized" in result["disclaimer"]
+ # One context call built from README and description, then one call per PR that sees that context.
+ assert "# Flow analytics" in fake.prompts[0] and "Public flow analytics" in fake.prompts[0]
+ assert len(fake.prompts) == 4
+ assert all("Trustworthy flow metrics" in prompt for prompt in fake.prompts[1:])
+
+
+def test_framing_is_evidence_not_value(services):
+ fake = services(assessments={1: assessment("Low"), 2: assessment("Low"), 3: assessment("Low")})
+ result = run()
+ pr1 = next(i for i in result["items"] if i["number"] == 1)
+ assert pr1["framing"] == "Outcome" and pr1["expected_value"] == "Low"
+ assert "framing, not value" in fake.prompts[1]
+
+
+def test_one_failed_pr_does_not_lose_the_others(services):
+ services(assessments={1: assessment("High"), 3: assessment("Banana", confidence="Total")})
+ result = run()
+ by_number = {i["number"]: i for i in result["items"]}
+ assert by_number[2]["status"] == "failed" and "expected_value" not in by_number[2]
+ assert by_number[3]["expected_value"] == "Unclear" and by_number[3]["confidence"] == "Low"
+ assert result["assessed"] == 2 and result["failed"] == 1
+
+
+def test_without_key_nothing_is_called(services):
+ fake = services()
+ result = run(key=None)
+ assert result["status"] == "unavailable" and result["items"] == []
+ assert fake.prompts == []
+
+
+def test_context_failure_skips_pr_assessment(services):
+ fake = services(context_status=503)
+ result = run()
+ assert result["status"] == "failed" and "context" in result["reason"]
+ assert len(fake.prompts) == 1
+
+
+def test_sample_is_capped_and_keeps_open_prs():
+ data = {"recent_prs": [{"number": n, "title": f"PR {n}"} for n in range(1, 41)],
+ "open_prs": [{"number": n, "title": f"PR {n}"} for n in range(100, 120)]}
+ selected = product_value.select_prs(data, product_value.compute_value_classification(data), max_prs=30)
+ cohorts = [item["cohort"] for item, _ in selected]
+ assert len(selected) == 30 and cohorts.count("open") == 10
+
+
+def test_hosted_analysis_attaches_product_value_before_caching(monkeypatch):
+ async def allowed(_):
+ return {"success": True}
+
+ async def public_metadata(*_, **__):
+ return 200, {}, {"private": False}
+
+ async def collected(repo, token):
+ return {"repo": repo}
+
+ seen = {}
+
+ async def fake_assess(repo, raw, key, token):
+ seen["args"] = (repo, raw, key)
+ return {"status": "ok", "items": []}
+
+ class Cache:
+ stored = {}
+
+ async def get(self, _):
+ return None
+
+ async def put(self, key, value, expiration_ttl):
+ self.stored[key] = json.loads(value)
+
+ monkeypatch.setattr(hosted, "request_json", public_metadata)
+ monkeypatch.setattr(hosted, "collect_public_data", collected)
+ monkeypatch.setattr(hosted, "compute_flow_metrics", lambda raw: {"repo": raw["repo"], "recent_stats": {"total": 1}})
+ monkeypatch.setattr(hosted, "assess_product_value", fake_assess)
+ cache = Cache()
+ env = SimpleNamespace(AUTH_REQUIRED="false", ANALYZE_LIMIT=SimpleNamespace(limit=allowed),
+ GEMINI_API_KEY="k", ANALYTICS_CACHE=cache)
+ response = hosted_client(env).post("/api/analyze", json={"repo_url": "o/r"})
+ assert response.status_code == 200
+ assert response.json()["product_value"]["status"] == "ok"
+ assert seen["args"] == ("o/r", {"repo": "o/r"}, "k")
+ assert cache.stored[hosted.METRICS_CACHE_PREFIX + "o/r"]["product_value"]["status"] == "ok"
diff --git a/tests/integration/test_security_boundaries.py b/tests/integration/test_security_boundaries.py
index ede6fc7..2d3a9e7 100644
--- a/tests/integration/test_security_boundaries.py
+++ b/tests/integration/test_security_boundaries.py
@@ -54,7 +54,9 @@ def test_local_public_repository_can_be_analyzed(monkeypatch):
monkeypatch.setattr(subprocess, 'run', lambda cmd, **kwargs: subprocess.CompletedProcess(cmd, 0, stdout='false\n'))
monkeypatch.setattr(local, 'collect_data', lambda repo: {'repo': repo})
monkeypatch.setattr(local, 'compute_flow_metrics', lambda raw: raw)
- assert local._run_analysis('o/r', False) == {'repo': 'o/r'}
+ result = local._run_analysis('o/r', False)
+ assert result['repo'] == 'o/r'
+ assert result['product_value']['status'] == 'unavailable'
@pytest.mark.parametrize('payload', [
diff --git a/tests/test_chat.py b/tests/test_chat.py
index cb64d81..f3273e5 100644
--- a/tests/test_chat.py
+++ b/tests/test_chat.py
@@ -90,7 +90,7 @@ async def test_chat_reads_cached_metrics_without_client_payload(self):
with patch("cloudflare_app.httpx.AsyncClient", return_value=client):
result = await chat(req, fake_request)
self.assertEqual(result["reply"], "Throughput rose.")
- self.assertEqual(cache.keys, ["metrics:v2:github/spec-kit"])
+ self.assertEqual(cache.keys, ["metrics:v3:github/spec-kit"])
self.assertIn("throughput", client.body["system_instruction"]["parts"][0]["text"].lower())
self.assertIn("gemini-3.5-flash-lite", client.url)
self.assertEqual(client.headers["x-goog-api-key"], "test")
From 37a0bf6f40615e43dcb2542645eaa956fe7e4cf6 Mon Sep 17 00:00:00 2001
From: "tessl-app[bot]"
Date: Fri, 23 Oct 2026 14:14:57 +0000
Subject: [PATCH 2/5] fix: harden product value assessment per review (#15)
- Validate and normalize Gemini's product context inside the fail-soft path.
- Read repository metadata first and send nothing to Gemini unless it is public.
- Enforce request deadlines with asyncio.wait_for so they hold on Workers fetch.
- Select the most recent PRs by date and pair each with its own cohort record.
- Report the selected sample size and use it as the dashboard denominator.
- Downgrade assessments without reasoning to Unclear with Low confidence.
- Cache analyses with Gemini failures for ten minutes instead of six hours.
- Disclose product value data sent to Gemini on the privacy page.
- Document how cached analyses relate to the Gemini key state.
Co-Authored-By: Claude Opus 5.5
---
README.md | 4 +-
cloudflare_app.py | 5 +-
index.html | 2 +-
privacy.html | 1 +
product_value.py | 69 ++++++++++++++++++------
public/index.html | 2 +-
public/privacy.html | 1 +
tests/integration/test_product_value.py | 71 ++++++++++++++++++++++---
8 files changed, 128 insertions(+), 27 deletions(-)
diff --git a/README.md b/README.md
index 22f69d8..bae4995 100644
--- a/README.md
+++ b/README.md
@@ -71,7 +71,9 @@ who benefits, why it matters, the matching goal, and missing context. Content fr
is passed as evidence, but clear outcome language alone does not imply high value.
These are expectations, not verified realized impact. Without a key, or if the context
call fails, `/api/analyze` returns `product_value` with a status and reason and the
-rest of the analysis is unchanged. The dashboard shows the context and per-PR
+rest of the analysis is unchanged. The hosted Worker caches each analysis for up to six
+hours (ten minutes when a Gemini call failed), so adding or removing the key shows on the
+next uncached or force-refreshed analysis. The dashboard shows the context and per-PR
assessments under Content framing.
## Cloudflare deployment
diff --git a/cloudflare_app.py b/cloudflare_app.py
index 73c369c..af1a1e9 100644
--- a/cloudflare_app.py
+++ b/cloudflare_app.py
@@ -243,7 +243,10 @@ async def analyze_repo(req: AnalyzeRequest, request: Request):
raise HTTPException(status_code=422, detail="No merged pull requests were found for this public repository.")
metrics["product_value"] = await assess_product_value(repo, raw, getattr(env, "GEMINI_API_KEY", None) if env else None, token)
if cache:
- await cache.put(cache_key, json.dumps(metrics, separators=(",", ":")), expiration_ttl=21600)
+ value = metrics["product_value"]
+ # Keep Gemini failures briefly so a later analysis can recover once the service does.
+ ttl = 600 if value.get("status") == "failed" or value.get("failed") else 21600
+ await cache.put(cache_key, json.dumps(metrics, separators=(",", ":")), expiration_ttl=ttl)
return metrics
diff --git a/index.html b/index.html
index e6ca5e6..2f6f0d6 100644
--- a/index.html
+++ b/index.html
@@ -804,7 +804,7 @@
Antigravity AI Coach
return;
}
const sources = value.sources || {};
- note.textContent = `${value.disclaimer} Assessed ${value.assessed} of ${value.total_prs} sampled PRs` +
+ note.textContent = `${value.disclaimer} Assessed ${value.assessed} of the ${value.selected} most recent of ${value.total_prs} sampled PRs` +
(value.failed ? ` (${value.failed} failed)` : '') + '. ' +
value.levels.map(level => `${level}: ${value.counts[level]}`).join(' · ') +
`. Context from ${[sources.description && 'description', sources.readme && (sources.readme_truncated ? 'README (truncated)' : 'README')].filter(Boolean).join(' and ') || 'no repository text'} via ${value.model}.`;
diff --git a/privacy.html b/privacy.html
index b8968bd..844a271 100644
--- a/privacy.html
+++ b/privacy.html
@@ -14,6 +14,7 @@
Information saved
When you sign in, we save your verified Google email address, Google's stable account identifier, the first and most recent sign-in times, and a sign-in count. We use this information to recognize returning users and understand account usage. We do not use it for marketing, sell it, or send it to the AI coach.
Repository and AI requests
Repository analysis uses public GitHub data. If you ask the AI coach a question, the question and repository metrics are sent to Google's Gemini service. Your Google sign-in details are not included in that request.
+
When an analysis estimates each pull request's expected product value, the repository name, description, topics, homepage and README, and the titles, bodies and change sizes of up to 30 recent pull requests are sent to Google's Gemini service to infer the product's context and judge each pull request. These requests contain only public repository data and no sign-in details.
Storage and deletion
Account records and short-lived sign-in sessions are stored in Cloudflare's database. Choose Delete account in the app to remove your account record and sign-in sessions. A session cookie stays in your browser for up to fourteen days and is protected from JavaScript access.
diff --git a/product_value.py b/product_value.py
index 652824c..f544487 100644
--- a/product_value.py
+++ b/product_value.py
@@ -22,6 +22,10 @@
README_CHARS = 12_000
BODY_CHARS = 4_000
CONCURRENCY = 5
+GEMINI_TIMEOUT = 25
+CANVAS_KEYS = ("customer_segments", "problem", "solution", "unique_value_proposition",
+ "channels", "revenue_streams", "cost_structure", "key_metrics", "unfair_advantage")
+NARRATIVE_KEYS = ("value_summary", "beneficiaries", "why_it_matters")
DISCLAIMER = ("Expected value judged by Gemini from PR text and the repository's stated product. "
"Not verified realized impact. Clear outcome framing alone does not imply high value.")
@@ -29,9 +33,7 @@
CONTEXT_SCHEMA = {"type": "OBJECT", "properties": {
"product_summary": _STRING,
"value_proposition": _STRING,
- "lean_canvas": {"type": "OBJECT", "properties": {key: _STRING for key in (
- "customer_segments", "problem", "solution", "unique_value_proposition",
- "channels", "revenue_streams", "cost_structure", "key_metrics", "unfair_advantage")}},
+ "lean_canvas": {"type": "OBJECT", "properties": {key: _STRING for key in CANVAS_KEYS}},
"strategic_goals": {"type": "ARRAY", "items": _STRING},
"missing_context": _STRING,
}, "required": ["product_summary", "value_proposition", "lean_canvas", "strategic_goals", "missing_context"]}
@@ -89,14 +91,23 @@ def _github_headers(token):
return headers
+async def _request(url, timeout, **kwargs):
+ # The Workers fetch transport ignores request_json's timeout, so enforce it here.
+ return await asyncio.wait_for(request_json(url, timeout=timeout, **kwargs), timeout)
+
+
async def fetch_product_sources(repo, token=None):
- """Repository description, topics, homepage and README text from GitHub's REST API."""
+ """Repository description, topics, homepage and README text from GitHub's REST API.
+
+ Raises ValueError unless the repository is public when read, so private
+ content is never sent to Gemini even if visibility changed mid-analysis.
+ """
headers = _github_headers(token)
base = f"https://api.github.com/repos/{repo}"
- (meta_status, _, meta), (readme_status, _, readme) = await asyncio.gather(
- request_json(base, headers=headers, timeout=10),
- request_json(f"{base}/readme", headers=headers, timeout=10))
- meta = meta if 200 <= meta_status < 300 else {}
+ meta_status, _, meta = await _request(base, 10, headers=headers)
+ if not 200 <= meta_status < 300 or meta.get("private") is not False:
+ raise ValueError("Repository is not public")
+ readme_status, _, readme = await _request(f"{base}/readme", 10, headers=headers)
text = ""
if 200 <= readme_status < 300 and readme.get("encoding") == "base64":
text = base64.b64decode(readme.get("content", "")).decode("utf-8", "replace")
@@ -110,8 +121,8 @@ async def gemini_json(key, prompt, schema, max_tokens=1200):
body = {"contents": [{"role": "user", "parts": [{"text": prompt}]}],
"generationConfig": {"temperature": 0.2, "maxOutputTokens": max_tokens,
"responseMimeType": "application/json", "responseSchema": schema}}
- status, _, payload = await request_json(GEMINI_URL, method="POST", headers={"x-goog-api-key": key},
- body=body, timeout=25)
+ status, _, payload = await _request(GEMINI_URL, GEMINI_TIMEOUT, method="POST",
+ headers={"x-goog-api-key": key}, body=body)
if status < 200 or status >= 300:
raise ValueError(f"Gemini returned HTTP {status}")
try:
@@ -123,11 +134,31 @@ async def gemini_json(key, prompt, schema, max_tokens=1200):
def select_prs(data, value_classification, max_prs=DEFAULT_MAX_PRS):
"""Most recent sampled PRs to assess: up to a third open, the rest merged."""
- raw = {pr.get("number"): pr for key in ("recent_prs", "open_prs") for pr in data.get(key) or []}
- items = value_classification["prs"]["items"]
- open_items = [i for i in items if i["cohort"] == "open"][:max_prs // 3]
- merged = [i for i in items if i["cohort"] == "merged"][:max_prs - len(open_items)]
- return [(item, raw.get(item["number"], {})) for item in merged + open_items]
+ raw = {(cohort, pr.get("number")): pr for cohort, key in (("open", "open_prs"), ("merged", "recent_prs"))
+ for pr in reversed(data.get(key) or [])} # reversed so the first record of a number wins
+
+ def newest(cohort, date_key):
+ pairs = [(i, raw.get((cohort, i["number"]), {})) for i in value_classification["prs"]["items"]
+ if i["cohort"] == cohort]
+ return sorted(pairs, key=lambda pair: pair[1].get(date_key) or "", reverse=True)
+
+ open_pairs = newest("open", "createdAt")[:max_prs // 3]
+ return newest("merged", "mergedAt")[:max_prs - len(open_pairs)] + open_pairs
+
+
+def _clean_context(context):
+ """Normalize Gemini's product context; raise ValueError when it is not one."""
+ if not isinstance(context, dict):
+ raise ValueError("Gemini returned a context that is not an object")
+ canvas = context.get("lean_canvas")
+ canvas = canvas if isinstance(canvas, dict) else {}
+ goals = context.get("strategic_goals")
+ goals = goals if isinstance(goals, list) else []
+ return {"product_summary": str(context.get("product_summary") or "").strip(),
+ "value_proposition": str(context.get("value_proposition") or "").strip(),
+ "lean_canvas": {key: str(canvas[key]).strip() for key in CANVAS_KEYS if canvas.get(key)},
+ "strategic_goals": [str(goal).strip() for goal in goals if goal],
+ "missing_context": str(context.get("missing_context") or "").strip()}
def _context_text(context):
@@ -145,6 +176,9 @@ def _clean(assessment):
result["expected_value"] = "Unclear"
if result["confidence"] not in CONFIDENCE_LEVELS:
result["confidence"] = "Low"
+ if not all(result[key] for key in NARRATIVE_KEYS): # a rating without its reasoning is unsupported
+ result["expected_value"], result["confidence"] = "Unclear", "Low"
+ result["missing_context"] = result["missing_context"] or "Gemini gave no reasoning for this PR."
return result
@@ -179,6 +213,7 @@ async def assess_product_value(repo, data, key, token=None, max_prs=DEFAULT_MAX_
repo=repo, description=sources["description"] or "(none)",
topics=", ".join(sources["topics"]) or "(none)", homepage=sources["homepage"] or "(none)",
readme=sources["readme"] or "(no README)"), CONTEXT_SCHEMA, 1500)
+ context = _clean_context(context)
except Exception: # httpx errors locally, JS fetch errors on Workers, bad answers
return {**result, "status": "failed", "reason": "Product context could not be generated."}
result["sources"] = {"description": bool(sources["description"]), "readme": bool(sources["readme"]),
@@ -191,7 +226,9 @@ async def bounded(item, pr):
async with limit:
return await assess_pr(key, context_text, item, pr)
- result["items"] = list(await asyncio.gather(*(bounded(item, pr) for item, pr in select_prs(data, value_classification, max_prs))))
+ selected = select_prs(data, value_classification, max_prs)
+ result["selected"] = len(selected)
+ result["items"] = list(await asyncio.gather(*(bounded(item, pr) for item, pr in selected)))
counts = dict.fromkeys(VALUE_LEVELS, 0)
for item in result["items"]:
if item["status"] == "assessed":
diff --git a/public/index.html b/public/index.html
index e6ca5e6..2f6f0d6 100644
--- a/public/index.html
+++ b/public/index.html
@@ -804,7 +804,7 @@
Antigravity AI Coach
return;
}
const sources = value.sources || {};
- note.textContent = `${value.disclaimer} Assessed ${value.assessed} of ${value.total_prs} sampled PRs` +
+ note.textContent = `${value.disclaimer} Assessed ${value.assessed} of the ${value.selected} most recent of ${value.total_prs} sampled PRs` +
(value.failed ? ` (${value.failed} failed)` : '') + '. ' +
value.levels.map(level => `${level}: ${value.counts[level]}`).join(' · ') +
`. Context from ${[sources.description && 'description', sources.readme && (sources.readme_truncated ? 'README (truncated)' : 'README')].filter(Boolean).join(' and ') || 'no repository text'} via ${value.model}.`;
diff --git a/public/privacy.html b/public/privacy.html
index b8968bd..844a271 100644
--- a/public/privacy.html
+++ b/public/privacy.html
@@ -14,6 +14,7 @@
Information saved
When you sign in, we save your verified Google email address, Google's stable account identifier, the first and most recent sign-in times, and a sign-in count. We use this information to recognize returning users and understand account usage. We do not use it for marketing, sell it, or send it to the AI coach.
Repository and AI requests
Repository analysis uses public GitHub data. If you ask the AI coach a question, the question and repository metrics are sent to Google's Gemini service. Your Google sign-in details are not included in that request.
+
When an analysis estimates each pull request's expected product value, the repository name, description, topics, homepage and README, and the titles, bodies and change sizes of up to 30 recent pull requests are sent to Google's Gemini service to infer the product's context and judge each pull request. These requests contain only public repository data and no sign-in details.
Storage and deletion
Account records and short-lived sign-in sessions are stored in Cloudflare's database. Choose Delete account in the app to remove your account record and sign-in sessions. A session cookie stays in your browser for up to fourteen days and is protected from JavaScript access.