diff --git a/.cloudflare/preview-resources.json b/.cloudflare/preview-resources.json new file mode 100644 index 0000000..3d53bfe --- /dev/null +++ b/.cloudflare/preview-resources.json @@ -0,0 +1,10 @@ +{ + "account_id": "6fe100eefdfd984dd38a91a1a5643520", + "worker": "github-flow-analytics", + "cache_namespace": "github-flow-analytics-preview-cache", + "users_database": "github-flow-analytics-preview-users", + "rate_limit_namespaces": { + "ANALYZE_LIMIT": "2001", + "CHAT_LIMIT": "2002" + } +} diff --git a/README.md b/README.md index c9962ae..e26e9f4 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,26 @@ 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. Only public repositories are assessed, and the README is fetched +without the GitHub token so GitHub refuses it if the repository has just gone private; +unauthenticated GitHub calls are limited to 60 per hour per IP, so when that limit is +hit the context uses the description and topics alone. 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 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 This project uses Cloudflare Python Workers (FastAPI), Workers Static Assets, KV for cached public results, and native Worker rate-limit bindings. @@ -82,6 +102,23 @@ runtime dependencies and SDK, and stages only the runtime source files under Local and CI pip dependencies live in `requirements-local.txt` and `requirements-dev.txt`; Pywrangler rejects a root `requirements.txt`. +Branch builds use `npx wrangler preview` (Wrangler 4.135.0 or newer), which requires +an explicit `previews` block. Preview resources are declared in +`.cloudflare/preview-resources.json`. Run `python scripts/configure-cloudflare-previews.py` +to inspect the setup. After authorizing resource creation, export the existing +Cloudflare API token from Bitwarden and run the same command with `--apply`. +It reuses or creates the named Preview KV namespace and D1 database, initializes +the empty users/session schema, and writes their real IDs to `wrangler.jsonc`. +Rerunning it reuses those resources. It preserves production bindings and data. + +Previews share these staging resources with other branches. They require Google +sign-in and use separate rate-limit namespaces with the same request limits. +Preview URLs are public; protected API endpoints still require a session. The +configured Google OAuth client must allow the Preview's JavaScript origin before +sign-in can work there. This setup leaves Google OAuth settings unchanged. +Preview service secrets are configured separately in Cloudflare's Previews Base; +Gemini assessment requires a Preview `GEMINI_API_KEY`. + The `public/` assets are synced from the root HTML files during deployment. Do not add credentials to `.dev.vars`, source files, or commits. The deployed API only accepts public repositories. Check current Cloudflare plan limits and pricing before deployment; repository analysis and AI requests incur provider usage. 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..af1a1e9 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,8 +241,12 @@ 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) + 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 1eca295..2f6f0d6 100644 --- a/index.html +++ b/index.html @@ -579,6 +579,12 @@

Batch Size & Flow Timeline

+ @@ -781,6 +787,45 @@

Antigravity AI Coach

