diff --git a/README.md b/README.md index 192e980..0569512 100644 --- a/README.md +++ b/README.md @@ -193,18 +193,23 @@ The guide's request body, the same xz-compressed bytes the service receives, is never carries `source.json`, and it is left out when no guide request goes out. A third request, `POST /v1/merge-risk`, goes to the same base URL at the same time and sends -no analysis: only the pull request's changed files with their patches, as GitHub lists them. -With `closed_features_source: false` it sends no patches, only each file's path, additions and -deletions, so the diff's size and the areas its paths fall in still count. A diff too large to -send with its patches goes the same way. Without patches the checks that read added code (areas it -mentions, new dependencies) cannot run: the answer says so in `facts.patches`, the run logs a -notice, and the web platform shows it rather than reading the silence as clean. This input does not -keep code from the review guide, whose request carries the changed files at both commits. -The answer, the diff's merge-risk facts and the reasons they give, is saved as -`closed/merge_risk.json` with the head it describes, and summed up in one hidden line of the -review comment, ``, which the web platform's dashboard -reads. When the request fails, or the pull request moved on to a newer head during the run, -neither is written and the run logs one notice. +no analysis: only the pull request's title, description and changed files with their patches, as +GitHub lists them. The service counts size and tests itself, asks a fixed eight-question checklist +about the diff (sign-in and access, billing, stored data, releases, dependency and platform versions, +public interfaces), has a model decide each answer and a second pass drop the false alarms, with a +sentence and the changed line behind each risk it keeps. With your own provider key it sends the +same provider headers as the guide: your model makes the decision and the review, and the +checklist's classifier, which only CodeBoarding's key can reach, is skipped. With +`closed_features_source: false` it sends neither patches nor the description, only each file's +path, additions and deletions; a diff too large to send with its patches goes the same way. +Without patches the checklist cannot run: the answer comes back `partial` with size and tests only, +the run logs a notice, and the web platform shows the level as not assessed rather than reading the +silence as clean. This input does not keep code from the review guide, whose request carries the +changed files at both commits. +The answer is saved as `closed/merge_risk.json` with the head it describes, and summed up in one +hidden line of the review comment, ``, which the web +platform's dashboard reads. When the request fails, or the pull request moved on to a newer head +during the run, neither is written and the run logs one notice. Only architecture receives optional `source.json`: tracked Python, JavaScript/TypeScript and C# files (`.py`, `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.cs`, `.csproj`), excluding @@ -212,8 +217,9 @@ dependency/build directories, docs/public/fixtures, minified JS and TypeScript d Symlinks are not read. Individual files are capped at 300 KB and source at 16 MB. If adding source exceeds the 4.3 MB compressed request limit, it is omitted with a reason; architecture still runs with the required inputs. `closed_features_source: false` also omits source, and -merge risk then sends its file list without patches. -An unsupported provider skips the guide, but architecture can still return measured findings. +merge risk then sends its file list without patches and leaves out the pull request's description. +An unsupported provider skips the guide, but architecture can still return measured findings, and +merge risk returns size and tests only (`unchecked: no_model`). ### Providers @@ -425,7 +431,7 @@ The update runs after the baseline is saved, stops itself after 10 minutes and n | `codeboarding_analysis_location` | both | `codeboarding_branch` | Where the synced branch's analysis is stored: `codeboarding_branch` (on `codeboarding/baseline`, for the default branch; the code is never written) or `in_place` (committed as `.codeboarding/` on the synced branch). Sync saves it there and review reads it from there. | | `warmstart_retention_days` | review | `1` | Days to keep the reusable analysis. Only the next run reads it. | | `review_guide_url` | both | `https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/` | Experimental. Shared base URL for `/v1/review-guide`, `/v1/architecture` and `/v1/merge-risk`, and for sync's `/v1/briefing` when `problem_history` is on. Saves `review_guide.json`, `closed/architecture.json`, `closed/merge_risk.json` and the guide's request (`closed/bundle.json.xz`) in the review artifact. Set to `''` to disable them all. Never fails the run. | -| `closed_features_source` | review | `true` | Whether architecture checks may read this repository's source. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees code around a finding, never the tree. With `false`, source-dependent checks and model review do not run, and the result says so; merge risk sends the changed files' paths and line counts without their patches. It does not change what the review guide's request carries. | +| `closed_features_source` | review | `true` | Whether architecture checks may read this repository's source. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees code around a finding, never the tree. With `false`, source-dependent checks and model review do not run, and the result says so; merge risk sends the changed files' paths and line counts without their patches, and not the pull request's description. It does not change what the review guide's request carries. | | `problem_history` | sync | `false` | Opt-in. With `'true'`, each sync sends this repository's issues and merged pull requests to `review_guide_url` and commits the returned problem list as `problems.json` on the orphan branch `codeboarding/briefing`. Needs `contents: write`, `issues: read`, `pull-requests: read`, `actions: read` and `id-token: write` on the sync job. See [Problem history](#problem-history). Never fails the run. | `target_branch` and `sync_strategy` are deprecated, and read as the `codeboarding_analysis_location` they stand for, with a warning: `sync_strategy: push` as `in_place`, `sync_strategy: pull_request` as `codeboarding_branch`. `target_branch` is accepted only when it names the branch the run is on: the push trigger picks the branch. `force_full: true` is ignored with a warning. Anything the new input cannot express fails, linking to [moving an existing setup](#moving-an-existing-setup). diff --git a/action.yml b/action.yml index 682314f..82410b8 100644 --- a/action.yml +++ b/action.yml @@ -147,10 +147,10 @@ inputs: description: >- Experimental. Service base URL for POST /v1/review-guide, POST /v1/architecture and POST /v1/merge-risk. Defaults to production. The first two receive this run's analysis and - the third its changed files, independently; results are stored as review_guide.json, - closed/architecture.json and closed/merge_risk.json, and the guide's request as sent as - closed/bundle.json.xz. Merge risk is also summed up in a hidden line of the review comment. - Set to an empty string to disable all three. + the third its title, description and changed files, independently; results are stored as + review_guide.json, closed/architecture.json and closed/merge_risk.json, and the guide's + request as sent as closed/bundle.json.xz. Merge risk is also summed up in a hidden line of + the review comment. Set to an empty string to disable all three. Sync's opt-in problem_history calls POST /v1/briefing on the same URL. required: false default: 'https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/' @@ -160,7 +160,8 @@ inputs: need the whole tree and to verify a finding. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees the code around a finding, never the tree. With 'false' those checks and the model review do not run, and the result says so. Merge - risk then sends the changed files' paths and line counts without their patches. + risk then sends the changed files' paths and line counts without their patches, and leaves + out the pull request's description, which can quote code. required: false default: 'true' problem_history: diff --git a/scripts/problem_history.py b/scripts/problem_history.py index fea3bc1..7c8e5c8 100644 --- a/scripts/problem_history.py +++ b/scripts/problem_history.py @@ -581,16 +581,11 @@ def review_findings(gh: GitHub, repo: str, pr: int, sha: str) -> dict | None: def _unread(ledger: dict | None) -> list[dict]: - """The ledger's merged pull requests whose findings were never read. A ledger from before - `warningsRead` has no flag; a merge with warnings stored counts as read.""" - warned = {w.get("pr") for w in (ledger or {}).get("warnings") or [] if isinstance(w, dict)} + """The ledger's merged pull requests whose findings were never read.""" return [ m for m in (ledger or {}).get("merged") or [] - if isinstance(m, dict) - and isinstance(m.get("number"), int) - and m.get("warningsRead") is not True - and m["number"] not in warned + if isinstance(m, dict) and isinstance(m.get("number"), int) and m.get("warningsRead") is not True ] diff --git a/scripts/remote_features.py b/scripts/remote_features.py index eaa7e95..8231287 100644 --- a/scripts/remote_features.py +++ b/scripts/remote_features.py @@ -7,8 +7,9 @@ including partial, skipped and failed results. The guide's request, exactly as sent, is stored as closed/bundle.json.xz, so a guide can be generated again from the same inputs. Merge risk is stored as closed/merge_risk.json when the service answered, and nothing is written when it did not. It sends -only the pull request's changed files with their patches, never the analysis, and no patches when the -workflow turns source off. +only the pull request's title, description and changed files with their patches, never the +analysis, and neither patches nor description when the workflow turns source off, in which case the +service answers with size and tests alone and says its checklist did not run. What a request sends -------------------- @@ -127,9 +128,6 @@ # preset, so its patches go before compressing rather than after. MERGE_RISK_PRESET = 1 MERGE_RISK_PATCH_RATIO = 10 -# The most dependency names the review comment's merge-risk line carries. The dashboard reads only -# whether there are any; the four it names come from the reason's own params. -MAX_MARKER_DEPS = 20 # The most the hidden line may take of the review comment, whose body GitHub caps at 65,536 characters. MAX_MARKER_CHARS = 8_000 @@ -690,7 +688,7 @@ def _no_architecture(ctx: dict, status: str, reason: str) -> dict: """Preserve the architecture envelope even when the request cannot complete.""" return { "feature": "architecture", - "schema": 1, + "schema": 2, "status": status, "repo": ctx["repo"], "pr": ctx["pr"], @@ -743,34 +741,35 @@ def run_architecture(service_url: str, ctx: dict, data: bytes, headers: dict) -> return _no_architecture(ctx, "skipped" if isinstance(error, Skip) else "failed", str(error)) -def merge_risk_files(ctx: dict) -> list[dict]: - """The pull request's changed files as GitHub lists them (at most 3,000, a very large file without - its patch), or Skip when the head moved on, since a newer run answers for that head.""" +def merge_risk_files(ctx: dict) -> tuple[str, str, list[dict]]: + """The pull request's title, description and changed files as GitHub lists them (at most 3,000, a very large + file without its patch), or Skip when the head moved on, since a newer run answers for that head.""" files: list[dict] = [] for page in range(1, 31): listed = _github_json(f"/repos/{ctx['repo']}/pulls/{ctx['pr']}/files?per_page=100&page={page}") files += [{field: changed.get(field) for field in MERGE_RISK_FIELDS} for changed in listed] if len(listed) < 100: break - if _github_json(f"/repos/{ctx['repo']}/pulls/{ctx['pr']}")["head"]["sha"] != ctx["head"]: + pull = _github_json(f"/repos/{ctx['repo']}/pulls/{ctx['pr']}") + if pull["head"]["sha"] != ctx["head"]: raise Skip("the pull request moved on to a newer head") - return files + return pull.get("title") or "", pull.get("body") or "", files def merge_risk_line(result: dict) -> str | None: """The review comment's hidden merge-risk line, for the web platform's dashboard. Compact JSON with `<`, `>` and `=` escaped, so nothing in it can end the comment (no `>`, so no `-->`) or match the - status line's `key=value` reader; a JSON parser reads the escapes back. None when it would be over - MAX_MARKER_CHARS, since a comment has room for 65,536 characters in all.""" + status line's `key=value` reader; a JSON parser reads the escapes back. It carries what the level + needs (the checklist's sensitive yeses, size, the reasons' codes) and leaves the explanations to + the artifact. None when it would be over MAX_MARKER_CHARS, since a comment has room for 65,536 + characters in all.""" compact = { - "v": 1, + "v": 2, "head": result["headSha"], + "checked": result["checklist"] is not None, "sensitive": result["sensitive"], - "areas": [area["name"] for area in result["facts"].get("areas") or [] if area.get("critical")], - "deps": (result["facts"].get("deps") or [])[:MAX_MARKER_DEPS], - "srcLines": result["facts"].get("srcLines", 0), - "sourceFiles": result["facts"].get("sourceFiles", 0), - "patches": result["facts"].get("patches", "all"), + "srcLines": result["facts"]["srcLines"], + "sourceFiles": result["facts"]["sourceFiles"], "reasons": [ {"level": reason["level"], "code": reason["code"], "params": reason.get("params") or {}} for reason in result["reasons"] @@ -783,11 +782,18 @@ def merge_risk_line(result: dict) -> str | None: return line if len(line) <= MAX_MARKER_CHARS else None -def merge_risk_request(ctx: dict, files: list[dict], with_patches: bool) -> bytes: +def merge_risk_request(ctx: dict, title: str, description: str, files: list[dict], with_patches: bool) -> bytes: """The merge-risk request, compressed at MERGE_RISK_PRESET. Its patches go when the workflow turns source off, or when the file list is over either limit with them: before compressing when the JSON alone is over MERGE_RISK_PATCH_RATIO times the compressed limit. Sizes and paths count without them.""" - body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files} + body = { + "version": 1, + "repo": ctx["repo"], + "pr": ctx["pr"], + "title": title, + "description": description, + "files": files, + } if with_patches: clearly_over = MERGE_RISK_PATCH_RATIO * MAX_COMPRESSED_BYTES try: @@ -803,30 +809,55 @@ def run_merge_risk(service_url: str, ctx: dict, headers: dict, env: dict, artifa the step's `merge_risk_line` output. It needs neither the analysis nor the guide, so it runs whatever happens to them, and a failure is one line in the log.""" try: - data = merge_risk_request(ctx, merge_risk_files(ctx), source_allowed(env)) + title, description, files = merge_risk_files(ctx) + source = source_allowed(env) + # With source off the description stays on the runner too: it can quote code. + data = merge_risk_request(ctx, title, description if source else "", files, source) answer = _post(f"{service_url.rstrip('/')}/v1/merge-risk", data, headers, timeout=120) if not isinstance(answer, dict) or not isinstance(answer.get("facts"), dict): raise ValueError("the service returned no merge-risk facts") + for fact in ("srcLines", "sourceFiles", "patches"): + if fact not in answer["facts"]: + raise ValueError(f"the service returned merge-risk facts without {fact}") + if answer.get("status") not in ("ok", "partial"): + raise ValueError(f"the service returned merge-risk status {answer.get('status')!r}") + for field in ("reasons", "sensitive"): + if not isinstance(answer.get(field), list): + raise ValueError(f"the service returned no merge-risk {field} list") + for reason in answer["reasons"]: + if not isinstance(reason, dict) or "level" not in reason or "code" not in reason: + raise ValueError("the service returned a merge-risk reason without a level and a code") + if not all(isinstance(question, str) for question in answer["sensitive"]): + raise ValueError("the service returned a merge-risk sensitive question that is not a string") + checklist = answer.get("checklist") + if checklist is not None and not isinstance(checklist, dict): + raise ValueError("the service returned a merge-risk checklist that is not an object") result = { "feature": "merge-risk", - "schema": 1, + "schema": 2, "repo": ctx["repo"], "pr": ctx["pr"], "headSha": ctx["head"], + "status": answer["status"], "facts": answer["facts"], - "reasons": answer.get("reasons") if isinstance(answer.get("reasons"), list) else [], - "sensitive": bool(answer.get("sensitive")), + "checklist": checklist, + # Verbatim, so keys the line does not read (an engine id, relatedTo) reach the artifact. + "reasons": answer["reasons"], + "sensitive": answer["sensitive"], } - patches = answer["facts"].get("patches", "all") - if patches != "all": - why = ( - "source is off for this workflow" - if not source_allowed(env) - else "the diff was too large" if patches == "none" else "GitHub left some out" - ) - print( - f"::notice::merge-risk read {patches} of the patches ({why}): mentions and new dependencies not checked" - ) + for step in ("unchecked", "unhinted", "undecided", "unreviewed"): + if isinstance(answer.get(step), str): + result[step] = answer[step] + if "unchecked" in result: + if not source: + why = "source is off for this workflow" + elif result["unchecked"] == "no_patches": + why = "the diff was too large to send" + else: + why = result["unchecked"] + print(f"::notice::merge-risk checklist did not run ({why}): the level reads as not assessed") + elif result["facts"]["patches"] != "all": + print("::notice::merge-risk read some of the patches: GitHub left some out") # Both are built before either is written, so the artifact and the comment never disagree. line, stored = merge_risk_line(result), json.dumps(result, ensure_ascii=False, indent=1) path = artifact / "closed" / MERGE_RISK_NAME @@ -841,17 +872,16 @@ def run_merge_risk(service_url: str, ctx: dict, headers: dict, env: dict, artifa print(f"::notice::merge-risk {'skipped' if isinstance(error, Skip) else 'failed'}: {error}") -def _guide_and_architecture(pool, service_url: str, ctx: dict, bearer: dict, env: dict, artifact: Path) -> dict: +def _guide_and_architecture(pool, service_url: str, ctx: dict, headers: dict, env: dict, artifact: Path) -> dict: """Collect the analysis once, ask for the guide and architecture side by side, and return architecture's envelope, which records why when neither request went out.""" try: - headers = {**bearer, **model_headers(env)} guide_request, architecture_request = _requests(ctx, collect(env), env) except TooLarge as error: print(f"::notice::review-guide skipped: {error}") return _no_architecture(ctx, "skipped", str(error)) except Exception as error: - reason = f"collecting inputs or credentials failed: {type(error).__name__}: {error}" + reason = f"collecting inputs failed: {type(error).__name__}: {error}" print(f"::notice::review-guide failed: {reason}") return _no_architecture(ctx, "failed", reason) guide = pool.submit(run_review_guide, service_url, guide_request, headers, artifact) @@ -870,8 +900,10 @@ def main(env: dict | None = None) -> int: if not service_url.strip(): return 0 try: - bearer = _bearer(env) - except Exception as error: # every request needs it, so each feature says it did not run + # The run's own provider for every feature: its model decides, and its code reaches no + # other model. Headers that cannot be built fail them all rather than fall back to ours. + headers = {**_bearer(env), **model_headers(env)} + except Exception as error: # every request needs them, so each feature says it did not run reason = f"getting credentials failed: {type(error).__name__}: {error}" print(f"::notice::merge-risk failed: {reason}") print(f"::notice::review-guide failed: {reason}") @@ -879,8 +911,8 @@ def main(env: dict | None = None) -> int: else: with ThreadPoolExecutor(max_workers=3) as pool: # Before collecting the analysis, which merge risk does not need. - pool.submit(run_merge_risk, service_url, ctx, bearer, env, artifact) - architecture = _guide_and_architecture(pool, service_url, ctx, bearer, env, artifact) + pool.submit(run_merge_risk, service_url, ctx, headers, env, artifact) + architecture = _guide_and_architecture(pool, service_url, ctx, headers, env, artifact) path = artifact / "closed" / "architecture.json" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(architecture, ensure_ascii=False, indent=1)) diff --git a/tests/test_problem_history.py b/tests/test_problem_history.py index 26c9c04..b9f551f 100644 --- a/tests/test_problem_history.py +++ b/tests/test_problem_history.py @@ -34,7 +34,7 @@ "ACTIONS_ID_TOKEN_REQUEST_URL": "https://oidc.test/token", "ACTIONS_ID_TOKEN_REQUEST_TOKEN": "oidc", } -ENVELOPE = {"feature": "architecture", "schema": 1, "status": "ok", "pr": 41, "data": {"findings": [{}]}} +ENVELOPE = {"feature": "architecture", "schema": 2, "status": "ok", "pr": 41, "data": {"findings": [{}]}} def ledger(**fields): @@ -764,13 +764,12 @@ def test_unread_merges_are_asked_again_newest_first_at_most_10(self): merged = [{"number": n, "mergedAt": f"2026-11-01T{n:02d}:00:00Z"} for n in range(1, 21)] merged[19]["warningsRead"] = True # #20 read merged[18]["warningsRead"] = False # #19 not - stored = {"merged": merged, "warnings": [{"id": "warning:o/r#18:x", "pr": 18}]} + stored = {"merged": merged} new = [{"number": 30, "mergedAt": "2026-11-06T00:00:00Z"}] gh = FakeGitHub() asked = self.asked(new, {30: "h30"}, stored, gh) - # #18 has warnings stored, which a ledger from before warningsRead counts as read. - self.assertEqual([n for n, _ in asked], [30, 19, 17, 16, 15, 14, 13, 12, 11, 10, 9]) - self.assertEqual([h for _, h in asked][:3], ["h30", "head19", "head17"]) + self.assertEqual([number for number, _ in asked], [30, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10]) + self.assertEqual([head for _, head in asked][:3], ["h30", "head19", "head18"]) # The ten head commits come from one query. self.assertEqual(len(gh.calls("pullRequest(number:")), 1) diff --git a/tests/test_remote_features.py b/tests/test_remote_features.py index ef8f3f9..acd63f9 100644 --- a/tests/test_remote_features.py +++ b/tests/test_remote_features.py @@ -27,7 +27,7 @@ GUIDE = {"version": 1, "changes": [{"id": "u1"}]} ENVELOPE = { "feature": "architecture", - "schema": 1, + "schema": 2, "status": "partial", "repo": "o/r", "pr": 7, @@ -582,10 +582,35 @@ def test_either_limit_omits_source_then_skips_if_required_inputs_too_large(self) self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "skipped") +RISK_CHECKLIST = { + "model": "typesafe/jev-1.14-20261014", + "version": 1, + "probabilities": {"signin": 0.1, "billing": 0.95}, + "cut": False, + "yes": ["billing"], + "decided": True, + "reviewed": True, +} RISK_ANSWER = { - "facts": {"files": 1, "sourceFiles": 1, "srcLines": 60, "tests": 0, "dirs": 1, "areas": [], "deps": []}, - "reasons": [{"level": "low", "code": "no_tests", "params": {"srcLines": 60}}], - "sensitive": False, + "status": "ok", + "facts": {"files": 1, "sourceFiles": 1, "srcLines": 60, "tests": 0, "patches": "all"}, + "checklist": RISK_CHECKLIST, + "reasons": [ + { + "level": "medium", + "code": "checklist", + "params": {"question": "billing"}, + "explanation": "Changes what an order is charged.", + "file": "app.py", + "line": 1, + "side": "RIGHT", + "id": "W1", + "shown": True, + }, + {"level": "low", "code": "no_tests", "params": {"srcLines": 60}}, + ], + "sensitive": ["billing"], + "usage": {"checklist": {"inputTokens": 900, "cost": 0.00004}}, } RISK_FILES = [{"filename": "app.py", "additions": 60, "deletions": 0, "patch": "@@ -0,0 +1 @@\n+x"}] @@ -602,7 +627,9 @@ class MergeRiskTests(_ServiceCase): def setUp(self): super().setUp() - patch = mock.patch.object(remote_features, "merge_risk_files", return_value=RISK_FILES) + patch = mock.patch.object( + remote_features, "merge_risk_files", return_value=("Add a route", "Adds GET /items.", RISK_FILES) + ) self.files = patch.start() self.addCleanup(patch.stop) self.env["GITHUB_OUTPUT"] = str(Path(self.env["ARTIFACT_DIR"]).parent / "github_output") @@ -621,14 +648,36 @@ def test_sends_the_file_list_and_keeps_the_answer_with_the_head_it_describes(sel [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] self.assertEqual(request["headers"]["Authorization"], "Bearer ghs_run") self.assertEqual( - json.loads(lzma.decompress(request["body"])), {"version": 1, "repo": "o/r", "pr": 7, "files": RISK_FILES} + json.loads(lzma.decompress(request["body"])), + { + "version": 1, + "repo": "o/r", + "pr": 7, + "title": "Add a route", + "description": "Adds GET /items.", + "files": RISK_FILES, + }, ) - expected = {"feature": "merge-risk", "schema": 1, "repo": "o/r", "pr": 7, "headSha": "H", **RISK_ANSWER} + stored = {key: value for key, value in RISK_ANSWER.items() if key != "usage"} + expected = {"feature": "merge-risk", "schema": 2, "repo": "o/r", "pr": 7, "headSha": "H", **stored} self.assertEqual(self.result(), expected) self.assertEqual(self.output(), f"merge_risk_line={remote_features.merge_risk_line(expected)}\n") self.assertEqual(_read(self.env, "review_guide.json"), GUIDE) self.assertEqual(_read(self.env, "closed/architecture.json"), ENVELOPE) + def test_merge_risk_carries_the_runs_own_provider_as_the_guide_does(self): + self.env.update({"LLM": "openai", "OPENAI_API_KEY": "sk-their", "AGENT_MODEL": "gpt-5.5"}) + service = self.run_service(_answer) + [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] + sent = {name.lower(): value for name, value in request["headers"].items()} + self.assertEqual( + (sent.get("x-llm-provider"), sent.get("x-llm-api-key"), sent.get("x-llm-model")), + ("openai", "sk-their", "gpt-5.5"), + ) + self.env["LLM"] = "hosted" + [request] = [sent for sent in self.run_service(_answer).requests if sent["path"] == "/v1/merge-risk"] + self.assertNotIn("x-llm-provider", {name.lower() for name in request["headers"]}) + def test_a_failed_merge_risk_writes_nothing_and_leaves_the_others_alone(self): self.run_service(lambda path, body: (500, {}) if path == "/v1/merge-risk" else _answer(path, body)) self.assertIsNone(self.result()) @@ -647,12 +696,16 @@ def test_merge_risk_does_not_need_the_analysis_or_the_guide(self): self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "failed") def test_without_room_for_patches_it_sends_the_files_without_them(self): - self.files.return_value = [{**RISK_FILES[0], "patch": os.urandom(3000).hex()}] + self.files.return_value = ("Add a route", "", [{**RISK_FILES[0], "patch": os.urandom(3000).hex()}]) with mock.patch.object(remote_features, "MAX_COMPRESSED_BYTES", 2000): service = self.run_service(_answer) [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] self.assertEqual(json.loads(lzma.decompress(request["body"]))["files"], [{**RISK_FILES[0], "patch": None}]) + def sent_description(self, service): + [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] + return json.loads(lzma.decompress(request["body"]))["description"] + def sent_files(self, service): [request] = [sent for sent in service.requests if sent["path"] == "/v1/merge-risk"] return json.loads(lzma.decompress(request["body"]))["files"] @@ -662,6 +715,7 @@ def test_with_source_turned_off_it_sends_the_files_without_patches(self): self.env["CLOSED_FEATURES_SOURCE"] = setting service = self.run_service(_answer) self.assertEqual(self.sent_files(service), [{**RISK_FILES[0], "patch": None}]) + self.assertEqual(self.sent_description(service), "") self.assertEqual(self.result()["facts"], RISK_ANSWER["facts"]) self.env["CLOSED_FEATURES_SOURCE"] = "true" self.assertEqual(self.sent_files(self.run_service(_answer)), RISK_FILES) @@ -675,21 +729,42 @@ def run_logged(self, respond): self.assertEqual(remote_features.main(self.env), 0) return service, [call.args[0] for call in log.call_args_list] - def test_withheld_patches_are_logged_and_ride_on_the_line(self): - withheld = {**RISK_ANSWER, "facts": {**RISK_ANSWER["facts"], "patches": "none"}} + def test_a_checklist_that_did_not_run_is_logged_stored_and_rides_on_the_line(self): + unchecked = { + **RISK_ANSWER, + "status": "partial", + "unchecked": "no_patches", + "checklist": None, + "facts": {**RISK_ANSWER["facts"], "patches": "none"}, + "reasons": [RISK_ANSWER["reasons"][1]], + } self.env["CLOSED_FEATURES_SOURCE"] = "false" _, printed = self.run_logged( - lambda path, body: (200, withheld) if path == "/v1/merge-risk" else _answer(path, body) + lambda path, body: (200, unchecked) if path == "/v1/merge-risk" else _answer(path, body) ) self.assertIn( - "::notice::merge-risk read none of the patches (source is off for this workflow): " - "mentions and new dependencies not checked", + "::notice::merge-risk checklist did not run (source is off for this workflow): " + "the level reads as not assessed", printed, ) - self.assertIn('"patches":"none"', self.output()) + self.assertEqual((self.result()["status"], self.result()["unchecked"]), ("partial", "no_patches")) + self.assertIn('"checked":false', self.output()) self.env["CLOSED_FEATURES_SOURCE"] = "true" _, printed = self.run_logged(_answer) - self.assertFalse([line for line in printed if "read none" in line or "read some" in line]) + self.assertFalse([line for line in printed if "merge-risk" in line]) + for code, why in (("no_patches", "the diff was too large to send"), ("no_model", "no_model")): + answer = {**unchecked, "unchecked": code} + _, printed = self.run_logged( + lambda path, body: (200, answer) if path == "/v1/merge-risk" else _answer(path, body) + ) + self.assertIn( + f"::notice::merge-risk checklist did not run ({why}): the level reads as not assessed", printed + ) + some = {**RISK_ANSWER, "facts": {**RISK_ANSWER["facts"], "patches": "some"}} + _, printed = self.run_logged( + lambda path, body: (200, some) if path == "/v1/merge-risk" else _answer(path, body) + ) + self.assertIn("::notice::merge-risk read some of the patches: GitHub left some out", printed) def test_a_credentials_failure_is_logged_for_merge_risk_too(self): with mock.patch.object(remote_features, "_bearer", side_effect=RuntimeError("no OIDC token")): @@ -701,14 +776,74 @@ def test_a_credentials_failure_is_logged_for_merge_risk_too(self): self.assertIsNone(self.result()) self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "failed") - def test_an_answer_the_line_cannot_carry_writes_neither_file_nor_line(self): - unreadable = {**RISK_ANSWER, "reasons": [{"code": "no_tests"}]} # no level - _, printed = self.run_logged( - lambda path, body: (200, unreadable) if path == "/v1/merge-risk" else _answer(path, body) - ) - self.assertIsNone(self.result()) - self.assertEqual(self.output(), "") - self.assertIn("::notice::merge-risk failed: 'level'", printed) + def test_provider_headers_that_cannot_be_built_fail_every_feature_and_are_built_once(self): + with mock.patch.object(remote_features, "model_headers", side_effect=RuntimeError("bad key")) as build: + service, printed = self.run_logged(_answer) + reason = "getting credentials failed: RuntimeError: bad key" + self.assertIn(f"::notice::merge-risk failed: {reason}", printed) + self.assertIn(f"::notice::review-guide failed: {reason}", printed) + self.assertEqual(service.requests, []) + self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "failed") + self.env.update({"LLM": "openai", "OPENAI_API_KEY": "sk-their"}) + with mock.patch.object(remote_features, "model_headers", wraps=remote_features.model_headers) as build: + service = self.run_service(_answer) + build.assert_called_once() + providers = [ + {name.lower(): value for name, value in sent["headers"].items()}["x-llm-provider"] + for sent in service.requests + ] + self.assertEqual(providers, ["openai"] * 3) + + def test_reasons_are_stored_verbatim(self): + linked = [RISK_ANSWER["reasons"][0], {**RISK_ANSWER["reasons"][1], "id": "W2", "relatedTo": "W1"}] + answer = {**RISK_ANSWER, "reasons": linked} + self.run_service(lambda path, body: (200, answer) if path == "/v1/merge-risk" else _answer(path, body)) + self.assertEqual(self.result()["reasons"], linked) + + def test_an_answer_without_a_known_status_facts_or_lists_is_refused(self): + facts = RISK_ANSWER["facts"] + refused = { + "status": ({"status": "done"}, "the service returned merge-risk status 'done'"), + "no status": ({"status": None}, "the service returned merge-risk status None"), + "reasons": ({"reasons": None}, "the service returned no merge-risk reasons list"), + "sensitive": ({"sensitive": "billing"}, "the service returned no merge-risk sensitive list"), + "sensitive non-string": ( + {"sensitive": ["billing", 3]}, + "the service returned a merge-risk sensitive question that is not a string", + ), + "reason without level": ( + {"reasons": [{"code": "no_tests"}]}, + "the service returned a merge-risk reason without a level and a code", + ), + "reason without code": ( + {"reasons": [{"level": "low"}]}, + "the service returned a merge-risk reason without a level and a code", + ), + "reason not an object": ( + {"reasons": ["no_tests"]}, + "the service returned a merge-risk reason without a level and a code", + ), + **{ + f"facts without {fact}": ( + {"facts": {key: value for key, value in facts.items() if key != fact}}, + f"the service returned merge-risk facts without {fact}", + ) + for fact in ("srcLines", "sourceFiles", "patches") + }, + "checklist": ( + {"checklist": ["contract"]}, + "the service returned a merge-risk checklist that is not an object", + ), + } + for case, (change, message) in refused.items(): + with self.subTest(case=case): + answer = {**RISK_ANSWER, **change} + _, printed = self.run_logged( + lambda path, body: (200, answer) if path == "/v1/merge-risk" else _answer(path, body) + ) + self.assertIsNone(self.result()) + self.assertEqual(self.output(), "") + self.assertIn(f"::notice::merge-risk failed: {message}", printed) def test_merge_risk_compresses_fast_and_the_guide_as_before(self): presets = {} @@ -739,7 +874,7 @@ def recording(data, preset): started = time.monotonic() with mock.patch.object(lzma, "compress", side_effect=recording): - data = remote_features.merge_risk_request({"repo": "o/r", "pr": 7}, files, with_patches=True) + data = remote_features.merge_risk_request({"repo": "o/r", "pr": 7}, "t", "", files, with_patches=True) elapsed = time.monotonic() - started sent = json.loads(lzma.decompress(data))["files"] self.assertEqual(sent, [{**file, "patch": None} for file in files]) @@ -759,12 +894,12 @@ def test_reads_every_page_and_keeps_the_fields_the_service_reads(self): def github(path): if path.endswith("/pulls/7"): - return {"head": {"sha": "H"}} + return {"head": {"sha": "H"}, "title": "Add files", "body": "Why."} return pages[path.rsplit("&", 1)[1]] with mock.patch.object(remote_features, "_github_json", side_effect=github): - files = remote_features.merge_risk_files({"repo": "o/r", "pr": 7, "head": "H"}) - self.assertEqual(len(files), 130) + title, description, files = remote_features.merge_risk_files({"repo": "o/r", "pr": 7, "head": "H"}) + self.assertEqual((title, description, len(files)), ("Add files", "Why.", 130)) self.assertEqual(files[129], {"filename": "f129.py", "additions": 129, "deletions": 0, "patch": None}) def test_a_head_that_moved_on_is_skipped(self): @@ -780,8 +915,9 @@ class MergeRiskLineTests(unittest.TestCase): def test_a_negative_number_reads_back_and_an_oversized_line_is_left_out(self): result = { "headSha": "abc123", - "sensitive": False, - "facts": {"srcLines": 3, "sourceFiles": 1, "deps": [], "areas": []}, + "sensitive": [], + "checklist": None, + "facts": {"srcLines": 3, "sourceFiles": 1}, "reasons": [{"level": "low", "code": "future_rule", "params": {"delta": -4}}], } line = remote_features.merge_risk_line(result) @@ -791,17 +927,19 @@ def test_a_negative_number_reads_back_and_an_oversized_line_is_left_out(self): self.assertIsNone(remote_features.merge_risk_line(huge)) def test_nothing_in_the_line_can_end_the_comment_and_json_reads_it_back(self): - reason = {"level": "medium", "code": "area_changed", "params": {"files": ["a-->b=.ts"]}, "file": "x"} + reason = { + "level": "medium", + "code": "checklist", + "params": {"question": "a-->b=d"}, + "file": "x", + "line": 3, + "explanation": "Calls --> the service.", + } result = { "headSha": "abc123", - "sensitive": True, - "facts": { - "srcLines": 1815, - "sourceFiles": 31, - "tests": 0, - "deps": ["zod"], - "areas": [{"name": "Sign-in and access", "critical": True}, {"name": "Review", "critical": False}], - }, + "sensitive": ["signin"], + "checklist": RISK_CHECKLIST, + "facts": {"srcLines": 1815, "sourceFiles": 31, "tests": 0, "patches": "some"}, "reasons": [reason], } match = re.fullmatch(r"", remote_features.merge_risk_line(result)) @@ -811,15 +949,13 @@ def test_nothing_in_the_line_can_end_the_comment_and_json_reads_it_back(self): self.assertEqual( json.loads(payload), { - "v": 1, + "v": 2, "head": "abc123", - "sensitive": True, - "areas": ["Sign-in and access"], - "deps": ["zod"], + "checked": True, + "sensitive": ["signin"], "srcLines": 1815, "sourceFiles": 31, - "patches": "all", - "reasons": [{"level": "medium", "code": "area_changed", "params": reason["params"]}], + "reasons": [{"level": "medium", "code": "checklist", "params": reason["params"]}], }, ) diff --git a/tests/test_review_comment.py b/tests/test_review_comment.py index b3b7541..4e37424 100644 --- a/tests/test_review_comment.py +++ b/tests/test_review_comment.py @@ -83,7 +83,7 @@ def test_a_changed_analysed_file_gets_no_verdict_even_at_zero_components(self) - def test_merge_risk_rides_on_its_own_hidden_line_before_the_last(self) -> None: with tempfile.TemporaryDirectory() as tmp: - line = '' + line = '' lines = _build(Path(tmp), MERGE_RISK_LINE=line).rstrip("\n").splitlines() self.assertEqual(lines[-2], line) self.assertTrue(lines[-1].startswith("