Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(security): give a security finding a verified line and a commit date (#1668)

Raghav Chamadiya7a3ae3889cff
diff --git a/packages/api-client/src/security.ts b/packages/api-client/src/security.ts
index 768a59687..772c03c79 100644
--- a/packages/api-client/src/security.ts
+++ b/packages/api-client/src/security.ts
@@ -7,6 +7,10 @@ export interface SecurityFinding {
severity: "high" | "med" | "low" | string;
snippet: string | null;
detected_at: string;
+ /** Verified against the live tree; `null` when the snippet has moved away. */
+ line_number: number | null;
+ line_verified: boolean;
+ commit_at: string | null;
}
export async function listSecurityFindings(
diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.py
index c1f919b5b..cd79856fb 100644
--- a/packages/core/src/repowise/core/analysis/security_scan.py
+++ b/packages/core/src/repowise/core/analysis/security_scan.py
@@ -63,6 +63,13 @@ _SYMBOL_KEYWORDS = re.compile(
# trufflehog rather than a noisy replacement.
SECRET_KINDS: frozenset[str] = frozenset({"hardcoded_password", "hardcoded_secret"})
+# Kinds whose ``snippet`` is a symbol *name* rather than the text of the line
+# it sits on (see the symbol-name scan below). Serve-time line verification
+# must not treat these like pattern snippets: a bare identifier recurs all over
+# a file, so relocating on it lands somewhere arbitrary and failing to find it
+# does not mean the code is gone.
+SYMBOL_NAME_KINDS: frozenset[str] = frozenset({"security_sensitive_symbol"})
+
class SecurityScanner:
"""Scan a single file for security signals and persist to the database."""
diff --git a/packages/server/src/repowise/server/routers/security.py b/packages/server/src/repowise/server/routers/security.py
index b8bdb1e0f..a6e2eda69 100644
--- a/packages/server/src/repowise/server/routers/security.py
+++ b/packages/server/src/repowise/server/routers/security.py
@@ -2,13 +2,16 @@
from __future__ import annotations
+from pathlib import Path
+
from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.persistence.models import SecurityFinding
+from repowise.core.persistence.models import Repository, SecurityFinding
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import SecurityFindingResponse
+from repowise.server.services.security_lines import check_finding_line
router = APIRouter(
prefix="/api/repos",
@@ -50,16 +53,79 @@ async def list_security_findings(
result = await session.execute(stmt)
rows = result.scalars().all()
- return [
- SecurityFindingResponse(
- id=row.id,
- file_path=row.file_path,
- kind=row.kind,
- severity=row.severity,
- snippet=row.snippet,
- detected_at=row.detected_at,
- commit_sha=row.commit_sha or None,
- found_in_history=bool(row.commit_sha),
+ repo_root = await _repo_root(session, repo_id)
+ # One read per distinct file in this page, not per finding — findings
+ # cluster heavily by file. Ceiling: at limit=500 this is up to 500 reads
+ # on a cold cache. If that ever bites, verify at scan time and persist the
+ # outcome instead of re-deriving it per request.
+ file_cache: dict[str, list[str] | None] = {}
+
+ responses = []
+ for row in rows:
+ check = check_finding_line(
+ _read_lines(repo_root, row.file_path, file_cache),
+ row.line_number,
+ row.snippet,
+ row.kind,
+ )
+ responses.append(
+ SecurityFindingResponse(
+ id=row.id,
+ file_path=row.file_path,
+ kind=row.kind,
+ severity=row.severity,
+ snippet=row.snippet,
+ detected_at=row.detected_at,
+ line_number=check.line_number,
+ line_verified=check.verified,
+ commit_sha=row.commit_sha or None,
+ commit_at=row.commit_at,
+ found_in_history=bool(row.commit_sha),
+ )
)
- for row in rows
- ]
+ return responses
+
+
+async def _repo_root(session: AsyncSession, repo_id: str) -> Path | None:
+ """Live checkout root for *repo_id*, or None when it is not on disk."""
+ repo = await session.get(Repository, repo_id)
+ if repo is None or not repo.local_path:
+ return None
+ root = Path(repo.local_path).resolve()
+ return root if root.is_dir() else None
+
+
+def _read_lines(
+ repo_root: Path | None,
+ file_path: str,
+ cache: dict[str, list[str] | None],
+) -> list[str] | None:
+ """Live file split into lines, or None when it cannot be read.
+
+ A history finding's file may have been deleted since; that is a None, and
+ the caller degrades the line rather than failing the row.
+
+ Guarded the same way ``/file-content`` is (``routers/repos.py``), and for
+ the same reason: containment alone is not enough, because ``.repowise/.env``
+ and ``.git/config`` live inside the root too. History findings make this
+ load-bearing rather than theoretical — their paths come from git tree
+ entries, not from the indexer's own file list.
+ """
+ if repo_root is None:
+ return None
+ if file_path not in cache:
+ cache[file_path] = _read_guarded(repo_root, file_path)
+ return cache[file_path]
+
+
+def _read_guarded(repo_root: Path, file_path: str) -> list[str] | None:
+ segments = file_path.replace("\\", "/").split("/")
+ if segments and segments[0] in (".git", ".repowise"):
+ return None
+ try:
+ target = (repo_root / file_path).resolve()
+ if not target.is_relative_to(repo_root):
+ return None
+ return target.read_text(encoding="utf-8", errors="replace").splitlines()
+ except (OSError, ValueError):
+ return None
diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.py
index 9bb78c429..1f19919d0 100644
--- a/packages/server/src/repowise/server/schemas/code_quality.py
+++ b/packages/server/src/repowise/server/schemas/code_quality.py
@@ -88,9 +88,18 @@ class SecurityFindingResponse(BaseModel):
severity: str
snippet: str | None
detected_at: datetime
+ # Where in the file. Checked against the live tree before serving, so a
+ # line that drifted is either corrected or withdrawn — see
+ # ``services/security_lines.py``. ``None`` means the snippet is gone from
+ # the file and no line can honestly be given.
+ line_number: int | None
+ # False when the line above could not be confirmed against live source
+ # (file unreadable, or the snippet recurs). Surfaces must mark it.
+ line_verified: bool
# Present when the finding was sourced from git history (full-history
# scan). ``None`` for working-tree findings produced during indexing.
commit_sha: str | None
+ commit_at: datetime | None
found_in_history: bool
diff --git a/packages/server/src/repowise/server/services/security_lines.py b/packages/server/src/repowise/server/services/security_lines.py
new file mode 100644
index 000000000..5c15b8d4d
--- /dev/null
+++ b/packages/server/src/repowise/server/services/security_lines.py
@@ -0,0 +1,77 @@
+"""Serve-time verification that a security finding's line still points at it.
+
+``SecurityFinding.line_number`` is written at scan time and the file may have
+changed since. A wrong line on a security finding is worse than no line: it
+sends the reader to innocent code and looks authoritative doing it. So the
+line is checked against the live file before it is served, the same way
+``mcp_server/_verify.py`` gates symbol bounds.
+
+The contract, mirroring that module:
+
+* ``verified: True`` — the snippet was found on the served line (either the
+ stored line still holds, or the snippet moved and the line was corrected).
+* ``verified: False`` with a line — the snippet is ambiguous in the file, so
+ the line is a guess and the surface must mark it as such.
+* ``line_number: None`` — the snippet is gone from the file entirely. The
+ finding is stale; a line here would point at unrelated code.
+
+For the pattern scan the snippet is ``line.strip()[:120]`` (``security_scan.py``),
+so it is always a substring of the line it came from and containment is a sound
+gate. The symbol-name scan is the exception: its snippet is a bare identifier,
+which recurs all over a file, so those kinds are checked in place and never
+relocated or withdrawn — see ``SYMBOL_NAME_KINDS``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from repowise.core.analysis.security_scan import SYMBOL_NAME_KINDS
+
+
+@dataclass(frozen=True)
+class LineCheck:
+ """Outcome of checking one finding's line against live source."""
+
+ line_number: int | None
+ verified: bool
+
+
+def check_finding_line(
+ lines: list[str] | None,
+ line_number: int | None,
+ snippet: str | None,
+ kind: str | None = None,
+) -> LineCheck:
+ """Verify (and if needed correct) *line_number* against *lines*.
+
+ ``lines`` is the live file split into lines, or None when the file could
+ not be read. Without a file or a snippet there is nothing to check
+ against, so the stored line is passed through unverified rather than
+ being claimed as correct.
+ """
+ if lines is None or not snippet:
+ return LineCheck(line_number=line_number, verified=False)
+
+ if (
+ line_number is not None
+ and 1 <= line_number <= len(lines)
+ and snippet in lines[line_number - 1]
+ ):
+ return LineCheck(line_number=line_number, verified=True)
+
+ if kind in SYMBOL_NAME_KINDS:
+ # A bare identifier is not discriminating enough to relocate on, and
+ # its absence from the stored line does not mean the symbol is gone.
+ return LineCheck(line_number=line_number, verified=False)
+
+ matches = [i + 1 for i, text in enumerate(lines) if snippet in text]
+ if len(matches) == 1:
+ return LineCheck(line_number=matches[0], verified=True)
+ if matches:
+ # Ambiguous: the snippet recurs and the stored line is not one of the
+ # hits. Serve the first as a pointer, but never as verified.
+ return LineCheck(line_number=matches[0], verified=False)
+
+ # Gone from the file: the finding outlived the code it describes.
+ return LineCheck(line_number=None, verified=False)
diff --git a/packages/types/__tests__/contracts.test.ts b/packages/types/__tests__/contracts.test.ts
index a5d22cfd3..cee8dbc46 100644
--- a/packages/types/__tests__/contracts.test.ts
+++ b/packages/types/__tests__/contracts.test.ts
@@ -182,10 +182,21 @@ describe("SecurityFinding canonical shape", () => {
severity: "high",
snippet: null,
detected_at: "2026-05-02T00:00:00Z",
+ line_number: 42,
+ line_verified: true,
+ commit_at: null,
};
expectTypeOf(f.snippet).toEqualTypeOf<string | null>();
expectTypeOf(f.detected_at).toEqualTypeOf<string>();
});
+
+ it("a line is nullable and always paired with its verification flag", () => {
+ // Both required: an optional line_verified would let a consumer read a
+ // drifted line as confirmed by omitting the flag.
+ expectTypeOf<SecurityFinding["line_number"]>().toEqualTypeOf<number | null>();
+ expectTypeOf<SecurityFinding["line_verified"]>().toEqualTypeOf<boolean>();
+ expectTypeOf<SecurityFinding["commit_at"]>().toEqualTypeOf<string | null>();
+ });
});
describe("Canonical Hotspot key shape", () => {
diff --git a/packages/types/src/security.ts b/packages/types/src/security.ts
index 13e6453ae..a46dfbf78 100644
--- a/packages/types/src/security.ts
+++ b/packages/types/src/security.ts
@@ -15,6 +15,20 @@ export interface SecurityFinding {
severity: SecuritySeverity;
snippet: string | null;
detected_at: string;
+ /**
+ * Line the finding sits on, checked against the live tree before it is
+ * served. `null` means the snippet is no longer in the file, so no line can
+ * honestly be given — render the path alone rather than a stale number.
+ */
+ line_number: number | null;
+ /**
+ * False when the line could not be confirmed (file unreadable, or the
+ * snippet recurs). Surfaces must mark it rather than presenting a guess as
+ * fact.
+ */
+ line_verified: boolean;
+ /** When the introducing commit landed; only set for history findings. */
+ commit_at: string | null;
}
export interface SecurityFindingList {
diff --git a/packages/ui/__tests__/wiki/security-panel.test.tsx b/packages/ui/__tests__/wiki/security-panel.test.tsx
index 47358aa0f..47ab0b68a 100644
--- a/packages/ui/__tests__/wiki/security-panel.test.tsx
+++ b/packages/ui/__tests__/wiki/security-panel.test.tsx
@@ -10,6 +10,9 @@ const finding: SecurityFinding = {
severity: "high",
snippet: "API_KEY = \"sk-1234\"",
detected_at: "2026-01-01T00:00:00Z",
+ line_number: 12,
+ line_verified: true,
+ commit_at: null,
};
describe("SecurityPanel", () => {
diff --git a/packages/ui/src/security/findings-table.tsx b/packages/ui/src/security/findings-table.tsx
index 5ba6081b7..5103c8d71 100644
--- a/packages/ui/src/security/findings-table.tsx
+++ b/packages/ui/src/security/findings-table.tsx
@@ -7,15 +7,13 @@ import { Input } from "../ui/input";
import { EmptyState } from "../shared/empty-state";
import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
import { AiPromptButton } from "../health/ai-prompt-button";
+import { formatRelativeTimeOrNull } from "../lib/format";
+import type { SecurityFinding } from "@repowise-dev/types";
-export interface SecurityFinding {
- id: number;
- file_path: string;
- kind: string;
- severity: string;
- snippet: string | null;
- detected_at: string;
-}
+// One declaration of the wire shape, not a third hand-kept copy: this file's
+// local interface had already drifted behind the endpoint, which is how the
+// line number went unrendered.
+export type { SecurityFinding };
const SEVERITY_VARIANT: Record<string, "outdated" | "stale" | "outline"> = {
high: "outdated",
@@ -23,6 +21,59 @@ const SEVERITY_VARIANT: Record<string, "outdated" | "stale" | "outline"> = {
low: "outline",
};
+/**
+ * `path:line` for a finding, degrading honestly.
+ *
+ * The server checks the stored line against the live tree, so there are three
+ * states and they must look different: a confirmed line, a line it could not
+ * confirm (prefixed `~`, never presented as fact), and no line at all when the
+ * flagged code has moved away entirely. A wrong line here sends the reader to
+ * innocent code looking authoritative, which is worse than showing none.
+ */
+function FindingLocation({ finding }: { finding: SecurityFinding }) {
+ const line = finding.line_number;
+ const verified = finding.line_verified;
+
+ // Every state carries words, not just a colour and a tooltip: `title` is
+ // invisible to touch and to assistive tech, which is why VerificationBadge
+ // keeps an sr-only label beside its icon. Same convention here.
+ if (line == null) {
+ return (
+ <span
+ className="block max-w-[280px] truncate font-mono text-xs text-[var(--color-text-primary)]"
+ title={`${finding.file_path} — the flagged code is no longer at the recorded line`}
+ >
+ {finding.file_path}
+ <span className="ml-1.5 not-italic text-2xs text-[var(--color-text-tertiary)]">
+ (line moved)
+ </span>
+ </span>
+ );
+ }
+
+ return (
+ <span
+ className="block max-w-[280px] truncate font-mono text-xs text-[var(--color-text-primary)]"
+ title={
+ verified
+ ? `${finding.file_path}:${line}`
+ : `${finding.file_path}:${line} — could not be confirmed against the current file`
+ }
+ >
+ {finding.file_path}
+ <span
+ className={
+ verified ? "text-[var(--color-text-secondary)]" : "text-[var(--color-text-tertiary)]"
+ }
+ >
+ :{verified ? "" : "~"}
+ {line}
+ </span>
+ {!verified && <span className="sr-only"> (line unconfirmed)</span>}
+ </span>
+ );
+}
+
export interface SecurityFindingsTableProps {
findings: SecurityFinding[];
onSelect?: (finding: SecurityFinding) => void;
@@ -64,14 +115,7 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:
{
key: "file_path",
header: "File",
- render: (f) => (
- <span
- className="block max-w-[280px] truncate font-mono text-xs text-[var(--color-text-primary)]"
- title={f.file_path}
- >
- {f.file_path}
- </span>
- ),
+ render: (f) => <FindingLocation finding={f} />,
},
{
key: "kind",
@@ -92,6 +136,22 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:
</span>
),
},
+ {
+ key: "commit_at",
+ header: "Committed",
+ headerClassName: "w-28",
+ priority: 3,
+ // Only history findings carry an introducing commit; a working-tree
+ // finding has no commit to date, hence the dash.
+ render: (f) => (
+ <span
+ className="text-xs tabular-nums text-[var(--color-text-tertiary)]"
+ title={f.commit_at ? new Date(f.commit_at).toLocaleString() : undefined}
+ >
+ {formatRelativeTimeOrNull(f.commit_at)}
+ </span>
+ ),
+ },
{
key: "detected_at",
header: "Detected",
diff --git a/packages/ui/src/wiki/security-panel.tsx b/packages/ui/src/wiki/security-panel.tsx
index f0e3cd838..d1b832c0d 100644
--- a/packages/ui/src/wiki/security-panel.tsx
+++ b/packages/ui/src/wiki/security-panel.tsx
@@ -48,6 +48,22 @@ export function SecurityPanel({ findings, isLoading }: SecurityPanelProps) {
<span className="text-xs font-medium text-[var(--color-text-secondary)] truncate">
{f.kind}
</span>
+ {f.line_number != null ? (
+ <span
+ className="text-[10px] font-mono text-[var(--color-text-tertiary)] tabular-nums"
+ title={
+ f.line_verified
+ ? undefined
+ : "line could not be confirmed against the current file"
+ }
+ >
+ line {f.line_verified ? "" : "~"}
+ {f.line_number}
+ {!f.line_verified && <span className="sr-only"> (unconfirmed)</span>}
+ </span>
+ ) : (
+ <span className="text-[10px] text-[var(--color-text-tertiary)]">line moved</span>
+ )}
</div>
{f.snippet && (
<pre className="text-[10px] font-mono text-[var(--color-text-tertiary)] whitespace-pre-wrap break-all line-clamp-3 leading-relaxed">
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index a26807bef..ce8c2e70b 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -49,6 +49,7 @@ def _create_test_app():
refactoring,
repos,
search,
+ security,
symbols,
webhooks,
)
@@ -97,6 +98,7 @@ def _create_test_app():
app.include_router(overview.router)
app.include_router(refactoring.router)
app.include_router(providers.router)
+ app.include_router(security.router)
return app
diff --git a/tests/unit/server/test_security.py b/tests/unit/server/test_security.py
new file mode 100644
index 000000000..f60b9491d
--- /dev/null
+++ b/tests/unit/server/test_security.py
@@ -0,0 +1,218 @@
+"""Tests for the security findings endpoint.
+
+The endpoint had no tests at all, which is how it shipped serving a snippet
+with no line number for its whole life. These pin the line contract: a line is
+served only when it was checked against the live file, corrected when the code
+moved, and withdrawn when the code is gone — never handed over as a guess
+dressed as fact.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import SecurityFinding
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _insert(session_factory, repo_id: str, **kw) -> None:
+ async with get_session(session_factory) as session:
+ session.add(
+ SecurityFinding(
+ repository_id=repo_id,
+ file_path=kw.get("file_path", "app.py"),
+ kind=kw.get("kind", "hardcoded_secret"),
+ severity=kw.get("severity", "high"),
+ snippet=kw.get("snippet"),
+ line_number=kw.get("line_number"),
+ commit_sha=kw.get("commit_sha", ""),
+ commit_at=kw.get("commit_at"),
+ detected_at=datetime.now(UTC),
+ )
+ )
+ await session.commit()
+
+
+async def test_list_security_empty(client: AsyncClient) -> None:
+ repo = await create_test_repo(client)
+ resp = await client.get(f"/api/repos/{repo['id']}/security")
+ assert resp.status_code == 200
+ assert resp.json() == []
+
+
+async def test_line_number_verified_against_live_file(client: AsyncClient, app) -> None:
+ """The stored line still holds, so it is served verified."""
+ repo = await create_test_repo(client)
+ src = Path(repo["local_path"]) / "app.py"
+ src.write_text("import os\npassword = 'letmein'\nprint(1)\n")
+
+ await _insert(
+ app.state.session_factory,
+ repo["id"],
+ snippet="password = 'letmein'",
+ line_number=2,
+ )
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ assert row["line_number"] == 2
+ assert row["line_verified"] is True
+
+
+async def test_line_number_corrected_when_code_moved(client: AsyncClient, app) -> None:
+ """Lines inserted above the finding move it; the served line follows."""
+ repo = await create_test_repo(client)
+ src = Path(repo["local_path"]) / "app.py"
+ src.write_text("# new\n# header\n# lines\nimport os\npassword = 'letmein'\n")
+
+ await _insert(
+ app.state.session_factory,
+ repo["id"],
+ snippet="password = 'letmein'",
+ line_number=2,
+ )
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ assert row["line_number"] == 5, "the line should follow the code, not stay stale"
+ assert row["line_verified"] is True
+
+
+async def test_line_withdrawn_when_code_is_gone(client: AsyncClient, app) -> None:
+ """No line at all beats a line pointing at innocent code."""
+ repo = await create_test_repo(client)
+ src = Path(repo["local_path"]) / "app.py"
+ src.write_text("import os\nprint('all clean now')\n")
+
+ await _insert(
+ app.state.session_factory,
+ repo["id"],
+ snippet="password = 'letmein'",
+ line_number=2,
+ )
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ assert row["line_number"] is None
+ assert row["line_verified"] is False
+
+
+async def test_ambiguous_line_is_not_claimed_verified(client: AsyncClient, app) -> None:
+ """A snippet that recurs cannot be pinned, so it is served unverified."""
+ repo = await create_test_repo(client)
+ src = Path(repo["local_path"]) / "app.py"
+ src.write_text("eval(x)\nprint(1)\neval(x)\n")
+
+ await _insert(
+ app.state.session_factory,
+ repo["id"],
+ kind="eval_call",
+ snippet="eval(x)",
+ line_number=99,
+ )
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ assert row["line_number"] is not None
+ assert row["line_verified"] is False
+
+
+async def test_symbol_name_finding_is_never_relocated_or_withdrawn(
+ client: AsyncClient, app
+) -> None:
+ """A symbol-name snippet is a bare identifier, not the text of its line.
+
+ Relocating on it lands on the first coincidental use, and failing to find
+ it does not mean the symbol is gone — so it is checked in place only.
+ """
+ repo = await create_test_repo(client)
+ src = Path(repo["local_path"]) / "app.py"
+ src.write_text("token = 1\nuse(token)\nuse(token)\n")
+
+ await _insert(
+ app.state.session_factory,
+ repo["id"],
+ kind="security_sensitive_symbol",
+ severity="low",
+ snippet="token",
+ line_number=42,
+ )
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ assert row["line_number"] == 42, "must not be relocated onto a coincidental use"
+ assert row["line_verified"] is False
+
+
+async def test_path_outside_the_repo_is_not_read(client: AsyncClient, app) -> None:
+ """A finding path is not a licence to read anywhere on disk."""
+ repo = await create_test_repo(client)
+ await _insert(
+ app.state.session_factory,
+ repo["id"],
+ file_path="../../../../etc/passwd",
+ snippet="root:",
+ line_number=1,
+ )
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ # Unreadable, so the line degrades — it must never come back verified.
+ assert row["line_verified"] is False
+
+
+async def test_credential_directories_are_not_read(client: AsyncClient, app) -> None:
+ """`.repowise/.env` and `.git/config` live inside the root; both stay shut."""
+ repo = await create_test_repo(client)
+ secrets = Path(repo["local_path"]) / ".repowise"
+ secrets.mkdir(exist_ok=True)
+ (secrets / ".env").write_text("OPENAI_API_KEY=sk-real-key\n")
+
+ await _insert(
+ app.state.session_factory,
+ repo["id"],
+ file_path=".repowise/.env",
+ snippet="OPENAI_API_KEY=sk-real-key",
+ line_number=1,
+ )
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ assert row["line_verified"] is False
+
+
+async def test_history_finding_carries_commit_date(client: AsyncClient, app) -> None:
+ """A secret found in history says when it landed, not just that it did."""
+ repo = await create_test_repo(client)
+ committed = datetime(2026, 3, 1, 12, 0, tzinfo=UTC)
+ await _insert(
+ app.state.session_factory,
+ repo["id"],
+ snippet="password = 'old'",
+ line_number=1,
+ commit_sha="abc123def456",
+ commit_at=committed,
+ )
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ assert row["found_in_history"] is True
+ assert row["commit_sha"] == "abc123def456"
+ assert row["commit_at"] is not None
+ assert row["commit_at"].startswith("2026-03-01")
+
+
+async def test_working_tree_finding_has_no_commit_date(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _insert(app.state.session_factory, repo["id"], snippet="x", line_number=1)
+
+ row = (await client.get(f"/api/repos/{repo['id']}/security")).json()[0]
+ assert row["found_in_history"] is False
+ assert row["commit_at"] is None