From b07da25604b461a848e34d988e95979242da0592 Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:52:24 +0800 Subject: [PATCH 1/2] fix(frontend): resolve react-hooks/set-state-in-effect in PrView The URL-driven fetch lived in an effect that also called setError and setLoading synchronously, which the current react-hooks plugin flags. Split PrView into a wrapper that remounts the inner reader with key=url and derive the missing-URL error during render instead. --- frontend/src/pages/PrView.tsx | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/frontend/src/pages/PrView.tsx b/frontend/src/pages/PrView.tsx index 07d244d..2706a7e 100644 --- a/frontend/src/pages/PrView.tsx +++ b/frontend/src/pages/PrView.tsx @@ -14,20 +14,19 @@ const KIND_STYLE: Record = { export default function PrView() { const [params] = useSearchParams(); - const navigate = useNavigate(); - const { t } = useI18n(); const url = params.get("url") ?? ""; + return ; +} +function PrReading({ url }: { url: string }) { + const navigate = useNavigate(); + const { t } = useI18n(); const [data, setData] = useState(null); const [error, setError] = useState(""); - const [loading, setLoading] = useState(true); + const [loading, setLoading] = useState(Boolean(url)); useEffect(() => { - if (!url) { - setError(t("缺少 PR 链接。", "Missing PR URL.")); - setLoading(false); - return; - } + if (!url) return; let cancelled = false; getPrReading(url, true) .then((r) => { @@ -67,9 +66,9 @@ export default function PrView() { {t("正在读取这个 PR…", "Reading this pull request…")} )} - {error && ( + {(error || !url) && (
- {error} + {url ? error : t("缺少 PR 链接。", "Missing PR URL.")}
)} From ebd6e3185b4a0929ead528c2453c843a4a9b443a Mon Sep 17 00:00:00 2001 From: Yufeng He <40085740+he-yufeng@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:52:37 +0800 Subject: [PATCH 2/2] feat: offline before/after project comparison New POST /api/project/compare plus a /compare page: drop the folder as delivered and the folder that came back, and CodeABC shows which files were added, deleted or modified with a bounded unified diff, plus the delta in static risk warnings. Matching is by relative path; a path filtered out on either side (dependency dirs, binaries, over limits) is reported as not compared rather than as a deletion. Security findings are matched as a multiset on (file, category, snippet) so a line shift does not manufacture a resolved/new pair. Snapshots cap at 500 files and 5 MiB of text; no source is executed and no LLM is called. --- backend/models.py | 58 ++++++++ backend/routers/project.py | 17 +++ backend/services/comparison.py | 168 +++++++++++++++++++++ frontend/src/App.tsx | 2 + frontend/src/lib/api.ts | 73 +++++++++ frontend/src/pages/CompareView.tsx | 231 +++++++++++++++++++++++++++++ frontend/src/pages/Home.tsx | 11 ++ tests/test_comparison.py | 192 ++++++++++++++++++++++++ 8 files changed, 752 insertions(+) create mode 100644 backend/services/comparison.py create mode 100644 frontend/src/pages/CompareView.tsx create mode 100644 tests/test_comparison.py diff --git a/backend/models.py b/backend/models.py index b77d8de..d3f73f1 100644 --- a/backend/models.py +++ b/backend/models.py @@ -647,3 +647,61 @@ class AnalyzeRequest(BaseModel): files: list[UploadedFile] project_name: str = "untitled" + + +class ComparisonSnapshot(AnalyzeRequest): + files: list[UploadedFile] = Field(max_length=500) + + +class CompareRequest(BaseModel): + before: ComparisonSnapshot + after: ComparisonSnapshot + + +class ComparedFile(BaseModel): + path: str + status: str + before_bytes: int + after_bytes: int + before_hash: str | None = None + after_hash: str | None = None + diff: str = "" + diff_truncated: bool = False + + +class ComparisonSummary(BaseModel): + added: int = 0 + deleted: int = 0 + modified: int = 0 + unchanged: int = 0 + not_compared: int = 0 + + +class FindingChange(BaseModel): + status: str + before: SecurityFinding | None = None + after: SecurityFinding | None = None + + +class SecurityComparison(BaseModel): + complete: bool + before_total: int + after_total: int + introduced: int | None = None + no_longer_detected: int | None = None + persistent: int | None = None + changes: list[FindingChange] = [] + display_truncated: bool = False + + +class ProjectComparison(BaseModel): + schema_version: int = 1 + before_name: str + after_name: str + before_files: int + after_files: int + summary: ComparisonSummary + files: list[ComparedFile] + excluded_paths: list[str] + security: SecurityComparison + notes: list[str] diff --git a/backend/routers/project.py b/backend/routers/project.py index 87698a0..2c56ede 100644 --- a/backend/routers/project.py +++ b/backend/routers/project.py @@ -23,6 +23,7 @@ CliCommand, CoChangeCoupling, CodeWalkStep, + CompareRequest, ComplexFile, ConfigFile, ContributionGuide, @@ -54,6 +55,7 @@ LicenseSummary, OrphanModule, PackageDependency, + ProjectComparison, ProjectHealth, ProjectMeta, ProjectSummary, @@ -86,6 +88,7 @@ ci_checks, codemap_export, commands, + comparison, complexity, config_files, contributing, @@ -455,6 +458,20 @@ def _content_analyses( } +@router.post("/project/compare", response_model=ProjectComparison) +def compare_uploaded_projects(req: CompareRequest): + """Compare source snapshots without storing them or calling an LLM.""" + try: + return comparison.compare_projects( + [file.model_dump() for file in req.before.files], + [file.model_dump() for file in req.after.files], + before_name=req.before.project_name, + after_name=req.after.project_name, + ) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + + @router.post("/project/upload", response_model=ProjectMeta) async def upload_project(req: AnalyzeRequest): """Receive files uploaded from the frontend (webkitdirectory).""" diff --git a/backend/services/comparison.py b/backend/services/comparison.py new file mode 100644 index 0000000..548ca7c --- /dev/null +++ b/backend/services/comparison.py @@ -0,0 +1,168 @@ +"""Compare two uploaded source snapshots without executing either one.""" + +from __future__ import annotations + +import difflib +import hashlib +from collections import defaultdict, deque +from itertools import islice +from pathlib import PurePosixPath + +from backend.services import scanner, security + +_MAX_SNAPSHOT_BYTES = 5 * 1024 * 1024 +_MAX_DIFF_LINES = 80 +_MAX_DIFF_CHARS = 8000 +_MAX_SOURCE_LINES_FOR_DIFF = 2000 +_MAX_FINDINGS = 5000 +_MAX_DISPLAY_FINDINGS = 200 + + +def _snapshot(files: list[dict]) -> tuple[dict[str, str], set[str]]: + contents: dict[str, str] = {} + total_bytes = 0 + for item in files: + path = str(PurePosixPath(item["path"].replace("\\", "/"))) + if path in contents: + raise ValueError(f"Duplicate file path: {path}") + content = item["content"] + total_bytes += len(content.encode("utf-8")) + if total_bytes > _MAX_SNAPSHOT_BYTES: + raise ValueError("Each snapshot must contain at most 5 MiB of text") + contents[path] = content + scanned = scanner.scan_uploaded_files( + [{"path": p, "content": c} for p, c in contents.items() if "\0" not in c] + ) + allowed = {item["path"] for item in scanned} + return {p: c for p, c in contents.items() if p in allowed}, contents.keys() - allowed + + +def _preview(path: str, before: str, after: str) -> tuple[str, bool]: + old_lines, new_lines = before.splitlines(), after.splitlines() + if max(len(old_lines), len(new_lines)) > _MAX_SOURCE_LINES_FOR_DIFF: + return "", True + lines = list( + islice( + difflib.unified_diff( + old_lines, new_lines, fromfile=f"before/{path}", tofile=f"after/{path}", lineterm="" + ), + _MAX_DIFF_LINES + 1, + ) + ) + text = "\n".join(lines[:_MAX_DIFF_LINES]) + return text[:_MAX_DIFF_CHARS], len(lines) > _MAX_DIFF_LINES or len(text) > _MAX_DIFF_CHARS + + +def _security_changes(before: dict[str, str], after: dict[str, str]) -> dict: + old = security.scan_security(before, limit=_MAX_FINDINGS) + new = security.scan_security(after, limit=_MAX_FINDINGS) + complete = old["total"] <= _MAX_FINDINGS and new["total"] <= _MAX_FINDINGS + result = { + "complete": complete, + "before_total": old["total"], + "after_total": new["total"], + "introduced": None, + "no_longer_detected": None, + "persistent": None, + "changes": [], + "display_truncated": False, + } + if not complete: + return result + + # A line insertion must not turn the same warning into a resolved/new pair. + previous: dict[tuple, deque] = defaultdict(deque) + for finding in old["findings"]: + key = (finding["file"], finding["category"], finding["snippet"]) + previous[key].append(finding) + changes = [] + for finding in new["findings"]: + key = (finding["file"], finding["category"], finding["snippet"]) + match = previous[key].popleft() if previous[key] else None + changes.append( + { + "status": "persistent" if match else "introduced", + "before": match, + "after": finding, + } + ) + for remaining in previous.values(): + for finding in remaining: + changes.append({"status": "no_longer_detected", "before": finding, "after": None}) + order = {"introduced": 0, "no_longer_detected": 1, "persistent": 2} + changes.sort( + key=lambda change: ( + order[change["status"]], + (change["after"] or change["before"])["file"], + (change["after"] or change["before"])["line"], + ) + ) + for status in order: + result[status] = sum(change["status"] == status for change in changes) + result["changes"] = changes[:_MAX_DISPLAY_FINDINGS] + result["display_truncated"] = len(changes) > _MAX_DISPLAY_FINDINGS + return result + + +def compare_projects( + before_files: list[dict], + after_files: list[dict], + *, + before_name: str = "before", + after_name: str = "after", +) -> dict: + before, before_excluded = _snapshot(before_files) + after, after_excluded = _snapshot(after_files) + excluded = before_excluded | after_excluded + # An unreadable/filtered new version is unknown, not a deleted source file. + before = {p: c for p, c in before.items() if p not in excluded} + after = {p: c for p, c in after.items() if p not in excluded} + summary = { + "added": 0, + "deleted": 0, + "modified": 0, + "unchanged": 0, + "not_compared": len(excluded), + } + changes = [] + for path in sorted(before.keys() | after.keys()): + old, new = before.get(path), after.get(path) + if old == new: + summary["unchanged"] += 1 + continue + status = "added" if old is None else "deleted" if new is None else "modified" + summary[status] += 1 + preview, truncated = _preview(path, old or "", new or "") + changes.append( + { + "path": path, + "status": status, + "before_bytes": len(old.encode("utf-8")) if old is not None else 0, + "after_bytes": len(new.encode("utf-8")) if new is not None else 0, + "before_hash": hashlib.sha256(old.encode("utf-8")).hexdigest() + if old is not None + else None, + "after_hash": hashlib.sha256(new.encode("utf-8")).hexdigest() + if new is not None + else None, + "diff": preview, + "diff_truncated": truncated, + } + ) + return { + "schema_version": 1, + "before_name": before_name, + "after_name": after_name, + "before_files": len(before), + "after_files": len(after), + "summary": summary, + "files": changes, + "excluded_paths": sorted(excluded), + "security": _security_changes(before, after), + "notes": [ + "Only the supplied readable text is compared; filtered files are unknown, not deleted.", + "Files are matched by relative path. A rename appears as a deletion and an addition.", + "Risk warnings are static pattern matches, not confirmed vulnerabilities or fixes.", + "No source code is executed and no language model is called.", + ], + } diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6248979..b79b1b0 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,7 @@ import { BrowserRouter, Routes, Route } from "react-router-dom"; import Home from "./pages/Home"; import PrView from "./pages/PrView"; +import CompareView from "./pages/CompareView"; import Overview from "./pages/Overview"; import FileView from "./pages/FileView"; import { I18nProvider } from "./lib/i18n"; @@ -12,6 +13,7 @@ function App() { } /> } /> + } /> } /> } /> diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 33d7044..7b5f3d2 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -804,3 +804,76 @@ export async function getPrReading(url: string, explain = false): Promise { + const res = await apiFetch(`${BASE}/project/compare`, { + method: "POST", + headers: getHeaders(), + body: JSON.stringify({ + before: { files: beforeFiles, project_name: beforeName }, + after: { files: afterFiles, project_name: afterName }, + }), + }); + if (!res.ok) { + const err = await res.json().catch(() => ({ detail: "" })); + throw new Error(err.detail || "Failed to compare the two folders"); + } + return res.json(); +} diff --git a/frontend/src/pages/CompareView.tsx b/frontend/src/pages/CompareView.tsx new file mode 100644 index 0000000..6470ffb --- /dev/null +++ b/frontend/src/pages/CompareView.tsx @@ -0,0 +1,231 @@ +import { useState } from "react"; +import { useNavigate } from "react-router-dom"; +import UploadZone from "../components/UploadZone"; +import { compareProjects } from "../lib/api"; +import type { ProjectComparison, ComparedFile } from "../lib/api"; +import { useI18n, LanguageToggle } from "../lib/i18n"; +import { friendlyError } from "../lib/errors"; + +const STATUS_LABEL: Record = { + added: ["新增", "added"], + deleted: ["删除", "deleted"], + modified: ["修改", "modified"], +}; + +const STATUS_STYLE: Record = { + added: "bg-green-100 text-green-700", + deleted: "bg-red-100 text-red-700", + modified: "bg-amber-100 text-amber-700", +}; + +export default function CompareView() { + const navigate = useNavigate(); + const { t } = useI18n(); + const [before, setBefore] = useState<{ path: string; content: string }[]>([]); + const [after, setAfter] = useState<{ path: string; content: string }[]>([]); + const [beforeName, setBeforeName] = useState("旧版本"); + const [afterName, setAfterName] = useState("新版本"); + const [result, setResult] = useState(null); + const [error, setError] = useState(""); + const [loading, setLoading] = useState(false); + + const runCompare = async () => { + setError(""); + setLoading(true); + try { + setResult(await compareProjects(before, beforeName, after, afterName)); + } catch (e: unknown) { + const raw = e instanceof Error ? e.message : ""; + setError(friendlyError(raw, t) || t("对比失败,请重试。", "Comparison failed — please try again.")); + } finally { + setLoading(false); + } + }; + + return ( +
+
+ +
+
+ +

+ {t("对比两个版本", "Compare two versions")} +

+

+ {t( + "把交付前后的两个项目文件夹分别拖进来,看看实际改了哪些文件、有没有新的风险信号。全程离线,不需要 API Key。", + "Drop the before/after project folders to see what actually changed and whether new risk signals appeared. Fully offline, no API key needed.", + )} +

+ + {!result && ( + <> +
+
+

+ {t("旧版本(交付前)", "Before")} +

+ { + setBefore(files); + setBeforeName(name || beforeName); + }} + disabled={loading} + /> + {before.length > 0 && ( +

+ {t(`已读取 ${before.length} 个文件`, `${before.length} files read`)} +

+ )} +
+
+

+ {t("新版本(交付后)", "After")} +

+ { + setAfter(files); + setAfterName(name || afterName); + }} + disabled={loading} + /> + {after.length > 0 && ( +

+ {t(`已读取 ${after.length} 个文件`, `${after.length} files read`)} +

+ )} +
+
+ + {error && ( +
+ {error} +
+ )} + + )} + + {result && ( + <> +
+

+ {t( + `${result.before_name} → ${result.after_name}:新增 ${result.summary.added},删除 ${result.summary.deleted},修改 ${result.summary.modified},未变 ${result.summary.unchanged}。`, + `${result.before_name} → ${result.after_name}: ${result.summary.added} added, ${result.summary.deleted} deleted, ${result.summary.modified} modified, ${result.summary.unchanged} unchanged.`, + )} +

+ {result.summary.not_compared > 0 && ( +

+ {t( + `另有 ${result.summary.not_compared} 个路径被过滤(依赖目录/二进制/超上限),未参与对比。`, + `${result.summary.not_compared} more paths were filtered out (dependency dirs, binaries, over limits) and not compared.`, + )} +

+ )} +
+ + {result.security.complete && + ((result.security.introduced ?? 0) > 0 || + (result.security.no_longer_detected ?? 0) > 0) && ( +
+

+ {t("风险提示变化", "Risk signal changes")} +

+

+ {t( + `新出现 ${result.security.introduced} 处,不再命中 ${result.security.no_longer_detected} 处,仍存在 ${result.security.persistent} 处。`, + `${result.security.introduced} new, ${result.security.no_longer_detected} no longer detected, ${result.security.persistent} still present.`, + )} +

+
+ {result.security.changes + .filter((c) => c.status !== "persistent") + .slice(0, 20) + .map((c, i) => { + const f = c.after ?? c.before; + if (!f) return null; + return ( +
+ + {c.status === "introduced" + ? t("新出现", "new") + : t("不再命中", "resolved")} + + + {f.file}:{f.line} + +
+ ); + })} +
+
+ )} + +
+ {result.files.map((f) => ( +
+
+ + {t(...STATUS_LABEL[f.status])} + + + {f.path} + + + {f.before_bytes} → {f.after_bytes} B + +
+ {f.diff && ( +
+                      {f.diff}
+                      {f.diff_truncated && "\n…"}
+                    
+ )} +
+ ))} +
+ + + + )} +
+
+ ); +} diff --git a/frontend/src/pages/Home.tsx b/frontend/src/pages/Home.tsx index 10d1e30..a899297 100644 --- a/frontend/src/pages/Home.tsx +++ b/frontend/src/pages/Home.tsx @@ -125,6 +125,17 @@ export default function Home() { + {/* Offline folder comparison */} +

+ {t("拿到别人改过的代码,想知道动了什么?", "Got a folder back from someone else?")} + +

+ {/* Error message */} {error && (
diff --git a/tests/test_comparison.py b/tests/test_comparison.py new file mode 100644 index 0000000..66c31e4 --- /dev/null +++ b/tests/test_comparison.py @@ -0,0 +1,192 @@ +"""Source snippets are inert scanner inputs; none of the uploaded code is executed.""" + +import pytest +from fastapi.testclient import TestClient + +from backend.app import app +from backend.services import comparison + + +def files(**contents): + return [{"path": path, "content": content} for path, content in contents.items()] + + +def compare(before, after): + return comparison.compare_projects(files(**before), files(**after)) + + +def test_changes_use_content_not_size_and_leave_inputs_untouched(): + before = {"same.py": "x = 1\n", "edited.py": "a = 1\n", "deleted.py": "pass\n"} + after = {"same.py": "x = 1\n", "edited.py": "a = 2\n", "new.py": "pass\n"} + original = before.copy(), after.copy() + report = compare(before, after) + assert report["summary"] == { + "added": 1, + "deleted": 1, + "modified": 1, + "unchanged": 1, + "not_compared": 0, + } + edited = next(f for f in report["files"] if f["path"] == "edited.py") + assert edited["before_bytes"] == edited["after_bytes"] + assert edited["before_hash"] != edited["after_hash"] + assert "-a = 1" in edited["diff"] and "+a = 2" in edited["diff"] + assert (before, after) == original + + +def test_empty_snapshots_and_empty_files_are_distinct_from_missing_files(): + assert compare({}, {})["summary"]["unchanged"] == 0 + added = compare({}, {"empty.py": ""}) + assert added["summary"]["added"] == 1 + assert added["files"][0]["before_hash"] is None + assert added["files"][0]["after_hash"] is not None + assert compare({"empty.py": ""}, {})["summary"]["deleted"] == 1 + assert compare({"empty.py": ""}, {"empty.py": ""})["summary"]["unchanged"] == 1 + + +def test_no_changes_report_is_stable_and_never_runs_uploaded_code(): + source = "raise AssertionError('this is only source text')\n" + report = compare({"app.py": source}, {"app.py": source}) + assert report["files"] == [] + assert report["summary"]["unchanged"] == 1 + assert report["security"]["introduced"] == 0 + + +def test_utf8_sizes_and_newline_only_edits_remain_visible(): + report = compare({"app.py": "你好\r\n"}, {"app.py": "你好\n"}) + assert report["summary"]["modified"] == 1 + assert report["files"][0]["before_bytes"] == 8 + assert report["files"][0]["after_bytes"] == 7 + + +def test_paths_match_across_windows_separators(): + report = comparison.compare_projects( + [{"path": "src\\app.py", "content": "x=1"}], + [{"path": "src/app.py", "content": "x=1"}], + ) + assert report["summary"]["unchanged"] == 1 + + +def test_duplicate_normalized_paths_are_rejected(): + with pytest.raises(ValueError, match="Duplicate file path"): + comparison.compare_projects( + [{"path": "app.py", "content": "x=1"}, {"path": "./app.py", "content": "x=2"}], [] + ) + + +def test_sensitive_generated_unsafe_and_binary_files_stay_out_of_reports(): + source = { + "app.py": "x=1", + ".env": "DO_NOT_INCLUDE_THIS_VALUE", + "node_modules/pkg/index.js": "eval('not source')", + "../escape.py": "eval('not source')", + "binary.py": "\0eval('not source')", + "bundle.min.js": "eval('not source')", + } + report = compare({}, source) + assert [f["path"] for f in report["files"]] == ["app.py"] + assert report["summary"]["not_compared"] == 5 + assert report["security"]["after_total"] == 0 + assert "DO_NOT_INCLUDE_THIS_VALUE" not in str(report) + + +def test_filtered_new_file_is_unknown_not_a_deletion_or_a_resolved_warning(): + report = compare({"app.py": "eval(value)\n"}, {"app.py": "x" * (100 * 1024 + 1)}) + assert report["files"] == [] + assert report["summary"]["deleted"] == 0 + assert report["excluded_paths"] == ["app.py"] + assert report["security"]["no_longer_detected"] == 0 + + +def test_finding_deltas_keep_old_and_new_locations_without_line_shift_noise(): + report = compare( + {"app.py": "eval(value)\nDEBUG = True\n"}, + {"app.py": "# heading\neval(value)\nos.system(command)\n"}, + ) + delta = report["security"] + assert delta["complete"] + assert (delta["introduced"], delta["no_longer_detected"], delta["persistent"]) == (1, 1, 1) + matched = next(f for f in delta["changes"] if f["status"] == "persistent") + assert matched["before"]["line"] == 1 + assert matched["after"]["line"] == 2 + assert ( + next(f for f in delta["changes"] if f["status"] == "introduced")["after"]["category"] + == "shell_injection" + ) + + +def test_duplicate_warning_lines_are_matched_as_a_multiset(): + delta = compare({"app.py": "eval(value)\neval(value)\n"}, {"app.py": "eval(value)\n"})[ + "security" + ] + assert delta["persistent"] == 1 + assert delta["no_longer_detected"] == 1 + assert delta["introduced"] == 0 + + +def test_truncated_scans_do_not_claim_findings_disappeared(monkeypatch): + monkeypatch.setattr(comparison, "_MAX_FINDINGS", 1) + delta = compare({"app.py": "eval(a)\neval(b)\n"}, {})["security"] + assert not delta["complete"] + assert delta["before_total"] == 2 + assert delta["no_longer_detected"] is None + assert delta["changes"] == [] + + +def test_diff_preview_is_bounded_without_hiding_the_file_change(): + report = compare({"big.py": "x=1\n" * 2100}, {"big.py": "x=2\n" * 2100}) + assert report["summary"]["modified"] == 1 + assert report["files"][0]["diff_truncated"] + report = compare({"a.txt": "a" * 9000}, {"a.txt": "b" * 9000}) + assert len(report["files"][0]["diff"]) <= 8000 + assert report["files"][0]["diff_truncated"] + + +def test_snapshot_budget_counts_bytes_not_characters(monkeypatch): + monkeypatch.setattr(comparison, "_MAX_SNAPSHOT_BYTES", 8) + with pytest.raises(ValueError, match="at most 5 MiB"): + compare({}, {"a.txt": "你好啊"}) + + +def test_http_comparison_is_available_without_a_key_and_does_not_save_projects(monkeypatch): + from backend.services import cache + + async def must_not_save(*args, **kwargs): + raise AssertionError("Comparisons must not persist uploaded code") + + monkeypatch.setattr(cache, "save_project", must_not_save) + response = TestClient(app).post( + "/api/project/compare", + json={ + "before": {"project_name": "old", "files": files(**{"app.py": "x=1"})}, + "after": {"project_name": "new", "files": files(**{"app.py": "x=2"})}, + }, + ) + assert response.status_code == 200 + result = response.json() + assert result["schema_version"] == 1 + assert result["before_name"] == "old" and result["after_name"] == "new" + assert result["summary"]["modified"] == 1 + + +def test_http_limits_reject_instead_of_silently_truncating_files(): + response = TestClient(app).post( + "/api/project/compare", + json={ + "before": {"files": files(**{f"{i}.py": "pass" for i in range(501)})}, + "after": {"files": []}, + }, + ) + assert response.status_code == 422 + + +def test_http_ambiguous_paths_return_a_clear_error(): + response = TestClient(app).post( + "/api/project/compare", + json={ + "before": {"files": [{"path": "a.py", "content": ""}] * 2}, + "after": {"files": []}, + }, + ) + assert response.status_code == 400 + assert "Duplicate file path" in response.json()["detail"]