renderComet(d.comet_points); renderIssues(d.issues); renderValueClassification(d.value_classification); + renderProductValue(d.product_value); + } + + function renderProductValue(value) { + const card = document.getElementById('product-value-card'); + card.style.display = value ? 'block' : 'none'; + if (!value) return; + const note = document.getElementById('product-value-note'); + const contextEl = document.getElementById('product-value-context'); + const table = document.getElementById('product-value-items'); + if (value.status !== 'ok') { + note.textContent = `Not assessed: ${value.reason || 'unavailable.'} ${value.disclaimer}`; + contextEl.innerHTML = ''; + table.innerHTML = ''; + return; + } + const sources = value.sources || {}; + 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}.`; + const ctx = value.context || {}; + const goals = (ctx.strategic_goals || []).map(goal => `
  • ${escapeHtml(goal)}
  • `).join(''); + const canvas = Object.entries(ctx.lean_canvas || {}).map(([key, text]) => + `${escapeHtml(key.replace(/_/g, ' '))}${escapeHtml(text)}`).join(''); + contextEl.innerHTML = `

    Product: ${escapeHtml(ctx.product_summary || 'Unknown')}

    ` + + `

    Value proposition: ${escapeHtml(ctx.value_proposition || 'Unknown')}

    ` + + (goals ? `

    Strategic goals (inferred)

      ${goals}
    ` : '') + + (canvas ? `
    Lean canvas (inferred)${canvas}
    ` : '') + + (ctx.missing_context ? `

    Missing context: ${escapeHtml(ctx.missing_context)}

    ` : ''); + table.innerHTML = 'PRStateFramingExpected valueWhat, who, whyUncertainty' + + (value.items.map(item => item.status !== 'assessed' ? + `#${escapeHtml(item.number)} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.framing)}Assessment failed.` : + `#${escapeHtml(item.number)} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.framing)}` + + `${escapeHtml(item.expected_value)}
    ${escapeHtml(item.confidence)} confidence` + + `${escapeHtml(item.value_summary)}
    Benefits: ${escapeHtml(item.beneficiaries)}
    Why: ${escapeHtml(item.why_it_matters)}` + + (item.strategic_goal && item.strategic_goal !== 'None' ? `
    Goal: ${escapeHtml(item.strategic_goal)}` : '') + '' + + `${escapeHtml(item.missing_context)}`).join('') || + 'No PRs in this sample.') + ''; } let valueClassification = null; 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.

    Return to the dashboard

    diff --git a/product_value.py b/product_value.py new file mode 100644 index 0000000..794e24b --- /dev/null +++ b/product_value.py @@ -0,0 +1,237 @@ +"""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 +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.") + +_STRING = {"type": "STRING"} +CONTEXT_SCHEMA = {"type": "OBJECT", "properties": { + "product_summary": _STRING, + "value_proposition": _STRING, + "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"]} + +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 _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. + + Raises ValueError unless the repository is public when read. The README is + fetched without the token, so GitHub itself refuses it if the repository went + private after the metadata check; a refused or rate-limited README is skipped. + """ + base = f"https://api.github.com/repos/{repo}" + meta_status, _, meta = await _request(base, 10, headers=_github_headers(token)) + 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=_github_headers(None)) + 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(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: + 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 = {(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): + 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" + 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 + + +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) + 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"]), + "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) + + 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": + 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..2f6f0d6 100644 --- a/public/index.html +++ b/public/index.html @@ -579,6 +579,12 @@

    Batch Size & Flow Timeline

    + @@ -781,6 +787,45 @@

    Antigravity AI Coach

    renderComet(d.comet_points); renderIssues(d.issues); renderValueClassification(d.value_classification); + renderProductValue(d.product_value); + } + + function renderProductValue(value) { + const card = document.getElementById('product-value-card'); + card.style.display = value ? 'block' : 'none'; + if (!value) return; + const note = document.getElementById('product-value-note'); + const contextEl = document.getElementById('product-value-context'); + const table = document.getElementById('product-value-items'); + if (value.status !== 'ok') { + note.textContent = `Not assessed: ${value.reason || 'unavailable.'} ${value.disclaimer}`; + contextEl.innerHTML = ''; + table.innerHTML = ''; + return; + } + const sources = value.sources || {}; + 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}.`; + const ctx = value.context || {}; + const goals = (ctx.strategic_goals || []).map(goal => `
  • ${escapeHtml(goal)}
  • `).join(''); + const canvas = Object.entries(ctx.lean_canvas || {}).map(([key, text]) => + `${escapeHtml(key.replace(/_/g, ' '))}${escapeHtml(text)}`).join(''); + contextEl.innerHTML = `

    Product: ${escapeHtml(ctx.product_summary || 'Unknown')}

    ` + + `

    Value proposition: ${escapeHtml(ctx.value_proposition || 'Unknown')}

    ` + + (goals ? `

    Strategic goals (inferred)

      ${goals}
    ` : '') + + (canvas ? `
    Lean canvas (inferred)${canvas}
    ` : '') + + (ctx.missing_context ? `

    Missing context: ${escapeHtml(ctx.missing_context)}

    ` : ''); + table.innerHTML = 'PRStateFramingExpected valueWhat, who, whyUncertainty' + + (value.items.map(item => item.status !== 'assessed' ? + `#${escapeHtml(item.number)} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.framing)}Assessment failed.` : + `#${escapeHtml(item.number)} ${escapeHtml(item.title)}${escapeHtml(item.cohort)}${escapeHtml(item.framing)}` + + `${escapeHtml(item.expected_value)}
    ${escapeHtml(item.confidence)} confidence` + + `${escapeHtml(item.value_summary)}
    Benefits: ${escapeHtml(item.beneficiaries)}
    Why: ${escapeHtml(item.why_it_matters)}` + + (item.strategic_goal && item.strategic_goal !== 'None' ? `
    Goal: ${escapeHtml(item.strategic_goal)}` : '') + '' + + `${escapeHtml(item.missing_context)}`).join('') || + 'No PRs in this sample.') + ''; } let valueClassification = null; 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.

    Return to the dashboard

    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/configure-cloudflare-previews.py b/scripts/configure-cloudflare-previews.py new file mode 100644 index 0000000..ef2f11c --- /dev/null +++ b/scripts/configure-cloudflare-previews.py @@ -0,0 +1,110 @@ +"""Plan isolated Preview resources; --apply provisions them and updates Wrangler. + +Requires CLOUDFLARE_API_TOKEN with Workers KV Storage Write and D1 Write when +applying. Never deploys, copies production data, or changes Google OAuth settings. +Python standard library only; works on macOS, Linux and Windows. +""" +import argparse +from copy import deepcopy +import json +import os +from pathlib import Path +import re +import urllib.error +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +CONFIG = ROOT / 'wrangler.jsonc' +MANIFEST = ROOT / '.cloudflare' / 'preview-resources.json' + + +def api(account, path, method='GET', payload=None): + request = urllib.request.Request( + f'https://api.cloudflare.com/client/v4/accounts/{account}/{path}', + data=json.dumps(payload).encode() if payload is not None else None, + headers={'Authorization': f'Bearer {os.environ["CLOUDFLARE_API_TOKEN"]}', + 'Content-Type': 'application/json'}, method=method) + try: + with urllib.request.urlopen(request, timeout=60) as response: # nosec B310: fixed HTTPS origin + body = json.load(response) + except urllib.error.HTTPError as exc: + raise RuntimeError(f'Cloudflare {method} failed (HTTP {exc.code}); response suppressed.') from None + if not body.get('success'): + raise RuntimeError(f'Cloudflare {method} failed; response suppressed.') + result = body['result'] + if isinstance(result, list) and any(item.get('success') is False for item in result): + raise RuntimeError('Cloudflare query failed; response suppressed.') + return result + + +def find_resource(account, path, field, name): + matches = [] + page = 1 + while True: + items = api(account, f'{path}?page={page}&per_page=100') + matches.extend(item for item in items if item.get(field) == name) + if len(items) < 100: + break + page += 1 + if len(matches) > 1: + raise ValueError(f'Multiple resources named {name}; refusing to choose one.') + return matches[0] if matches else None + + +def assert_isolated(config, kv, database): + if kv and kv['id'] in {item.get('id') for item in config.get('kv_namespaces', [])}: + raise ValueError('Preview KV must not use a production namespace.') + if database and database['uuid'] in {item.get('database_id') for item in config.get('d1_databases', [])}: + raise ValueError('Preview D1 must not use a production database.') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--apply', action='store_true', help='Create missing Preview resources, initialize schema, and write config') + args = parser.parse_args() + manifest = json.loads(MANIFEST.read_text(encoding='utf-8')) + config = json.loads(CONFIG.read_text(encoding='utf-8')) + if config['name'] != manifest['worker'] or not re.fullmatch(r'[a-f0-9]{32}', manifest['account_id']): + raise ValueError('Preview manifest must identify this Worker and a valid account ID.') + if any(not manifest[key].startswith(config['name'] + '-preview-') for key in ['cache_namespace', 'users_database']): + raise ValueError('Preview resources must use this Worker\'s preview prefix.') + production_limits = {item['namespace_id'] for item in config['ratelimits']} + preview_limits = list(manifest['rate_limit_namespaces'].values()) + if len(set(preview_limits)) != len(preview_limits) or production_limits.intersection(preview_limits): + raise ValueError('Preview rate-limit namespaces must be distinct from each other and production.') + print(json.dumps(manifest, indent=2)) + if not args.apply: + print('Plan only. --apply reuses or creates the named KV/D1 resources, initializes the Preview schema, ' + 'and writes Preview bindings. No deployment, production data copy, or OAuth change.') + return 0 + if not os.environ.get('CLOUDFLARE_API_TOKEN'): + raise RuntimeError('Export CLOUDFLARE_API_TOKEN from Bitwarden before --apply.') + account = manifest['account_id'] + kv = find_resource(account, 'storage/kv/namespaces', 'title', manifest['cache_namespace']) + database = find_resource(account, 'd1/database', 'name', manifest['users_database']) + assert_isolated(config, kv, database) # Check both before creating or mutating anything. + if kv is None: + kv = api(account, 'storage/kv/namespaces', 'POST', {'title': manifest['cache_namespace']}) + if database is None: + database = api(account, 'd1/database', 'POST', {'name': manifest['users_database']}) + assert_isolated(config, kv, database) + # This initial schema is idempotent (IF NOT EXISTS), contains no user records, + # and runs only against the independently resolved Preview database. + api(account, f'd1/database/{database["uuid"]}/query', 'POST', + {'sql': (ROOT / 'migrations' / '0001_users.sql').read_text(encoding='utf-8')}) + preview = config.setdefault('previews', {}) + preview['vars'] = {**preview.get('vars', {}), 'AUTH_REQUIRED': 'true', + 'GOOGLE_OAUTH_CLIENT_ID': config['vars']['GOOGLE_OAUTH_CLIENT_ID']} + preview['kv_namespaces'] = [{'binding': 'ANALYTICS_CACHE', 'id': kv['id']}] + preview['d1_databases'] = [{'binding': 'USERS_DB', 'database_name': manifest['users_database'], + 'database_id': database['uuid']}] + preview['ratelimits'] = deepcopy(config['ratelimits']) + for item in preview['ratelimits']: + item['namespace_id'] = manifest['rate_limit_namespaces'][item['name']] + CONFIG.write_text(json.dumps(config, indent=2) + '\n', encoding='utf-8') + print('Isolated Preview resources and schema are ready; Wrangler config updated. Nothing deployed.') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) 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..9d969eb --- /dev/null +++ b/tests/integration/test_product_value.py @@ -0,0 +1,230 @@ +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.", + context=CONTEXT, private=False): + self.assessments = assessments or {} + self.context_status = context_status + self.readme = readme + self.context = context + self.private = private + self.prompts = [] + self.urls = [] + self.readme_headers = None + + async def __call__(self, url, *, headers, method="GET", body=None, timeout=15): + self.urls.append(url) + if url.endswith("/readme"): + self.readme_headers = headers + if self.readme is None: + return 403, {}, {"message": "API rate limit exceeded"} + 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": "", + "private": self.private} + 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(self.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 result["selected"] == 3 and result["total_prs"] == 3 + 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 + + +@pytest.mark.parametrize("context", [["not", "an", "object"], {**CONTEXT, "lean_canvas": "text"}]) +def test_malformed_context_fails_soft_or_is_normalized(services, context): + services(context=context, assessments={n: assessment("Low") for n in (1, 2, 3)}) + result = run() + if isinstance(context, list): + assert result["status"] == "failed" and "context" in result["reason"] + else: + assert result["status"] == "ok" and result["context"]["lean_canvas"] == {} + + +def test_private_repository_sends_nothing_to_gemini(services): + fake = services(private=True) + result = run() + assert result["status"] == "failed" + assert fake.prompts == [] and not any(url.endswith("/readme") for url in fake.urls) + + +def test_readme_is_fetched_without_the_token_and_skipped_when_refused(services): + fake = services(readme=None) + result = run(token="secret") + assert "Authorization" not in fake.readme_headers + assert result["status"] == "ok" and result["sources"]["readme"] is False + assert "(no README)" in fake.prompts[0] + + +def test_unresponsive_gemini_times_out_as_failed(monkeypatch): + async def hang(url, **_): + if "generativelanguage" in url: + await asyncio.sleep(10) + return 200, {}, {"private": False} + + monkeypatch.setattr(product_value, "request_json", hang) + monkeypatch.setattr(product_value, "GEMINI_TIMEOUT", 0.01) + assert run()["status"] == "failed" + + +def test_empty_reasoning_is_downgraded_to_unclear(services): + services(assessments={n: assessment("High", value_summary="", confidence="High") for n in (1, 2, 3)}) + item = run()["items"][0] + assert (item["expected_value"], item["confidence"]) == ("Unclear", "Low") + assert item["missing_context"] + + +def test_selection_is_most_recent_and_pairs_each_cohort_with_its_own_record(): + data = {"recent_prs": [{"number": 1, "title": "Old", "mergedAt": "2026-01-01T00:00:00Z", "body": "merged"}, + {"number": 2, "title": "New", "mergedAt": "2026-09-01T00:00:00Z"}], + "open_prs": [{"number": 1, "title": "Old", "createdAt": "2026-10-01T00:00:00Z", "body": "open"}]} + selected = product_value.select_prs(data, product_value.compute_value_classification(data)) + assert [(item["number"], item["cohort"]) for item, _ in selected] == [(2, "merged"), (1, "merged")] + assert selected[1][1]["body"] == "merged" + + +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 + + +@pytest.mark.parametrize("value, ttl", [({"status": "ok", "items": []}, 21600), + ({"status": "failed", "items": []}, 600), + ({"status": "ok", "items": [], "failed": 2}, 600)]) +def test_hosted_analysis_attaches_product_value_before_caching(monkeypatch, value, ttl): + 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 value + + class Cache: + stored = {} + ttls = [] + + async def get(self, _): + return None + + async def put(self, key, value, expiration_ttl): + self.stored[key] = json.loads(value) + self.ttls.append(expiration_ttl) + + 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"] == value["status"] + assert seen["args"] == ("o/r", {"repo": "o/r"}, "k") + assert cache.stored[hosted.METRICS_CACHE_PREFIX + "o/r"]["product_value"]["status"] == value["status"] + assert cache.ttls[-1] == ttl 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") diff --git a/tests/unit/test_cloudflare_previews.py b/tests/unit/test_cloudflare_previews.py new file mode 100644 index 0000000..eb71aeb --- /dev/null +++ b/tests/unit/test_cloudflare_previews.py @@ -0,0 +1,93 @@ +"""Preview setup must never mutate production or write resources without --apply.""" +import importlib.util +import json +from pathlib import Path +import sys + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('cloudflare_previews', ROOT / 'scripts/configure-cloudflare-previews.py') +script = importlib.util.module_from_spec(spec) +spec.loader.exec_module(script) + + +def test_default_only_describes_the_plan(monkeypatch): + monkeypatch.setattr(sys, 'argv', ['configure-cloudflare-previews.py']) + monkeypatch.setattr(script, 'api', lambda *args, **kwargs: pytest.fail('Plan must not call Cloudflare')) + assert script.main() == 0 + + +def test_apply_is_resumable_and_never_recreates_existing_resources(monkeypatch, tmp_path): + config_path = tmp_path / 'wrangler.jsonc' + config_path.write_text((ROOT / 'wrangler.jsonc').read_text()) + monkeypatch.setattr(script, 'CONFIG', config_path) + monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-token') + monkeypatch.setattr(sys, 'argv', ['configure-cloudflare-previews.py', '--apply']) + calls = [] + + def fake(account, path, method='GET', payload=None): + calls.append((path, method, payload)) + if method == 'GET': + return [{'id': 'preview-kv', 'title': 'github-flow-analytics-preview-cache'}] if 'storage/kv' in path else [ + {'uuid': 'preview-d1', 'name': 'github-flow-analytics-preview-users'}] + assert path == 'd1/database/preview-d1/query' + assert 'CREATE TABLE IF NOT EXISTS users' in payload['sql'] + return [{'success': True}] + + monkeypatch.setattr(script, 'api', fake) + assert script.main() == 0 + assert script.main() == 0 + assert [method for _, method, _ in calls].count('POST') == 2 # schema only, on the preview database + preview = json.loads(config_path.read_text())['previews'] + assert preview['vars']['AUTH_REQUIRED'] == 'true' + assert preview['kv_namespaces'][0]['id'] == 'preview-kv' + assert preview['d1_databases'][0]['database_id'] == 'preview-d1' + + +@pytest.mark.parametrize('kind', ['kv', 'd1']) +def test_refuses_production_resources_before_any_write(monkeypatch, tmp_path, kind): + config_path = tmp_path / 'wrangler.jsonc' + config = json.loads((ROOT / 'wrangler.jsonc').read_text()) + production_id = config['d1_databases'][0]['database_id'] if kind == 'd1' else config['kv_namespaces'][0]['id'] + config_path.write_text(json.dumps(config)) + monkeypatch.setattr(script, 'CONFIG', config_path) + monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-token') + monkeypatch.setattr(sys, 'argv', ['configure-cloudflare-previews.py', '--apply']) + + def fake(account, path, method='GET', payload=None): + assert method == 'GET', 'Production isolation must be checked before any write' + if 'storage/kv' in path: + return [{'id': production_id, 'title': 'github-flow-analytics-preview-cache'}] if kind == 'kv' else [] + return [{'uuid': production_id, 'name': 'github-flow-analytics-preview-users'}] if kind == 'd1' else [] + + monkeypatch.setattr(script, 'api', fake) + with pytest.raises(ValueError, match='production'): + script.main() + + +def test_apply_creates_missing_resources_then_initializes_only_the_new_database(monkeypatch, tmp_path): + config_path = tmp_path / 'wrangler.jsonc' + original = json.loads((ROOT / 'wrangler.jsonc').read_text()) + config_path.write_text(json.dumps(original)) + monkeypatch.setattr(script, 'CONFIG', config_path) + monkeypatch.setenv('CLOUDFLARE_API_TOKEN', 'test-token') + monkeypatch.setattr(sys, 'argv', ['configure-cloudflare-previews.py', '--apply']) + writes = [] + + def fake(account, path, method='GET', payload=None): + if method == 'GET': + return [] + writes.append((path, payload)) + if path == 'storage/kv/namespaces': + return {'id': 'new-preview-kv'} + if path == 'd1/database': + return {'uuid': 'new-preview-d1'} + assert path == 'd1/database/new-preview-d1/query' + return [{'success': True}] + + monkeypatch.setattr(script, 'api', fake) + assert script.main() == 0 + assert [path for path, _ in writes] == ['storage/kv/namespaces', 'd1/database', 'd1/database/new-preview-d1/query'] + updated = json.loads(config_path.read_text()) + assert {k: v for k, v in updated.items() if k != 'previews'} == {k: v for k, v in original.items() if k != 'previews'} diff --git a/uv.lock b/uv.lock index 198b7f9..d159a70 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.13" resolution-markers = [ "python_full_version >= '3.14'", @@ -39,11 +39,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.7.22" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -648,14 +648,14 @@ wheels = [ [[package]] name = "opentelemetry-api" -version = "1.45.0" +version = "1.45.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1f/dc/e12c1fe1ed8a7b7149777127b1a0e12ce5bd5a81d97408bedc2128c260f5/opentelemetry_api-1.45.0.tar.gz", hash = "sha256:711ede81773c8025c2c03dac0450bc89f3d30aea6eabcc815c570d4e35a963f7", size = 72115, upload-time = "2026-09-25T12:32:28.399Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2e/02/6e0ae9cc61bd3169d401077b507b3ebc344745171e1051ab430be012dcd9/opentelemetry_api-1.45.1.tar.gz", hash = "sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75", size = 72804, upload-time = "2026-10-06T17:32:58.133Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/44/b9/040d1a1c7836922828e6480cd2366bb8fe0ebf75b413d2bb51a9b0e7f78f/opentelemetry_api-1.45.0-py3-none-any.whl", hash = "sha256:80e068aba7cd56c8b58512d6a36f8d25cb1dfaa0c0a4cc1c938ccf9f362d9cb3", size = 60020, upload-time = "2026-09-25T12:32:03.192Z" }, + { url = "https://files.pythonhosted.org/packages/1e/41/f7dcf80b81ee8e71c1a2b59f14208bc723edbd89ed027a73b175abf6348e/opentelemetry_api-1.45.1-py3-none-any.whl", hash = "sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb", size = 60256, upload-time = "2026-10-06T17:32:33.506Z" }, ] [[package]] diff --git a/wrangler.jsonc b/wrangler.jsonc index 4540d6e..e1a780e 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -62,5 +62,42 @@ "build": { "command": "python3 scripts/prepare-cloudflare-build.py" }, - "base_dir": ".wrangler/worker" + "base_dir": ".wrangler/worker", + "previews": { + "vars": { + "AUTH_REQUIRED": "true", + "GOOGLE_OAUTH_CLIENT_ID": "914195447285-huoatl4c0c0e8qrcou5m3n2aalaj7jri.apps.googleusercontent.com" + }, + "kv_namespaces": [ + { + "binding": "ANALYTICS_CACHE", + "id": "1321f14a5ac34563a73d6289e94d775e" + } + ], + "d1_databases": [ + { + "binding": "USERS_DB", + "database_name": "github-flow-analytics-preview-users", + "database_id": "f3a968e1-41a1-4e9f-a0f9-e427cea95b01" + } + ], + "ratelimits": [ + { + "name": "ANALYZE_LIMIT", + "namespace_id": "2001", + "simple": { + "limit": 6, + "period": 60 + } + }, + { + "name": "CHAT_LIMIT", + "namespace_id": "2002", + "simple": { + "limit": 12, + "period": 60 + } + } + ] + } }