Second entry in the action registry, proving it is a real extension point. No cluster mutation: the action is one Jenkins rebuild. - hermes_infra_signals: reviewable marker set across DNS/connectivity, image pull, upstream 5xx and agent-channel loss; Ariadne independently confirms a marker in the evidence before any retry, and records which marker justified it. "no space left on device" is deliberately excluded because a retry lands on the same full volume. - decision: classification -> action registry (action_classifications), falling back to the previous single-classification behavior - repair: retry_build posts to /build for unparameterized real jobs and buildWithParameters for the fixture demo job - orchestrator: retry path records requested/accepted/executed and moves the incident to awaiting_rebuild so the existing success path resolves it; one action per incident still enforced, so a retry cannot loop - events layer split out of the orchestrator to stay under the LOC cap Motivated by real failures tonight: pip DNS resolution and a Gitea 443 connect timeout, plus live incident metis/271 (SCM checkout timeout). 30 new tests; 368 pass in the hermes suite. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
339 lines
12 KiB
Python
339 lines
12 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import json
|
|
from typing import Any
|
|
|
|
|
|
ALLOWED_FACT_SOURCES = {"jenkins", "opensearch", "victoriametrics", "kubernetes", "flux", "gitea"}
|
|
RUN_ARIADNE_JOB_ACTION = "run_ariadne_job"
|
|
AUTHORIZED_REASON = "authorized"
|
|
|
|
_TOP_LEVEL_KEYS = {
|
|
"incident_id",
|
|
"classification",
|
|
"confidence",
|
|
"facts",
|
|
"inferences",
|
|
"first_failed_gate",
|
|
"requested_action",
|
|
"human_required",
|
|
"reason",
|
|
}
|
|
_STRING_FIELDS = ("incident_id", "classification", "first_failed_gate", "reason")
|
|
_FACT_KEYS = {"statement", "source", "reference"}
|
|
_ACTION_KEYS = {"type", "id"}
|
|
_CONFIDENCE_MIN = 0.0
|
|
_CONFIDENCE_MAX = 1.0
|
|
_DEFAULT_MIN_CONFIDENCE = 1.0
|
|
_DEFAULT_MAX_ACTIONS = 1
|
|
_DEFAULT_EXPECTED_CLASSIFICATION = "known_demo_fixture_failure"
|
|
_ACTION_CLASSIFICATIONS_KEY = "action_classifications"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TriageFact:
|
|
"""Represent one evidence fact cited by a Hermes triage response.
|
|
|
|
Inputs: a validated `facts[]` entry from the frozen response schema.
|
|
Outputs: the statement plus its allowlisted source system and reference.
|
|
"""
|
|
|
|
statement: str
|
|
source: str
|
|
reference: str
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RequestedAction:
|
|
"""Represent the single remediation action a triage response may request.
|
|
|
|
Inputs: a validated `requested_action` object from the response schema.
|
|
Outputs: the action type (always run_ariadne_job) and the job identifier.
|
|
"""
|
|
|
|
type: str
|
|
id: str
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TriageDecision:
|
|
"""Represent a fully validated Hermes auto-triage response.
|
|
|
|
Inputs: the parsed top-level fields of the frozen response schema.
|
|
Outputs: typed fields safe for the authorization gate chain.
|
|
"""
|
|
|
|
incident_id: str
|
|
classification: str
|
|
confidence: float
|
|
facts: list[TriageFact]
|
|
inferences: list[Any]
|
|
first_failed_gate: str
|
|
requested_action: RequestedAction | None
|
|
human_required: bool
|
|
reason: str
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DecisionOutcome:
|
|
"""Represent the result of parsing and validating a triage response.
|
|
|
|
Inputs: raw Hermes output run through `parse_triage_response`.
|
|
Outputs: validity, the decision when valid, whether a human must review,
|
|
and a specific reject reason when invalid.
|
|
"""
|
|
|
|
valid: bool
|
|
decision: TriageDecision | None
|
|
human_required: bool
|
|
reject_reason: str | None
|
|
|
|
|
|
def parse_triage_response(raw_output: str, expected_incident_id: str) -> DecisionOutcome:
|
|
"""Extract, parse, and validate a Hermes triage response payload.
|
|
|
|
Inputs: raw model output (JSON, optionally fenced or wrapped in prose)
|
|
and the incident id the response must reference.
|
|
Outputs: a DecisionOutcome; any schema violation yields valid=False with
|
|
human_required=True and 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)
|
|
decision = _decision_from_payload(payload)
|
|
return DecisionOutcome(
|
|
valid=True,
|
|
decision=decision,
|
|
human_required=decision.human_required,
|
|
reject_reason=None,
|
|
)
|
|
|
|
|
|
def authorize_action( # noqa: PLR0913 - gate signature is part of the frozen module contract
|
|
outcome: DecisionOutcome,
|
|
cfg: dict,
|
|
prior_action_count: int,
|
|
build_is_terminal_failure: bool,
|
|
job_allowlisted: bool,
|
|
evidence_has_signature: bool,
|
|
) -> tuple[bool, str]:
|
|
"""Apply every autoremediation gate and name the first failing gate.
|
|
|
|
Inputs: the parsed DecisionOutcome, gate config, and deterministic facts
|
|
established outside the model (prior action count, build terminality,
|
|
job allowlist membership, evidence signature presence). `cfg` may carry
|
|
`action_classifications`, a classification -> action id registry; when it
|
|
is present and non-empty the classification must be a registered key and
|
|
the requested action must be exactly the action mapped to it (and still
|
|
allowlisted). Without it the single `expected_classification` is enforced.
|
|
Outputs: (allowed, reason); reason is "authorized" only when every gate
|
|
passes, otherwise it names the first failing gate.
|
|
"""
|
|
|
|
if not outcome.valid or outcome.decision is None:
|
|
return False, f"response_invalid: {outcome.reject_reason or 'missing_decision'}"
|
|
decision = outcome.decision
|
|
action = decision.requested_action
|
|
allowed_actions = [str(item) for item in (cfg.get("allowed_actions") or [])]
|
|
min_confidence = _float_value(cfg.get("min_confidence"), _DEFAULT_MIN_CONFIDENCE)
|
|
max_actions = _int_value(cfg.get("max_actions_per_incident"), _DEFAULT_MAX_ACTIONS)
|
|
gates: list[tuple[bool, str]] = [
|
|
(not outcome.human_required and not decision.human_required, "human_required"),
|
|
(build_is_terminal_failure, "build_not_terminal_failure"),
|
|
(job_allowlisted, "job_not_allowlisted"),
|
|
_classification_gate(decision, cfg),
|
|
(action is not None, "requested_action_missing"),
|
|
(action is None or action.type == RUN_ARIADNE_JOB_ACTION, "requested_action_type_invalid"),
|
|
(action is None or action.id in allowed_actions, f"action_not_allowlisted: {_action_id(action)!r}"),
|
|
_action_classification_gate(decision, action, cfg),
|
|
(
|
|
decision.confidence >= min_confidence,
|
|
f"confidence_below_minimum: {decision.confidence} < {min_confidence}",
|
|
),
|
|
(evidence_has_signature, "evidence_signature_missing"),
|
|
(_int_value(prior_action_count, 0) < max_actions, "max_actions_reached"),
|
|
(bool(cfg.get("autoremediation_enabled")), "autoremediation_disabled"),
|
|
]
|
|
for passed, reason in gates:
|
|
if not passed:
|
|
return False, reason
|
|
return True, AUTHORIZED_REASON
|
|
|
|
|
|
def _action_classifications(cfg: dict) -> dict[str, str]:
|
|
raw = cfg.get(_ACTION_CLASSIFICATIONS_KEY)
|
|
if not isinstance(raw, dict):
|
|
return {}
|
|
return {str(key): str(value) for key, value in raw.items() if str(key) and str(value)}
|
|
|
|
|
|
def _classification_gate(decision: TriageDecision, cfg: dict) -> tuple[bool, str]:
|
|
mapping = _action_classifications(cfg)
|
|
if not mapping:
|
|
expected = str(cfg.get("expected_classification") or _DEFAULT_EXPECTED_CLASSIFICATION)
|
|
return (
|
|
decision.classification == expected,
|
|
f"classification_mismatch: got {decision.classification!r} expected {expected!r}",
|
|
)
|
|
return (
|
|
decision.classification in mapping,
|
|
f"classification_not_supported: {decision.classification!r}",
|
|
)
|
|
|
|
|
|
def _action_classification_gate(
|
|
decision: TriageDecision, action: RequestedAction | None, cfg: dict
|
|
) -> tuple[bool, str]:
|
|
expected_action = _action_classifications(cfg).get(decision.classification)
|
|
if expected_action is None or action is None:
|
|
return True, ""
|
|
return (
|
|
action.id == expected_action,
|
|
f"action_does_not_match_classification: {action.id!r} expected {expected_action!r}",
|
|
)
|
|
|
|
|
|
def _rejected(reason: str) -> DecisionOutcome:
|
|
return DecisionOutcome(valid=False, decision=None, human_required=True, reject_reason=reason)
|
|
|
|
|
|
def _extract_json_object(raw: str) -> str | None:
|
|
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:
|
|
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)
|
|
type_error = (
|
|
_validate_scalar_fields(payload)
|
|
or _validate_confidence(payload["confidence"])
|
|
or _validate_facts(payload["facts"])
|
|
or _validate_requested_action(payload["requested_action"])
|
|
)
|
|
if type_error:
|
|
return type_error
|
|
if payload["incident_id"] != expected_incident_id:
|
|
return f"incident_id_mismatch: got {payload['incident_id']!r} expected {expected_incident_id!r}"
|
|
return None
|
|
|
|
|
|
def _validate_scalar_fields(payload: dict[str, Any]) -> str | None:
|
|
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"
|
|
if not isinstance(payload["inferences"], list):
|
|
return "field_type_invalid: inferences must be a list"
|
|
return None
|
|
|
|
|
|
def _validate_confidence(confidence: Any) -> str | None:
|
|
if isinstance(confidence, bool) or not isinstance(confidence, (int, float)):
|
|
return "field_type_invalid: confidence must be a number"
|
|
if not _CONFIDENCE_MIN <= float(confidence) <= _CONFIDENCE_MAX:
|
|
return f"confidence_out_of_range: {confidence}"
|
|
return None
|
|
|
|
|
|
def _validate_facts(facts: Any) -> str | None:
|
|
if not isinstance(facts, list):
|
|
return "field_type_invalid: facts must be a list"
|
|
for index, fact in enumerate(facts):
|
|
if not isinstance(fact, dict):
|
|
return f"fact_invalid: facts[{index}] must be an object"
|
|
if set(fact) != _FACT_KEYS:
|
|
return f"fact_invalid: facts[{index}] must have exactly statement, source, reference"
|
|
if not all(isinstance(fact[key], str) for key in _FACT_KEYS):
|
|
return f"fact_invalid: facts[{index}] fields must be strings"
|
|
if fact["source"] not in ALLOWED_FACT_SOURCES:
|
|
return f"fact_source_invalid: facts[{index}] source {fact['source']!r}"
|
|
return None
|
|
|
|
|
|
def _validate_requested_action(action: Any) -> str | None:
|
|
if action is None:
|
|
return None
|
|
if not isinstance(action, dict):
|
|
return "requested_action_invalid: must be an object or null"
|
|
if set(action) != _ACTION_KEYS:
|
|
return "requested_action_invalid: must have exactly type and id"
|
|
if action["type"] != RUN_ARIADNE_JOB_ACTION:
|
|
return f"requested_action_invalid: unsupported type {action['type']!r}"
|
|
if not isinstance(action["id"], str) or not action["id"].strip():
|
|
return "requested_action_invalid: id must be a non-empty string"
|
|
return None
|
|
|
|
|
|
def _decision_from_payload(payload: dict[str, Any]) -> TriageDecision:
|
|
action = payload["requested_action"]
|
|
return TriageDecision(
|
|
incident_id=payload["incident_id"],
|
|
classification=payload["classification"],
|
|
confidence=float(payload["confidence"]),
|
|
facts=[
|
|
TriageFact(statement=fact["statement"], source=fact["source"], reference=fact["reference"])
|
|
for fact in payload["facts"]
|
|
],
|
|
inferences=list(payload["inferences"]),
|
|
first_failed_gate=payload["first_failed_gate"],
|
|
requested_action=None if action is None else RequestedAction(type=action["type"], id=action["id"]),
|
|
human_required=payload["human_required"],
|
|
reason=payload["reason"],
|
|
)
|
|
|
|
|
|
def _action_id(action: RequestedAction | None) -> str:
|
|
return action.id if action is not None else ""
|
|
|
|
|
|
def _float_value(value: Any, default: float) -> float:
|
|
try:
|
|
return float(value)
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
|
|
def _int_value(value: Any, default: int) -> int:
|
|
try:
|
|
return int(value)
|
|
except (TypeError, ValueError):
|
|
return default
|