Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 36 additions & 19 deletions loopx/canary/maintainability_ratchet.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
from collections import Counter
from importlib.util import resolve_name
import json
import os
from pathlib import Path
import subprocess
from typing import Any, Mapping, Sequence

from ..paths import display_path_text


MAINTAINABILITY_REPORT_SCHEMA_VERSION = "control_plane_maintainability_report_v0"
MODULE_METRIC_BASELINE_SCHEMA_VERSION = "control_plane_module_metric_baseline_v0"
Expand Down Expand Up @@ -209,18 +212,24 @@ def tracked_python_paths(repository_root: Path) -> set[Path]:
# `-z` frames each pathname on NUL, so a path carrying U+0085/U+2028/U+2029
# stays one record even in a repository that sets `core.quotePath=false`,
# where `git ls-files` emits it raw and `str.splitlines()` would tear it.
# The read stays in bytes so the record's own identity survives: a text
# read turns a CR inside a legal name into LF and an undecodable record
# into U+FFFD, and the rebuilt path would not name the tracked file, so
# that module would silently leave the ratchet.
completed = subprocess.run(
["git", "ls-files", "-z", "*.py"],
cwd=repository_root,
check=True,
text=True, encoding="utf-8", errors="replace",
stdout=subprocess.PIPE,
)
return {
repository_root / relative_path
for relative_path in completed.stdout.split("\0")
if relative_path and (repository_root / relative_path).is_file()
}
paths: set[Path] = set()
for record in completed.stdout.split(b"\0"):
if not record:
continue
path = repository_root / os.fsdecode(record)
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
if path.is_file():
paths.add(path)
return paths


def _dependency_finding(
Expand All @@ -236,12 +245,14 @@ def _dependency_finding(
if imported_name:
identity += f":{imported_name}"
return {
"id": _finding_id("dependency_debt", identity),
"id": _finding_id("dependency_debt", display_path_text(identity)),
"category": "dependency_debt",
"rule": rule,
"path": path.relative_to(repository_root).as_posix(),
"source": source,
"target": target,
# A name Git can hold but UTF-8 cannot encode would otherwise write
# bytes no JSON reader can parse; the label keeps the record locatable.
"path": display_path_text(path.relative_to(repository_root).as_posix()),
"source": display_path_text(source),
"target": display_path_text(target),
**({"imported_name": imported_name} if imported_name else {}),
}

Expand Down Expand Up @@ -459,10 +470,14 @@ def collect_oversized_decision_functions(
identity = f"{module}:{qualified_name}"
findings.append(
{
"id": _finding_id("oversized_decision_function", identity),
"id": _finding_id(
"oversized_decision_function", display_path_text(identity)
),
"category": "oversized_decision_function",
"path": path.relative_to(repository_root).as_posix(),
"module": module,
"path": display_path_text(
path.relative_to(repository_root).as_posix()
),
"module": display_path_text(module),
"symbol": qualified_name,
"line": function.lineno,
"metrics": {
Expand Down Expand Up @@ -615,10 +630,10 @@ def collect_module_metric_findings(
continue
findings.append(
{
"id": _finding_id("module_metric_budget", relative),
"id": _finding_id("module_metric_budget", display_path_text(relative)),
"category": "module_metric_budget",
"path": relative,
"module": _module_name(path, package_root),
"path": display_path_text(relative),
"module": display_path_text(_module_name(path, package_root)),
"metrics": metrics,
"metric_ceilings": ceilings,
"regressions": regressions,
Expand Down Expand Up @@ -692,9 +707,11 @@ def diff_scoped_module_ceiling_violations(
if crossed_inherited_ceiling and head_ceiling < head_lines:
violations.append(
{
"id": _finding_id("module_metric_budget", relative),
"id": _finding_id(
"module_metric_budget", display_path_text(relative)
),
"category": "module_metric_budget",
"path": relative,
"path": display_path_text(relative),
"base_lines": 0 if base_lines is None else len(base_lines.splitlines()),
"base_ceiling": base_ceiling,
"head_lines": head_lines,
Expand Down Expand Up @@ -825,7 +842,7 @@ def build_control_plane_maintainability_report(
)
return {
"schema_version": MAINTAINABILITY_REPORT_SCHEMA_VERSION,
"repository_root": str(repository_root),
"repository_root": display_path_text(repository_root),
"policy": {
"decision_statement_limit": DECISION_STATEMENT_LIMIT,
"decision_point_limit": DECISION_POINT_LIMIT,
Expand Down
28 changes: 22 additions & 6 deletions loopx/cli_commands/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
from pathlib import Path
from typing import Any

from ..contract import check_contract, render_contract_markdown
from ..contract import (
check_contract,
display_report_value,
render_contract_markdown,
)
from ..paths import display_path_text
from ..control_plane.coordination.local_authority import LocalCoordinationAuthorityUnavailable
from ..control_plane.runtime.status_projection_cache import (
load_status_projection_cache,
Expand Down Expand Up @@ -167,17 +172,24 @@ def handle_check_command(
allow_missing_registry=allow_missing_registry,
)
except Exception as exc:
scan_roots = args.scan_path or [args.scan_root]
payload = {
"ok": False,
"registry": str(registry_path),
"runtime_root": runtime_root_arg,
"scan_roots": args.scan_path or [args.scan_root],
"registry": display_path_text(registry_path),
"runtime_root": (
display_path_text(runtime_root_arg)
if runtime_root_arg is not None
else None
),
"scan_roots": [display_path_text(path) for path in scan_roots],
"summary": {"errors": 1, "warnings": 0, "checks": 0},
"errors": [str(exc)],
"warnings": [],
"checks": [],
}
print_payload(payload, args.format, render_contract_markdown)
print_payload(
display_report_value(payload), args.format, render_contract_markdown
)
return 0 if payload.get("ok") else 1


Expand Down Expand Up @@ -288,7 +300,11 @@ def handle_status_command(
if isinstance(exc, LocalCoordinationAuthorityUnavailable):
payload["error_code"] = exc.code
payload["authority_read"] = exc.payload
print_payload(payload, output_format(args), render_status_markdown)
print_payload(
display_report_value(payload),
output_format(args),
render_status_markdown,
)
return 0 if payload.get("ok") else 1


Expand Down
16 changes: 15 additions & 1 deletion loopx/cli_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,20 @@ def error(self, message: str) -> None:
raise _SelectedParseRejected(message)


def report_json_text(payload: object) -> str:
r"""Encode one machine report as strictly UTF-8 decodable JSON.

Ordinary text keeps its literal spelling. A report can still carry a code
point no UTF-8 stream can encode - the lone surrogate that spells one
undecodable path byte inside a structured identity. Those become ``\uXXXX``
escapes, which JSON reads back as the same value, so identity round trips
and the report stays parseable byte for byte.
"""

text = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
return text.encode("utf-8", "backslashreplace").decode("utf-8")


def print_payload(
payload: dict[str, object],
fmt: str,
Expand All @@ -122,7 +136,7 @@ def print_payload(
if fmt == "json":
# JSON is the machine contract; retain every value and remove only
# presentation whitespace. Human-readable output remains Markdown.
print(json.dumps(payload, ensure_ascii=False, separators=(",", ":")))
print(report_json_text(payload))
else:
print(markdown_renderer(payload))

Expand Down
Loading
Loading