from __future__ import annotations from dataclasses import dataclass import json from typing import Any VALID_REASON = "valid" _TOP_LEVEL_KEYS = {"incident_id", "analysis", "patch", "human_required", "reason"} _PATCH_KEYS = {"path", "original", "replacement", "rationale"} _STRING_FIELDS = ("incident_id", "analysis", "reason") _NONEMPTY_PATCH_FIELDS = ("path", "original", "replacement") @dataclass(frozen=True) class ProposedPatch: """Represent one minimal source patch proposed by Hermes. Inputs: a validated `patch` object from the frozen response schema. Outputs: the repository-relative path, the exact snippet expected in the current file, its replacement, and the model's rationale. """ path: str original: str replacement: str rationale: str @dataclass(frozen=True) class PatchOutcome: """Represent the result of parsing a Hermes patch response. Inputs: raw Hermes output run through `parse_patch_response`. Outputs: validity, the proposed patch when valid, and a specific reject reason when invalid. """ valid: bool patch: ProposedPatch | None reject_reason: str | None def parse_patch_response(raw_output: str, expected_incident_id: str) -> PatchOutcome: """Extract, parse, and validate a Hermes patch response payload. Inputs: raw model output (JSON, optionally fenced or wrapped in prose) and the incident id the response must reference. Outputs: a PatchOutcome; any schema violation, incident mismatch, missing patch, or human_required escalation yields valid=False with a specific reject_reason. Never raises. """ candidate = _extract_json_object(str(raw_output or "")) if candidate is None: return _rejected("no_json_object_found") try: payload = json.loads(candidate) except json.JSONDecodeError as exc: return _rejected(f"invalid_json: {exc}") error = _validate_payload(payload, expected_incident_id) if error: return _rejected(error) patch = payload["patch"] return PatchOutcome( valid=True, patch=ProposedPatch( path=patch["path"], original=patch["original"], replacement=patch["replacement"], rationale=patch["rationale"], ), reject_reason=None, ) def parse_analysis(raw_output: str) -> str: """Return the analysis string from a patch response, or "" when absent. Inputs: the same raw Hermes output given to `parse_patch_response`. Outputs: the top-level analysis string when one can be extracted; used only for human-facing pull-request context. Never raises. """ candidate = _extract_json_object(str(raw_output or "")) if candidate is None: return "" try: payload = json.loads(candidate) except json.JSONDecodeError: return "" analysis = payload.get("analysis") if isinstance(payload, dict) else None return analysis if isinstance(analysis, str) else "" def validate_patch(patch: ProposedPatch, cfg: dict, file_contents: str) -> tuple[bool, str]: """Apply every patch gate and name the first failing gate. Inputs: the proposed patch, cfg with allowed_path_prefixes, allowed_suffixes, max_patch_bytes, and max_changed_lines, plus the current contents of the candidate file. Outputs: (ok, reason); reason is "valid" only when every gate passes, otherwise it names the first failing gate. """ prefixes = [str(item) for item in (cfg.get("allowed_path_prefixes") or [])] suffixes = [str(item) for item in (cfg.get("allowed_suffixes") or [])] max_bytes = _int_value(cfg.get("max_patch_bytes")) max_lines = _int_value(cfg.get("max_changed_lines")) occurrences = file_contents.count(patch.original) changed_lines = max(patch.original.count("\n"), patch.replacement.count("\n")) + 1 gates: list[tuple[bool, str]] = [ (_path_is_safe(patch.path), "path_unsafe"), (any(patch.path.startswith(prefix) for prefix in prefixes), "path_prefix_not_allowed"), (any(patch.path.endswith(suffix) for suffix in suffixes), "path_suffix_not_allowed"), (len(patch.original) + len(patch.replacement) <= max_bytes, "patch_too_large"), (changed_lines <= max_lines, "too_many_changed_lines"), (occurrences != 0, "original_missing"), (occurrences <= 1, "original_ambiguous"), (patch.replacement != patch.original, "replacement_identical"), ] for passed, reason in gates: if not passed: return False, reason return True, VALID_REASON def apply_patch(file_contents: str, patch: ProposedPatch) -> str: """Replace the patch's original snippet with its replacement exactly once. Inputs: the current file contents and a validated ProposedPatch. Outputs: the patched contents. Raises ValueError unless the original snippet appears exactly once. """ occurrences = file_contents.count(patch.original) if occurrences != 1: raise ValueError(f"original snippet must appear exactly once, found {occurrences}") return file_contents.replace(patch.original, patch.replacement) def _rejected(reason: str) -> PatchOutcome: """Build the invalid PatchOutcome for one reject reason.""" return PatchOutcome(valid=False, patch=None, reject_reason=reason) def _extract_json_object(raw: str) -> str | None: """Return the first balanced top-level JSON object in raw text.""" depth = 0 start = -1 in_string = False escaped = False for index, char in enumerate(raw): if in_string: if escaped: escaped = False elif char == "\\": escaped = True elif char == '"': in_string = False continue if char == '"' and depth > 0: in_string = True elif char == "{": if depth == 0: start = index depth += 1 elif char == "}" and depth > 0: depth -= 1 if depth == 0: return raw[start : index + 1] return None def _validate_payload(payload: dict[str, Any], expected_incident_id: str) -> str | None: """Validate the frozen patch-response schema, returning the first error.""" shape_error = ( _validate_keys(payload) or _validate_scalar_fields(payload) or _validate_patch_field(payload["patch"]) ) if shape_error: return shape_error if payload["incident_id"] != expected_incident_id: return f"incident_id_mismatch: got {payload['incident_id']!r} expected {expected_incident_id!r}" if payload["human_required"]: return "human_required" if payload["patch"] is None: return "patch_missing" return None def _validate_keys(payload: dict[str, Any]) -> str | None: """Require exactly the frozen top-level keys.""" keys = set(payload) missing = sorted(_TOP_LEVEL_KEYS - keys) if missing: return "missing_keys: " + ", ".join(missing) extra = sorted(keys - _TOP_LEVEL_KEYS) if extra: return "unexpected_keys: " + ", ".join(extra) return None def _validate_scalar_fields(payload: dict[str, Any]) -> str | None: """Type-check the scalar top-level fields of the response.""" for key in _STRING_FIELDS: if not isinstance(payload[key], str): return f"field_type_invalid: {key} must be a string" if not isinstance(payload["human_required"], bool): return "field_type_invalid: human_required must be a boolean" return None def _validate_patch_field(patch: Any) -> str | None: """Validate the patch object shape, tolerating an explicit null.""" if patch is None: return None if not isinstance(patch, dict): return "patch_invalid: must be an object or null" if set(patch) != _PATCH_KEYS: return "patch_invalid: must have exactly path, original, replacement, rationale" if not all(isinstance(patch[key], str) for key in _PATCH_KEYS): return "patch_invalid: fields must be strings" for key in _NONEMPTY_PATCH_FIELDS: if not patch[key]: return f"patch_field_empty: {key}" return None def _path_is_safe(path: str) -> bool: """Reject traversal, absolute, backslash, and NUL-bearing paths.""" if not path or "\x00" in path or "\\" in path: return False if path.startswith("/"): return False return ".." not in path def _int_value(value: Any) -> int: """Coerce a value to int, defaulting to zero.""" try: return int(value) except (TypeError, ValueError): return 0