Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(check): local change policy with repowise check (policies.yaml, SARIF, JUnit) (#3779)
Raghav Chamadiya93469aae7c9d
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 2b741268f..f94179a6c 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -36,6 +36,7 @@ Grouped by what you're trying to do, not alphabetically. `PATH` and flag details[`dead-code`](#repowise-dead-code-path) ·[`doc-drift`](#repowise-doc-drift-path) ·[`security`](#repowise-security) ·+[`check`](#repowise-check-revspec) ·[`impacted-tests`](#repowise-impacted-tests-revspec) ·[`coverage`](#repowise-coverage) ·[`components`](#repowise-components) ·@@ -1603,6 +1604,18 @@ repowise changes show REF [--path PATH] [--format table|json|in-toto]---+### `repowise check [REVSPEC]`++Evaluates `.repowise/policies.yaml` (see [CONFIG.md](CONFIG.md#repowisepoliciesyaml)) against a change: components touched and their tags, provenance from public git markers, and, with an index, reaching tests, governing decisions crossed and bus factor. Rules that wrap a gate run `security check`, `coverage check` or `doc-drift --check` exactly as those commands run alone, and without a policy file every gate behaves as before while `check` reports nothing to evaluate. Exit 1 when a `fail` rule fires, 2 when the policy is invalid or a `fail` gate cannot be evaluated, else 0; `--sarif-file` writes SARIF 2.1.0 for code scanning or reviewdog and `--junit-file` a JUnit report from the same run.++```bash+repowise check [REVSPEC] [--path PATH] [--policies FILE] [--sarif-file FILE] [--junit-file FILE] [--format table|json|sarif|junit]+```++Teams that already run OPA can use the `evidence` object of `repowise check --format json` as OPA `input`: it is the change's evidence checklist, one item per kind (`components_touched`, `provenance`, `reaching_tests`, `decisions_crossed`, `contracts`) with its status, basis and per-file details. `opa eval --input check.json --data policy.rego 'data.repowise.deny'` then evaluates Rego rules over `input.evidence.items` next to, or instead of, `policies.yaml`.++---+### `repowise distill <command>`Run a command and print a compact, reversible rendering of its output. Noisediff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex 72db5bdb1..bb340c386 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -14,6 +14,7 @@ The `.repowise/` directory, provider setup, API keys, and what's customizable.[The `hooks:` block](#the-hooks-block) ·[The `mcp:` block](#the-mcp-block) ·[The `decisions:` block](#the-decisions-block) ·+[`policies.yaml`](#repowisepoliciesyaml) ·[The `security:` block](#the-security-block) ·[The `attribution:` block](#the-attribution-block) ·[The `refactoring:` block](#the-refactoring-block) ·@@ -571,6 +572,28 @@ re-extraction.Components name the parts of a repository that health, hotspots, bus factor, test reach and dead code roll up to. The file is multi-document Backstage YAML (`Component`, `System` and `Group` on `backstage.io/v1alpha1`), with Repowise data in `repowise.dev/paths` (gitignore-style globs written with `/`, matched case-sensitively), `repowise.dev/criticality` (`low`, `medium`, `high`, `critical`), `repowise.dev/tags` and `repowise.dev/capability` annotations; a repo-root `catalog-info.yaml` is read the same way, so a developer portal and Repowise share one file. Without a file, components are derived from workspace services, then module pages, then top-level directories; a declared component claims the files its globs match (where two match a file, the first declared wins), and one named like a derived component replaces it and, with no paths of its own, keeps its directory. See [examples/components](../../examples/components/components.yaml) and `repowise components check`.+### `.repowise/policies.yaml`++The change policy `repowise check` evaluates. Each rule selects components (`match`, `exclude`), tests conditions over the change's evidence (`when`, all must hold) and names an action: `warn`, `require_owner_review`, `require_tests` or `fail`. A rule can instead wrap an existing gate (`security`, `coverage` or `doc_drift`) with that command's options under `with`; it runs exactly as the command does on its own, and `doc_drift` is scoped to the change (`since`) unless the rule sets it. `require_owner_review` and `require_tests` are advisory: they are reported in every format and `repowise check` still exits 0; only `fail` exits 1.++```yaml+version: 1+rules:+ - name: agent-pci-needs-owner+ match:+ components: {tags: [pci]} # also names, criticality; each list is any-of+ when:+ attribution: agent # agent, human_attested or unknown+ reaching_tests: missing # a changed file in scope has no reaching test+ action: require_owner_review+ - name: no-new-secrets+ gate: security+ with: {fail_on: high, baseline: .security-baseline.json}+ action: fail # the default for a gate+```++Conditions are `attribution`, `agent_tier` (1, 2 or 3), `reaching_tests` (`missing` or `present`), `contract_break`, `decision_crossed` and `bus_factor_below`; there is no risk-score condition. A condition whose evidence is not available (no index, attribution off) leaves the rule not evaluated, and it never fires. Exit 2 (`policy_invalid`, every problem listed) on an unknown key, condition or gate option, a bad action, or a duplicate rule name.+### The `security:` blockSecret shapes of your own for `repowise security check`.diff --git a/packages/cli/src/repowise/cli/commands/check_cmd.py b/packages/cli/src/repowise/cli/commands/check_cmd.pynew file mode 100644index 000000000..7979db244--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/check_cmd.py@@ -0,0 +1,314 @@+"""``repowise check``: evaluate ``.repowise/policies.yaml`` against a change, in CI.++Each rule either tests conditions over the change's evidence (components and+their tags, provenance, reaching tests, contract breaks, decisions crossed,+bus factor) or wraps an existing gate (``security``, ``coverage``,+``doc_drift``), which runs as its own command with the options the rule gives.+Those commands are untouched: without a policy file they behave as they always+have, and ``repowise check`` reports that there is nothing to evaluate.++Exit codes follow :mod:`repowise.cli.ci`: 0 nothing failed, 1 a ``fail`` rule+fired, 2 the policy is invalid, the change cannot be read, or a ``fail`` gate+could not be evaluated.+"""++from __future__ import annotations++import json+import subprocess+import sys+from pathlib import Path+from typing import Any++import click++from repowise.cli.ci import (+ CannotEvaluateError,+ cannot_evaluate,+ change_set,+ ci_notices,+ ci_revspec,+ repo_root,+)+from repowise.cli.output import emit_json, format_option++_FORMATS = ("table", "json", "sarif", "junit")++#: Gate kind -> (argv after ``repowise``, "module:command" for option checks, takes REVSPEC).+_GATES: dict[str, tuple[tuple[str, ...], str, bool]] = {+ "security": (("security", "check"), "security_cmd:security_command", True),+ "coverage": (("coverage", "check"), "coverage_check_cmd:coverage_check", True),+ "doc_drift": (("doc-drift", "--check"), "doc_drift_cmd:doc_drift_command", False),+}+#: A gate still running after this is reported as not evaluated.+GATE_TIMEOUT_SECONDS = 1800+#: Options ``repowise check`` sets itself, or that would write files.+_RESERVED = frozenset(+ {"format", "path", "repo", "staged", "write_baseline", "check", "json", "no_workspace"}+)++[email protected]("check")[email protected]("revspec", required=False, default=None)[email protected]("--path", "repo", default=None, help="A path inside the repository (defaults to cwd).")+ "--policies",+ "policies_path",+ default=None,+ help="Policy file to evaluate (default .repowise/policies.yaml).",+)+ "--sarif-file",+ type=click.Path(dir_okay=False, path_type=Path),+ default=None,+ help="Also write SARIF 2.1.0 here, for code scanning or reviewdog.",+)+ "--junit-file",+ type=click.Path(dir_okay=False, path_type=Path),+ default=None,+ help="Also write JUnit XML here, for a CI test report.",+)+@format_option(+ choices=_FORMATS,+ help="Output format. ``json`` carries the evidence too (usable as OPA input).",+)+def check_command(+ revspec: str | None,+ repo: str | None,+ policies_path: str | None,+ sarif_file: Path | None,+ junit_file: Path | None,+ fmt: str,+) -> None:+ """Evaluate the change policy in .repowise/policies.yaml against a change.++ REVSPEC is the change (``origin/main...HEAD``, ``base..head`` or one+ commit); without it, the CI's pull-request target branch...HEAD, else the+ remote's default branch...HEAD.+ """+ from repowise.core.policy import PolicyError, load_policy++ try:+ root = repo_root(repo)+ policy = load_policy(root, policies_path)+ if policy is None:+ _emit_nothing(fmt, sarif_file, junit_file)+ return+ _check_gate_options(policy)+ resolved = ci_revspec(str(root), revspec)+ change = change_set(str(root), resolved)+ except PolicyError as exc:+ cannot_evaluate(fmt, "policy_invalid", "\n".join([f"{exc.source} is invalid:", *exc.problems]))+ except CannotEvaluateError as exc:+ cannot_evaluate(fmt, exc.code, str(exc))++ from repowise.core.policy import evaluate, exit_code++ gate_runs = {r.name: _run_gate(root, r, resolved) for r in policy.rules if r.gate}+ evidence = _gather(root, change) if any(not r.gate for r in policy.rules) else None+ results = evaluate(policy, evidence, gate_runs)+ anchor = min([*change.files, *change.deleted], default=None)+ _emit(fmt, policy, results, evidence, change.label, sarif_file, junit_file, anchor=anchor)+ code = exit_code(results)+ if code:+ raise click.exceptions.Exit(code)+++def _gather(root: Path, change: Any) -> dict[str, Any]:+ # Interim: swap for the Change Record evidence builder+ # (repowise.core.changes.evidence) once it lands; the shape is the same.+ from repowise.cli.helpers import repo_index_session, run_async+ from repowise.core.policy.interim_evidence import gather_evidence++ async def go() -> dict[str, Any]:+ async with repo_index_session(root) as opened:+ if opened is None:+ return await gather_evidence(root, change)+ session, repo_id = opened+ return await gather_evidence(root, change, session=session, repo_id=repo_id)++ return run_async(go())+++# -- gates --------------------------------------------------------------------+++def _gate_command(kind: str) -> click.Command:+ import importlib++ module, _, attr = _GATES[kind][1].partition(":")+ command = getattr(importlib.import_module(f"repowise.cli.commands.{module}"), attr)+ if isinstance(command, click.Group):+ command = command.commands[_GATES[kind][0][1]]+ return command+++def _check_gate_options(policy: Any) -> None:+ """Every ``with`` key names an option of its gate's command, or the policy is invalid."""+ from repowise.core.policy import PolicyError++ problems = []+ for rule in policy.rules:+ if not rule.gate:+ continue+ flags = {+ opt.lstrip("-").replace("-", "_")+ for p in _gate_command(rule.gate).params+ if isinstance(p, click.Option)+ for opt in p.opts+ if opt.startswith("--")+ } - _RESERVED+ for key in rule.gate_args:+ if key not in flags:+ known = ", ".join(sorted(flags))+ problems.append(f"rule {rule.name}: the {rule.gate} gate has no option {key!r} (options: {known})")+ if problems:+ raise PolicyError(policy.source, problems)+++def _gate_argv(rule: Any, revspec: str) -> list[str]:+ argv, _cmd, takes_revspec = _GATES[rule.gate]+ out = [*argv]+ args = dict(rule.gate_args)+ if not takes_revspec:+ # doc-drift judges the tree; scope it to this change unless the rule says otherwise.+ args.setdefault("since", revspec)+ for key, value in args.items():+ flag = "--" + key.replace("_", "-")+ if value is True:+ out.append(flag)+ elif value is False:+ continue+ else:+ # ``--flag=value`` so a value starting with "-" is never read as an option.+ out += [f"{flag}={v}" for v in (value if isinstance(value, list) else [value])]+ out += ["--format", "json"]+ # ``--`` ends the options, so REVSPEC is always the positional argument.+ return [*out, "--", revspec] if takes_revspec else out+++def _verdict(kind: str, doc: Any) -> bool | None:+ """Whether the gate's own JSON verdict says it failed; ``None`` when there is none."""+ gate = doc.get("gate") if isinstance(doc, dict) else None+ if kind == "coverage":+ return gate == "fail" if isinstance(gate, str) else None+ passed = gate.get("passed") if isinstance(gate, dict) else None+ return (not passed) if isinstance(passed, bool) else None+++def _run_gate(root: Path, rule: Any, revspec: str) -> Any:+ """Run the gate as its own command does, in a child process, and read its verdict.++ Only a JSON verdict that agrees with the exit code counts: a crash, a+ refusal or anything else unreadable is "could not be evaluated", never a+ fired rule.+ """+ import os++ from repowise.core.policy import GateRun++ argv = _gate_argv(rule, revspec)+ shown = "repowise " + " ".join(a for a in argv if a not in ("--format", "json", "--"))+ env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}+ try:+ proc = subprocess.run(+ [sys.executable, "-m", "repowise.cli.main", *argv],+ cwd=root,+ env=env,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ stdin=subprocess.DEVNULL,+ timeout=GATE_TIMEOUT_SECONDS,+ check=False,+ )+ except subprocess.TimeoutExpired:+ return GateRun(2, f"{shown} did not finish within {GATE_TIMEOUT_SECONDS} seconds")+ except OSError as exc:+ return GateRun(2, f"could not start {shown}: {exc}")+ try:+ doc = json.loads(proc.stdout or "null")+ except ValueError:+ doc = None+ failed = _verdict(rule.gate, doc)+ if failed is None or proc.returncode != int(failed):+ message = doc.get("message") if isinstance(doc, dict) else None+ last = (proc.stderr.strip().splitlines() or [""])[-1]+ return GateRun(2, message or last or f"{shown} exited {proc.returncode} with no verdict")+ locations = []+ for f in (doc["gate"].get("failing") or ()) if isinstance(doc["gate"], dict) else ():+ line = None if f.get("commit") else f.get("line_number")+ locations.append((str(f.get("file_path")), line, f.get("fingerprint")))+ return GateRun(proc.returncode, f"Reproduce with: {shown}", tuple(locations))+++# -- output -------------------------------------------------------------------+++def _emit_nothing(fmt: str, sarif_file: Path | None, junit_file: Path | None) -> None:+ from repowise.core.policy import Policy++ notice = (+ "No .repowise/policies.yaml: nothing to evaluate. The security, coverage "+ "and doc-drift gates run on their own as before."+ )+ _emit(fmt, Policy(()), [], None, "", sarif_file, junit_file, notice=notice)+++def _emit(+ fmt: str,+ policy: Any,+ results: list,+ evidence: dict | None,+ revspec: str,+ sarif_file: Path | None,+ junit_file: Path | None,+ *,+ notice: str | None = None,+ anchor: str | None = None,+) -> None:+ from repowise.cli import __version__+ from repowise.core.policy.report import render_junit, render_sarif++ sarif = render_sarif(+ policy, results, tool_version=__version__, revspec=revspec, fallback_path=anchor+ )+ junit = render_junit(results, revspec=revspec)+ if sarif_file:+ sarif_file.write_text(json.dumps(sarif, indent=2), encoding="utf-8")+ if junit_file:+ junit_file.write_text(junit, encoding="utf-8")+ if fmt == "json":+ emit_json(+ {+ "revspec": revspec,+ "policy_file": policy.source if policy.rules else None,+ "results": [r.to_dict() for r in results],+ "evidence": evidence,+ }+ )+ elif fmt == "sarif":+ emit_json(sarif)+ elif fmt == "junit":+ click.echo(junit, nl=False)+ if notice:+ ci_notices(fmt).print(notice)+ elif fmt == "table":+ _print_table(results, revspec)+++_STYLE = {"triggered": "bold", "passed": "green", "not_applicable": "dim", "unknown": "yellow"}+++def _print_table(results: list, revspec: str) -> None:+ from rich.markup import escape++ from repowise.cli.helpers import console++ console.print(f"Change policy for [bold]{escape(revspec)}[/bold]: {len(results)} rule(s)")+ for r in results:+ label = r.rule.action.upper() if r.outcome == "triggered" else r.outcome.replace("_", " ")+ style = "red" if r.fails else _STYLE[r.outcome]+ console.print(f" [{style}]{escape(label):<22}[/{style}] {escape(r.rule.name)}: {escape(r.message)}")diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex fd5302452..72dc306c1 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -73,6 +73,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (("coverage", "coverage_cmd:coverage_group"),("components", "components_cmd:components_group"),("changes", "changes_cmd:changes_group"),+ ("check", "check_cmd:check_command"),("impacted-tests", "impacted_tests_cmd:impacted_tests_command"),("search", "search_cmd:search_command"),("ask", "ask_cmd:ask_command"),diff --git a/packages/core/src/repowise/core/policy/__init__.py b/packages/core/src/repowise/core/policy/__init__.pynew file mode 100644index 000000000..fe44d593d--- /dev/null+++ b/packages/core/src/repowise/core/policy/__init__.py@@ -0,0 +1,29 @@+"""Local change policy: ``.repowise/policies.yaml`` evaluated over a change's evidence."""++from __future__ import annotations++from repowise.core.policy.rules import (+ POLICIES_FILE,+ GateRun,+ Policy,+ PolicyError,+ Rule,+ RuleResult,+ evaluate,+ exit_code,+ load_policy,+ parse_policy,+)++__all__ = [+ "POLICIES_FILE",+ "GateRun",+ "Policy",+ "PolicyError",+ "Rule",+ "RuleResult",+ "evaluate",+ "exit_code",+ "load_policy",+ "parse_policy",+]diff --git a/packages/core/src/repowise/core/policy/interim_evidence.py b/packages/core/src/repowise/core/policy/interim_evidence.pynew file mode 100644index 000000000..09d4ddd71--- /dev/null+++ b/packages/core/src/repowise/core/policy/interim_evidence.py@@ -0,0 +1,251 @@+"""The evidence ``repowise check`` evaluates, read from the existing analyzers.++Interim: this adapter is swapped for the Change Record evidence builder+(``repowise.core.changes.evidence``) once that lands; both emit the same+``ChangeEvidence`` shape, so the policy evaluator does not change.++Git alone gives the components a change touches (declared in the catalog) and+its provenance. An index adds derived components, bus factor, reaching tests+and the governing decisions the change crosses; without one those items are+``unknown`` and the rules that need them are not evaluated. Contract breaks+need a parse of both sides and are left to the evidence builder.+"""++from __future__ import annotations++import asyncio+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++#: Commits of one change labelled for provenance; past it the label is unknown.+MAX_COMMITS = 500+++def _item(+ kind: str, label: str, status: str, basis: str, value: Any, details: list, source: str+) -> dict[str, Any]:+ return {+ "kind": kind,+ "label": label,+ "status": status,+ "basis": basis,+ "value": value,+ "details": details,+ "source": source,+ }+++def _unknown(kind: str, label: str, why: str) -> dict[str, Any]:+ return _item(kind, label, "unknown", "unresolved", None, [{"reason": why}], "repowise check")+++async def gather_evidence(+ repo_root: Path | str,+ change: Any,+ *,+ session: Any = None,+ repo_id: str | None = None,+) -> dict[str, Any]:+ """``ChangeEvidence`` for *change* (a ``ChangeSet``); *session* is an open index, if any."""+ root = Path(repo_root)+ changed = sorted({*change.files, *change.deleted})+ indexed = session is not None and repo_id is not None+ items = [+ await _components(root, changed, session, repo_id) if indexed else _declared(root, changed),+ await asyncio.to_thread(_provenance, root, change),+ ]+ if indexed:+ items.append(await _reaching_tests(session, repo_id, root, change))+ items.append(await _decisions(session, repo_id, changed))+ else:+ items.append(_unknown("reaching_tests", "Reaching tests", "no index"))+ items.append(_unknown("decisions_crossed", "Decisions crossed", "no index"))+ items.append(+ _unknown("contracts", "Contracts", "contract comparison comes from the evidence builder")+ )+ return {+ "schema_version": 1,+ "change_id": change.head or change.label,+ "revspec": change.label,+ "generated_at": datetime.now(UTC).isoformat(),+ "items": items,+ }+++def _component_row(comp: Any, files: list[str], bus_factor: int | None = None) -> dict[str, Any]:+ from repowise.core.components.catalog import owner_group_name++ return {+ "name": comp.name,+ "criticality": comp.criticality,+ "tags": list(comp.tags),+ "owner": owner_group_name(comp.owner) if comp.owner else None,+ "source": comp.source,+ "files": files,+ "bus_factor": bus_factor,+ }+++def _declared(root: Path, changed: list[str]) -> dict[str, Any]:+ from repowise.core.components import read_catalog, resolve_components++ catalog = read_catalog(root)+ resolved = resolve_components(catalog.components, [], changed)+ rows = [_component_row(c, resolved.files[c.name]) for c in resolved.components if resolved.files[c.name]]+ return _item(+ "components_touched", "Components touched", "ok", "declared", len(rows), rows,+ ", ".join(catalog.sources) or "no catalog file",+ )+++async def _components(root: Path, changed: list[str], session: Any, repo_id: str) -> dict[str, Any]:+ from repowise.core.components.store import (+ component_rollups,+ load_repo_components,+ workspace_services,+ )++ repo = await load_repo_components(session, repo_id, root, services=workspace_services(root))+ wanted = set(changed)+ touched = [+ c for c in repo.resolved.components if wanted & set(repo.resolved.files.get(c.name, ()))+ ]+ rollups = await component_rollups(+ session, repo_id, {c.name: repo.resolved.files[c.name] for c in touched}, repo.test_files+ )+ rows = []+ for c in touched:+ bus = (rollups.get(c.name) or {}).get("bus_factor") or {}+ value = bus.get("value") if bus.get("basis") == "measured" else None+ rows.append(_component_row(c, sorted(wanted & set(repo.resolved.files[c.name])), value))+ # Files no component claims do not count as touching a component.+ return _item(+ "components_touched", "Components touched", "ok", "measured", len(rows), rows,+ "index and " + (", ".join(repo.catalog.sources) or "derived components"),+ )+++def _provenance(root: Path, change: Any) -> dict[str, Any]:+ from repowise.core.attribution import attribution_enabled+ from repowise.core.changes.store import change_provenance++ label = "Provenance"+ if not attribution_enabled(root):+ return _unknown("provenance", label, "attribution is off for this repository")+ if not (change.base and change.head):+ return _unknown("provenance", label, "uncommitted changes have no commits to label")+ commits = _labelled_commits(root, change.base, change.head)+ if commits is None:+ return _unknown("provenance", label, f"more than {MAX_COMMITS} commits, or git failed")+ labels = {c["sha"]: (c["label"], c["agent"]) for c in commits}+ state, agent, known = change_provenance(list(labels), labels)+ return _item(+ "provenance", label, "ok", "declared",+ {"label": state, "agent_commits": agent, "known_commits": known, "commits": len(commits)},+ commits, "public git markers: bot authors, trailers, footers, git-ai notes, Agent Trace",+ )+++def _labelled_commits(root: Path, base: str, head: str) -> list[dict[str, Any]] | None:+ import subprocess++ from repowise.core.analysis.git_cli import _git+ from repowise.core.ingestion.git_commit_index import load_git_ai_note_agents+ from repowise.core.ingestion.git_indexer.agent_provenance import (+ AgentTraceIndex,+ classifier_from_repo_config,+ classify_commit,+ )+ from repowise.core.ingestion.git_indexer.records import (+ _LOG_FORMAT,+ _RECORD_SEP,+ _parse_commit_record,+ )++ try:+ raw = _git(+ ["log", f"-{MAX_COMMITS + 1}", "--numstat", f"--format={_LOG_FORMAT}", f"{base}..{head}"],+ str(root),+ )+ except (subprocess.SubprocessError, OSError):+ return None+ records = [r for r in (_parse_commit_record(c) for c in raw.split(_RECORD_SEP) if c.strip()) if r]+ if len(records) > MAX_COMMITS:+ return None+ try:+ import git++ repo = git.Repo(root)+ except Exception:+ repo = None+ classifier = classifier_from_repo_config(root)+ notes = load_git_ai_note_agents(repo, MAX_COMMITS) if repo is not None else {}+ traces = AgentTraceIndex.load(repo) if repo is not None else None+ out = []+ for header, numstat in records:+ paths = {line.split("\t", 2)[2] for line in numstat if line.count("\t") >= 2}+ prov, _hit = classify_commit(classifier, header, paths, notes, traces)+ out.append(+ {+ "sha": header["sha"],+ "label": prov.attribution,+ "agent": prov.agent,+ "tier": prov.autonomy_tier,+ "channel": prov.channel,+ }+ )+ return out+++async def _reaching_tests(session: Any, repo_id: str, root: Path, change: Any) -> dict[str, Any]:+ from repowise.core.analysis.test_collection import collect++ label = "Reaching tests"+ out = await collect(session, repo_id, root, change)+ if out.get("index_problem") or out.get("graph_error"):+ return _unknown("reaching_tests", label, str(out.get("index_problem") or out["graph_error"]))+ # A file nothing knows a test for is a known absence only when a current,+ # complete coverage map measured it; otherwise it is not known.+ measured = not (out.get("map_empty") or out.get("map_truncated")) and out.get("map_current")+ tests: dict[str, dict[str, str] | None] = {}+ for test_id, row in (out.get("covered") or {}).items():+ for path in row.get("source_files") or ():+ tests.setdefault(path, {})[test_id] = "measured"+ for row in out.get("inferred") or ():+ found = tests.setdefault(row["source_file"], {})+ found.setdefault(row["test_file"], "inferred")+ for path in out.get("unknown") or ():+ tests.setdefault(path, {} if measured else None)+ rows = [+ {+ "path": path,+ "tests": None if found is None else sorted(found),+ "basis": "unresolved"+ if found is None+ else ("measured" if not found or "measured" in found.values() else "inferred"),+ }+ for path, found in sorted(tests.items())+ ]+ if rows and all(r["tests"] is None for r in rows):+ return _unknown("reaching_tests", label, "no measured coverage and no test found")+ return _item(+ "reaching_tests", label, "ok", "measured" if measured else "inferred",+ sum(1 for r in rows if r["tests"] == []), rows, "coverage map and dependency graph",+ )+++async def _decisions(session: Any, repo_id: str, changed: list[str]) -> dict[str, Any]:+ from repowise.core.persistence.crud.authority import governing_decisions_by_file++ by_file = await governing_decisions_by_file(session, repo_id)+ crossed: dict[str, dict[str, Any]] = {}+ for path in changed:+ for decision_id, title in by_file.get(path, ()):+ row = crossed.setdefault(decision_id, {"id": decision_id, "title": title, "paths": []})+ row["paths"].append(path)+ rows = list(crossed.values())+ return _item(+ "decisions_crossed", "Decisions crossed", "ok", "declared", len(rows), rows,+ "governing decisions that name a changed file",+ )diff --git a/packages/core/src/repowise/core/policy/report.py b/packages/core/src/repowise/core/policy/report.pynew file mode 100644index 000000000..11dea992f--- /dev/null+++ b/packages/core/src/repowise/core/policy/report.py@@ -0,0 +1,109 @@+"""Policy results as SARIF 2.1.0 and JUnit XML.++SARIF carries one result per rule that fired, so code scanning on any forge+and reviewdog show it on the change: ``fail`` is an ``error``, every other+action a ``warning``, and the action, components, owners and the basis of each+evidence kind ride in the result's ``properties``. A result with no file of+its own is located on the policy file. Rules that could not be evaluated are+listed in the run's properties, never as results.++JUnit has one test case per rule: a ``failure`` for a ``fail`` that fired,+``skipped`` for a rule whose evidence was not available, and a pass with the+message in ``system-out`` for every other action that fired.+"""++from __future__ import annotations++import hashlib+import xml.etree.ElementTree as ET+from collections.abc import Sequence+from pathlib import PurePath, PureWindowsPath+from typing import Any++from repowise.core.ci import sarif+from repowise.core.policy.rules import POLICIES_FILE, TRIGGERED, UNKNOWN, Policy, RuleResult++TOOL_NAME = "repowise-check"+FINGERPRINT_KEY = "repowisePolicy/v1"+++def _rule_id(name: str) -> str:+ return f"policy/{name}"+++def render_sarif(+ policy: Policy,+ results: Sequence[RuleResult],+ *,+ tool_version: str,+ revspec: str,+ fallback_path: str | None = None,+) -> dict:+ """*fallback_path* (repo-relative) locates file-less results when the policy+ file lies outside the repository, so every uri stays relative to it."""+ anchor = policy.source+ if PurePath(anchor).is_absolute() or PureWindowsPath(anchor).is_absolute():+ anchor = fallback_path or POLICIES_FILE+ rules = [+ sarif.rule(+ _rule_id(r.name),+ r.name,+ r.description or f"Change policy rule {r.name}",+ r.description or f"Change policy rule {r.name} ({r.gate or 'conditions'}, {r.action}).",+ )+ for r in policy.rules+ ]+ out: list[dict] = []+ for res in results:+ if res.outcome != TRIGGERED:+ continue+ properties: dict[str, Any] = {"action": res.rule.action}+ for key in ("components", "owners", "reasons"):+ if getattr(res, key):+ properties[key] = getattr(res, key)+ if res.evidence:+ properties["evidence"] = res.evidence+ for path, line, own in res.locations or [(anchor, None, None)]:+ ident = own or f"{path}:{line or 0}"+ out.append(+ sarif.result(+ _rule_id(res.rule.name),+ "error" if res.rule.action == "fail" else "warning",+ res.message,+ path,+ line,+ FINGERPRINT_KEY,+ hashlib.sha256(f"{res.rule.name}|{ident}".encode()).hexdigest()[:32],+ properties,+ )+ )+ not_evaluated = [r.rule.name for r in results if r.outcome == UNKNOWN]+ run_props: dict[str, Any] = {"revspec": revspec, "policyFile": policy.source}+ if not_evaluated:+ run_props["notEvaluated"] = not_evaluated+ return sarif.run(TOOL_NAME, tool_version, rules, out, properties=run_props)+++def render_junit(results: Sequence[RuleResult], *, revspec: str) -> str:+ suite = ET.Element(+ "testsuite",+ name=TOOL_NAME,+ tests=str(len(results)),+ failures=str(sum(r.fails for r in results)),+ errors="0",+ skipped=str(sum(r.outcome == UNKNOWN for r in results)),+ )+ ET.SubElement(ET.SubElement(suite, "properties"), "property", name="revspec", value=revspec)+ for res in results:+ case = ET.SubElement(suite, "testcase", name=res.rule.name, classname=f"{TOOL_NAME}.{res.rule.action}")+ if res.fails:+ failure = ET.SubElement(case, "failure", message=res.message, type=res.rule.action)+ failure.text = "\n".join(f"{p}{f':{ln}' if ln else ''}" for p, ln, _fp in res.locations) or None+ elif res.outcome == UNKNOWN:+ ET.SubElement(case, "skipped", message=res.message)+ elif res.outcome == TRIGGERED:+ ET.SubElement(case, "system-out").text = f"{res.rule.action}: {res.message}"+ root = ET.Element("testsuites", name=TOOL_NAME)+ root.append(suite)+ ET.indent(root)+ return '<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(root, encoding="unicode") + "\n"diff --git a/packages/core/src/repowise/core/policy/rules.py b/packages/core/src/repowise/core/policy/rules.pynew file mode 100644index 000000000..06450d04b--- /dev/null+++ b/packages/core/src/repowise/core/policy/rules.py@@ -0,0 +1,566 @@+"""``.repowise/policies.yaml``: change rules read, validated and evaluated.++A rule has the shape of a Kyverno rule (``match``, ``exclude``, then+conditions under ``when``) and an action from an Allstar-style ladder:+``warn``, ``require_owner_review``, ``require_tests`` or ``fail``. A rule+either tests conditions over a change's evidence, or wraps one of the existing+CI gates (``gate: security|coverage|doc_drift``), which runs exactly as its+own command does.++Evaluation reads a plain evidence mapping, ``{schema_version, change_id,+revspec, generated_at, items: [{kind, label, status, basis, value, details,+source}]}``, and only these detail fields:++* ``components_touched``: rows ``{name, criticality, tags, owner, files,+ bus_factor}``;+* ``provenance``: ``value`` is the change's label (``agent``,+ ``human_attested`` or ``unknown``), or a mapping holding it as ``label``;+ rows ``{sha, label, tier}``;+* ``reaching_tests``: one row per changed source file, ``{path, tests}``; ``tests``+ is ``[]`` only for a known absence and ``null`` when nothing knows;+* ``contracts``: rows ``{path, breaking}``;+* ``decisions_crossed``: rows ``{id, title, paths}``.++An item whose status is ``unknown`` or whose basis is ``unresolved`` answers+nothing, so a condition that needs it is unknown and the rule does not fire:+a missed policy hit is preferred to a false one. There are no risk-score+conditions; change risk is not calibrated.+"""++from __future__ import annotations++import re+from collections.abc import Iterable, Mapping+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import yaml++POLICIES_FILE = ".repowise/policies.yaml"+MAX_POLICY_BYTES = 256_000++ACTIONS: tuple[str, ...] = ("warn", "require_owner_review", "require_tests", "fail")+GATES: tuple[str, ...] = ("security", "coverage", "doc_drift")+ATTRIBUTION_STATES: tuple[str, ...] = ("agent", "human_attested", "unknown")+CONDITIONS: tuple[str, ...] = (+ "attribution",+ "agent_tier",+ "reaching_tests",+ "contract_break",+ "decision_crossed",+ "bus_factor_below",+)+_SELECTOR_KEYS = ("names", "tags", "criticality")+_RULE_KEYS = ("name", "description", "match", "exclude", "when", "gate", "with", "action", "message")+_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$")++#: A rule's outcome. ``unknown``: evidence it needs was not available.+TRIGGERED, PASSED, NOT_APPLICABLE, UNKNOWN = "triggered", "passed", "not_applicable", "unknown"+++class PolicyError(ValueError):+ """The policy file is invalid; ``problems`` lists every reason."""++ def __init__(self, source: str, problems: list[str]) -> None:+ super().__init__(f"{source}: " + "; ".join(problems))+ self.source = source+ self.problems = problems+++@dataclass(frozen=True)+class Selector:+ """Components whose name, tags and criticality all match (each list is any-of)."""++ names: tuple[str, ...] = ()+ tags: tuple[str, ...] = ()+ criticality: tuple[str, ...] = ()++ def matches(self, component: Mapping[str, Any]) -> bool:+ tags = {str(t).lower() for t in component.get("tags") or ()}+ crit = str(component.get("criticality") or "").lower()+ return (+ (not self.names or str(component.get("name", "")).lower() in self.names)+ and (not self.tags or bool(tags & set(self.tags)))+ and (not self.criticality or crit in self.criticality)+ )+++@dataclass(frozen=True)+class Rule:+ name: str+ action: str+ description: str | None = None+ message: str | None = None+ match: Selector | None = None+ exclude: Selector | None = None+ when: Mapping[str, Any] = field(default_factory=dict)+ gate: str | None = None+ gate_args: Mapping[str, Any] = field(default_factory=dict)+++@dataclass(frozen=True)+class Policy:+ rules: tuple[Rule, ...]+ source: str = POLICIES_FILE+++# -- reading ------------------------------------------------------------------+++def load_policy(repo_root: Path | str, path: Path | str | None = None) -> Policy | None:+ """The policy at *path* (default ``.repowise/policies.yaml``), or ``None`` when absent.++ Raises :class:`PolicyError` listing every problem in a file that exists.+ """+ root = Path(repo_root)+ file = Path(path) if path else root / POLICIES_FILE+ if not file.is_absolute():+ file = root / file+ if not file.is_file():+ if path:+ raise PolicyError(str(path), ["file not found"])+ return None+ source = file.relative_to(root).as_posix() if file.is_relative_to(root) else str(file)+ try:+ if file.stat().st_size > MAX_POLICY_BYTES:+ raise PolicyError(source, [f"larger than {MAX_POLICY_BYTES} bytes"])+ text = file.read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError) as exc:+ raise PolicyError(source, [f"cannot read: {exc}"]) from exc+ return parse_policy(text, source)+++def parse_policy(text: str, source: str = POLICIES_FILE) -> Policy:+ """Validate *text*; raises :class:`PolicyError` with every problem found."""+ try:+ doc = yaml.safe_load(text)+ except yaml.YAMLError as exc:+ raise PolicyError(source, [f"invalid YAML: {exc}"]) from exc+ problems: list[str] = []+ if not isinstance(doc, dict):+ raise PolicyError(source, ["the file must be a mapping with a 'rules' list"])+ for key in sorted(set(doc) - {"version", "rules"}):+ problems.append(f"unknown top-level key {key!r} (expected version, rules)")+ if doc.get("version", 1) != 1:+ problems.append(f"version {doc.get('version')!r} is not supported (expected 1)")+ raw_rules = doc.get("rules")+ if not isinstance(raw_rules, list) or not raw_rules:+ problems.append("'rules' must be a non-empty list")+ raise PolicyError(source, problems)+ rules: list[Rule] = []+ seen: set[str] = set()+ for i, raw in enumerate(raw_rules):+ rule = _parse_rule(raw, f"rules[{i}]", problems)+ if rule is None:+ continue+ if rule.name in seen:+ problems.append(f"rules[{i}]: duplicate rule name {rule.name!r}")+ seen.add(rule.name)+ rules.append(rule)+ if problems:+ raise PolicyError(source, problems)+ return Policy(tuple(rules), source)+++def _parse_rule(raw: Any, at: str, problems: list[str]) -> Rule | None:+ if not isinstance(raw, dict):+ problems.append(f"{at}: a rule must be a mapping")+ return None+ start = len(problems)+ name = raw.get("name")+ if not isinstance(name, str) or not _NAME_RE.match(name):+ problems.append(+ f"{at}: 'name' is required: 1 to 63 of a-z, 0-9, _ and -, starting with a letter or digit"+ )+ name = None+ else:+ at = f"{at} ({name})"+ for key in sorted(set(raw) - set(_RULE_KEYS)):+ problems.append(f"{at}: unknown key {key!r}")+ gate = raw.get("gate")+ action = raw.get("action", "fail" if gate is not None else None)+ if action not in ACTIONS:+ problems.append(f"{at}: 'action' must be one of {', '.join(ACTIONS)}")+ for key in ("description", "message"):+ if key in raw and not isinstance(raw[key], str):+ problems.append(f"{at}: {key!r} must be a string")++ if gate is not None:+ _check_gate(raw, gate, at, problems)+ if len(problems) > start:+ return None+ return Rule(+ name=str(name),+ action=action,+ description=raw.get("description"),+ message=raw.get("message"),+ gate=gate,+ gate_args=dict(raw.get("with") or {}),+ )++ if "with" in raw:+ problems.append(f"{at}: 'with' only goes with 'gate'")+ match = _parse_selector(raw.get("match"), f"{at}.match", problems)+ exclude = _parse_selector(raw.get("exclude"), f"{at}.exclude", problems)+ when = _parse_when(raw.get("when"), f"{at}.when", problems)+ if len(problems) > start:+ return None+ return Rule(+ name=str(name),+ action=action,+ description=raw.get("description"),+ message=raw.get("message"),+ match=match,+ exclude=exclude,+ when=when,+ )+++def _check_gate(raw: dict, gate: Any, at: str, problems: list[str]) -> None:+ if gate not in GATES:+ problems.append(f"{at}: 'gate' must be one of {', '.join(GATES)}")+ for key in ("match", "exclude", "when"):+ if key in raw:+ problems.append(f"{at}: {key!r} does not go with 'gate'; a gate judges the whole change")+ args = raw.get("with")+ if args is None:+ return+ if not isinstance(args, dict):+ problems.append(f"{at}.with: must be a mapping of the gate's options")+ return+ for key, value in args.items():+ ok = isinstance(value, str | int | float | bool) or (+ isinstance(value, list) and all(isinstance(v, str | int | float) for v in value)+ )+ if not isinstance(key, str) or not ok:+ problems.append(f"{at}.with.{key}: must be a string, number, boolean or list of them")+++def _parse_selector(raw: Any, at: str, problems: list[str]) -> Selector | None:+ if raw is None:+ return None+ if not isinstance(raw, dict) or set(raw) != {"components"}:+ problems.append(f"{at}: must be a mapping with one key, 'components'")+ return None+ comps = raw["components"]+ if not isinstance(comps, dict) or not comps:+ problems.append(f"{at}.components: must name at least one of {', '.join(_SELECTOR_KEYS)}")+ return None+ out: dict[str, tuple[str, ...]] = {}+ for key, value in comps.items():+ if key not in _SELECTOR_KEYS:+ problems.append(f"{at}.components: unknown key {key!r} (expected {', '.join(_SELECTOR_KEYS)})")+ continue+ values = [value] if isinstance(value, str) else value+ if not isinstance(values, list) or not values or not all(isinstance(v, str) for v in values):+ problems.append(f"{at}.components.{key}: must be a string or a non-empty list of strings")+ continue+ out[key] = tuple(v.lower() for v in values)+ return Selector(**out)+++def _parse_when(raw: Any, at: str, problems: list[str]) -> dict[str, Any]:+ if not isinstance(raw, dict) or not raw:+ problems.append(f"{at}: a rule needs at least one condition ({', '.join(CONDITIONS)}) or a 'gate'")+ return {}+ out: dict[str, Any] = {}+ for key, value in raw.items():+ if key not in CONDITIONS:+ hint = " (risk is not calibrated, so there is no risk condition)" if "risk" in str(key) else ""+ problems.append(f"{at}: unknown condition {key!r}{hint}")+ elif key == "attribution":+ states = [value] if isinstance(value, str) else value+ if not isinstance(states, list) or not states or any(s not in ATTRIBUTION_STATES for s in states):+ problems.append(f"{at}.attribution: must be one or a list of {', '.join(ATTRIBUTION_STATES)}")+ else:+ out[key] = tuple(states)+ elif key == "agent_tier":+ tiers = [value] if isinstance(value, int) else value+ if not isinstance(tiers, list) or not tiers or any(t not in (1, 2, 3) for t in tiers):+ problems.append(f"{at}.agent_tier: must be one or a list of 1, 2, 3")+ else:+ out[key] = tuple(tiers)+ elif key == "reaching_tests":+ if value not in ("missing", "present"):+ problems.append(f"{at}.reaching_tests: must be 'missing' or 'present'")+ else:+ out[key] = value+ elif key in ("contract_break", "decision_crossed"):+ if not isinstance(value, bool):+ problems.append(f"{at}.{key}: must be true or false")+ else:+ out[key] = value+ elif key == "bus_factor_below":+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:+ problems.append(f"{at}.bus_factor_below: must be a whole number of at least 1")+ else:+ out[key] = value+ return out+++# -- evaluating ---------------------------------------------------------------+++#: ``(path, line or None, the finding's own fingerprint or None)``.+Location = tuple[str, int | None, str | None]+++@dataclass(frozen=True)+class GateRun:+ """What a wrapped gate command returned: its exit code and a one-line summary."""++ exit_code: int+ summary: str+ #: One per finding the gate failed on.+ locations: tuple[Location, ...] = ()+++@dataclass+class RuleResult:+ rule: Rule+ outcome: str+ message: str+ reasons: list[str] = field(default_factory=list)+ components: list[str] = field(default_factory=list)+ owners: list[str] = field(default_factory=list)+ locations: list[Location] = field(default_factory=list)+ #: Evidence kinds the rule read, with the basis each had.+ evidence: dict[str, str] = field(default_factory=dict)++ @property+ def fails(self) -> bool:+ return self.outcome == TRIGGERED and self.rule.action == "fail"++ def to_dict(self) -> dict[str, Any]:+ return {+ "rule": self.rule.name,+ "action": self.rule.action,+ "gate": self.rule.gate,+ "outcome": self.outcome,+ "message": self.message,+ "reasons": self.reasons,+ "components": self.components,+ "owners": self.owners,+ "locations": [+ {"path": p, "line": ln, **({"fingerprint": fp} if fp else {})}+ for p, ln, fp in self.locations+ ],+ "evidence": self.evidence,+ }+++def evaluate(+ policy: Policy,+ evidence: Mapping[str, Any] | None,+ gate_runs: Mapping[str, GateRun] | None = None,+) -> list[RuleResult]:+ """One result per rule, in file order. *gate_runs* is keyed by rule name."""+ items = {i.get("kind"): i for i in (evidence or {}).get("items") or () if isinstance(i, Mapping)}+ gate_runs = gate_runs or {}+ return [+ _gate_result(rule, gate_runs.get(rule.name)) if rule.gate else _rule_result(rule, items)+ for rule in policy.rules+ ]+++def _gate_result(rule: Rule, run: GateRun | None) -> RuleResult:+ if run is None or run.exit_code not in (0, 1):+ why = run.summary if run else "the gate did not run"+ return RuleResult(rule, UNKNOWN, f"The {rule.gate} gate could not be evaluated: {why}")+ if run.exit_code == 0:+ return RuleResult(rule, PASSED, f"The {rule.gate} gate passed. {run.summary}".strip())+ return RuleResult(+ rule,+ TRIGGERED,+ rule.message or f"The {rule.gate} gate failed. {run.summary}".strip(),+ locations=list(run.locations),+ )+++def _known(item: Mapping[str, Any] | None) -> bool:+ return item is not None and item.get("status") != "unknown" and item.get("basis") != "unresolved"+++def _rows(item: Mapping[str, Any] | None) -> list[Mapping[str, Any]]:+ return [r for r in (item or {}).get("details") or () if isinstance(r, Mapping)]+++def _rule_result(rule: Rule, items: Mapping[str, Mapping[str, Any]]) -> RuleResult:+ comps_item = items.get("components_touched")+ touched = _rows(comps_item) if _known(comps_item) else []+ used: dict[str, str] = {}+ if rule.match or rule.exclude:+ if not _known(comps_item):+ return RuleResult(+ rule, UNKNOWN, "Components touched are not known, so the match cannot be checked.",+ evidence={"components_touched": _basis(comps_item)},+ )+ used["components_touched"] = _basis(comps_item)+ matched = [+ c for c in touched+ if (rule.match is None or rule.match.matches(c))+ and not (rule.exclude and rule.exclude.matches(c))+ ]+ if not matched:+ return RuleResult(rule, NOT_APPLICABLE, "No touched component matches this rule.", evidence=used)+ scope: set[str] | None = {str(f) for c in matched for f in c.get("files") or ()}+ else:+ matched = touched+ scope = None # the whole change++ reasons: list[str] = []+ unknown: list[str] = []+ locations: list[Location] = []+ for cond, want in rule.when.items():+ verdict, why, where, kind = _CHECKS[cond](want, items, scope, matched)+ if kind:+ used[kind] = _basis(items.get(kind))+ if verdict is None:+ unknown.append(why)+ elif not verdict:+ return RuleResult(rule, PASSED, f"Not met: {why}.", evidence=used)+ else:+ reasons.append(why)+ locations += where+ names = [str(c.get("name")) for c in matched]+ owners = sorted({str(c["owner"]) for c in matched if c.get("owner")})+ if unknown:+ return RuleResult(+ rule, UNKNOWN, "Not evaluated: " + "; ".join(unknown) + ".",+ reasons=reasons, components=names, evidence=used,+ )+ if not locations and scope:+ locations = [(p, None, None) for p in sorted(scope)[:1]]+ return RuleResult(+ rule,+ TRIGGERED,+ rule.message or _default_message(rule, reasons, names, owners),+ reasons=reasons,+ components=names,+ owners=owners,+ locations=_dedupe(locations),+ evidence=used,+ )+++def _default_message(rule: Rule, reasons: list[str], names: list[str], owners: list[str]) -> str:+ where = f" in {', '.join(names)}" if names else ""+ need = {+ "require_owner_review": " Needs review by "+ + (", ".join(owners) if owners else "the component owner")+ + ".",+ "require_tests": " Needs a test that reaches the changed code.",+ }.get(rule.action, "")+ return f"{rule.name}{where}: {'; '.join(reasons)}.{need}"+++def _basis(item: Mapping[str, Any] | None) -> str:+ return str(item.get("basis") or "unresolved") if _known(item) else "unresolved"+++def _dedupe(locations: Iterable[Location]) -> list[Location]:+ return list(dict.fromkeys(locations))+++# Each check returns (verdict: True/False/None for unknown, reason, locations, evidence kind).+Check = tuple[bool | None, str, list[Location], str]+++def _provenance_label(item: Mapping[str, Any]) -> str | None:+ value = item.get("value")+ return value.get("label") if isinstance(value, Mapping) else value+++def _attribution(want, items, scope, matched) -> Check:+ item = items.get("provenance")+ label = _provenance_label(item) if _known(item) else None+ if label not in ATTRIBUTION_STATES:+ return None, "attribution is not known", [], "provenance"+ return label in want, f"attribution is {label}", [], "provenance"+++def _agent_tier(want, items, scope, matched) -> Check:+ item = items.get("provenance")+ if not _known(item):+ return None, "attribution is not known", [], "provenance"+ tiers = sorted({r.get("tier") for r in _rows(item) if r.get("label") == "agent" and r.get("tier")})+ hit = [t for t in tiers if t in want]+ return bool(hit), f"agent tier {', '.join(map(str, hit or tiers)) or 'none'}", [], "provenance"+++def _reaching_tests(want, items, scope, matched) -> Check:+ item = items.get("reaching_tests")+ if not _known(item):+ return None, "reaching tests are not known", [], "reaching_tests"+ rows = [r for r in _rows(item) if r.get("path") and (scope is None or r["path"] in scope)]+ # ``tests: []`` is a known absence; a missing or null list is not known.+ untested = [str(r["path"]) for r in rows if r.get("tests") == []]+ unknown = [r for r in rows if not isinstance(r.get("tests"), list)]+ if untested:+ why = f"{len(untested)} changed file(s) with no reaching test"+ return want == "missing", why, [(p, None, None) for p in untested], "reaching_tests"+ if not rows:+ return False, "no changed source file in scope", [], "reaching_tests"+ if unknown:+ return None, "reaching tests are not known for every changed file", [], "reaching_tests"+ return want == "present", "every changed file has a reaching test", [], "reaching_tests"+++def _contract_break(want, items, scope, matched) -> Check:+ item = items.get("contracts")+ if not _known(item):+ return None, "contract changes are not known", [], "contracts"+ broken = [+ str(r["path"]) for r in _rows(item)+ if r.get("breaking") and r.get("path") and (scope is None or r["path"] in scope)+ ]+ found = bool(broken)+ why = f"{len(broken)} breaking contract change(s)" if found else "no breaking contract change"+ return found == want, why, [(p, None, None) for p in broken], "contracts"+++def _decision_crossed(want, items, scope, matched) -> Check:+ item = items.get("decisions_crossed")+ if not _known(item):+ return None, "decisions crossed are not known", [], "decisions_crossed"+ hits: list[str] = []+ where: list[Location] = []+ for r in _rows(item):+ paths = [str(p) for p in r.get("paths") or ()]+ inside = paths if scope is None else [p for p in paths if p in scope]+ if inside or (not paths and scope is None):+ hits.append(str(r.get("title") or r.get("id")))+ where += [(p, None, None) for p in inside]+ found = bool(hits)+ why = f"crosses decision(s): {', '.join(hits)}" if found else "crosses no governing decision"+ return found == want, why, where, "decisions_crossed"+++def _bus_factor_below(want, items, scope, matched) -> Check:+ known = [c for c in matched if isinstance(c.get("bus_factor"), int)]+ if not matched or len(known) < len(matched):+ return None, "bus factor is not known for every component", [], "components_touched"+ low = [f"{c['name']} ({c['bus_factor']})" for c in known if c["bus_factor"] < want]+ why = f"bus factor below {want}: {', '.join(low)}" if low else f"bus factor at least {want}"+ return bool(low), why, [], "components_touched"+++_CHECKS = {+ "attribution": _attribution,+ "agent_tier": _agent_tier,+ "reaching_tests": _reaching_tests,+ "contract_break": _contract_break,+ "decision_crossed": _decision_crossed,+ "bus_factor_below": _bus_factor_below,+}+++def exit_code(results: Iterable[RuleResult]) -> int:+ """1 when a ``fail`` rule fired; else 2 when a ``fail`` gate could not run; else 0."""+ results = list(results)+ if any(r.fails for r in results):+ return 1+ if any(r.rule.gate and r.rule.action == "fail" and r.outcome == UNKNOWN for r in results):+ return 2+ return 0diff --git a/tests/unit/cli/test_check_cmd.py b/tests/unit/cli/test_check_cmd.pynew file mode 100644index 000000000..8eca9547e--- /dev/null+++ b/tests/unit/cli/test_check_cmd.py@@ -0,0 +1,228 @@+"""``repowise check``: policies.yaml over a change, and the gates without one."""++from __future__ import annotations++import json+import xml.etree.ElementTree as ET++import pytest++from repowise.cli.commands.check_cmd import check_command+from repowise.cli.commands.security_cmd import security_command+from tests.unit.analysis.test_security_gate_extras import KEY, _git, _write, init_repo+from tests.unit.cli.test_format_json_rollout import _split_runner++CATALOG = """\+apiVersion: backstage.io/v1alpha1+kind: Component+metadata:+ name: payments+ annotations:+ repowise.dev/paths: src/pay/**+ repowise.dev/criticality: critical+ repowise.dev/tags: pci+spec: {type: service, lifecycle: production, owner: group:default/payments-team}+"""++AGENT_PCI = """\+rules:+ - name: agent-pci+ match:+ components: {tags: [pci]}+ when: {attribution: agent}+ action: fail+"""+++def repo(tmp_path):+ root = init_repo(tmp_path)+ (root / ".repowise").mkdir()+ (root / "src" / "pay").mkdir(parents=True)+ return root+++def _commit(repo, name: str, text: str, message: str = "change") -> None:+ _write(repo, name, text)+ _git(repo, "add", "-A")+ _git(repo, "commit", "-qm", message)+++def _policy(repo, text: str) -> None:+ (repo / ".repowise" / "policies.yaml").write_text(text, encoding="utf-8")+++def _check(repo, *args: str):+ return _split_runner().invoke(check_command, ["main...HEAD", "--path", str(repo), *args])+++def _agent_change(repo) -> None:+ _write(repo, ".repowise/components.yaml", CATALOG)+ _commit(repo, "src/pay/charge.py", "x = 1\n", "add charge\n\nGenerated with Claude Code")+++def test_no_policy_file_has_nothing_to_evaluate(repo):+ _commit(repo, "app.py", "x = 2\n")+ table = _check(repo)+ assert table.exit_code == 0, table.output+ assert "nothing to evaluate" in table.output++ doc = json.loads(_check(repo, "--format", "json").stdout)+ assert doc["results"] == [] and doc["policy_file"] is None+ sarif = json.loads(_check(repo, "--format", "sarif").stdout)+ assert sarif["version"] == "2.1.0" and sarif["runs"][0]["results"] == []+++def test_existing_gates_are_unchanged_with_or_without_a_policy(repo):+ _commit(repo, "cfg.py", f"AWS = '{KEY}'\n")+ args = ["check", "main...HEAD", "--path", str(repo), "--format", "json"]+ before = _split_runner().invoke(security_command, args)+ _policy(repo, "rules: [{name: sec, gate: security, action: warn}]")+ after = _split_runner().invoke(security_command, args)+ assert before.exit_code == after.exit_code == 1+ assert before.stdout == after.stdout+++def test_agent_change_to_a_pci_component_fails(repo, tmp_path):+ _agent_change(repo)+ _policy(repo, AGENT_PCI)+ sarif_file, junit_file = tmp_path / "out.sarif", tmp_path / "out.xml"+ result = _check(+ repo, "--format", "json", "--sarif-file", str(sarif_file), "--junit-file", str(junit_file)+ )+ assert result.exit_code == 1, result.output+ doc = json.loads(result.stdout)+ (row,) = doc["results"]+ assert row["outcome"] == "triggered" and row["components"] == ["payments"]+ assert row["locations"] == [{"path": "src/pay/charge.py", "line": None}]+ kinds = {i["kind"]: i for i in doc["evidence"]["items"]}+ assert kinds["provenance"]["value"]["label"] == "agent"+ assert kinds["reaching_tests"]["status"] == "unknown" # no index++ sarif = json.loads(sarif_file.read_text(encoding="utf-8"))+ assert sarif["runs"][0]["results"][0]["level"] == "error"+ suite = ET.fromstring(junit_file.read_text(encoding="utf-8")).find("testsuite")+ assert suite.get("failures") == "1"+++def test_an_unattributed_change_passes_and_missing_evidence_never_fails(repo):+ _write(repo, ".repowise/components.yaml", CATALOG)+ _commit(repo, "src/pay/charge.py", "x = 1\n", "add charge")+ _policy(+ repo,+ AGENT_PCI+ + """\+ - name: untested-pci+ match: {components: {tags: [pci]}}+ when: {reaching_tests: missing}+ action: fail+""",+ )+ result = _check(repo)+ assert result.exit_code == 0, result.output+ assert "agent-pci" in result.output and "not evaluated" in result.output.lower()+++def test_security_gate_wrapped_as_a_rule(repo):+ _policy(repo, "rules: [{name: no-secrets, gate: security, with: {fail_on: high}}]")+ _commit(repo, "app.py", "x = 2\n")+ clean = _check(repo, "--format", "junit")+ assert clean.exit_code == 0, clean.output+ assert ET.fromstring(clean.stdout).find("testsuite").get("failures") == "0"++ _commit(repo, "cfg.py", f"AWS = '{KEY}'\n")+ dirty = _check(repo, "--format", "json")+ assert dirty.exit_code == 1, dirty.output+ (row,) = json.loads(dirty.stdout)["results"]+ assert row["outcome"] == "triggered" and row["locations"][0]["path"] == "cfg.py"+ assert "repowise security check --fail-on=high main...HEAD" in row["message"]+ assert row["locations"][0]["fingerprint"]+++ ("policy", "problem"),+ [+ ("rules: [{name: x, when: {risk_above: 5}, action: fail}]", "risk is not calibrated"),+ ("rules: [{name: x, gate: security, with: {fail_under: 80}}]", "has no option 'fail_under'"),+ ("rules: [{name: x, gate: security, with: {format: sarif}}]", "has no option 'format'"),+ ],+)+def test_invalid_policy_exits_two(repo, policy, problem):+ _commit(repo, "app.py", "x = 2\n")+ _policy(repo, policy)+ result = _check(repo, "--format", "json")+ assert result.exit_code == 2+ doc = json.loads(result.stdout)+ assert doc["error"] == "policy_invalid" and problem in doc["message"]+++ ("returncode", "stdout"),+ [+ (1, "Traceback (most recent call last):\n ...\nRuntimeError: boom\n"),+ (1, '{"gate": {"passed": true}}'),+ (0, '{"gate": {"passed": false}}'),+ (1, ""),+ ],+)+def test_a_gate_without_a_matching_verdict_is_not_evaluated(repo, monkeypatch, returncode, stdout):+ import subprocess++ from repowise.cli.commands import check_cmd++ real = subprocess.run++ def crashed(argv, **kwargs):+ if "repowise.cli.main" not in argv:+ return real(argv, **kwargs)+ return subprocess.CompletedProcess(argv, returncode, stdout, "RuntimeError: boom\n")++ monkeypatch.setattr(check_cmd.subprocess, "run", crashed)+ _policy(repo, "rules: [{name: sec, gate: security}]")+ _commit(repo, "app.py", "x = 2\n")+ result = _check(repo, "--format", "json")+ assert result.exit_code == 2, result.output+ (row,) = json.loads(result.stdout)["results"]+ assert row["outcome"] == "unknown"+++def test_a_gate_that_runs_too_long_is_not_evaluated(repo, monkeypatch):+ import subprocess++ from repowise.cli.commands import check_cmd++ real = subprocess.run++ def slow(argv, **kwargs):+ if "repowise.cli.main" not in argv:+ return real(argv, **kwargs)+ raise subprocess.TimeoutExpired(argv, kwargs["timeout"])++ monkeypatch.setattr(check_cmd.subprocess, "run", slow)+ _policy(repo, "rules: [{name: sec, gate: security, action: warn}]")+ _commit(repo, "app.py", "x = 2\n")+ result = _check(repo, "--format", "json")+ assert result.exit_code == 0+ (row,) = json.loads(result.stdout)["results"]+ assert row["outcome"] == "unknown" and "did not finish" in row["message"]+++def test_gate_arguments_scope_doc_drift_and_end_options_before_revspec():+ from repowise.cli.commands.check_cmd import _gate_argv+ from repowise.core.policy import parse_policy++ sec, drift, pinned = parse_policy(+ """\+rules:+ - {name: s, gate: security, with: {baseline: -odd.json}}+ - {name: d, gate: doc_drift}+ - {name: p, gate: doc_drift, with: {since: auto}}+"""+ ).rules+ assert _gate_argv(sec, "-x...HEAD") == [+ "security", "check", "--baseline=-odd.json", "--format", "json", "--", "-x...HEAD"+ ]+ assert _gate_argv(drift, "main...HEAD") == [+ "doc-drift", "--check", "--since=main...HEAD", "--format", "json"+ ]+ assert "--since=auto" in _gate_argv(pinned, "main...HEAD")diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex 2271d626b..18dcb7c63 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -33,7 +33,7 @@ from repowise.core.registry import CLIRegistry, LazyCommand#: command is meant to require editing it._EXPECTED_NAMES = frozenset({- "agents", "ask", "attribution", "augment", "changes", "components", "config", "context", "corrections",+ "agents", "ask", "attribution", "augment", "changes", "check", "components", "config", "context", "corrections","costs", "coverage","dead-code", "decision", "delete", "distill", "doc-drift", "doctor","expand",diff --git a/tests/unit/persistence/test_policy_interim_evidence.py b/tests/unit/persistence/test_policy_interim_evidence.pynew file mode 100644index 000000000..597632821--- /dev/null+++ b/tests/unit/persistence/test_policy_interim_evidence.py@@ -0,0 +1,139 @@+"""The interim ``repowise check`` evidence, read from an index and from git."""++from __future__ import annotations++from sqlalchemy import select++from repowise.core.analysis.changed_lines import change_set+from repowise.core.persistence.crud import bulk_upsert_decisions+from repowise.core.persistence.crud.authority import accept_decision+from repowise.core.persistence.models import DecisionRecord, GitMetadata, GraphNode+from repowise.core.policy import evaluate, parse_policy+from repowise.core.policy.interim_evidence import gather_evidence+from tests.unit.analysis.test_security_gate_extras import _git, _write, init_repo+from tests.unit.persistence.helpers import insert_repo+from tests.unit.persistence.test_decision_authority import _dict++CATALOG = """\+apiVersion: backstage.io/v1alpha1+kind: Component+metadata:+ name: payments+ annotations:+ repowise.dev/paths: src/pay/**+ repowise.dev/tags: pci+spec: {type: service, lifecycle: production, owner: group:default/payments-team}+"""+FILES = [f"src/pay/m{i}.py" for i in range(6)]+++def _repo(tmp_path):+ root = init_repo(tmp_path)+ (root / ".repowise").mkdir()+ (root / "src" / "pay").mkdir(parents=True)+ _write(root, ".repowise/components.yaml", CATALOG)+ _write(root, "src/pay/m0.py", "x = 1\n")+ _git(root, "add", "-A")+ _git(root, "commit", "-qm", "pay\n\nCo-authored-by: Claude <[email protected]>")+ return root+++async def _seed(session, repo_id: str) -> None:+ session.add_all(GraphNode(repository_id=repo_id, node_id=f, node_type="file") for f in FILES)+ session.add_all(+ GitMetadata(+ repository_id=repo_id,+ file_path=f,+ primary_owner_name="Ada",+ primary_owner_email="[email protected]",+ )+ for f in FILES+ )+ await bulk_upsert_decisions(+ session, repo_id, [_dict("Use idempotent charges", affected_files=["src/pay/m0.py"])]+ )+ record = (+ await session.execute(select(DecisionRecord).where(DecisionRecord.repository_id == repo_id))+ ).scalar_one()+ await accept_decision(session, record, accepter="tester")+ await session.flush()+++async def test_index_adds_bus_factor_tests_and_decisions(async_session, tmp_path):+ root = _repo(tmp_path)+ repo = await insert_repo(async_session, local_path=str(root))+ await _seed(async_session, repo.id)++ change = change_set(str(root), "main...HEAD")+ evidence = await gather_evidence(root, change, session=async_session, repo_id=repo.id)+ items = {i["kind"]: i for i in evidence["items"]}++ (payments,) = items["components_touched"]["details"]+ assert payments["name"] == "payments" and payments["tags"] == ["pci"]+ assert payments["owner"] == "payments-team" and payments["bus_factor"] == 1+ assert payments["files"] == ["src/pay/m0.py"]+ assert items["provenance"]["value"]["label"] == "agent"+ assert items["provenance"]["details"][0]["tier"] == 3+ (decision,) = items["decisions_crossed"]["details"]+ assert decision["title"] == "Use idempotent charges" and decision["paths"] == ["src/pay/m0.py"]+ # An empty coverage map and no test found: not a measured absence.+ assert items["reaching_tests"]["status"] == "unknown"+ assert items["contracts"]["status"] == "unknown"++ policy = parse_policy(+ """\+rules:+ - name: pci-agent+ match: {components: {tags: [pci]}}+ when: {attribution: agent, agent_tier: [3], decision_crossed: true, bus_factor_below: 2}+ action: require_owner_review+ - name: pci-untested+ match: {components: {tags: [pci]}}+ when: {reaching_tests: missing}+ action: fail+"""+ )+ fired, untested = evaluate(policy, evidence)+ assert fired.outcome == "triggered", fired.message+ assert fired.owners == ["payments-team"]+ assert untested.outcome == "unknown"+++async def test_a_measured_map_makes_an_untested_file_a_known_absence(+ async_session, tmp_path, monkeypatch+):+ from repowise.core.analysis import test_collection++ async def measured(*args, **kwargs):+ out = test_collection.empty_result(1)+ out.update(map_empty=False, map_current=True, unknown=["src/pay/m0.py"])+ return out++ monkeypatch.setattr(test_collection, "collect", measured)+ root = _repo(tmp_path)+ repo = await insert_repo(async_session, local_path=str(root))+ change = change_set(str(root), "main...HEAD")+ evidence = await gather_evidence(root, change, session=async_session, repo_id=repo.id)+ (item,) = [i for i in evidence["items"] if i["kind"] == "reaching_tests"]+ assert item["status"] == "ok" and item["basis"] == "measured"+ assert item["details"] == [{"path": "src/pay/m0.py", "tests": [], "basis": "measured"}]+++async def test_git_alone_reads_declared_components_and_provenance(tmp_path):+ root = _repo(tmp_path)+ evidence = await gather_evidence(root, change_set(str(root), "main...HEAD"))+ items = {i["kind"]: i for i in evidence["items"]}+ assert items["components_touched"]["basis"] == "declared"+ assert items["components_touched"]["details"][0]["bus_factor"] is None+ assert items["provenance"]["status"] == "ok"+ for kind in ("reaching_tests", "decisions_crossed", "contracts"):+ assert items[kind]["status"] == "unknown" and items[kind]["basis"] == "unresolved"+ assert evidence["schema_version"] == 1 and evidence["revspec"] == "main...HEAD"+++async def test_attribution_off_leaves_provenance_unknown(tmp_path):+ root = _repo(tmp_path)+ _write(root, ".repowise/config.yaml", "attribution:\n enabled: false\n")+ evidence = await gather_evidence(root, change_set(str(root), "main...HEAD"))+ (prov,) = [i for i in evidence["items"] if i["kind"] == "provenance"]+ assert prov["status"] == "unknown" and prov["value"] is Nonediff --git a/tests/unit/test_policy_report.py b/tests/unit/test_policy_report.pynew file mode 100644index 000000000..738d8d57d--- /dev/null+++ b/tests/unit/test_policy_report.py@@ -0,0 +1,130 @@+"""``repowise.core.policy.report``: SARIF 2.1.0 and JUnit XML for policy results."""++from __future__ import annotations++import xml.etree.ElementTree as ET++from repowise.core.policy import GateRun, evaluate, parse_policy+from repowise.core.policy.report import render_junit, render_sarif++POLICY = parse_policy(+ """\+rules:+ - name: decisions+ description: Changes that cross a governing decision fail.+ when: {decision_crossed: true}+ action: fail+ - name: agent-review+ when: {attribution: agent}+ action: require_owner_review+ - name: tests+ when: {reaching_tests: missing}+ action: require_tests+ - name: sec+ gate: security+"""+)+EVIDENCE = {+ "schema_version": 1,+ "change_id": "abc",+ "revspec": "main...HEAD",+ "generated_at": "now",+ "items": [+ {+ "kind": "decisions_crossed",+ "status": "ok",+ "basis": "declared",+ "details": [{"id": "d1", "title": "T", "paths": ["src/a.py"]}],+ },+ {"kind": "provenance", "status": "ok", "basis": "declared", "value": "agent", "details": []},+ {"kind": "reaching_tests", "status": "unknown", "basis": "unresolved", "details": []},+ ],+}+++def _results():+ return evaluate(POLICY, EVIDENCE, {"sec": GateRun(0, "")})+++def test_sarif_has_the_fields_code_scanning_and_reviewdog_read():+ log = render_sarif(POLICY, _results(), tool_version="1.2.3", revspec="main...HEAD")+ assert log["version"] == "2.1.0" and log["$schema"].endswith("sarif-2.1.0.json")+ (run,) = log["runs"]+ driver = run["tool"]["driver"]+ assert driver["name"] == "repowise-check" and driver["version"] == "1.2.3"+ assert [r["id"] for r in driver["rules"]] == [+ "policy/decisions",+ "policy/agent-review",+ "policy/tests",+ "policy/sec",+ ]+ for rule in driver["rules"]:+ assert rule["shortDescription"]["text"] and rule["fullDescription"]["text"]+ decision, review = run["results"]+ assert decision["ruleId"] == "policy/decisions" and decision["level"] == "error"+ assert decision["ruleIndex"] == 0+ loc = decision["locations"][0]["physicalLocation"]+ assert loc["artifactLocation"] == {"uri": "src/a.py", "uriBaseId": "%SRCROOT%"}+ assert decision["message"]["text"]+ assert decision["partialFingerprints"]["repowisePolicy/v1"]+ assert decision["properties"]["action"] == "fail"+ assert decision["properties"]["evidence"] == {"decisions_crossed": "declared"}+ # A change-level result with no file of its own sits on the policy file.+ assert review["level"] == "warning"+ assert review["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] == (+ ".repowise/policies.yaml"+ )+ # Not evaluated is reported on the run, never as a result.+ assert run["properties"]["notEvaluated"] == ["tests"]+++def test_fingerprints_are_stable_across_runs():+ one = render_sarif(POLICY, _results(), tool_version="1", revspec="a...b")+ two = render_sarif(POLICY, _results(), tool_version="2", revspec="c...d")+ prints = [[r["partialFingerprints"] for r in log["runs"][0]["results"]] for log in (one, two)]+ assert prints[0] == prints[1]+++def test_junit_marks_fail_skipped_and_passing_cases():+ root = ET.fromstring(render_junit(_results(), revspec="main...HEAD"))+ (suite,) = root.findall("testsuite")+ assert suite.get("tests") == "4" and suite.get("failures") == "1" and suite.get("skipped") == "1"+ cases = {c.get("name"): c for c in suite.findall("testcase")}+ assert cases["decisions"].find("failure").get("type") == "fail"+ assert cases["decisions"].find("failure").text == "src/a.py"+ assert cases["tests"].find("skipped") is not None+ assert "require_owner_review" in cases["agent-review"].find("system-out").text+ assert list(cases["sec"]) == []+++def test_empty_results_render_valid_documents():+ empty = parse_policy("rules: [{name: s, gate: security}]")+ log = render_sarif(empty, [], tool_version="1", revspec="")+ assert log["runs"][0]["results"] == []+ assert ET.fromstring(render_junit([], revspec="")).find("testsuite").get("tests") == "0"+++def test_findings_in_one_file_keep_their_own_fingerprints():+ policy = parse_policy("rules: [{name: sec, gate: security}]")+ run = GateRun(1, "x", (("a.py", 3, "f1"), ("a.py", 9, "f2"), ("a.py", 12, None)))+ log = render_sarif(policy, evaluate(policy, None, {"sec": run}), tool_version="1", revspec="")+ prints = {r["partialFingerprints"]["repowisePolicy/v1"] for r in log["runs"][0]["results"]}+ assert len(prints) == 3+++def test_a_policy_outside_the_repository_locates_on_a_repo_file():+ policy = parse_policy(+ "rules: [{name: d, when: {decision_crossed: true}, action: warn}]",+ "C:/elsewhere/policies.yaml",+ )+ evidence = {+ "items": [+ {"kind": "decisions_crossed", "status": "ok", "basis": "declared",+ "details": [{"id": "d1", "title": "T"}]},+ ]+ }+ log = render_sarif(+ policy, evaluate(policy, evidence), tool_version="1", revspec="", fallback_path="src/a.py"+ )+ (res,) = log["runs"][0]["results"]+ assert res["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] == "src/a.py"diff --git a/tests/unit/test_policy_rules.py b/tests/unit/test_policy_rules.pynew file mode 100644index 000000000..1cea751d3--- /dev/null+++ b/tests/unit/test_policy_rules.py@@ -0,0 +1,269 @@+"""``repowise.core.policy.rules``: reading policies.yaml and evaluating it over evidence."""++from __future__ import annotations++import pytest++from repowise.core.policy import (+ GateRun,+ PolicyError,+ evaluate,+ exit_code,+ load_policy,+ parse_policy,+)++PCI_RULE = """\+rules:+ - name: agent-pci-needs-owner+ match:+ components: {tags: [pci]}+ when:+ attribution: agent+ reaching_tests: missing+ action: require_owner_review+"""+++def _item(kind, details, value=None, status="ok", basis="measured"):+ return {+ "kind": kind,+ "label": kind,+ "status": status,+ "basis": basis,+ "value": value,+ "details": details,+ "source": "test",+ }+++def _evidence(*items):+ return {+ "schema_version": 1,+ "change_id": "abc",+ "revspec": "main...HEAD",+ "generated_at": "2026-10-14T00:00:00+00:00",+ "items": list(items),+ }+++PAYMENTS = {+ "name": "payments",+ "criticality": "critical",+ "tags": ["pci"],+ "owner": "payments-team",+ "files": ["src/pay/charge.py", "src/pay/refund.py"],+ "bus_factor": 1,+}+DOCS = {"name": "docs", "criticality": "low", "tags": [], "owner": None, "files": ["docs/a.md"]}+++def _components(*rows):+ return _item("components_touched", list(rows), value=len(rows), basis="declared")+++def _provenance(label, tiers=()):+ rows = [{"sha": f"s{i}", "label": "agent", "tier": t} for i, t in enumerate(tiers)]+ return _item("provenance", rows, value={"label": label}, basis="declared")+++def _tests(**by_path):+ return _item("reaching_tests", [{"path": p, "tests": t} for p, t in by_path.items()])+++# -- parsing ------------------------------------------------------------------+++def test_parses_a_condition_rule_and_a_gate_rule():+ policy = parse_policy(+ PCI_RULE+ + """\+ - name: no-new-secrets+ gate: security+ with: {fail_on: med}+"""+ )+ rule, gate = policy.rules+ assert rule.match.tags == ("pci",) and rule.when["attribution"] == ("agent",)+ assert gate.gate == "security" and gate.action == "fail" and gate.gate_args == {"fail_on": "med"}+++ ("text", "problem"),+ [+ ("rules: []", "'rules' must be a non-empty list"),+ ("version: 2\nrules: [{name: a, when: {decision_crossed: true}, action: warn}]", "version 2"),+ ("rules: [{name: A!, when: {decision_crossed: true}, action: warn}]", "'name' is required"),+ ("rules: [{name: a, when: {decision_crossed: true}, action: block}]", "'action' must be one of"),+ ("rules: [{name: a, when: {risk_above: 7}, action: fail}]", "risk is not calibrated"),+ ("rules: [{name: a, action: fail}]", "needs at least one condition"),+ ("rules: [{name: a, when: {attribution: robot}, action: fail}]", "attribution: must be"),+ ("rules: [{name: a, when: {reaching_tests: none}, action: fail}]", "'missing' or 'present'"),+ ("rules: [{name: a, when: {bus_factor_below: 0}, action: fail}]", "at least 1"),+ ("rules: [{name: a, gate: lint}]", "'gate' must be one of"),+ ("rules: [{name: a, gate: security, when: {decision_crossed: true}}]", "does not go with 'gate'"),+ ("rules: [{name: a, when: {decision_crossed: true}, action: warn, with: {x: 1}}]", "only goes with"),+ (+ "rules: [{name: a, match: {components: {team: x}}, when: {decision_crossed: true}, action: warn}]",+ "unknown key 'team'",+ ),+ ("rules: [{name: a, gate: security}, {name: a, gate: coverage}]", "duplicate rule name 'a'"),+ ("rules: [{name: a, gate: security, colour: red}]", "unknown key 'colour'"),+ ("rules: [", "invalid YAML"),+ ],+)+def test_invalid_policies_name_the_problem(text, problem):+ with pytest.raises(PolicyError) as err:+ parse_policy(text)+ assert any(problem in p for p in err.value.problems), err.value.problems+++def test_every_problem_is_listed_at_once():+ with pytest.raises(PolicyError) as err:+ parse_policy("rules: [{name: a, action: block}, {name: b, gate: lint}]")+ assert len(err.value.problems) == 3+++def test_load_policy_absent_is_none_and_named_missing_file_is_an_error(tmp_path):+ assert load_policy(tmp_path) is None+ with pytest.raises(PolicyError):+ load_policy(tmp_path, "custom.yaml")+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / "policies.yaml").write_text(PCI_RULE, encoding="utf-8")+ assert load_policy(tmp_path).source == ".repowise/policies.yaml"+++# -- evaluating ---------------------------------------------------------------+++def test_agent_change_to_untested_pci_component_requires_owner_review():+ policy = parse_policy(PCI_RULE)+ evidence = _evidence(+ _components(PAYMENTS, DOCS),+ _provenance("agent", tiers=(2,)),+ _tests(**{"src/pay/charge.py": [], "src/pay/refund.py": ["tests/test_refund.py"], "x.py": []}),+ )+ (result,) = evaluate(policy, evidence)+ assert result.outcome == "triggered"+ assert result.components == ["payments"] and result.owners == ["payments-team"]+ # Only the untested file inside the matched component is located.+ assert result.locations == [("src/pay/charge.py", None, None)]+ assert "payments-team" in result.message+ assert result.evidence == {+ "components_touched": "declared",+ "provenance": "declared",+ "reaching_tests": "measured",+ }+ assert not result.fails and exit_code([result]) == 0+++def test_human_or_tested_changes_pass():+ policy = parse_policy(PCI_RULE)+ human = evaluate(policy, _evidence(_components(PAYMENTS), _provenance("human_attested")))+ assert human[0].outcome == "passed"+ tested = _tests(**{"src/pay/charge.py": ["t1"], "src/pay/refund.py": ["t2"]})+ covered = evaluate(policy, _evidence(_components(PAYMENTS), _provenance("agent"), tested))+ assert covered[0].outcome == "passed"+++def test_no_matching_component_is_not_applicable():+ (result,) = evaluate(parse_policy(PCI_RULE), _evidence(_components(DOCS), _provenance("agent")))+ assert result.outcome == "not_applicable"+++def test_exclude_removes_a_matched_component():+ policy = parse_policy(+ PCI_RULE.replace(" when:", " exclude:\n components: {names: [payments]}\n when:")+ )+ (result,) = evaluate(policy, _evidence(_components(PAYMENTS), _provenance("agent")))+ assert result.outcome == "not_applicable"+++def test_unknown_evidence_never_fires():+ policy = parse_policy(PCI_RULE)+ no_tests = _evidence(+ _components(PAYMENTS),+ _provenance("agent"),+ _item("reaching_tests", [], status="unknown", basis="unresolved"),+ )+ (result,) = evaluate(policy, no_tests)+ assert result.outcome == "unknown" and "reaching tests are not known" in result.message+ (missing,) = evaluate(policy, _evidence(_components(PAYMENTS)))+ assert missing.outcome == "unknown"+ (no_components,) = evaluate(policy, _evidence())+ assert no_components.outcome == "unknown"+++def test_a_false_condition_wins_over_an_unknown_one():+ policy = parse_policy(PCI_RULE)+ (result,) = evaluate(policy, _evidence(_components(PAYMENTS), _provenance("human_attested")))+ assert result.outcome == "passed"+++def test_whole_change_conditions_and_fail_exit_code():+ policy = parse_policy(+ """\+rules:+ - name: decisions+ when: {decision_crossed: true}+ action: fail+ - name: contracts+ when: {contract_break: true}+ action: warn+ - name: low-bus-factor+ match: {components: {criticality: [critical]}}+ when: {bus_factor_below: 2, agent_tier: [1]}+ action: require_tests+"""+ )+ evidence = _evidence(+ _components(PAYMENTS),+ _provenance("agent", tiers=(1, 3)),+ _item("decisions_crossed", [{"id": "d1", "title": "Use Stripe", "paths": ["src/pay/charge.py"]}]),+ _item("contracts", [{"path": "src/pay/charge.py", "breaking": False}]),+ )+ decisions, contracts, bus = evaluate(policy, evidence)+ assert decisions.outcome == "triggered" and decisions.fails+ assert "Use Stripe" in decisions.message+ assert decisions.locations == [("src/pay/charge.py", None, None)]+ assert contracts.outcome == "passed"+ assert bus.outcome == "triggered" and "payments (1)" in bus.message+ assert exit_code([decisions, contracts, bus]) == 1+++def test_bus_factor_unknown_for_a_component_is_unknown():+ policy = parse_policy("rules: [{name: b, when: {bus_factor_below: 2}, action: warn}]")+ (result,) = evaluate(policy, _evidence(_components(PAYMENTS, DOCS)))+ assert result.outcome == "unknown"+++def test_gate_runs_map_to_outcomes_and_exit_codes():+ policy = parse_policy(+ "rules: [{name: sec, gate: security}, {name: cov, gate: coverage, action: warn}]"+ )+ failed = evaluate(policy, None, {"sec": GateRun(1, "x", (("a.py", 3, "fp1"),)), "cov": GateRun(1, "y")})+ assert [r.outcome for r in failed] == ["triggered", "triggered"]+ assert failed[0].locations == [("a.py", 3, "fp1")] and exit_code(failed) == 1++ broken = evaluate(policy, None, {"sec": GateRun(2, "no report"), "cov": GateRun(0, "")})+ assert [r.outcome for r in broken] == ["unknown", "passed"] and exit_code(broken) == 2++ warn_only = evaluate(policy, None, {"sec": GateRun(0, ""), "cov": GateRun(2, "no report")})+ assert exit_code(warn_only) == 0+++def test_a_file_nothing_knows_a_test_for_is_not_missing():+ policy = parse_policy(PCI_RULE)+ unknown = _tests(**{"src/pay/charge.py": None, "src/pay/refund.py": ["t2"]})+ (result,) = evaluate(policy, _evidence(_components(PAYMENTS), _provenance("agent"), unknown))+ assert result.outcome == "unknown"+ # A measured absence elsewhere in scope still fires.+ mixed = _tests(**{"src/pay/charge.py": None, "src/pay/refund.py": []})+ (fired,) = evaluate(policy, _evidence(_components(PAYMENTS), _provenance("agent"), mixed))+ assert fired.outcome == "triggered" and fired.locations == [("src/pay/refund.py", None, None)]+++def test_no_changed_source_file_in_scope_is_not_missing():+ policy = parse_policy("rules: [{name: t, when: {reaching_tests: missing}, action: fail}]")+ (result,) = evaluate(policy, _evidence(_tests()))+ assert result.outcome == "passed"