Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

204 KB
Raw Blame
#!/usr/bin/env python3
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""
Harbor Skill Evaluation Verifier -- standalone.

Reads:
  /logs/agent/trajectory.json   -- ATIF trajectory from any agent (preferred)
  /logs/agent/claude-code.txt   -- Claude Code stream JSONL fallback (synthetic ATIF)
  /logs/agent/cursor-cli.txt    -- Cursor CLI stdout fallback (heuristic synthetic ATIF)
  /tests/entry.json             -- dataset entry with expected_skill, expected_behavior, etc.

Writes:
  /logs/verifier/reward.json       -- Harbor-safe numeric scores
  /logs/verifier/skill_evaluator_reward.json  -- rich SkillEvaluator scores + details
  /logs/verifier/reward.txt        -- overall score (0.0-1.0)

LLM judges use the configured public provider environment variables.
RAGAS is used for goal_accuracy when available. Judges return verdicts only and
the scores are computed here; every judge attempt is saved, redacted, to
/logs/verifier/judge_attempts.json.
"""

from __future__ import annotations

import contextlib
import hashlib
import importlib.util
import io
import ipaddress
import json
import logging
import math
import os
import random
import re
import signal
import ssl
import sys
import threading
import time
import unicodedata
import urllib.error
import urllib.request
from collections.abc import Iterator
from contextvars import ContextVar
from functools import partial
from pathlib import Path
from typing import Any, NamedTuple
from urllib.parse import quote, unquote_to_bytes, urlparse, urlsplit

import idna

_SCRIPT_TESTS_DIR = Path(__file__).resolve().parent
if str(_SCRIPT_TESTS_DIR) not in sys.path:
    sys.path.insert(0, str(_SCRIPT_TESTS_DIR))
try:
    from log_converters import load_trajectory_with_fallback
except ImportError:  # pragma: no cover -- older task bundles

    def load_trajectory_with_fallback(trajectory_path, logs_dir=None):
        _ = logs_dir  # full implementation reads sibling logs; stub is trajectory.json only
        meta: dict[str, Any] = {"source": None, "warning": None, "note": None}
        if trajectory_path.exists():
            try:
                data = json.loads(trajectory_path.read_text(encoding="utf-8"))
                if isinstance(data, dict) and data.get("steps"):
                    meta["source"] = "trajectory.json"
                    return data, meta
            except (json.JSONDecodeError, OSError) as e:
                meta["warning"] = str(e)
        return None, meta


try:
    import codex_tool_call_normalizer as _tool_normalizer
except ImportError:  # pragma: no cover -- source-tree import only
    from skillevaluator.tier3.eval_core import codex_tool_call_normalizer as _tool_normalizer

atif_content_has_text = _tool_normalizer.atif_content_has_text
atif_content_text = _tool_normalizer.atif_content_text
iter_normalized_tool_calls = _tool_normalizer.iter_normalized_tool_calls
normalized_tool_call_error_flag = _tool_normalizer.normalized_tool_call_error_flag
normalized_tool_call_is_error = _tool_normalizer.normalized_tool_call_is_error
normalized_tool_call_observation = _tool_normalizer.normalized_tool_call_observation
normalized_tool_call_wrapper_observation = _tool_normalizer.normalized_tool_call_wrapper_observation

try:
    import evidence as _evidence
except ImportError:  # pragma: no cover -- source-tree import only
    from skillevaluator import evidence as _evidence

evidence_ref_identity = _evidence.evidence_ref_identity

try:
    from character_facts import append_character_facts, character_facts_enabled
except ImportError:  # pragma: no cover -- source-tree import only
    from skillevaluator.tier3.eval_core.character_facts import append_character_facts, character_facts_enabled


_CHECKS_PATH = _SCRIPT_TESTS_DIR / "checks.py"
if _CHECKS_PATH.is_file():
    # A host process may already have an unrelated module named "checks".
    # Reuse only this bundle's module; otherwise load its exact file without
    # replacing another caller's module cache. Import errors must propagate.
    _shared_checks = sys.modules.get("checks")
    if getattr(_shared_checks, "__file__", None) != str(_CHECKS_PATH):
        _checks_spec = importlib.util.spec_from_file_location("checks", _CHECKS_PATH)
        assert _checks_spec and _checks_spec.loader
        _shared_checks = importlib.util.module_from_spec(_checks_spec)
        _checks_spec.loader.exec_module(_shared_checks)
else:  # Source-tree template: the canonical module lives in the package.
    from skillevaluator.tier3.eval_core import checks as _shared_checks

_DECLARATIVE_CHECKS_PATH = _SCRIPT_TESTS_DIR / "declarative_checks.py"
if _DECLARATIVE_CHECKS_PATH.is_file():
    _declarative_spec = importlib.util.spec_from_file_location(
        "_skillevaluator_shared_declarative_checks", _DECLARATIVE_CHECKS_PATH
    )
    assert _declarative_spec and _declarative_spec.loader
    _shared_declarative_checks = importlib.util.module_from_spec(_declarative_spec)
    _had_checks_module = "checks" in sys.modules
    _previous_checks_module = sys.modules.get("checks")
    sys.modules["checks"] = _shared_checks
    try:
        _declarative_spec.loader.exec_module(_shared_declarative_checks)
    finally:
        if _had_checks_module:
            sys.modules["checks"] = _previous_checks_module
        else:
            sys.modules.pop("checks", None)
else:
    from skillevaluator.tier3.eval_core import declarative_checks as _shared_declarative_checks

AMBIGUOUS_OUTER_EXEC_OBSERVATION = _shared_checks.AMBIGUOUS_OUTER_EXEC_OBSERVATION
UNOBSERVED_INNER_CALL = _shared_checks.UNOBSERVED_INNER_CALL
UNSUPPORTED_NATIVE_CODEX_EXEC = _shared_checks.UNSUPPORTED_NATIVE_CODEX_EXEC

# Existing names with compatible argument binding and behavior.
# Include private names: downstream differential tools and tests use them.
_accepted_skill_names = _shared_checks._accepted_skill_names
_allowed_workspace_skills = _shared_checks._allowed_workspace_skills
_apply_arithmetic_assignments = _shared_checks._apply_arithmetic_assignments
_apply_binding_builtin = _shared_checks._apply_binding_builtin
_apply_eval_bindings = _shared_checks._apply_eval_bindings
_apply_patch_call = _shared_checks._apply_patch_call
_apply_patch_bodies_are_data = _shared_checks._apply_patch_bodies_are_data
_apply_patch_command_evidence = _shared_checks._apply_patch_command_evidence
_apply_patch_heredoc_pieces = _shared_checks._apply_patch_heredoc_pieces
_apply_patch_heredoc_text = _shared_checks._apply_patch_heredoc_text
_apply_patch_path_text = _shared_checks._apply_patch_path_text
_apply_patch_prefix_is_unsettled = _shared_checks._apply_patch_prefix_is_unsettled
_apply_patch_protected_entry = _shared_checks._apply_patch_protected_entry
_apply_set_options = _shared_checks._apply_set_options
_arithmetic_close = _shared_checks._arithmetic_close
_arithmetic_names = _shared_checks._arithmetic_names
_arithmetic_texts = _shared_checks._arithmetic_texts
_attribute_changes = _shared_checks._attribute_changes
_bind = _shared_checks._bind
_bind_unsettled = _shared_checks._bind_unsettled
_binding_readings = _shared_checks._binding_readings
_carries_a_nested_invocation = _shared_checks._carries_a_nested_invocation
_case_pattern_end = _shared_checks._case_pattern_end
_child_environment = _shared_checks._child_environment
_cmd_executes_script = _shared_checks._cmd_executes_script
_cmd_reads_skill_md = _shared_checks._cmd_reads_skill_md
_command_input_args = _shared_checks._command_input_args
_command_names_script = _shared_checks._command_names_script
_command_prefix_end = _shared_checks._command_prefix_end
_command_position_words = _shared_checks._command_position_words
_command_reads_skill_md_arg = _shared_checks._command_reads_skill_md_arg
_command_run_before_refusal = _shared_checks._command_run_before_refusal
_command_start = _shared_checks._command_start
_compound_after_assignment = _shared_checks._compound_after_assignment
_compound_closer_ends = _shared_checks._compound_closer_ends
_compound_keywords = _shared_checks._compound_keywords
_compound_reads_input = _shared_checks._compound_reads_input
_declaration_options = _shared_checks._declaration_options
_double_parens_are_arithmetic = _shared_checks._double_parens_are_arithmetic
_failed_single_skill_read = _shared_checks._failed_single_skill_read
_function_header_end = _shared_checks._function_header_end
_has_literal_secret = _shared_checks._has_literal_secret
_has_unquoted_secret_var = _shared_checks._has_unquoted_secret_var
_has_unsupported_native_codex_call = _shared_checks._has_unsupported_native_codex_call
_heredoc_body_spans = _shared_checks._heredoc_body_spans
_heredoc_header = _shared_checks._heredoc_header
_heredoc_operator_index = _shared_checks._heredoc_operator_index
_integer_may_fail = _shared_checks._integer_may_fail
_interpreter_operands = _shared_checks._interpreter_operands
_interpreter_script_arg = _shared_checks._interpreter_script_arg
_is_apply_patch_action = _shared_checks._is_apply_patch_action
_is_editor_view = _shared_checks._is_editor_view
_is_execution_action = _shared_checks._is_execution_action
_is_file_read_action = _shared_checks._is_file_read_action
_is_heredoc_redirect = _shared_checks._is_heredoc_redirect
_is_httpie_body_item = _shared_checks._is_httpie_body_item
_is_network_exfiltration_command = _shared_checks._is_network_exfiltration_command
_is_output_redirect = _shared_checks._is_output_redirect
_is_redirection_operator = _shared_checks._is_redirection_operator
_keeps_patch_header = _shared_checks._keeps_patch_header
_keep_attached_descriptors = _shared_checks._keep_attached_descriptors
_lexical_path_components = _shared_checks._lexical_path_components
_looks_like_refusal = _shared_checks._looks_like_refusal
_loop_header_is_empty = _shared_checks._loop_header_is_empty
_loop_header_is_unresolved = _shared_checks._loop_header_is_unresolved
_mark_literal_dollars = _shared_checks._mark_literal_dollars
_mark_quoted_newlines = _shared_checks._mark_quoted_newlines
_mark_quoted_syntax = _shared_checks._mark_quoted_syntax
_mask_non_assignment_equals = _shared_checks._mask_non_assignment_equals
_mentions_skill_artifact = _shared_checks._mentions_skill_artifact
_names_script_anywhere = _shared_checks._names_script_anywhere
_network_client_uploads = _shared_checks._network_client_uploads
_network_executable = _shared_checks._network_executable
_network_lookup_readings = _shared_checks._network_lookup_readings
_network_redirection = _shared_checks._network_redirection
_network_shell_tokens = _shared_checks._network_shell_tokens
_network_tokens_exfiltrate = _shared_checks._network_tokens_exfiltrate
_normalize_sensitive_path_text = _shared_checks._normalize_sensitive_path_text
_normalize_skill_names = _shared_checks._normalize_skill_names
_normalized_write_path = _shared_checks._normalized_write_path
_normpath_word = _shared_checks._normpath_word
_number_may_fail = _shared_checks._number_may_fail
_parse_unit_starts = _shared_checks._parse_unit_starts
_pass_to_reference = _shared_checks._pass_to_reference
_path_entry_in = _shared_checks._path_entry_in
_path_with_shell_cwd = _shared_checks._path_with_shell_cwd
_pipeline_last_stage_keeps_bindings = _shared_checks._pipeline_last_stage_keeps_bindings
_pipeline_upstream_names_script = _shared_checks._pipeline_upstream_names_script
_plain_pipeline = _shared_checks._plain_pipeline
_possibly_references_target_directory = _shared_checks._possibly_references_target_directory
_prefixed_scope = _shared_checks._prefixed_scope
_protected_write_entry = _shared_checks._protected_write_entry
_reader_scope = _shared_checks._reader_scope
_reads_program_from_stdin = _shared_checks._reads_program_from_stdin
_record_builtin_reassignments = _shared_checks._record_builtin_reassignments
_redact_network_evidence = _shared_checks._redact_network_evidence
_redirects_script_to_stdin = _shared_checks._redirects_script_to_stdin
_references_exact_target_artifact = _shared_checks._references_exact_target_artifact
_refuse_assignment = _shared_checks._refuse_assignment
_relative_dotfile_entry = _shared_checks._relative_dotfile_entry
_resolve_lookups = _shared_checks._resolve_lookups
_resolve_network_client_lookups = _shared_checks._resolve_network_client_lookups
_resolved_shell_arg = _shared_checks._resolved_shell_arg
_resolved_workdir = _shared_checks._resolved_workdir
_rm_brace_sequence = _shared_checks._rm_brace_sequence
_rm_brace_words = _shared_checks._rm_brace_words
_rm_call_workdirs = _shared_checks._rm_call_workdirs
_rm_cd_workdirs = _shared_checks._rm_cd_workdirs
_rm_dot_glob_paths = _shared_checks._rm_dot_glob_paths
_rm_find_exec_protected = _shared_checks._rm_find_exec_protected
_rm_force_operand_is_protected = _shared_checks._rm_force_operand_is_protected
_rm_group_end = _shared_checks._rm_group_end
_rm_inline_code = _shared_checks._rm_inline_code
_rm_operand_follows_find = _shared_checks._rm_operand_follows_find
_rm_sequence_workdirs = _shared_checks._rm_sequence_workdirs
_rm_sequential_commands = _shared_checks._rm_sequential_commands
_rm_shell_tokens = _shared_checks._rm_shell_tokens
_rm_shell_workdirs = _shared_checks._rm_shell_workdirs
_rm_spend = _shared_checks._rm_spend
_rm_stdin_code = _shared_checks._rm_stdin_code
_rm_stdin_codes = _shared_checks._rm_stdin_codes
_rm_symbolic_link_command = _shared_checks._rm_symbolic_link_command
_rm_symlink_call_seen = _shared_checks._rm_symlink_call_seen
_rm_symlink_creation_seen = _shared_checks._rm_symlink_creation_seen
_rm_symlink_fallback = _shared_checks._rm_symlink_fallback
_rm_targets_fallback = _shared_checks._rm_targets_fallback
_rm_targets_outside_tmp = _shared_checks._rm_targets_outside_tmp
_rm_tmp_operand_is_exempt = _shared_checks._rm_tmp_operand_is_exempt
_rm_token_workdirs = _shared_checks._rm_token_workdirs
_rm_wrapped_command_index = _shared_checks._rm_wrapped_command_index
_rm_xargs_context = _shared_checks._rm_xargs_context
_rm_xargs_fallback = _shared_checks._rm_xargs_fallback
_runs_inline_code = _shared_checks._runs_inline_code
_scope_events = _shared_checks._scope_events
_script_path_matches = _shared_checks._script_path_matches
_search_path_is_root = _shared_checks._search_path_is_root
_secret_exposure_finding = _shared_checks._secret_exposure_finding
_security_finding = _shared_checks._security_finding
_sensitive_path_match = _shared_checks._sensitive_path_match
_sensitive_write_target = _shared_checks._sensitive_write_target
_shell_c_payload = _shared_checks._shell_c_payload
_shell_c_positional = _shared_checks._shell_c_positional
_shell_executable = _shared_checks._shell_executable
_shell_substitution_payloads = _shared_checks._shell_substitution_payloads
_shell_text_regions = _shared_checks._shell_text_regions
_shell_tokens = _shared_checks._shell_tokens
_shell_write_scans = _shared_checks._shell_write_scans
_shell_write_targets = _shared_checks._shell_write_targets
_shell_write_texts = _shared_checks._shell_write_texts
_skill_match_details = _shared_checks._skill_match_details
_skill_md_arg = _shared_checks._skill_md_arg
_skill_name_from_ref = _shared_checks._skill_name_from_ref
_skip_arithmetic = _shared_checks._skip_arithmetic
_skip_transparent_prefixes = _shared_checks._skip_transparent_prefixes
_skip_wrapper_options = _shared_checks._skip_wrapper_options
_split_glued_syntax = _shared_checks._split_glued_syntax
_split_heredoc_body = _shared_checks._split_heredoc_body
_split_heredocs = _shared_checks._split_heredocs
_split_punctuation_runs = _shared_checks._split_punctuation_runs
_string_argument = _shared_checks._string_argument
_substitution_command_names = _shared_checks._substitution_command_names
_tool_call_shell = _shared_checks._tool_call_shell
_tool_searches_root = _shared_checks._tool_searches_root
_unit_is_complete = _shared_checks._unit_is_complete
_unquoted_separator_index = _shared_checks._unquoted_separator_index
_unresolved_value = _shared_checks._unresolved_value
_unsettle_every_binding = _shared_checks._unsettle_every_binding
_unsettled_cd_operand = _shared_checks._unsettled_cd_operand
_unsupported_native_codex_result = _shared_checks._unsupported_native_codex_result
_unwrap_shell_command = _shared_checks._unwrap_shell_command
_value_now = _shared_checks._value_now
_walk_for_invocation = _shared_checks._walk_for_invocation
_without_plain_patch_headers = _shared_checks._without_plain_patch_headers
_without_redirections = _shared_checks._without_redirections
check_error_recovery = _shared_checks.check_error_recovery
check_script_execution = _shared_checks.check_script_execution
normalize_optional_reference = _shared_checks.normalize_optional_reference
normalize_expected_behaviors = _shared_checks.normalize_expected_behaviors
resolve_should_trigger = _shared_checks.resolve_should_trigger
score_skill_execution = _shared_checks.score_skill_execution
skill_efficiency_not_applicable_reason = _shared_checks.skill_efficiency_not_applicable_reason
skill_execution_not_applicable_reason = _shared_checks.skill_execution_not_applicable_reason

# All 148 constant initializers are AST-identical at the fixed base; shared
# constants added since are aliased here too.
ACCEPTABLE_ALTERNATE_SCORE = _shared_checks.ACCEPTABLE_ALTERNATE_SCORE
WASTE_INDICATORS = _shared_checks.WASTE_INDICATORS
_ALLEXPORT_MARK = _shared_checks._ALLEXPORT_MARK
_APPLY_PATCH_BODY_RE = _shared_checks._APPLY_PATCH_BODY_RE
_APPLY_PATCH_CD_RE = _shared_checks._APPLY_PATCH_CD_RE
_APPLY_PATCH_CDPATH_RE = _shared_checks._APPLY_PATCH_CDPATH_RE
_APPLY_PATCH_COMMAND_RE = _shared_checks._APPLY_PATCH_COMMAND_RE
_APPLY_PATCH_DEFAULT_WORKDIR = _shared_checks._APPLY_PATCH_DEFAULT_WORKDIR
_APPLY_PATCH_HEADER_RE = _shared_checks._APPLY_PATCH_HEADER_RE
_APPLY_PATCH_HEREDOC_COMMAND_RE = _shared_checks._APPLY_PATCH_HEREDOC_COMMAND_RE
_APPLY_PATCH_HEREDOC_WORD_RE = _shared_checks._APPLY_PATCH_HEREDOC_WORD_RE
_APPLY_PATCH_OUTPUT_USE_RE = _shared_checks._APPLY_PATCH_OUTPUT_USE_RE
_APPLY_PATCH_QUOTED_RE = _shared_checks._APPLY_PATCH_QUOTED_RE
_APPLY_PATCH_SHELL_PATH_RE = _shared_checks._APPLY_PATCH_SHELL_PATH_RE
_APPLY_PATCH_UNMODELLED_SHELL_RE = _shared_checks._APPLY_PATCH_UNMODELLED_SHELL_RE
_APPLY_PATCH_UNSETTLED_DIR_RE = _shared_checks._APPLY_PATCH_UNSETTLED_DIR_RE
_APPLY_PATCH_UNSETTLED_PREFIX_RE = _shared_checks._APPLY_PATCH_UNSETTLED_PREFIX_RE
_ARITHMETIC_ASSIGNMENT_RE = _shared_checks._ARITHMETIC_ASSIGNMENT_RE
_ARITHMETIC_EXPANSION_RE = _shared_checks._ARITHMETIC_EXPANSION_RE
_ASSIGNMENT_MASK = _shared_checks._ASSIGNMENT_MASK
_ASSIGNMENT_REFUSED = _shared_checks._ASSIGNMENT_REFUSED
_ATTACHED_DESCRIPTOR_RE = _shared_checks._ATTACHED_DESCRIPTOR_RE
_ATTACHED_REDIRECT_RE = _shared_checks._ATTACHED_REDIRECT_RE
_ATTRIBUTE_LETTERS = _shared_checks._ATTRIBUTE_LETTERS
_ATTRIBUTE_MARK = _shared_checks._ATTRIBUTE_MARK
_BAD_REFERENCE_STOPS = _shared_checks._BAD_REFERENCE_STOPS
_BASED_VALUE_RE = _shared_checks._BASED_VALUE_RE
_BUILTIN_REACHES_BUILTINS = _shared_checks._BUILTIN_REACHES_BUILTINS
_COMMAND_INTRODUCING_WORDS = _shared_checks._COMMAND_INTRODUCING_WORDS
_COMMAND_POSITION_LEADERS = _shared_checks._COMMAND_POSITION_LEADERS
_COMMAND_REACHES_BUILTINS = _shared_checks._COMMAND_REACHES_BUILTINS
_COMMAND_SUBSTITUTION_RE = _shared_checks._COMMAND_SUBSTITUTION_RE
_COMMENT_WORD_BREAKS = _shared_checks._COMMENT_WORD_BREAKS
_COMPOUND_CLOSERS = _shared_checks._COMPOUND_CLOSERS
_COMPOUND_OPENERS = _shared_checks._COMPOUND_OPENERS
_CURL_OR_WGET_WORD_RE = _shared_checks._CURL_OR_WGET_WORD_RE
_CURL_DATA_FLAGS = _shared_checks._CURL_DATA_FLAGS
_CURL_SHORT_OPTS_WITH_ARG = _shared_checks._CURL_SHORT_OPTS_WITH_ARG
_CURL_UPLOAD_FLAGS = _shared_checks._CURL_UPLOAD_FLAGS
_DECIMAL_VALUE_RE = _shared_checks._DECIMAL_VALUE_RE
_DECLARATION_ASSIGNS_IN_ORDER = _shared_checks._DECLARATION_ASSIGNS_IN_ORDER
_DECLARATION_BUILTINS = _shared_checks._DECLARATION_BUILTINS
_DECLARATION_KEEPS_VALUE = _shared_checks._DECLARATION_KEEPS_VALUE
_DECLARATION_OPTIONS = _shared_checks._DECLARATION_OPTIONS
_DECLARATION_OPTION_SHELLS = _shared_checks._DECLARATION_OPTION_SHELLS
_DECLARING_BUILTINS = _shared_checks._DECLARING_BUILTINS
_DESCRIPTOR_OPERATOR_RE = _shared_checks._DESCRIPTOR_OPERATOR_RE
_DESTRUCTIVE_PATTERNS = _shared_checks._DESTRUCTIVE_PATTERNS
_DURATION_ARG_RE = _shared_checks._DURATION_ARG_RE
_DYNAMIC_ARGUMENT_RE = _shared_checks._DYNAMIC_ARGUMENT_RE
_EMPTY_REFERENCE_SHELLS = _shared_checks._EMPTY_REFERENCE_SHELLS
_EXECUTION_TOOL_HINTS = _shared_checks._EXECUTION_TOOL_HINTS
_EXPORTED_MARK = _shared_checks._EXPORTED_MARK
_FD_REDIRECT_TARGET_RE = _shared_checks._FD_REDIRECT_TARGET_RE
_FILE_READ_VERBS = _shared_checks._FILE_READ_VERBS
_FUNCTION_HEADER_NAME_RE = _shared_checks._FUNCTION_HEADER_NAME_RE
_GLUED_AKIA_BODY = _shared_checks._GLUED_AKIA_BODY
_GLUED_CASE_PATTERN_RE = _shared_checks._GLUED_CASE_PATTERN_RE
_GLUED_FUNCTION_HEADER_RE = _shared_checks._GLUED_FUNCTION_HEADER_RE
_GLUED_KEYWORD_RE = _shared_checks._GLUED_KEYWORD_RE
_GROUPING_TOKENS = _shared_checks._GROUPING_TOKENS
_HEREDOC_DELIMITER_RE = _shared_checks._HEREDOC_DELIMITER_RE
_HEREDOC_OPERAND_RE = _shared_checks._HEREDOC_OPERAND_RE
_HEREDOC_REDIRECTS = _shared_checks._HEREDOC_REDIRECTS
_HOME_ANCHOR_RE = _shared_checks._HOME_ANCHOR_RE
_HOME_CREDENTIAL_PATHS = _shared_checks._HOME_CREDENTIAL_PATHS
_HOME_DIR_PREFIX_RE = _shared_checks._HOME_DIR_PREFIX_RE
_HOME_SENSITIVE_WRITE_PATHS = _shared_checks._HOME_SENSITIVE_WRITE_PATHS
_HOME_SHORTHAND_RE = _shared_checks._HOME_SHORTHAND_RE
_HTTPIE_BODY_FLAGS = _shared_checks._HTTPIE_BODY_FLAGS
_INERT_PRINT_COMMANDS = _shared_checks._INERT_PRINT_COMMANDS
_INERT_SHELL_PRODUCERS = _shared_checks._INERT_SHELL_PRODUCERS
_INLINE_CODE = _shared_checks._INLINE_CODE
_INPUT_REDIRECTS = _shared_checks._INPUT_REDIRECTS
_INPUT_REDIRECT_OPERATORS = _shared_checks._INPUT_REDIRECT_OPERATORS
_INTEGER_ERROR_GOES_ON = _shared_checks._INTEGER_ERROR_GOES_ON
_INTEGER_VALUE_RE = _shared_checks._INTEGER_VALUE_RE
_INTERPRETER_GRAMMARS = _shared_checks._INTERPRETER_GRAMMARS
_JUSTIFYING_SHELLS = _shared_checks._JUSTIFYING_SHELLS
_LAST_STAGE_IN_CURRENT_SHELL = _shared_checks._LAST_STAGE_IN_CURRENT_SHELL
_LAST_STAGE_IN_SUBSHELL = _shared_checks._LAST_STAGE_IN_SUBSHELL
_LINE_CONTINUATION_RE = _shared_checks._LINE_CONTINUATION_RE
_LISTING_ACTS_ON_NAMES = _shared_checks._LISTING_ACTS_ON_NAMES
_LITERAL_DOLLAR = _shared_checks._LITERAL_DOLLAR
_LOOP_HEADER_WORDS = _shared_checks._LOOP_HEADER_WORDS
_MAPFILE_OPTIONS_WITH_ARG = _shared_checks._MAPFILE_OPTIONS_WITH_ARG
_MAX_HEREDOCS_PER_LINE = _shared_checks._MAX_HEREDOCS_PER_LINE
_MAX_HEREDOC_DEPTH = _shared_checks._MAX_HEREDOC_DEPTH
_MAX_HEREDOC_OPERANDS = _shared_checks._MAX_HEREDOC_OPERANDS
_MAX_LOOKUP_READINGS = _shared_checks._MAX_LOOKUP_READINGS
_MAX_NETWORK_ACTION_CHARS = _shared_checks._MAX_NETWORK_ACTION_CHARS
_MAX_PARSE_UNIT_LINES = _shared_checks._MAX_PARSE_UNIT_LINES
_MAX_PARSE_UNIT_READ = _shared_checks._MAX_PARSE_UNIT_READ
_MAX_SHELL_REFERENCE_CHARS = _shared_checks._MAX_SHELL_REFERENCE_CHARS
_MAX_SHELL_REFERENCE_DEPTH = _shared_checks._MAX_SHELL_REFERENCE_DEPTH
_MAX_SHELL_REFERENCE_TOKENS = _shared_checks._MAX_SHELL_REFERENCE_TOKENS
_MAX_SHELL_WRAPPERS = _shared_checks._MAX_SHELL_WRAPPERS
_NAMEREF_SHELLS = _shared_checks._NAMEREF_SHELLS
_NEGATIVE_NUMBER_RE = _shared_checks._NEGATIVE_NUMBER_RE
_NESTED_QUOTING_RE = _shared_checks._NESTED_QUOTING_RE
_NETWORK_CLIENT_FAST_PATTERN = _shared_checks._NETWORK_CLIENT_FAST_PATTERN
_NETWORK_CLIENT_PATTERN = _shared_checks._NETWORK_CLIENT_PATTERN
_NETWORK_COMMAND_RUNNERS = _shared_checks._NETWORK_COMMAND_RUNNERS
_NETWORK_EXECUTABLES = _shared_checks._NETWORK_EXECUTABLES
_NETWORK_INPUT_REDIRECTS = _shared_checks._NETWORK_INPUT_REDIRECTS
_NETWORK_OUTPUT_REDIRECTS = _shared_checks._NETWORK_OUTPUT_REDIRECTS
_NOT_A_SIMPLE_COMMAND = _shared_checks._NOT_A_SIMPLE_COMMAND
_NO_HERE_STRING_SHELLS = _shared_checks._NO_HERE_STRING_SHELLS
_NO_SCRIPT = _shared_checks._NO_SCRIPT
_NUMERIC_ATTRIBUTES = _shared_checks._NUMERIC_ATTRIBUTES
_NUMERIC_ATTRIBUTE_STOPS = _shared_checks._NUMERIC_ATTRIBUTE_STOPS
_OPAQUE_SHELL_BUILTINS = _shared_checks._OPAQUE_SHELL_BUILTINS
_OPENERS_REFUSED_AFTER_ASSIGNMENT = _shared_checks._OPENERS_REFUSED_AFTER_ASSIGNMENT
_OPERATOR_TOKEN_RE = _shared_checks._OPERATOR_TOKEN_RE
_OUTPUT_REDIRECTS = _shared_checks._OUTPUT_REDIRECTS
_PARSES_WHOLE_TEXT_FIRST = _shared_checks._PARSES_WHOLE_TEXT_FIRST
_PASS_THROUGH_WRAPPERS = _shared_checks._PASS_THROUGH_WRAPPERS
_PATH_ARG_KEYS = _shared_checks._PATH_ARG_KEYS
_PATH_COMPONENT_END = _shared_checks._PATH_COMPONENT_END
_PATH_WORD_RE = _shared_checks._PATH_WORD_RE
_PIPELINE_OPTION_RE = _shared_checks._PIPELINE_OPTION_RE
_POSITIONAL_SET_RE = _shared_checks._POSITIONAL_SET_RE
_PREFIX_EXPANDS_FIRST = _shared_checks._PREFIX_EXPANDS_FIRST
_PREFIX_OUTLIVES_SPECIAL_BUILTIN = _shared_checks._PREFIX_OUTLIVES_SPECIAL_BUILTIN
_PROC_CWD_ALIAS_RE = _shared_checks._PROC_CWD_ALIAS_RE
_PROC_ROOT_ALIAS_RE = _shared_checks._PROC_ROOT_ALIAS_RE
_PROMPT_INJECTION_PATTERNS = _shared_checks._PROMPT_INJECTION_PATTERNS
_PROTECTED_WRITE_PATHS = _shared_checks._PROTECTED_WRITE_PATHS
_PUNCTUATION_PIECE_RE = _shared_checks._PUNCTUATION_PIECE_RE
_PUNCTUATION_RUN_RE = _shared_checks._PUNCTUATION_RUN_RE
_QUOTED_NEWLINE = _shared_checks._QUOTED_NEWLINE
_QUOTED_STRING_RE = _shared_checks._QUOTED_STRING_RE
_QUOTED_SYNTAX_MARK = _shared_checks._QUOTED_SYNTAX_MARK
_QUOTE_CHARS = _shared_checks._QUOTE_CHARS
_READONLY_ATTRIBUTES = _shared_checks._READONLY_ATTRIBUTES
_READONLY_MARK = _shared_checks._READONLY_MARK
_READS_ARGV0_RE = _shared_checks._READS_ARGV0_RE
_READS_POSITIONAL_RE = _shared_checks._READS_POSITIONAL_RE
_READ_OPTIONS_WITH_ARG = _shared_checks._READ_OPTIONS_WITH_ARG
_READ_TOOL_HINTS = _shared_checks._READ_TOOL_HINTS
_REDIRECTION_OPERATOR_RE = _shared_checks._REDIRECTION_OPERATOR_RE
_REDIRECTION_WORD_RE = _shared_checks._REDIRECTION_WORD_RE
_REDIRECT_TARGET_RE = _shared_checks._REDIRECT_TARGET_RE
_REFERENCE_MARK = _shared_checks._REFERENCE_MARK
_REFERENCE_SHELLS = _shared_checks._REFERENCE_SHELLS
_REFUSED_ASSIGNMENT_GOES_ON = _shared_checks._REFUSED_ASSIGNMENT_GOES_ON
_RELATIVE_HEADER_ROOT = _shared_checks._RELATIVE_HEADER_ROOT
_RM_CD_RE = _shared_checks._RM_CD_RE
_RM_FIND_EXEC_ACTIONS = _shared_checks._RM_FIND_EXEC_ACTIONS
_RM_FORCE_PROTECTED_ROOTS = _shared_checks._RM_FORCE_PROTECTED_ROOTS
_RM_MAX_BRACE_WORDS = _shared_checks._RM_MAX_BRACE_WORDS
_RM_MAX_DOT_GLOB_COMPONENTS = _shared_checks._RM_MAX_DOT_GLOB_COMPONENTS
_RM_MAX_FORCE_RESOLUTIONS = _shared_checks._RM_MAX_FORCE_RESOLUTIONS
_RM_MAX_WORKDIRS = _shared_checks._RM_MAX_WORKDIRS
_RUNNER_COMMAND_PREFIXES = _shared_checks._RUNNER_COMMAND_PREFIXES
_RUNTIME_BINDING_BUILTINS = _shared_checks._RUNTIME_BINDING_BUILTINS
_SCRIPT = _shared_checks._SCRIPT
_SCRIPT_INTERPRETERS = _shared_checks._SCRIPT_INTERPRETERS
_SECRET_PATTERNS = _shared_checks._SECRET_PATTERNS
_SECRET_VAR_NAME_RE = _shared_checks._SECRET_VAR_NAME_RE
_SED_IN_PLACE_FLAG_RE = _shared_checks._SED_IN_PLACE_FLAG_RE
_SED_OPERANDS_RE = _shared_checks._SED_OPERANDS_RE
_SED_SCRIPT_OPTION_RE = _shared_checks._SED_SCRIPT_OPTION_RE
_SENSITIVE_PATH_DIRECTORIES = _shared_checks._SENSITIVE_PATH_DIRECTORIES
_SENSITIVE_WRITE_PATHS = _shared_checks._SENSITIVE_WRITE_PATHS
_SHELL_ASSIGNMENT_RE = _shared_checks._SHELL_ASSIGNMENT_RE
_SHELL_COMMAND_INTERPRETERS = _shared_checks._SHELL_COMMAND_INTERPRETERS
_SHELL_EXPANSION_CHARS = _shared_checks._SHELL_EXPANSION_CHARS
_SHELL_LINE_FILL_RE = _shared_checks._SHELL_LINE_FILL_RE
_SHELL_METACHARS = _shared_checks._SHELL_METACHARS
_SHELL_NAME_RE = _shared_checks._SHELL_NAME_RE
_SHELL_SCAN_RE = _shared_checks._SHELL_SCAN_RE
_SHELL_SEPARATORS = _shared_checks._SHELL_SEPARATORS
_SHELL_VARIABLE_RE = _shared_checks._SHELL_VARIABLE_RE
_SHELL_WORD = _shared_checks._SHELL_WORD
_SOURCING_COMMANDS = _shared_checks._SOURCING_COMMANDS
_SPECIAL_BUILTINS = _shared_checks._SPECIAL_BUILTINS
_SPECIAL_BUILTIN_ERROR_STOPS = _shared_checks._SPECIAL_BUILTIN_ERROR_STOPS
_STDIN_ARGV_RE = _shared_checks._STDIN_ARGV_RE
_STDIN_DEPENDENT_WRAPPERS = _shared_checks._STDIN_DEPENDENT_WRAPPERS
_STDIN_TEXT_CONSUMERS = _shared_checks._STDIN_TEXT_CONSUMERS
_STR_REPLACE_EDITORS = _shared_checks._STR_REPLACE_EDITORS
_SYNTAX_SHAPE_RE = _shared_checks._SYNTAX_SHAPE_RE
_SYNTAX_WORDS = _shared_checks._SYNTAX_WORDS
_TEE_OPERANDS_RE = _shared_checks._TEE_OPERANDS_RE
_TRANSPARENT_COMMAND_PREFIXES = _shared_checks._TRANSPARENT_COMMAND_PREFIXES
_UNAUTHORIZED_PATHS = _shared_checks._UNAUTHORIZED_PATHS
_UNDECIDABLE = _shared_checks._UNDECIDABLE
_UNIT_CLOSERS = _shared_checks._UNIT_CLOSERS
_UNIT_NEWLINE = _shared_checks._UNIT_NEWLINE
_UNKNOWN_CWD_ROOT = _shared_checks._UNKNOWN_CWD_ROOT
_UNMODELLED_CONTROL_WORDS = _shared_checks._UNMODELLED_CONTROL_WORDS
_UNRESOLVED_ARG_RE = _shared_checks._UNRESOLVED_ARG_RE
_UNSAFE_HTTP_METHODS = _shared_checks._UNSAFE_HTTP_METHODS
_UNSETTLED_EXPANSION_RE = _shared_checks._UNSETTLED_EXPANSION_RE
_UNSETTLED_VALUE = _shared_checks._UNSETTLED_VALUE
_UNSET_REFERENCE_SHELLS = _shared_checks._UNSET_REFERENCE_SHELLS
_VARIABLE_READING_BUILTINS = _shared_checks._VARIABLE_READING_BUILTINS
_VERSION_SUFFIX_RE = _shared_checks._VERSION_SUFFIX_RE
_WGET_DATA_FLAGS = _shared_checks._WGET_DATA_FLAGS
_WINDOWS_DRIVE_PREFIX_RE = _shared_checks._WINDOWS_DRIVE_PREFIX_RE
_WRAPPER_GRAMMARS = _shared_checks._WRAPPER_GRAMMARS
_WRAPPER_NONE = _shared_checks._WRAPPER_NONE
_WRAPPER_OK = _shared_checks._WRAPPER_OK
_WRAPPER_UNKNOWN = _shared_checks._WRAPPER_UNKNOWN
_WRITE_TOOL_HINTS = _shared_checks._WRITE_TOOL_HINTS

# Fifteen compatibility adapters preserve existing argument names, positional
# options, trajectory input, and output shape.


def _action_args(tc):
    return _shared_checks._action_args(tc)


def _action_text(tc):
    return _shared_checks._action_text(tc)


def _command_text(tc):
    return _shared_checks._command_text(tc)


def _extract_path(tc):
    return _shared_checks._extract_path(tc)


def _tool_mentions_any_skill(tc, expected_skill, acceptable_skills=None):
    return _shared_checks._tool_mentions_any_skill(tc, expected_skill, acceptable_skills)


def _tool_mentions_skill(tc, expected_skill):
    return _shared_checks._tool_mentions_skill(tc, expected_skill)


def _classify_skill_match(observed, expected_skill, acceptable_skills=None, fuzzy=False):
    return _shared_checks._classify_skill_match(observed, expected_skill, acceptable_skills, fuzzy=fuzzy)


def _cmd_references_exact_target(cmd, target_skill, _depth=0):
    return _shared_checks._cmd_references_exact_target(cmd, target_skill, _depth=_depth)


def _match_skill_name(observed, expected, fuzzy=False):
    # Retain the verifier's falsey fuzzy return value (including None, 0, '').
    # The host returns False instead. This tiny compatibility body is deliberate.
    if not observed or not expected:
        return False
    observed_l = str(observed).lower()
    expected_l = str(expected).lower()
    if observed_l == expected_l:
        return True
    return fuzzy and expected_l in observed_l


def check_activation(tool_calls, expected_skill, skill_tool_names=None, acceptable_skills=None):
    return _shared_checks.check_activation(
        tool_calls,
        expected_skill,
        skill_tool_names=skill_tool_names,
        acceptable_skills=acceptable_skills,
    )


def check_negative_case(tool_calls, skill_under_test, skill_tool_names=None):
    return _shared_checks.check_negative_case(tool_calls, skill_under_test, skill_tool_names=skill_tool_names)


def check_routing(
    tool_calls,
    expected_skill,
    skill_tool_names=None,
    workspace_skill_names=None,
    workspace_mode="isolated",
    acceptable_skills=None,
):
    return _shared_checks.check_routing(
        tool_calls,
        expected_skill,
        skill_tool_names=skill_tool_names,
        workspace_skill_names=workspace_skill_names,
        workspace_mode=workspace_mode,
        acceptable_skills=acceptable_skills,
    )


def check_workflow_order(tool_calls, skill_tool_names=None, expected_skill=None):
    return _shared_checks.check_workflow_order(
        tool_calls, skill_tool_names=skill_tool_names, expected_skill=expected_skill
    )


def check_security(traj, tool_calls, expected_skill=None, acceptable_skills=None, *, agent_workdir="/workspace"):
    return _shared_checks.check_security(
        tool_calls,
        get_agent_text(traj),
        user_text="\n".join(
            atif_content_text(step.get("message")) for step in traj.get("steps", []) if step.get("source") == "user"
        ),
        expected_skill=expected_skill or "",
        acceptable_skills=acceptable_skills,
        agent_workdir=agent_workdir,
    )


def check_tool_efficiency(tool_calls, expected_skill=None, expected_script=None):
    result = _shared_checks.check_tool_efficiency(tool_calls, expected_skill, expected_script)
    result.pop("details", None)
    return result


logger = logging.getLogger(__name__)


def _env_path(name, default):
    return Path(os.environ.get(name, str(default)))


def _declarative_workspace_roots():
    roots = [Path.cwd(), Path("/workspace"), Path("/workspace/output")]
    if artifact_root := os.environ.get("HARBOR_ARTIFACTS_DIR"):
        roots.append(Path(artifact_root))
    return list(dict.fromkeys(roots))


LOGS_DIR = _env_path("HARBOR_LOGS_DIR", "/logs")
AGENT_LOGS_DIR = _env_path("HARBOR_AGENT_LOGS_DIR", LOGS_DIR / "agent")
VERIFIER_DIR = _env_path("HARBOR_VERIFIER_DIR", LOGS_DIR / "verifier")
TESTS_DIR = _env_path("HARBOR_TESTS_DIR", "/tests")

ATIF_PATH = _env_path("HARBOR_ATIF_PATH", AGENT_LOGS_DIR / "trajectory.json")
ENTRY_PATH = _env_path("HARBOR_ENTRY_JSON", TESTS_DIR / "entry.json")
REWARD_JSON = _env_path("HARBOR_REWARD_JSON", VERIFIER_DIR / "reward.json")
REWARD_TXT = _env_path("HARBOR_REWARD_TXT", VERIFIER_DIR / "reward.txt")
SKILL_EVALUATOR_REWARD_JSON = _env_path(
    "HARBOR_SKILL_EVALUATOR_REWARD_JSON", VERIFIER_DIR / "skill_evaluator_reward.json"
)

OPENAI_CHAT_URL = "https://api.openai.com/v1/chat/completions"
NVIDIA_BUILD_CHAT_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
# Last-resort judge per provider when no model is configured. Keep in sync with
# skillevaluator.provider_config.CHAT_DEFAULT_MODELS (sandbox template cannot
# import the package — see drift tests).
DEFAULT_JUDGE_MODELS = {
    "openai": "gpt-6.1-sol",
    "anthropic": "claude-opus-5-5",
    "nv_build": "nvidia/nemotron-3.5-lightning-30b-a3b",
    "bedrock": "us.anthropic.claude-opus-5-5",
    "openai-compatible": "nvidia/nvidia/nemotron-3-super-120b-long-ctx",
}
JUDGE_REASONING_EFFORT = "medium"
REASONING_MAX_COMPLETION_TOKENS = 32768
ANTHROPIC_REFUSAL_FALLBACK_MODEL = "claude-opus-4-8"
ANTHROPIC_SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-07-01"
ANTHROPIC_REFUSAL_FALLBACK_MODEL_ENV = "SKILL_EVAL_LLM_REFUSAL_FALLBACK_MODEL"
_REFUSAL_FALLBACK_DISABLED_VALUES = frozenset({"none", "off", "disabled", "false", "0"})
_ANTHROPIC_DNS_LABEL_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")
_ANTHROPIC_INTERNAL_LABEL_RE = re.compile(r"^[A-Za-z0-9_](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?$")
_ANTHROPIC_IPV6_ZONE_RE = re.compile(r"^[A-Za-z0-9._~-]+$")
_ANTHROPIC_PATH_SAFE = "/:@!$&'()*+,;=-._~%"
_HEX_DIGITS = frozenset("0123456789abcdefABCDEF")
_HEX_DIGIT_BYTES = frozenset(b"0123456789abcdefABCDEF")
_UNRESERVED_BYTES = frozenset(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")

_ERROR_REDACTION_MARKER = "[REDACTED]"
_JUDGE_ERROR_REASON_LIMIT = 512
_JUDGE_TEXT_LIMIT = 512
# Shorter placeholders are not credible provider credentials and can corrupt report schema keys.
_MIN_EXACT_SECRET_LENGTH = 8
_CREDENTIAL_ENV_VARS = (
    "OPENAI_API_KEY",
    "NVIDIA_API_KEY",
    "ANTHROPIC_API_KEY",
    "SKILL_EVAL_LLM_API_KEY",
    "AWS_ACCESS_KEY_ID",
    "AWS_SECRET_ACCESS_KEY",
    "AWS_SECURITY_TOKEN",
    "AWS_SESSION_TOKEN",
    "AWS_BEARER_TOKEN_BEDROCK",
    "AWS_CONTAINER_AUTHORIZATION_TOKEN",
)


DEFAULT_METRIC_SET = "skill-evaluator-default-v2"
# Judges return verdicts and the verifier computes their scores. Rewards carry
# this marker so scores from older judge prompts are not mistaken for these.
JUDGE_CONTRACT = "skill-evaluator-judges-v2"
DEFAULT_SCORE_POLICY = "skill-evaluator-dimension-mean-v1"
DISPLAY_METRICS = [
    "security",
    "skill_execution",
    "skill_efficiency",
    "accuracy",
    "goal_accuracy",
    "behavior_check",
]


# checks.py imports this from secret_redaction.py, which _copy_verifier stages
# beside this file, so the verifier masks log text with the shared rules.
redact_secrets_in_log_line = _shared_checks.redact_secrets_in_log_line


# ── ATIF Helpers ─────────────────────────────────────────────────────────────


# Host and container evidence use the same implementation. The staged file
# takes precedence only when it exists beside this evaluator-owned verifier.
_ATIF_HELPERS_PATH = _SCRIPT_TESTS_DIR / "atif_helpers.py"
if _ATIF_HELPERS_PATH.is_file():
    import importlib.util

    _atif_spec = importlib.util.spec_from_file_location("_skillevaluator_shared_atif", _ATIF_HELPERS_PATH)
    assert _atif_spec and _atif_spec.loader
    _shared_atif = importlib.util.module_from_spec(_atif_spec)
    _atif_spec.loader.exec_module(_shared_atif)
else:
    from skillevaluator.tier3.eval_core import atif_helpers as _shared_atif

# Retain template helper names used by graders and differential tools.
iter_tool_calls = _shared_atif.iter_tool_calls
_tool_call_observation = _shared_atif._tool_call_observation
_tool_call_wrapper_observation = _shared_atif._tool_call_wrapper_observation
get_all_tool_calls = _shared_atif.get_all_tool_calls
get_skill_tool_calls = _shared_atif.get_skill_tool_calls
get_read_calls = _shared_atif.get_read_calls
get_bash_commands = _shared_atif.get_bash_commands
get_agent_text = _shared_atif.get_agent_text
extract_tool_calls_as_dicts = _shared_atif.extract_tool_calls_as_dicts
build_conversation_summary = _shared_atif.build_conversation_summary
_BEHAVIOR_EVIDENCE_MAX_CHARS = _shared_atif._BEHAVIOR_EVIDENCE_MAX_CHARS
_DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT = _shared_atif._DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT
_DEFAULT_BEHAVIOR_CHECK_BUDGET = _shared_atif._DEFAULT_BEHAVIOR_CHECK_BUDGET
_DEFAULT_TOOL_HISTORY_HEADROOM = _shared_atif._DEFAULT_TOOL_HISTORY_HEADROOM
_MIN_BEHAVIOR_HISTORY_HEADROOM = _shared_atif._MIN_BEHAVIOR_HISTORY_HEADROOM
_SECTION_COMPACT_TOOL_HISTORY = _shared_atif._SECTION_COMPACT_TOOL_HISTORY
_SECTION_FILE_CHANGES = _shared_atif._SECTION_FILE_CHANGES
_SECTION_FINAL_RESPONSE = _shared_atif._SECTION_FINAL_RESPONSE
_SECTION_USER_REQUEST = _shared_atif._SECTION_USER_REQUEST
_env_positive_int = _shared_atif._env_positive_int
_behavior_final_response_limit = _shared_atif._behavior_final_response_limit
_behavior_check_budget = _shared_atif._behavior_check_budget
_behavior_user_request_limit = _shared_atif._behavior_user_request_limit
_DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT = _shared_atif._DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT
_env_int_or_none = _shared_atif._env_int_or_none
_BEHAVIOR_SECTION_LABELS = _shared_atif._BEHAVIOR_SECTION_LABELS
_BEHAVIOR_REQUIRED_EVIDENCE = _shared_atif._BEHAVIOR_REQUIRED_EVIDENCE
_BEHAVIOR_EVIDENCE_GAP_HINT = _shared_atif._BEHAVIOR_EVIDENCE_GAP_HINT
_behavior_evidence_completeness = _shared_atif._behavior_evidence_completeness
_expected_behaviors_verified = _shared_atif._expected_behaviors_verified
behavior_evidence_gap = _shared_atif.behavior_evidence_gap
_BEHAVIOR_WRITE_TOOLS = _shared_atif._BEHAVIOR_WRITE_TOOLS
_BEHAVIOR_EXEC_TOOLS = _shared_atif._BEHAVIOR_EXEC_TOOLS
_BEHAVIOR_WRITE_COMMAND_MARKERS = _shared_atif._BEHAVIOR_WRITE_COMMAND_MARKERS
_BEHAVIOR_WRITE_REDIRECT_RE = _shared_atif._BEHAVIOR_WRITE_REDIRECT_RE
_BEHAVIOR_PYTHON_WRITE_RE = _shared_atif._BEHAVIOR_PYTHON_WRITE_RE
_TOOL_NAME_SEPARATORS = _shared_atif._TOOL_NAME_SEPARATORS
_get_final_response = _shared_atif.get_final_response
_truncate_for_behavior = _shared_atif._truncate_for_behavior
_append_section_with_budget = _shared_atif._append_section_with_budget
_tool_file_path = _shared_atif._tool_file_path
_tool_write_body = _shared_atif._tool_write_body
_command_looks_like_write = _shared_atif._command_looks_like_write
_tool_name_looks_like_write = _shared_atif._tool_name_looks_like_write
_collect_file_change_evidence = _shared_atif._collect_file_change_evidence
build_behavior_evidence = _shared_atif.build_behavior_evidence
_METRIC_EVIDENCE_REF_METRICS = _shared_atif._METRIC_EVIDENCE_REF_METRICS
_METRIC_EVIDENCE_EXCERPT_CHARS = _shared_atif._METRIC_EVIDENCE_EXCERPT_CHARS
_METRIC_EVIDENCE_MAX_TOOL_REFS = _shared_atif._METRIC_EVIDENCE_MAX_TOOL_REFS
_METRIC_EVIDENCE_MAX_FILE_REFS = _shared_atif._METRIC_EVIDENCE_MAX_FILE_REFS
_EXPECTED_ARTIFACT_PATH_RE = _shared_atif._EXPECTED_ARTIFACT_PATH_RE
_redact_evidence_text = _shared_atif._redact_evidence_text
_evidence_excerpt = _shared_atif._evidence_excerpt
_evidence_ref = _shared_atif._evidence_ref
_dedupe_evidence_refs = _shared_atif._dedupe_evidence_refs
_final_response_ref = _shared_atif._final_response_ref
_tool_call_ref = _shared_atif._tool_call_ref
_tool_call_refs = _shared_atif._tool_call_refs
_tool_observation_refs = _shared_atif._tool_observation_refs
_file_change_refs = _shared_atif._file_change_refs
_first_expected_artifact_path = _shared_atif._first_expected_artifact_path
_expected_artifact_refs = _shared_atif._expected_artifact_refs
_expected_behavior_refs = _shared_atif._expected_behavior_refs
_ground_truth_ref = _shared_atif._ground_truth_ref
build_metric_evidence_refs = _shared_atif.build_metric_evidence_refs
attach_metric_evidence_refs = _shared_atif.attach_metric_evidence_refs
_BUNDLE_ITEM_CHARS = _shared_atif._BUNDLE_ITEM_CHARS
_DEFAULT_ACCURACY_BUDGET = _shared_atif._DEFAULT_ACCURACY_BUDGET
_DEFAULT_GOAL_ACCURACY_BUDGET = _shared_atif._DEFAULT_GOAL_ACCURACY_BUDGET
_BUNDLE_BUDGETS = _shared_atif._BUNDLE_BUDGETS
_BUNDLE_ACCURACY_MAX_OBS = _shared_atif._BUNDLE_ACCURACY_MAX_OBS
_BUNDLE_GOAL_MAX_OBS = _shared_atif._BUNDLE_GOAL_MAX_OBS
_accuracy_budget = _shared_atif._accuracy_budget
_goal_accuracy_budget = _shared_atif._goal_accuracy_budget
_bundle_budgets = _shared_atif._bundle_budgets
_clip = _shared_atif._clip
_late_observation_excerpts = _shared_atif._late_observation_excerpts
_assemble = _shared_atif._assemble
_BACKTICK_TOKEN_RE = _shared_atif._BACKTICK_TOKEN_RE
_VERIFIED_FACTS_MAX = _shared_atif._VERIFIED_FACTS_MAX
_VERIFIED_FACT_LINE_MAX = _shared_atif._VERIFIED_FACT_LINE_MAX
_checkable_tokens = _shared_atif._checkable_tokens
build_verified_facts = _shared_atif.build_verified_facts
_build_verified_facts_section = _shared_atif._build_verified_facts_section
build_metric_evidence_bundles = _shared_atif.build_metric_evidence_bundles


def _slice_with_middle_marker(text, budget, marker, *, max_head=None, fallback_tail=False):
    """Compact *text* to fit *budget* by replacing the middle with *marker*."""
    if budget <= 0 or not text:
        return ""
    if len(text) <= budget:
        return text
    if budget <= len(marker) + 2:
        return text[-budget:] if fallback_tail else text[:budget]
    avail = budget - len(marker)
    head = max(1, avail // 2 if max_head is None else min(max_head, avail // 2))
    tail = max(1, avail - head)
    return f"{text[:head]}{marker}{text[-tail:]}"


def _compact_behavior_conversation(conversation_text, limit=None):
    """Keep both setup context and late outcome evidence in behavior prompts."""
    if limit is None:
        limit = _behavior_check_budget()
    if len(conversation_text) <= limit:
        return conversation_text
    marker = "\n...[middle truncated for behavior check]...\n"
    if limit <= len(marker) + 1:
        return conversation_text[:limit]
    final_limit = _behavior_final_response_limit()
    final_header = f"{_SECTION_FINAL_RESPONSE}\n"
    final_idx = -1
    if conversation_text.startswith(final_header):
        final_idx = 0
    else:
        pos = conversation_text.find(f"\n\n{final_header}")
        if pos != -1:
            final_idx = pos + 2

    if final_idx != -1:
        final_end = len(conversation_text)
        for next_hdr in (f"\n\n{_SECTION_USER_REQUEST}\n", f"\n\n{_SECTION_COMPACT_TOOL_HISTORY}\n"):
            pos = conversation_text.find(next_hdr, final_idx)
            if pos != -1 and pos < final_end:
                final_end = pos
        prefix = conversation_text[:final_idx]
        final_sec = conversation_text[final_idx:final_end]
        suffix = conversation_text[final_end:]

        reserved_other = min(1600, max(0, limit - final_limit), limit // 2)
        max_final = min(final_limit, max(1, limit - reserved_other))
        if len(final_sec) > max_final:
            final_body = final_sec[len(final_header) :]
            body_limit = max(1, max_final - len(final_header))
            final_sec = f"{final_header}{_truncate_for_behavior(final_body, body_limit)}"[:max_final]

        rem = limit - len(final_sec)
        if rem <= 0:
            return final_sec[:limit]
        if len(prefix) + len(suffix) <= rem:
            return f"{prefix}{final_sec}{suffix}"
        if not suffix:
            pre_comp = _slice_with_middle_marker(prefix, rem, marker)
            return f"{pre_comp}{final_sec}"[:limit]
        if len(prefix) <= rem // 2:
            suf_comp = _slice_with_middle_marker(suffix, rem - len(prefix), marker, max_head=800, fallback_tail=True)
            return f"{prefix}{final_sec}{suf_comp}"[:limit]
        pre_budget = max(1, min(len(prefix), rem // 2))
        suf_budget = max(0, rem - pre_budget)
        pre_comp = _slice_with_middle_marker(prefix, pre_budget, marker)
        suf_comp = _slice_with_middle_marker(suffix, suf_budget, marker, max_head=800, fallback_tail=True)
        return f"{pre_comp}{final_sec}{suf_comp}"[:limit]

    available = limit - len(marker)
    reserved_head = min(1600, available // 2)
    tail = max(1, available // 3, min(final_limit, max(1, available - max(1, reserved_head))))
    head = max(1, available - tail)
    return f"{conversation_text[:head]}{marker}{conversation_text[-tail:]}"


# ── Public Provider Caller ───────────────────────────────────────────────────


def _dedupe_models(models):
    seen = set()
    result = []
    for model in models:
        model = str(model or "").strip()
        if model and model not in seen:
            seen.add(model)
            result.append(model)
    return result


def _fallback_models(primary_model):
    env_fallbacks = [
        item.strip() for item in os.environ.get("LLM_JUDGE_FALLBACK_MODELS", "").split(",") if item.strip()
    ]
    return _dedupe_models([primary_model, *env_fallbacks])


def _judge_policy(name, choices):
    """Read one judge policy variable: unset or empty selects ``choices[0]``; another value raises."""
    value = os.environ.get(name, "").strip().lower()
    if not value:
        return choices[0]
    if value not in choices:
        raise ValueError(f"{name} must be {' or '.join(choices)}")
    return value


def _judge_fallback_policy():
    """Return LLM_JUDGE_FALLBACK_POLICY: ``append`` (default) or ``replace``.

    The only fallback model this verifier adds on its own is the Claude Opus
    4.8 refusal fallback for Claude 5.5 or later judges (server-side on the
    native Claude API, a second request on Bedrock). ``replace`` turns it off,
    so only the primary judge and the LLM_JUDGE_FALLBACK_MODELS entries answer.
    """
    return _judge_policy("LLM_JUDGE_FALLBACK_POLICY", ("append", "replace"))


def _judge_retry_policy():
    """Return LLM_JUDGE_RETRY_POLICY: ``legacy`` (default) or ``strict`` (see _call_strict_judge)."""
    return _judge_policy("LLM_JUDGE_RETRY_POLICY", ("legacy", "strict"))


def _judge_policies_valid():
    """Return whether LLM_JUDGE_FALLBACK_POLICY and LLM_JUDGE_RETRY_POLICY both hold a known value."""
    try:
        _judge_fallback_policy()
        _judge_retry_policy()
    except ValueError:
        return False
    return True


def _strict_judge_replies():
    """Return whether a completed judge reply must be one whole JSON object and is final.

    True under LLM_JUDGE_RETRY_POLICY=strict. An invalid policy value also
    counts as strict here; the provider call rejects it before sending anything.
    """
    try:
        return _judge_retry_policy() == "strict"
    except ValueError:
        return True


def _refusal_fallback_target(model):
    """Return the refusal fallback target for ``model``, or None for no fallback.

    SKILL_EVAL_LLM_REFUSAL_FALLBACK_MODEL replaces the built-in target; ``none``,
    ``off``, ``disabled``, ``false`` or ``0`` turns it off. An empty value counts
    as unset, and a target equal to ``model`` is never sent. Mirrors
    ``provider_config.anthropic_refusal_fallback_model``.
    """
    value = os.environ.get(ANTHROPIC_REFUSAL_FALLBACK_MODEL_ENV, "").strip()
    if value.casefold() in _REFUSAL_FALLBACK_DISABLED_VALUES:
        return None
    target = value or ANTHROPIC_REFUSAL_FALLBACK_MODEL
    return None if target == str(model or "").strip() else target


def _builtin_refusal_fallback_allowed():
    """Return whether the built-in Claude Opus 4.8 refusal fallback may answer a refused judge.

    It is off under LLM_JUDGE_FALLBACK_POLICY=replace, and under
    LLM_JUDGE_RETRY_POLICY=strict, where a refusal ends the judge.
    """
    try:
        return _judge_fallback_policy() == "append" and _judge_retry_policy() == "legacy"
    except ValueError:
        return False


# LLM_JUDGE_RETRY_POLICY=strict tries at most this many models, the primary
# first, and sends each at most this many requests. All of them share the
# judge's wall-time budget (_ACTIVE_JUDGE_DEADLINE).
_STRICT_JUDGE_MAX_MODELS = 3
_STRICT_JUDGE_REQUESTS_PER_MODEL = 2
# Requests left for the model the strict policy is trying; None outside it.
_STRICT_JUDGE_REQUESTS_LEFT: ContextVar[list[int] | None] = ContextVar("strict_judge_requests_left", default=None)
# Under the strict policy, a provider error that says one of these is not
# retried or handed to another model, even when it is an HTTP 429: another
# model cannot lift a quota, budget, billing or credit limit, and must not be
# asked to overturn a content-filter, safety or security rejection. Whole
# phrases only, joined by a space or underscore, so a model id or host name
# such as ``content-safety-judge`` or ``security-proxy`` is not a reason.
_STRICT_JUDGE_STOP_PATTERN = re.compile(
    r"\b(?:"
    r"insufficient[ _]quota|quota[ _]exceeded|exceeded (?:your|the) (?:current )?quota"
    r"|budget(?: has been)?[ _](?:exceeded|exhausted)|exceeded (?:your|the) (?:\w+ )?budget"
    r"|billing[ _](?:hard[ _]limit|not[ _]active)"
    r"|credit balance|insufficient[ _]credits?|out of credits"
    r"|content[ _](?:filter|policy|management policy)"
    r"|safety (?:system|filter|policy|block)"
    r"|security (?:policy|filter|block|violation)"
    r"|(?:blocked|flagged|rejected) by (?:the |a |an )?(?:\w+ )?(?:safety|security|content)"
    r"|policy[ _](?:rejection|violation)"
    r")\b",
    re.IGNORECASE,
)
_STRICT_JUDGE_ERROR_BODY_CHARS = 500


class _StrictJudgeRequestLimitError(RuntimeError):
    """The strict policy's per-model request limit is used up."""


def _spend_strict_judge_request():
    """Count one request against the strict per-model limit; a no-op outside the strict policy."""
    left = _STRICT_JUDGE_REQUESTS_LEFT.get()
    if left is None:
        return
    if left[0] <= 0:
        raise _StrictJudgeRequestLimitError(
            f"strict judge policy allows {_STRICT_JUDGE_REQUESTS_PER_MODEL} requests per model"
        )
    left[0] -= 1


def _provider_error_fields(body):
    """Return the code, type and message of a JSON error body, or None when the body has none."""
    if len(body) > _STRICT_JUDGE_ERROR_BODY_CHARS * 20:
        return None
    try:
        parsed = json.loads(body)
    except (RecursionError, ValueError):
        return None
    detail = parsed.get("error", parsed) if isinstance(parsed, dict) else None
    if isinstance(detail, str):
        return detail or None
    if not isinstance(detail, dict):
        return None
    fields = [detail[key] for key in ("code", "type", "message", "detail") if isinstance(detail.get(key), str)]
    return " ".join(fields) or None


def _strict_judge_error_stops(error):
    """Return whether a provider error is a quota, budget, billing, safety or security rejection.

    Only what the provider said is read: the code, type and message of a JSON
    error body, else the start of the body (the excerpt the error detail
    shows, so a long proxy error page's footer cannot end the judge), or a
    Bedrock error's code and message. A connection error has no provider
    verdict, so the words in its reason, such as a proxy host name, never count.
    """
    if isinstance(error, urllib.error.HTTPError):
        body = _http_error_body(error)
        text = _provider_error_fields(body)
        if text is None:
            text = body[:_STRICT_JUDGE_ERROR_BODY_CHARS]
    elif isinstance(error, (urllib.error.URLError, OSError)):
        return False
    else:
        response = getattr(error, "response", None)
        info = response.get("Error") if isinstance(response, dict) else None
        if isinstance(info, dict):
            text = f"{info.get('Code') or ''} {info.get('Message') or ''}"
        else:
            text = str(error)
    return _STRICT_JUDGE_STOP_PATTERN.search(text) is not None


# Besides the model errors every policy hands to LLM_JUDGE_FALLBACK_MODELS
# (_should_try_fallback), the strict policy reads these as a model the
# provider does not have or the key cannot use: OpenAI's model_not_found
# ("The model `x` does not exist ..."), a Claude not_found_error about the
# model, and Bedrock's access-denied, not-found and invalid-model errors.
_STRICT_MODEL_UNAVAILABLE_PATTERN = re.compile(
    r"\bmodel_not_found\b|\bnot_found_error model:|\bthe model\b.{0,200}?\bdoes not exist\b", re.IGNORECASE
)
_STRICT_BEDROCK_MODEL_UNAVAILABLE_CODES = frozenset({"AccessDeniedException", "ResourceNotFoundException"})


def _strict_model_unavailable(error):
    """Return whether a failed strict judge request says the model is missing or not open to the key."""
    if isinstance(error, urllib.error.HTTPError):
        body = _http_error_body(error)
        text = _provider_error_fields(body)
        if text is None:
            text = body[:_STRICT_JUDGE_ERROR_BODY_CHARS]
        return _STRICT_MODEL_UNAVAILABLE_PATTERN.search(text) is not None
    response = getattr(error, "response", None)
    info = response.get("Error") if isinstance(response, dict) else None
    if not isinstance(info, dict):
        return False
    code = str(info.get("Code") or "")
    return code in _STRICT_BEDROCK_MODEL_UNAVAILABLE_CODES or (
        code == "ValidationException" and "model identifier" in str(info.get("Message") or "").lower()
    )


def _strict_judge_retry_allowed(error):
    """Return whether the strict policy lets the transport retry *error* on the same model."""
    left = _STRICT_JUDGE_REQUESTS_LEFT.get()
    if left is None:
        return True
    return left[0] > 0 and not _strict_judge_error_stops(error)


def _resolve_url(provider):
    if provider == "nv_build":
        url = os.environ.get("SKILL_EVAL_LLM_BASE_URL") or NVIDIA_BUILD_CHAT_URL
        return _validate_http_url(url)
    base_url = os.environ.get("SKILL_EVAL_LLM_BASE_URL") or os.environ.get("OPENAI_BASE_URL")
    url = base_url.rstrip("/") + "/chat/completions" if base_url else OPENAI_CHAT_URL
    return _validate_http_url(url)


def _validate_http_url(url):
    """Allow explicit public provider endpoints, not local-file schemes."""
    parsed = urlparse(url)
    if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc:
        raise ValueError("Provider base URL must be an absolute HTTP or HTTPS URL")
    return url


def _configured_secret_values(extra_secret_values=()):
    values = {
        value
        for name in _CREDENTIAL_ENV_VARS
        if (value := os.environ.get(name, "")) and len(value) >= _MIN_EXACT_SECRET_LENGTH
    }
    for value in extra_secret_values:
        text = str(value) if value else ""
        if len(text) >= _MIN_EXACT_SECRET_LENGTH:
            values.add(text)
    return sorted(values, key=len, reverse=True)


def _redact_configured_credentials(text, extra_secret_values=()):
    redacted = str(text)
    for secret in _configured_secret_values(extra_secret_values):
        redacted = redacted.replace(secret, _ERROR_REDACTION_MARKER)
    return redacted


def _judge_error(error_reason, **metadata):
    """Return a bounded, redacted result that cannot be mistaken for a judged zero."""
    safe_reason = _redact_configured_credentials(error_reason).strip() or "LLM judge failed"
    if len(safe_reason) > _JUDGE_ERROR_REASON_LIMIT:
        safe_reason = safe_reason[: _JUDGE_ERROR_REASON_LIMIT - 3] + "..."
    return {**metadata, "score": None, "status": "error", "reason": safe_reason}


def _bounded_judge_text(value):
    """Normalize trusted-shape model text before it reaches artifacts and reports."""
    text = _redact_configured_credentials(value).strip() if isinstance(value, str) else ""
    if len(text) > _JUDGE_TEXT_LIMIT:
        text = text[: _JUDGE_TEXT_LIMIT - 3] + "..."
    return text


def _finite_score(value):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return None
    if isinstance(value, int):
        if value <= 0:
            return 0.0
        return 1.0
    score = float(value)
    if not math.isfinite(score):
        return None
    return max(0.0, min(1.0, score))


def _sanitize_error_value(value, extra_secret_values=()):
    secrets = _configured_secret_values(extra_secret_values)

    def sanitize(item):
        if isinstance(item, str):
            redacted = item
            for secret in secrets:
                redacted = redacted.replace(secret, _ERROR_REDACTION_MARKER)
            return redacted
        if isinstance(item, dict):
            return {sanitize(key): sanitize(nested) for key, nested in item.items()}
        if isinstance(item, list):
            return [sanitize(nested) for nested in item]
        if isinstance(item, tuple):
            return tuple(sanitize(nested) for nested in item)
        return item

    return sanitize(value)


def _http_error_body(error):
    """Return a failed response's body text, reading it only once."""
    body = getattr(error, "_skill_evaluator_body", None)
    if isinstance(body, str):
        return body
    try:
        body = error.read().decode("utf-8", "replace").strip()
    except Exception:
        body = ""
    with contextlib.suppress(Exception):
        error._skill_evaluator_body = body
    return body


def _format_http_error_with_fallback(error):
    body = _http_error_body(error)
    raw_detail = f"HTTP {error.code}: {error.reason}"
    safe_detail = raw_detail
    if body:
        raw_detail = f"{raw_detail} - {body}"
        safe_detail = f"{safe_detail} - {_redact_configured_credentials(body)[:500]}"
    return _redact_configured_credentials(safe_detail), _should_try_fallback(raw_detail)


def _format_http_error(error):
    return _format_http_error_with_fallback(error)[0]


def _should_try_fallback(error):
    text = error.lower()
    return (
        "key_model_access_denied" in text
        or "not allowed to access model" in text
        or "invalid model" in text
        or "model not found" in text
    )


# Model capability helpers. Keep in sync with skillevaluator.provider_config (drift test).


def _model_leaf(model):
    leaf = str(model or "").strip().casefold().rsplit("/", 1)[-1]
    leaf = re.sub(r"^(?:[a-z]+-)+?(?=(?:claude|gpt)-)", "", leaf, count=1)
    return re.sub(r"^(?:(?:[a-z]{2}|global)\.)?anthropic\.", "", leaf, count=1)


def _claude_version(model):
    match = re.fullmatch(
        r"claude-[a-z][a-z-]*-(?P<major>\d+)"
        r"(?:-(?P<minor>\d{1,2}))?"
        r"(?:-(?:\d{8}|latest))?"
        r"(?:-v\d+)?(?::\d+)?",
        _model_leaf(model),
    )
    if match is None:
        return None
    return int(match.group("major")), int(match.group("minor") or 0)


def _is_openai_reasoning_model(model):
    return _model_leaf(model).startswith(("gpt-5", "gpt-6"))


def _is_claude_5_5_or_later(model):
    version = _claude_version(model)
    return version is not None and version >= (5, 5)


def _supports_custom_temperature(model):
    if _is_openai_reasoning_model(model) or _model_leaf(model) == "claude-mythos-preview":
        return False
    version = _claude_version(model)
    return version is None or version < (4, 7)


def _completion_token_limit(model, max_tokens):
    return max(max_tokens, REASONING_MAX_COMPLETION_TOKENS) if _is_openai_reasoning_model(model) else max_tokens


def _effective_reasoning_effort(provider, model, effort):
    if provider == "anthropic":
        supported = _is_claude_5_5_or_later(model)
    else:
        supported = provider != "bedrock" and _model_leaf(model).startswith("gpt-6")
    return effort if supported else None


def _is_native_openai_chat_url(provider, request_url):
    if str(provider or "").strip().casefold() != "openai":
        return False

    raw_url = str(request_url or "")
    if raw_url != raw_url.strip() or any(ord(character) < 0x20 or ord(character) == 0x7F for character in raw_url):
        return False
    try:
        parsed = urlparse(raw_url)
        port = parsed.port
    except ValueError:
        return False

    return (
        parsed.scheme.casefold() == "https"
        and parsed.hostname is not None
        and parsed.hostname.casefold() == "api.openai.com"
        and parsed.netloc.casefold() in {"api.openai.com", "api.openai.com:443"}
        and port in {None, 443}
        and parsed.path in {"/v1/chat/completions", "/v1/chat/completions/"}
        and parsed.username is None
        and parsed.password is None
        and not parsed.params
        and not parsed.query
        and not parsed.fragment
        and ";" not in raw_url
        and "?" not in raw_url
        and "#" not in raw_url
    )


def _is_vertex_openapi_url(request_url):
    """Return whether a request URL targets a Vertex AI OpenAPI endpoint."""
    if not isinstance(request_url, str) or not request_url.strip():
        return False
    try:
        parsed = urlsplit(request_url.strip())
    except Exception:
        return False
    if parsed.scheme.lower() != "https" or not parsed.hostname:
        return False
    host = parsed.hostname.lower()
    if not re.fullmatch(r"(?:[a-z0-9]+-[a-z0-9]+(?:-[a-z0-9]+)?-)?aiplatform\.googleapis\.com", host):
        return False
    path = parsed.path.rstrip("/")
    return "/endpoints/openapi" in path


def _get_vertex_access_token(timeout_seconds=10.0):
    """Acquire or refresh a Google Cloud access token in-process for Vertex OpenAPI grading.

    Attempts discovery via:
    1. google.auth.default() (standard ADC library if installed)
    2. GKE / GCE metadata server at http://169.254.169.254 (zero-dependency container ADC)
    3. gcloud auth print-access-token (subprocess CLI fallback)
    """
    # 1. google.auth
    try:
        import google.auth
        import google.auth.transport.requests

        credentials, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
        request = google.auth.transport.requests.Request()
        credentials.refresh(request)
        if getattr(credentials, "token", None):
            return str(credentials.token)
    except Exception:
        pass

    # 2. GKE / GCE metadata server
    try:
        metadata_url = "http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token"
        req = urllib.request.Request(
            metadata_url,
            headers={"Metadata-Flavor": "Google"},
        )
        with urllib.request.urlopen(req, timeout=min(timeout_seconds, 5.0)) as resp:  # nosec B310
            data = json.loads(resp.read().decode("utf-8"))
            token = data.get("access_token")
            if token and isinstance(token, str):
                return token.strip()
    except Exception:
        pass

    # 3. gcloud CLI fallback
    import shutil
    import subprocess

    gcloud_path = shutil.which("gcloud")
    if gcloud_path:
        for args in (
            [gcloud_path, "auth", "application-default", "print-access-token"],
            [gcloud_path, "auth", "print-access-token"],
        ):
            try:
                proc = subprocess.run(
                    args,
                    capture_output=True,
                    text=True,
                    timeout=timeout_seconds,
                    check=False,
                )
                if proc.returncode == 0 and proc.stdout.strip():
                    return proc.stdout.strip()
            except Exception:
                pass

    return None


def _build_openai_response_format(schema, schema_name="judge_response"):
    return {
        "type": "json_schema",
        "json_schema": {
            "name": schema_name,
            "strict": True,
            "schema": schema,
        },
    }


def _build_anthropic_output_config(schema):
    return {
        "format": {
            "type": "json_schema",
            "schema": schema,
        }
    }


def _chat_completion_payload(
    model,
    prompt,
    max_tokens,
    temperature,
    provider=None,
    request_url=None,
    response_schema=None,
    schema_name="judge_response",
):
    resolved_provider = _public_provider() if provider is None else provider
    resolved_request_url = _resolve_url(resolved_provider) if request_url is None else request_url
    token_key = (
        "max_completion_tokens"
        if _is_openai_reasoning_model(model) and _is_native_openai_chat_url(resolved_provider, resolved_request_url)
        else "max_tokens"
    )
    payload = {
        "model": model,
        token_key: _completion_token_limit(model, max_tokens),
        "messages": [{"role": "user", "content": prompt}],
        "stream": False,
    }
    if temperature is not None and _supports_custom_temperature(model):
        payload["temperature"] = temperature
    if effort := _effective_reasoning_effort(resolved_provider, model, JUDGE_REASONING_EFFORT):
        payload["reasoning_effort"] = effort
    if response_schema is not None:
        payload["response_format"] = _build_openai_response_format(response_schema, schema_name)
    return payload


def _public_provider():
    configured = os.environ.get("SKILL_EVAL_LLM_PROVIDER", "").strip().lower()
    if configured:
        return configured
    providers = _configured_public_providers()
    return providers[0] if len(providers) == 1 else ""


def _configured_public_providers():
    providers = []
    if os.environ.get("OPENAI_API_KEY"):
        providers.append("openai")
    if os.environ.get("ANTHROPIC_API_KEY"):
        providers.append("anthropic")
    if os.environ.get("NVIDIA_API_KEY"):
        providers.append("nv_build")
    if os.environ.get("AWS_ACCESS_KEY_ID") or os.environ.get("AWS_PROFILE"):
        providers.append("bedrock")
    return providers


def _public_provider_error():
    providers = _configured_public_providers()
    if len(providers) > 1:
        return "Set SKILL_EVAL_LLM_PROVIDER because multiple provider credentials are configured"
    return "Configure SKILL_EVAL_LLM_PROVIDER and a public provider credential"


def _canonical_anthropic_authority(netloc, hostname):
    if netloc.startswith("["):
        closing_bracket = netloc.find("]")
        if closing_bracket < 0:
            return None
        literal = netloc[1:closing_bracket]
        suffix = netloc[closing_bracket + 1 :]
        if literal.casefold() != hostname.casefold() or (
            suffix and (not suffix.startswith(":") or not suffix[1:].isascii() or not suffix[1:].isdigit())
        ):
            return None

        address = literal
        zone = ""
        if "%" in literal:
            address, separator, zone = literal.partition("%25")
            if not separator or "%" in address or "%" in zone or not _ANTHROPIC_IPV6_ZONE_RE.fullmatch(zone):
                return None
        try:
            ipaddress.IPv6Address(address)
        except ValueError:
            return None
        return f"[{address}{'%25' + zone if zone else ''}]{suffix}"

    if "%" in netloc or "[" in netloc or "]" in netloc:
        return None
    host = netloc
    suffix = ""
    if ":" in netloc:
        host, port = netloc.rsplit(":", maxsplit=1)
        if ":" in host or not port.isascii() or not port.isdigit():
            return None
        suffix = f":{port}"
    if host.casefold() != hostname.casefold():
        return None

    if "." in hostname and all(character in "0123456789." for character in hostname):
        try:
            ipaddress.IPv4Address(hostname)
        except ValueError:
            return None
        return f"{host}{suffix}"

    trailing_dot = host.endswith(".")
    dns_name = host.removesuffix(".")
    if not dns_name:
        return None
    if dns_name.isascii() and "_" in dns_name:
        canonical_name = dns_name.lower()
        label_pattern = _ANTHROPIC_INTERNAL_LABEL_RE
    else:
        try:
            canonical_name = idna.encode(dns_name.lower()).decode("ascii")
        except idna.IDNAError:
            return None
        label_pattern = _ANTHROPIC_DNS_LABEL_RE
    if len(canonical_name) > 253 or not all(label_pattern.fullmatch(label) for label in canonical_name.split(".")):
        return None
    return f"{canonical_name}{'.' if trailing_dot else ''}{suffix}"


def _canonical_anthropic_path(path):
    canonical = []
    index = 0
    while index < len(path):
        character = path[index]
        if character != "%":
            canonical.append(character)
            index += 1
            continue

        if index + 2 >= len(path) or path[index + 1] not in _HEX_DIGITS or path[index + 2] not in _HEX_DIGITS:
            return None
        octet = int(path[index + 1 : index + 3], 16)
        if octet in {0x2F, 0x5C, 0x7F} or octet < 0x20:
            return None
        if octet in _UNRESERVED_BYTES:
            canonical.append(chr(octet))
        else:
            canonical.append(f"%{octet:02X}")
        index += 3

    canonical_path = "".join(canonical)
    if "//" in canonical_path.rstrip("/"):
        return None
    decoded_octets = unquote_to_bytes(canonical_path)
    # A decoded percent is safe as data unless it opens a second escape layer.
    if any(
        decoded_octets[index] == 0x25
        and index + 2 < len(decoded_octets)
        and decoded_octets[index + 1] in _HEX_DIGIT_BYTES
        and decoded_octets[index + 2] in _HEX_DIGIT_BYTES
        for index in range(len(decoded_octets))
    ):
        return None
    decoded_path = decoded_octets.decode("utf-8", errors="replace")
    if any(unicodedata.category(character) in {"Cc", "Cf", "Cs"} for character in decoded_path):
        return None
    if any(segment in {".", ".."} for segment in decoded_path.split("/")):
        return None
    return quote(canonical_path, safe=_ANTHROPIC_PATH_SAFE)


def _normalize_anthropic_base_url(value, variable):
    error = (
        f"{variable} must be an absolute HTTP or HTTPS URL representing an API root without credentials, query, fragment, "
        "whitespace, control characters, backslashes, an invalid authority, or a /v1/messages endpoint."
    )
    if "\\" in value or any(
        character.isspace() or unicodedata.category(character) in {"Cc", "Cf", "Cs"} for character in value
    ):
        raise ValueError(error)
    if "?" in value or "#" in value:
        raise ValueError(error)

    try:
        parsed = urlsplit(value)
        hostname = parsed.hostname
        _ = parsed.port
    except ValueError:
        raise ValueError(error) from None
    if (
        parsed.scheme.lower() not in {"http", "https"}
        or not parsed.netloc
        or hostname is None
        or parsed.netloc.endswith(":")
        or parsed.username is not None
        or parsed.password is not None
    ):
        raise ValueError(error)

    authority = _canonical_anthropic_authority(parsed.netloc, hostname)
    path = _canonical_anthropic_path(parsed.path)
    if authority is None or path is None:
        raise ValueError(error)

    path = path.rstrip("/")
    if path.endswith("/v1/messages"):
        raise ValueError(error)
    if path.endswith("/v1"):
        path = path.removesuffix("/v1")
    return parsed._replace(netloc=authority, path=path, query="", fragment="").geturl()


def _anthropic_url():
    for variable in ("SKILL_EVAL_LLM_BASE_URL", "ANTHROPIC_BASE_URL"):
        if base_url := os.environ.get(variable):
            root = _normalize_anthropic_base_url(base_url, variable)
            url = root + "/v1/messages"
            break
    else:
        url = "https://api.anthropic.com/v1/messages"
    return _validate_http_url(url)


# 501 Not Implemented and 505 HTTP Version Not Supported do not change on a retry.
_NON_RETRIABLE_5XX_CODES = frozenset({501, 505})


def _is_retriable_http_status(status):
    """408, 429, and every 5xx except 501 and 505 (same rule as ``skillevaluator.inference.retry``)."""
    if not isinstance(status, int) or isinstance(status, bool):
        return False
    return status in (408, 429) or (500 <= status <= 599 and status not in _NON_RETRIABLE_5XX_CODES)


def _is_certificate_failure(error):
    """Return whether ``error`` is, or wraps, a failed TLS certificate check; a retry cannot fix it."""
    pending = [error]
    seen = set()
    while pending and len(seen) < 32:
        current = pending.pop()
        if not isinstance(current, BaseException) or id(current) in seen:
            continue
        if isinstance(current, ssl.SSLCertVerificationError):
            return True
        seen.add(id(current))
        if isinstance(current, urllib.error.URLError):
            pending.append(current.reason)
        kwargs = getattr(current, "kwargs", None)
        if isinstance(kwargs, dict):
            pending.append(kwargs.get("error"))
        pending.extend(current.args)
        pending.extend((current.__cause__, current.__context__))
    return False


_DEFAULT_MAX_RETRIES = 3
_DEFAULT_BASE_DELAY = 1.0
_DEFAULT_MAX_DELAY = 30.0
# Three required judges run sequentially under the managed 600-second Harbor
# verifier timeout. Reserve one minute for deterministic checks and artifacts.
_JUDGE_WALL_TIME_BUDGET_SEC = 180.0
_ACTIVE_JUDGE_DEADLINE: ContextVar[float | None] = ContextVar("active_judge_deadline", default=None)
_ACTIVE_JUDGE_CALLS: ContextVar[list[dict[str, Any]] | None] = ContextVar("active_judge_calls", default=None)
_ACTIVE_JUDGE_EVIDENCE: ContextVar[list[dict[str, Any]] | None] = ContextVar("active_judge_evidence", default=None)


class EvalRetryConfig(NamedTuple):
    """Represent bounded retry and backoff settings for direct verifier LLM calls."""

    max_retries: int
    base_delay: float
    max_delay: float


class SchemaTargetKey(NamedTuple):
    """Identify a provider endpoint and model for structured output schema memoization."""

    provider: str
    base_url: str
    model: str


def _resolve_judge_wall_time_budget():
    """Resolve the per-judge wall-time budget in seconds from the environment."""
    raw = str(os.environ.get("SKILL_EVAL_LLM_JUDGE_BUDGET_SEC", "")).strip()
    if raw:
        try:
            val = float(raw)
            if math.isfinite(val) and val > 0.0:
                return val
        except ValueError:
            pass
    return _JUDGE_WALL_TIME_BUDGET_SEC


def _remaining_judge_timeout(timeout):
    """Bound one provider request by the remaining time for its judge."""
    deadline = _ACTIVE_JUDGE_DEADLINE.get()
    if deadline is None:
        return timeout
    remaining = deadline - time.monotonic()
    if remaining <= 0:
        raise TimeoutError("LLM judge time budget exhausted")
    return min(timeout, remaining)


def _parse_retry_after(header_value, fallback_delay):
    """Parse a Retry-After header as seconds or HTTP date, falling back to default."""
    if not header_value:
        return fallback_delay
    clean_val = str(header_value).strip()
    try:
        return max(0.0, float(clean_val))
    except ValueError:
        pass
    try:
        from datetime import datetime, timezone
        from email.utils import parsedate_to_datetime

        target = parsedate_to_datetime(clean_val)
        if target.tzinfo is None:
            target = target.replace(tzinfo=timezone.utc)  # noqa: UP017 - datetime.UTC needs Python 3.11; task images may run 3.9
        now = datetime.now(timezone.utc)  # noqa: UP017
        return max(0.0, (target - now).total_seconds())
    except Exception:
        return fallback_delay


def _calculate_jitter_delay(attempt, base_delay=1.0, max_delay=30.0):
    """Calculate exponential backoff with full jitter."""
    calculated = min(max_delay, base_delay * (2.0**attempt))
    return random.uniform(0.0, calculated)


def _resolve_eval_retry_config():
    """Resolve retry and backoff limits from environment variables with safe defaults."""

    def _read_int(name, default):
        """Read a non-negative integer from the environment variable or return default."""
        raw = str(os.environ.get(name, "")).strip()
        if raw:
            try:
                val = int(raw)
                return val if val >= 0 else default
            except ValueError:
                return default
        return default

    def _read_float(name, default):
        """Read a non-negative float from the environment variable or return default."""
        raw = str(os.environ.get(name, "")).strip()
        if raw:
            try:
                val = float(raw)
                return val if math.isfinite(val) and val >= 0.0 else default
            except ValueError:
                return default
        return default

    max_retries = _read_int("SKILL_EVAL_LLM_MAX_RETRIES", _DEFAULT_MAX_RETRIES)
    base_delay = _read_float("SKILL_EVAL_LLM_RETRY_BASE_DELAY", _DEFAULT_BASE_DELAY)
    raw_max_delay = _read_float("SKILL_EVAL_LLM_RETRY_MAX_DELAY", _DEFAULT_MAX_DELAY)
    return EvalRetryConfig(max_retries=max_retries, base_delay=base_delay, max_delay=max(base_delay, raw_max_delay))


def _compute_bounded_retry_delay(retry_after_str, *, attempt, base_delay, max_delay, error):
    """Compute a bounded retry sleep duration and verify the judge deadline allows it."""
    if retry_after_str is not None:
        parsed = _parse_retry_after(retry_after_str, fallback_delay=base_delay)
        if parsed > max_delay:
            raise error
        delay = parsed + random.uniform(0.1, 0.5)
    else:
        delay = _calculate_jitter_delay(attempt, base_delay=base_delay, max_delay=max_delay)

    sleep_duration = min(delay, max_delay)
    deadline = _ACTIVE_JUDGE_DEADLINE.get()
    if deadline is not None and time.monotonic() + sleep_duration >= deadline:
        raise TimeoutError("LLM judge time budget exhausted before retry") from error
    return sleep_duration


def _urlopen_with_retry(request, timeout=90):
    """Open a URL request with exponential backoff and full jitter on transient failures."""
    retry_config = _resolve_eval_retry_config()
    attempt = 0
    while True:
        request_timeout = _remaining_judge_timeout(timeout)
        _spend_strict_judge_request()
        try:
            with urllib.request.urlopen(request, timeout=request_timeout) as response:  # nosec B310
                return response.read()
        except Exception as error:
            is_http = isinstance(error, urllib.error.HTTPError)
            is_network = isinstance(error, (urllib.error.URLError, ConnectionError, OSError))
            if (
                attempt >= retry_config.max_retries
                or (not is_http and not is_network)
                or (is_http and not _is_retriable_http_status(error.code))
                or _is_certificate_failure(error)
                or not _strict_judge_retry_allowed(error)
            ):
                raise

            retry_after_str = None
            if is_http and error.headers:
                retry_after_str = error.headers.get("retry-after") or error.headers.get("Retry-After")

            sleep_duration = _compute_bounded_retry_delay(
                retry_after_str,
                attempt=attempt,
                base_delay=retry_config.base_delay,
                max_delay=retry_config.max_delay,
                error=error,
            )
            status_label = f"HTTP {error.code}" if is_http else type(error).__name__
            logger.warning(
                "LLM judge transient error (%s). Retrying in %.2fs (attempt %d/%d)...",
                status_label,
                sleep_duration,
                attempt + 1,
                retry_config.max_retries,
            )
            if is_http:
                error.close()
            time.sleep(sleep_duration)
            attempt += 1


_UNSUPPORTED_REASON_INDICATORS = (
    "unsupported",
    "not supported",
    "extra input",
    "extra inputs",
    "unknown parameter",
    "unknown field",
    "unknown argument",
    "unrecognized request argument",
    "unrecognized parameter",
    "unexpected keyword argument",
    "unexpected argument",
    "invalid parameter",
    "invalid argument",
    "not permitted",
    "not allowed",
    "disallowed",
    "unavailable",
)

# Gateways can turn a schema into a forced tool call, so a tool_choice rejection is a schema rejection too.
_SCHEMA_OPTION_PATTERN = (
    r"(?:response_format|response format|output_config|json_schema|structured[_ ]outputs?|tool_choice)"
)
_SCHEMA_REJECTION_REASON = (
    r"(?:unsupported|not supported|unavailable|not permitted|not allowed|disallowed|"
    r"unknown (?:parameter|field|argument)|unrecognized (?:request argument|parameter)|"
    r"unexpected (?:keyword )?argument|extra inputs?(?: are not permitted)?)"
)
_SCHEMA_REJECTION_AFTER_OPTION = re.compile(
    rf"\b{_SCHEMA_OPTION_PATTERN}\b(?:\.[a-z0-9_]+)*"
    rf"(?:\s+type)?"
    rf"(?:\s+of\s+type\s+['\"]?[a-z0-9_]+['\"]?)?"
    rf"\s*(?:(?:is|are|was|were)\s+(?:an?\s+)?|:\s*)?"
    rf"{_SCHEMA_REJECTION_REASON}\b",
    re.IGNORECASE,
)
_SCHEMA_REJECTION_BEFORE_OPTION = re.compile(
    rf"\b(?:unsupported|not supported|unavailable|extra inputs?(?: are not permitted)?|"
    rf"unknown (?:parameter|field|argument)|unrecognized (?:request argument|parameter)|"
    rf"unexpected (?:keyword argument|argument)|invalid (?:parameter|argument)|"
    rf"not permitted|not allowed|disallowed)\b"
    rf"(?:\s+supplied)?[\s:'\"\[\]{{}}(),-]{{0,32}}\b{_SCHEMA_OPTION_PATTERN}\b",
    re.IGNORECASE,
)


def _message_rejects_schema_option(text, param=None):
    """Match a rejection of the schema option itself, not unrelated error text."""
    if param:
        if not re.search(rf"\b{_SCHEMA_OPTION_PATTERN}\b", param, re.IGNORECASE):
            return False
        return any(indicator in text.lower() for indicator in _UNSUPPORTED_REASON_INDICATORS)
    return bool(_SCHEMA_REJECTION_AFTER_OPTION.search(text) or _SCHEMA_REJECTION_BEFORE_OPTION.search(text))


def _is_schema_unsupported_http_error(error):
    """Determine whether an HTTP error indicates structured output schema is unsupported."""
    if getattr(error, "code", None) not in {400, 422}:
        return False
    body_text = ""
    try:
        body_bytes = error.read()
        error.fp = io.BytesIO(body_bytes)
        body_text = body_bytes.decode("utf-8", "replace")
    except Exception:
        pass
    error_param = None
    try:
        body = json.loads(body_text)
        if isinstance(body, dict) and isinstance(body.get("error"), dict):
            param = body["error"].get("param")
            if isinstance(param, str):
                error_param = param
    except (TypeError, ValueError):
        pass
    text = f"{error} {getattr(error, 'reason', '')} {body_text}"
    return _message_rejects_schema_option(text, error_param)


_SCHEMA_UNSUPPORTED_TARGETS: set[SchemaTargetKey] = set()


class _JudgeRefusedError(RuntimeError):
    """The judge model declined the request (a safety-classifier refusal or content filter)."""


def _urlopen_with_schema_fallback(build_request, *, target_key, use_schema, timeout=90):
    """Open URL with retry, falling back to prompt-only on confirmed schema capability errors."""
    normalized_key = target_key if isinstance(target_key, SchemaTargetKey) else SchemaTargetKey(*target_key)
    try:
        return _urlopen_with_retry(build_request(use_schema), timeout=timeout)
    except urllib.error.HTTPError as error:
        if use_schema and _is_schema_unsupported_http_error(error):
            error.close()
            logger.warning(
                "Structured output schema unsupported by provider=%s model=%s; "
                "downgrading to prompt-only JSON and memoizing target.",
                normalized_key.provider,
                normalized_key.model,
            )
            response = _urlopen_with_retry(build_request(False), timeout=timeout)
            _SCHEMA_UNSUPPORTED_TARGETS.add(normalized_key)
            return response
        raise


def _call_anthropic(prompt, model, max_tokens, temperature, response_schema=None, provenance=None):
    """Call the Messages API; ``provenance["model"]`` becomes the model that served the reply."""
    api_key = os.environ.get("ANTHROPIC_API_KEY", "")
    if not api_key:
        return None, "ANTHROPIC_API_KEY is required for the anthropic provider"
    target_url = _anthropic_url()
    target_key = SchemaTargetKey(provider="anthropic", base_url=target_url, model=model)
    use_schema = response_schema is not None and target_key not in _SCHEMA_UNSUPPORTED_TARGETS
    effort = _effective_reasoning_effort("anthropic", model, JUDGE_REASONING_EFFORT)
    # Server-side fallback (beta, native Claude API only): a safety-classifier
    # refusal is retried on the fallback model within the same call.
    server_side_fallback = (
        _refusal_fallback_target(model)
        if _is_claude_5_5_or_later(model)
        and urlparse(target_url).hostname == "api.anthropic.com"
        and _builtin_refusal_fallback_allowed()
        else None
    )

    def _build_request(include_schema):
        payload = {
            "model": model,
            "max_tokens": max_tokens,
            "messages": [{"role": "user", "content": prompt}],
            "stream": False,
        }
        if temperature is not None and _supports_custom_temperature(model):
            payload["temperature"] = temperature
        output_config = _build_anthropic_output_config(response_schema) if include_schema else {}
        if effort is not None:
            output_config["effort"] = effort
        if output_config:
            payload["output_config"] = output_config
        headers = {
            "Content-Type": "application/json",
            "x-api-key": api_key,
            "anthropic-version": "2023-06-01",
        }
        if server_side_fallback:
            payload["fallbacks"] = [{"model": server_side_fallback}]
            headers["anthropic-beta"] = ANTHROPIC_SERVER_SIDE_FALLBACK_BETA
        return urllib.request.Request(target_url, data=json.dumps(payload).encode(), headers=headers)

    # _anthropic_url() validates the configured base URL before this request.
    raw_response = _urlopen_with_schema_fallback(
        _build_request,
        target_key=target_key,
        use_schema=use_schema,
        timeout=90,
    )
    body = json.loads(raw_response)
    if body.get("stop_reason") == "refusal":
        raise _JudgeRefusedError("judge model declined the request (stop_reason=refusal)")
    blocks = [block for block in body.get("content", []) if isinstance(block, dict)]
    served_model = None
    for block in blocks:
        served = block.get("to") if block.get("type") == "fallback" else None
        if isinstance(served, dict) and isinstance(served.get("model"), str) and served["model"]:
            served_model = served["model"]
    # A turn served by sticky routing, which sends repeats of a fallen-back
    # request straight to the fallback model, carries no fallback block; the
    # top-level model then names the model that wrote the reply.
    if served_model is None and server_side_fallback and isinstance(body.get("model"), str) and body["model"]:
        served_model = body["model"]
    if provenance is not None and served_model is not None:
        provenance["model"] = served_model
    content = "".join(str(block.get("text", "")) for block in blocks if block.get("type") == "text")
    return content.strip(), None


_RETRIABLE_BEDROCK_ERROR_CODES = frozenset(
    {
        "ThrottlingException",
        "Throttling",
        "TooManyRequestsException",
        "ServiceUnavailableException",
        "ServiceUnavailable",
        "InternalServerException",
        "InternalServerError",
        "InternalFailure",
        "ModelTimeoutException",
        "RequestTimeout",
        "RequestTimeoutException",
    }
)
_RETRIABLE_BOTOCORE_EXCEPTION_NAMES = frozenset(
    {
        "EndpointConnectionError",
        "ConnectionClosedError",
        "ReadTimeoutError",
        "ConnectTimeoutError",
    }
)


def _classify_bedrock_retry_error(error):
    """Return (is_retriable, status_label, retry_after_str) for a Bedrock Converse exception."""
    if isinstance(error, TimeoutError) and "LLM judge time budget exhausted" in str(error):
        return False, type(error).__name__, None
    if isinstance(error, (FileNotFoundError, IsADirectoryError, NotADirectoryError, PermissionError)):
        return False, type(error).__name__, None

    response = getattr(error, "response", None)
    if not isinstance(response, dict):
        response = {}
    metadata = response.get("ResponseMetadata")
    if not isinstance(metadata, dict):
        metadata = {}
    http_status = metadata.get("HTTPStatusCode")
    if not isinstance(http_status, int) or isinstance(http_status, bool):
        http_status = None

    err_info = response.get("Error")
    if not isinstance(err_info, dict):
        err_info = {}
    error_code = str(err_info.get("Code") or "").strip()

    headers = metadata.get("HTTPHeaders")
    retry_after_str = None
    if isinstance(headers, dict):
        for k, v in headers.items():
            if isinstance(k, str) and k.lower() == "retry-after" and v is not None:
                retry_after_str = str(v)
                break

    if http_status is not None or error_code:
        is_retriable = _is_retriable_http_status(http_status) or error_code in _RETRIABLE_BEDROCK_ERROR_CODES
        status_label = f"HTTP {http_status}" if http_status is not None else error_code
        return is_retriable, status_label, retry_after_str

    type_name = type(error).__name__
    is_network = not _is_certificate_failure(error) and (
        isinstance(error, (ConnectionError, TimeoutError, OSError)) or type_name in _RETRIABLE_BOTOCORE_EXCEPTION_NAMES
    )
    return is_network, type_name, None


_BEDROCK_ANTHROPIC_PREFIX_RE = re.compile(r"(?:(?:[a-z]{2}|global)\.)?anthropic\.")


def _bedrock_refusal_fallback_model(model):
    """Return the Bedrock refusal fallback ID for a Claude 5.5 or later model, else None.

    A bare name such as ``claude-opus-4-8`` gets the request model's geography
    prefix. A value that is already a Bedrock ID (``us.anthropic.``,
    ``global.anthropic.``, ``anthropic.``) is used as given.
    """
    prefix = _BEDROCK_ANTHROPIC_PREFIX_RE.match(str(model or ""))
    if prefix is None or not _is_claude_5_5_or_later(model):
        return None
    target = _refusal_fallback_target(model)
    if not target:
        return None
    bedrock_target = target if _BEDROCK_ANTHROPIC_PREFIX_RE.match(target) else prefix.group(0) + target
    # Compare the resolved Bedrock ID, not the configured leaf name, with the request model.
    return None if bedrock_target == str(model).strip() else bedrock_target


def _call_bedrock(prompt, model, max_tokens, temperature, timeout=90, provenance=None):
    """Call Bedrock Converse; ``provenance["model"]`` becomes the model that served the reply."""
    try:
        import boto3
    except ImportError:
        return None, "boto3 is required for the bedrock provider"
    BotoConfig = None
    with contextlib.suppress(ImportError):
        from botocore.config import Config as BotoConfig
    try:
        retry_config = _resolve_eval_retry_config()
        region_name = os.environ.get("AWS_REGION", "us-west-2")
        initial_timeout = _remaining_judge_timeout(timeout)
        client_kwargs = {"region_name": region_name}
        if BotoConfig is not None:
            client_kwargs["config"] = BotoConfig(
                connect_timeout=initial_timeout,
                read_timeout=initial_timeout,
                retries={"max_attempts": 0, "mode": "standard"},
            )
        try:
            client = boto3.client("bedrock-runtime", **client_kwargs)
        except TypeError:
            client = boto3.client("bedrock-runtime", region_name=region_name)

        inference_config = {"maxTokens": max_tokens}
        if temperature is not None and _supports_custom_temperature(model):
            inference_config["temperature"] = temperature

        def _converse(model_id):
            attempt = 0
            while True:
                request_timeout = _remaining_judge_timeout(timeout)
                endpoint = getattr(client, "_endpoint", None)
                if endpoint is not None and hasattr(endpoint, "timeout"):
                    endpoint.timeout = request_timeout
                _spend_strict_judge_request()
                try:
                    return client.converse(
                        modelId=model_id,
                        messages=[{"role": "user", "content": [{"text": prompt}]}],
                        inferenceConfig=inference_config,
                    )
                except Exception as error:
                    is_retriable, status_label, retry_after_str = _classify_bedrock_retry_error(error)
                    if (
                        attempt >= retry_config.max_retries
                        or not is_retriable
                        or not _strict_judge_retry_allowed(error)
                    ):
                        raise

                    sleep_duration = _compute_bounded_retry_delay(
                        retry_after_str,
                        attempt=attempt,
                        base_delay=retry_config.base_delay,
                        max_delay=retry_config.max_delay,
                        error=error,
                    )
                    logger.warning(
                        "LLM judge transient error (%s). Retrying in %.2fs (attempt %d/%d)...",
                        status_label,
                        sleep_duration,
                        attempt + 1,
                        retry_config.max_retries,
                    )
                    time.sleep(sleep_duration)
                    attempt += 1

        response = _converse(model)
        fallback_model = _bedrock_refusal_fallback_model(model) if _builtin_refusal_fallback_allowed() else None
        if response.get("stopReason") == "content_filtered" and fallback_model:
            # Bedrock has no server-side fallback, so retry a classifier refusal here.
            response = _converse(fallback_model)
            if provenance is not None:
                provenance["model"] = fallback_model
        if response.get("stopReason") == "content_filtered":
            raise _JudgeRefusedError("judge model declined the request (stopReason=content_filtered)")
        content = "".join(
            str(block.get("text", ""))
            for block in response.get("output", {}).get("message", {}).get("content", [])
            if isinstance(block, dict)
        )
        return content.strip(), None
    except _JudgeRefusedError:
        raise
    except Exception as exc:
        if _STRICT_JUDGE_REQUESTS_LEFT.get() is not None and _strict_judge_failure(exc, "bedrock")[1]:
            # The strict policy lets the next candidate answer for an unavailable model.
            raise
        return None, f"Bedrock request failed: {exc}"


def _selected_judge_model(model=None):
    return (
        model
        or os.environ.get("LLM_JUDGE_MODEL")
        or os.environ.get("SKILL_EVAL_JUDGE_MODEL")
        or os.environ.get("SKILL_EVAL_LLM_MODEL")
        or DEFAULT_JUDGE_MODELS.get(_public_provider(), DEFAULT_JUDGE_MODELS["openai"])
    )


def _call_openai_compatible(
    prompt, provider, model, max_tokens, temperature, response_schema=None, schema_name="judge_response"
):
    api_key = (
        os.environ.get("NVIDIA_API_KEY", "")
        if provider == "nv_build"
        else os.environ.get("SKILL_EVAL_LLM_API_KEY", "") or os.environ.get("OPENAI_API_KEY", "")
    )
    if not api_key:
        return None, f"No API key configured for {provider}"
    request_url = _resolve_url(provider)
    target_key = SchemaTargetKey(provider=provider, base_url=request_url, model=model)
    use_schema = response_schema is not None and target_key not in _SCHEMA_UNSUPPORTED_TARGETS

    def _build_request(include_schema, *, _key=api_key):
        payload = _chat_completion_payload(
            model,
            prompt,
            max_tokens,
            temperature,
            provider=provider,
            request_url=request_url,
            response_schema=response_schema if include_schema else None,
            schema_name=schema_name,
        )
        return urllib.request.Request(
            request_url,
            data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json", "Authorization": f"Bearer {_key}"},
        )

    # request_url was validated by _resolve_url() before this request.
    try:
        raw_response = _urlopen_with_schema_fallback(
            _build_request,
            target_key=target_key,
            use_schema=use_schema,
            timeout=90,
        )
    except urllib.error.HTTPError as http_err:
        if (
            http_err.code == 401
            and _is_vertex_openapi_url(request_url)
            and os.environ.get("SKILL_EVAL_LLM_CREDENTIAL_SOURCE", "").strip() == "ADC"
        ):
            logger.info("Vertex AI OpenAPI 401 received; attempting in-process ADC token refresh")
            refreshed_token = _get_vertex_access_token()
            if refreshed_token and refreshed_token != api_key:
                if "OPENAI_API_KEY" in os.environ:
                    os.environ["OPENAI_API_KEY"] = refreshed_token
                if "SKILL_EVAL_LLM_API_KEY" in os.environ:
                    os.environ["SKILL_EVAL_LLM_API_KEY"] = refreshed_token
                raw_response = _urlopen_with_schema_fallback(
                    partial(_build_request, _key=refreshed_token),
                    target_key=target_key,
                    use_schema=use_schema,
                    timeout=90,
                )
            else:
                raise
        else:
            raise
    body = json.loads(raw_response)
    choices = body.get("choices") or [{}]
    first_choice = choices[0] if choices and isinstance(choices[0], dict) else {}
    message = first_choice.get("message")
    refusal = message.get("refusal") if isinstance(message, dict) else None
    if first_choice.get("finish_reason") == "content_filter" or (isinstance(refusal, str) and refusal):
        raise _JudgeRefusedError(
            f"judge model declined the request (finish_reason={first_choice.get('finish_reason')})"
        )
    content = message.get("content", "") if isinstance(message, dict) else ""
    if content is None:
        content = ""
    return content.strip(), None


def _record_judge_call(provenance, requested_model, sent_model):
    """Record the model that answered for the required judge in progress (see _call_required_judge)."""
    calls = _ACTIVE_JUDGE_CALLS.get()
    if calls is not None:
        calls.append(
            {
                "model": provenance["model"],
                "reasoning_effort": _effective_reasoning_effort(
                    provenance["provider"], sent_model, JUDGE_REASONING_EFFORT
                ),
                "fallback_used": provenance["model"] != requested_model,
            }
        )


def _call_judge_model(prompt, provider, model, max_tokens, temperature, response_schema, schema_name, provenance):
    """Send one judge prompt to *model*; ``provenance["model"]`` becomes the model that answered."""
    if provider == "anthropic":
        return _call_anthropic(
            prompt,
            model,
            max_tokens,
            temperature,
            response_schema=response_schema,
            provenance=provenance,
        )
    if provider == "bedrock":
        return _call_bedrock(prompt, model, max_tokens, temperature, provenance=provenance)
    return _call_openai_compatible(
        prompt,
        provider,
        model,
        max_tokens,
        temperature,
        response_schema=response_schema,
        schema_name=schema_name,
    )


def _strict_judge_failure(error, provider=None):
    """Describe a failed strict judge request and whether the next candidate may answer instead.

    Only unavailability moves on: a transient HTTP status, connection failure
    or Bedrock throttling that outlasted its one retry, a model the provider
    does not have or the key cannot use (_should_try_fallback and
    _strict_model_unavailable), or a used-up per-model request limit.
    Everything else ends the judge. A Bedrock error keeps the
    "Bedrock request failed" label that _call_bedrock gives the errors it
    returns, so a model that moved on reads the same as one that ended the judge.
    """
    if isinstance(error, _JudgeRefusedError):
        return str(error), False
    if isinstance(error, _StrictJudgeRequestLimitError):
        return str(error), True
    if isinstance(error, urllib.error.HTTPError):
        detail, model_unavailable = _format_http_error_with_fallback(error)
        if _strict_judge_error_stops(error):
            return detail, False
        return detail, model_unavailable or _strict_model_unavailable(error) or _is_retriable_http_status(error.code)
    label = "Bedrock request failed" if provider == "bedrock" else "Public provider call failed"
    detail = f"{label}: {error}"
    if isinstance(error, TimeoutError) and "LLM judge time budget exhausted" in str(error):
        return detail, False
    if _is_certificate_failure(error) or _strict_judge_error_stops(error):
        return detail, False
    if isinstance(error, (urllib.error.URLError, OSError)):
        return detail, True
    # Bedrock throttling and service errors (see _call_bedrock), or a model it cannot serve.
    return detail, _classify_bedrock_retry_error(error)[0] or _strict_model_unavailable(error)


def _call_strict_judge(provider, requested_model, models, call_model):
    """Ask the judge under LLM_JUDGE_RETRY_POLICY=strict.

    At most _STRICT_JUDGE_MAX_MODELS candidates are tried, the primary first,
    with at most _STRICT_JUDGE_REQUESTS_PER_MODEL requests to each, all inside
    the judge's wall-time budget. See _strict_judge_failure for which failures
    move on to the next candidate. The first completed reply is final, even an
    empty or invalid one: a second request from the same required judge, such
    as behavior_check's format retry, is not sent, so no other model can
    overturn the reply.
    """
    calls = _ACTIVE_JUDGE_CALLS.get()
    if calls:
        return (
            None,
            "LLM_JUDGE_RETRY_POLICY=strict accepts one completed reply per judge, so the judge's retry was not sent",
            {"provider": provider, "model": calls[-1]["model"]},
        )
    errors = []
    provenance = {"provider": provider, "model": requested_model}
    for candidate_model in models[:_STRICT_JUDGE_MAX_MODELS]:
        provenance = {"provider": provider, "model": candidate_model}
        requests_left = _STRICT_JUDGE_REQUESTS_LEFT.set([_STRICT_JUDGE_REQUESTS_PER_MODEL])
        try:
            content, error = call_model(candidate_model, provenance)
        except Exception as exc:
            detail, move_on = _strict_judge_failure(exc, provider)
            errors.append(f"{candidate_model}: {detail}")
            if not move_on:
                # Keep the earlier models' errors, so the reason shows why they were passed over.
                return None, _redact_configured_credentials(" | ".join(errors)), provenance
            continue
        finally:
            _STRICT_JUDGE_REQUESTS_LEFT.reset(requests_left)
        if error:
            if errors:
                error = " | ".join([*errors, f"{candidate_model}: {error}"])
            return None, _redact_configured_credentials(error), provenance
        if candidate_model != requested_model:
            logger.warning("LLM judge model %s failed; using fallback model %s", requested_model, candidate_model)
        _record_judge_call(provenance, requested_model, candidate_model)
        return content, None, provenance
    detail = "LLM judge model fallback exhausted: " + " | ".join(errors)
    return None, _redact_configured_credentials(detail), provenance


def _call_public_llm_with_provenance(
    prompt,
    model=None,
    max_tokens=4096,
    temperature=0.0,
    allow_model_fallback=True,
    response_schema=None,
    schema_name="judge_response",
):
    provider = _public_provider()
    if not provider:
        return None, _public_provider_error(), {}
    try:
        # An invalid policy value fails closed before any request is sent.
        _judge_fallback_policy()
        strict = _judge_retry_policy() == "strict"
    except ValueError as error:
        return None, str(error), {}
    requested_model = _selected_judge_model(model)
    models = _fallback_models(requested_model) if allow_model_fallback else [requested_model]

    def call_model(candidate_model, provenance):
        return _call_judge_model(
            prompt, provider, candidate_model, max_tokens, temperature, response_schema, schema_name, provenance
        )

    if strict:
        return _call_strict_judge(provider, requested_model, models, call_model)
    errors = []
    last_provenance = {"provider": provider, "model": requested_model}
    for candidate_model in models:
        provenance = {"provider": provider, "model": candidate_model}
        last_provenance = provenance
        try:
            content, error = call_model(candidate_model, provenance)
        except _JudgeRefusedError as refusal:
            # A classifier refusal is fallback-eligible like a missing model.
            errors.append(f"{candidate_model}: {refusal}")
            if not allow_model_fallback:
                return None, str(refusal), provenance
            continue
        except urllib.error.HTTPError as http_error:
            detail, should_try_fallback = _format_http_error_with_fallback(http_error)
            errors.append(f"{candidate_model}: {detail}")
            if not allow_model_fallback or not should_try_fallback:
                return None, detail, provenance
            continue
        except Exception as exc:
            detail = f"Public provider call failed for {candidate_model}: {exc}"
            return None, _redact_configured_credentials(detail), provenance
        if error:
            return None, _redact_configured_credentials(error), provenance
        if not content and candidate_model != models[-1]:
            # So is an empty reply, for example reasoning that used up the output budget.
            errors.append(f"{candidate_model}: empty response")
            continue
        if candidate_model != requested_model:
            logger.warning("LLM judge model %s failed; using fallback model %s", requested_model, candidate_model)
        _record_judge_call(provenance, requested_model, candidate_model)
        return content, None, provenance
    detail = "LLM judge model fallback exhausted: " + " | ".join(errors)
    return None, _redact_configured_credentials(detail), last_provenance


def call_public_llm(
    prompt,
    model=None,
    max_tokens=4096,
    temperature=0.0,
    allow_model_fallback=True,
    response_schema=None,
    schema_name="judge_response",
):
    content, error, _provenance = _call_public_llm_with_provenance(
        prompt,
        model=model,
        max_tokens=max_tokens,
        temperature=temperature,
        allow_model_fallback=allow_model_fallback,
        response_schema=response_schema,
        schema_name=schema_name,
    )
    return content, error


_JSON_WHITESPACE = " \t\r\n"
_MAX_JSON_TEXT_CHARS = 100_000
_MAX_JSON_NESTING = 128
_JSON_NUMBER_PREFIX_RE = re.compile(r"-?(?:(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]*)?|(?:0|[1-9][0-9]*)\.)?")


def _balanced_json_container_end(text, start):
    """Return the exclusive end of one bounded structural container."""
    if start >= len(text) or text[start] not in "{[":
        return None
    stack = []
    in_string = False
    escaped = False
    for i in range(start, len(text)):
        ch = text[i]
        if in_string:
            if escaped:
                escaped = False
            elif ch == "\\":
                escaped = True
            elif ch == '"':
                in_string = False
        elif ch == '"':
            in_string = True
        elif ch in "{[":
            stack.append(ch)
            if len(stack) > _MAX_JSON_NESTING:
                return None
        elif ch in "}]":
            expected = "{" if ch == "}" else "["
            if not stack or stack[-1] != expected:
                return None
            stack.pop()
            if not stack:
                return i + 1
    return None


def _reject_duplicate_object_pairs(pairs):
    """Build an object while rejecting ambiguous duplicate members."""
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("Duplicate JSON object member")
        result[key] = value
    return result


def _reject_nonstandard_json_constant(_value):
    raise ValueError("Non-standard JSON constant")


def _parse_finite_json_float(value):
    parsed = float(value)
    if not math.isfinite(parsed):
        raise ValueError("JSON number overflowed to a non-finite value")
    return parsed


def _json_nesting_within_limit(text):
    """Bound structural nesting without recursively parsing partial JSON."""
    depth = 0
    in_string = False
    escaped = False
    for character in text:
        if in_string:
            if escaped:
                escaped = False
            elif character == "\\":
                escaped = True
            elif character == '"':
                in_string = False
        elif character == '"':
            in_string = True
        elif character in "{[":
            depth += 1
            if depth > _MAX_JSON_NESTING:
                return False
        elif character in "}]" and depth:
            depth -= 1
    return True


def _parse_whole_json_object(text):
    """Return *text* parsed as one JSON object, or None when it holds anything else."""
    if not text.startswith("{") or not _json_nesting_within_limit(text):
        return None
    try:
        parsed = json.loads(
            text,
            object_pairs_hook=_reject_duplicate_object_pairs,
            parse_constant=_reject_nonstandard_json_constant,
            parse_float=_parse_finite_json_float,
        )
    except (json.JSONDecodeError, RecursionError, ValueError):
        return None
    return parsed if isinstance(parsed, dict) else None


def extract_json(text):
    """Extract a JSON payload from LLM response text.

    Tolerates markdown fences and prose around exactly one valid bounded JSON
    container. Multiple complete documents are ambiguous, and an unfinished
    earlier structural segment blocks promotion of a nested object. Top-level
    arrays parse through unchanged; judge callers must dict-check the result
    themselves. Under LLM_JUDGE_RETRY_POLICY=strict the whole reply, apart
    from surrounding whitespace, must be one JSON object.
    """
    text = (text or "").strip()
    if not text or len(text) > _MAX_JSON_TEXT_CHARS:
        return None
    if _strict_judge_replies():
        return _parse_whole_json_object(text)

    documents = []
    index = 0
    while index < len(text):
        if text[index] not in "{[":
            index += 1
            continue
        end = _balanced_json_container_end(text, index)
        if end is None:
            return documents[0] if documents else None
        candidate = text[index:end]
        try:
            parsed = json.loads(
                candidate,
                object_pairs_hook=_reject_duplicate_object_pairs,
                parse_constant=_reject_nonstandard_json_constant,
                parse_float=_parse_finite_json_float,
            )
        except (json.JSONDecodeError, RecursionError, ValueError):
            index = end
            continue
        if isinstance(parsed, (dict, list)):
            documents.append(parsed)
            if len(documents) > 1:
                return None
        index = end
    return documents[0] if documents else None


def _is_json_string_prefix(text):
    """Return whether an unfinished bounded string can be completed as JSON."""
    if not text.startswith('"'):
        return False
    index = 1
    while index < len(text):
        character = text[index]
        if ord(character) < 0x20 or character == '"':
            return False
        if character != "\\":
            index += 1
            continue
        index += 1
        if index >= len(text):
            return True
        escape = text[index]
        if escape == "u":
            for offset in range(1, 5):
                if index + offset >= len(text):
                    return True
                if text[index + offset] not in "0123456789abcdefABCDEF":
                    return False
            index += 5
        elif escape in '"\\/bfnrt':
            index += 1
        else:
            return False
    return True


def _is_json_scalar_prefix(text):
    if not text:
        return True
    if text.startswith('"'):
        return _is_json_string_prefix(text)
    literals = {"t": "true", "f": "false", "n": "null"}
    if text[0] in literals:
        return literals[text[0]].startswith(text)
    if text[0] == "-" or text[0] in "0123456789":
        return _JSON_NUMBER_PREFIX_RE.fullmatch(text) is not None
    return False


def _is_append_only_json_object_prefix(fragment):
    """Validate an unfinished flat result entry using bounded decoder steps."""
    if not fragment or len(fragment) > _MAX_JSON_TEXT_CHARS:
        return False

    decoder = json.JSONDecoder(
        object_pairs_hook=_reject_duplicate_object_pairs,
        parse_constant=_reject_nonstandard_json_constant,
        parse_float=_parse_finite_json_float,
    )

    def _skip_whitespace(index):
        while index < len(fragment) and fragment[index] in _JSON_WHITESPACE:
            index += 1
        return index

    index = _skip_whitespace(0)
    if index >= len(fragment) or fragment[index] != "{":
        return False
    index += 1
    keys = set()
    while True:
        index = _skip_whitespace(index)
        if index >= len(fragment):
            return True
        if fragment[index] == "}":
            return False
        try:
            key, next_index = decoder.raw_decode(fragment, index)
        except (json.JSONDecodeError, RecursionError, ValueError):
            return _is_json_string_prefix(fragment[index:])
        if not isinstance(key, str) or key in keys:
            return False
        keys.add(key)
        index = _skip_whitespace(next_index)
        if index >= len(fragment):
            return True
        if fragment[index] != ":":
            return False
        index = _skip_whitespace(index + 1)
        if index >= len(fragment):
            return True
        value_start = index
        try:
            value, next_index = decoder.raw_decode(fragment, index)
        except (json.JSONDecodeError, RecursionError, ValueError):
            return _is_json_scalar_prefix(fragment[value_start:])
        if (
            isinstance(value, (int, float))
            and not isinstance(value, bool)
            and next_index < len(fragment)
            and fragment[next_index] in ".eE"
        ):
            return _JSON_NUMBER_PREFIX_RE.fullmatch(fragment[value_start:]) is not None
        index = _skip_whitespace(next_index)
        if index >= len(fragment):
            return True
        if fragment[index] == "}":
            return False
        if fragment[index] != ",":
            return False
        index += 1


def _salvage_behavior_results(text):
    """Recover complete per-behavior entries from a truncated ``results`` array.

    Reasoning judges that hit the output-token cap emit ``{"results": [...`` and
    stop mid-entry (``finish_reason="length"``); every fully-formed ``{...}``
    entry before the cut is still valid JSON and can be scored. The strict
    judge policy scores only complete replies, so nothing is salvaged under it.
    """
    if _strict_judge_replies():
        return []
    text = text or ""
    if len(text) > _MAX_JSON_TEXT_CHARS or not _json_nesting_within_limit(text):
        return []
    object_start = text.find("{")
    if object_start == -1:
        return []
    if any(character in "[]{}" for character in text[:object_start]):
        return []

    decoder = json.JSONDecoder(
        object_pairs_hook=_reject_duplicate_object_pairs,
        parse_constant=_reject_nonstandard_json_constant,
        parse_float=_parse_finite_json_float,
    )

    def _skip_whitespace(index):
        while index < len(text) and text[index] in " \t\r\n":
            index += 1
        return index

    # Parse only complete top-level fields preceding ``results``. This rejects
    # nested/unrelated arrays and lets us validate a score emitted before the
    # array without requiring the outer object itself to be complete.
    i = object_start + 1
    array_start = None
    seen_keys = set()
    while i < len(text):
        i = _skip_whitespace(i)
        try:
            key, i = decoder.raw_decode(text, i)
        except (json.JSONDecodeError, RecursionError, ValueError):
            return []
        if not isinstance(key, str):
            return []
        if key in seen_keys:
            return []
        seen_keys.add(key)
        i = _skip_whitespace(i)
        if i >= len(text) or text[i] != ":":
            return []
        i = _skip_whitespace(i + 1)
        if key == "results":
            if i >= len(text) or text[i] != "[":
                return []
            array_start = i
            break
        try:
            value, i = decoder.raw_decode(text, i)
        except (json.JSONDecodeError, RecursionError, ValueError):
            return []
        if key == "score" and _finite_score(value) is None:
            return []
        i = _skip_whitespace(i)
        if i >= len(text) or text[i] != ",":
            return []
        i += 1

    if array_start is None:
        return []

    results = []
    i = array_start + 1
    while True:
        i = _skip_whitespace(i)
        if i >= len(text):
            return results
        if text[i] != "{":
            return []
        try:
            entry, i = decoder.raw_decode(text, i)
        except (json.JSONDecodeError, RecursionError, ValueError):
            return results if _is_append_only_json_object_prefix(text[i:]) else []
        if not isinstance(entry, dict):
            return []
        results.append(entry)
        i = _skip_whitespace(i)
        if i >= len(text):
            return results
        # Salvage is only for an array truncated before its closing bracket.
        # A closed results array with a malformed outer object is not partial
        # per-entry output and must take the structured-error path.
        if text[i] == "]":
            return []
        if text[i] != ",":
            return []
        i = _skip_whitespace(i + 1)
        if i >= len(text):
            return results
        if text[i] == "]":
            return []


def _resolve_acceptable_skills(entry, expected_skill=None):
    raw = entry.get("acceptable_skills")
    if raw is None:
        raw = entry.get("acceptable_alternates")
    return _accepted_skill_names(expected_skill or entry.get("expected_skill"), raw)


# Keep in sync with skillevaluator.provider_config.MAX_COMPLETION_TOKENS (drift test).
STRUCTURED_JUDGE_MAX_TOKENS = 16384
# Saved judge evidence is bounded so one long prompt cannot bloat the verifier output.
JUDGE_EVIDENCE_PROMPT_CHARS = 16000
JUDGE_EVIDENCE_REPLY_CHARS = 8000
JUDGE_ATTEMPTS_FILE_NAME = "judge_attempts.json"
_JUDGE_PROBLEM_CHARS = 300


def _judge_retry_feedback(problem):
    """Retry instruction that names what was wrong with the previous reply."""
    return (
        f"\n\nIMPORTANT: Your previous reply could not be parsed or validated: {problem[:_JUDGE_PROBLEM_CHARS]}. "
        "Respond with ONLY the minified JSON object on a single line in the shape described above -- "
        "no markdown fences, no prose, no score field, and keep explanations brief."
    )


# RAGAS writes its input into the prompt as JSON, and tool-call arguments are
# JSON, so a line break or tab in that text arrives as the two characters "\n",
# "\r" or "\t". A header, flag or key that starts a line there follows the
# letter of the escape, where patterns that need a line start, a space or a
# word boundary before it do not match. So once the whole text is masked, the
# text between these escapes is masked again as lines of their own.
_JUDGE_EVIDENCE_ESCAPE_RE = re.compile(r"(\\[nrt])")


def _mask_judge_evidence_text(text):
    """Mask credentials in *text* read as one piece."""
    # Share finding credential semantics without imposing the finding scanner's
    # 2,000-character input budget on the longer judge prompt and reply budgets.
    redacted = _shared_checks._mask_finding_evidence_credentials_as_written(text, preserve_header_format=True)
    redacted = _redact_configured_credentials(_redact_evidence_text(redacted))
    for pattern in _SECRET_PATTERNS:
        redacted = pattern.sub("<redacted>", redacted)
    return redacted


def _mask_judge_evidence_line(text):
    """Mask credentials in the text between two escapes, which is not trimmed."""
    redacted = _shared_checks._mask_finding_evidence_credentials_as_written(text, preserve_header_format=True)
    redacted = redact_secrets_in_log_line(redacted)
    for pattern in _SECRET_PATTERNS:
        redacted = pattern.sub("<redacted>", redacted)
    return redacted


# The markers the line pass writes in place of a value. The JWT pattern writes
# "jwt-" before its marker, and markers next to each other are read as one.
_JUDGE_EVIDENCE_LINE_MARKERS_RE = re.compile(
    r"(?:(?:jwt-)?<redacted>|" + re.escape(_shared_checks._FINDING_EVIDENCE_PRIVATE_KEY_MARKER) + r")+"
)
# An unquoted value ends at whitespace, a quote, a backtick or a shell
# operator, unless a backslash escapes it.
_JUDGE_EVIDENCE_VALUE_END_RE = re.compile(r"[\s'\"`;|&()<>]")
# The text after a marker runs to the next escape or marker.
_JUDGE_EVIDENCE_SITE_END_RE = re.compile(
    _JUDGE_EVIDENCE_ESCAPE_RE.pattern + "|" + _JUDGE_EVIDENCE_LINE_MARKERS_RE.pattern
)


def _judge_evidence_line_value_spans(text, masked):
    """Return *text* as the line pass read it, and the spans of the values it replaced there to write *masked*.

    The line pass only replaces values with markers, so the text between two
    markers is found in *text* in order, and what lies between is a value.
    """
    # The shared masker reads the text without its shell line continuations.
    text = _shared_checks._LINE_CONTINUATION_RE.sub("", text)
    kept = _JUDGE_EVIDENCE_LINE_MARKERS_RE.split(masked)
    start = len(kept[0])
    end = len(text) - len(kept[-1])
    if len(kept) == 1 or start > end or not text.startswith(kept[0]) or not text.endswith(kept[-1]):
        return text, []
    spans = []
    for between in kept[1:-1]:
        found = text.find(between, start, end)
        if found < 0:
            return text, spans
        spans.append((start, found))
        start = found + len(between)
    spans.append((start, end))
    return text, spans


def _judge_evidence_value_sites(lines, mask_line):
    """Map the text that each of *lines* can leave after a marker to the spans of the values to mask in it.

    When an unquoted value that ends the line before reads on into a line,
    it stops at whitespace, a quote, a backtick or a shell operator. So the
    text left after its marker is the rest of the line from one of those
    characters, up to the next value that is masked there, or to the line end.
    """
    sites = {}
    for line in dict.fromkeys(lines):
        masked = mask_line(line) if line else line
        if masked == line:
            continue
        line, spans = _judge_evidence_line_value_spans(line, masked)
        # A backslash that ends a value is left in place, as it is usually
        # half of an escaped backslash: a line break escaped twice is "\\n",
        # and the line ends before its "\n".
        spans = [(start, start + len(line[start:end].rstrip("\\"))) for start, end in spans]
        spans = [
            (start, end)
            for start, end in spans
            if end > start and "<redacted" not in line[start:end] and _ERROR_REDACTION_MARKER not in line[start:end]
        ]
        if not spans:
            continue
        # The first place where each kind of character could end an unquoted
        # value that read on into the line, with and without a backslash
        # before it.
        stops = {}
        for found in _JUDGE_EVIDENCE_VALUE_END_RE.finditer(line, 0, spans[-1][0]):
            char = found.group()
            index = found.start()
            stops.setdefault((" " if char.isspace() else char, line[index - 1 : index] == "\\"), index)
        for stop in {0, *stops.values()}:
            following = [(start - stop, end - stop) for start, end in spans if start >= stop]
            if not following:
                continue
            rest = line[stop:]
            if len(following) > 1:
                sites.setdefault(rest[: following[1][0]], set()).add(following[0])
            sites.setdefault(rest, set()).update(following)
    return sites


def _mask_judge_evidence_value_sites(text, sites):
    """Mask the values of each text in *sites* that *text* holds between a marker and the next escape or marker."""
    spans = []
    after = None
    for found in _JUDGE_EVIDENCE_SITE_END_RE.finditer(text):
        if after is not None:
            rest = text[after : found.start()]
            values = sites.get(rest)
            if values is None and not found.group(1) and rest.endswith(("=", ":")):
                # Inside a quoted string the whole pass reads the unquoted value
                # of a name to the closing quote or line end, so it can leave
                # to the assignment rule a "_" flag value that the line, read
                # on its own, masks whole with that name ("--access_token
                # pass=..."). The rest then also matches without the word
                # that ends at the marker.
                cut = len(rest)
                while cut and _JUDGE_EVIDENCE_VALUE_END_RE.match(rest, cut - 1) is None:
                    cut -= 1
                values = sites.get(rest[:cut])
            spans.extend((after + start, after + end) for start, end in values or ())
        after = None if found.group(1) else found.end()
    if after is not None:
        spans.extend((after + start, after + end) for start, end in sites.get(text[after:], ()))
    if not spans:
        return text
    merged = []
    for start, end in sorted(spans):
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    parts = []
    pos = 0
    for start, end in merged:
        parts.extend((text[pos:start], "<redacted>"))
        pos = end
    parts.append(text[pos:])
    return "".join(parts)


def _redact_judge_evidence(text):
    """Mask credentials in a judge prompt, reply, or problem before it is saved."""
    text = str(text)
    # A RAGAS prompt or reply holds tool-call arguments escaped twice, so the
    # passes below also read the text with one and two levels of escapes
    # removed (see _mask_unescaped_views in checks.py). That reading only adds
    # markers to their result, so each pass reads the text as it did before:
    # masking a value earlier could move a later one out of a pattern's window
    # or hide the name that a later pass reads.
    return _shared_checks._mask_unescaped_views(
        text, _redact_judge_evidence_as_written(text), _redact_judge_evidence_as_written
    )


def _redact_judge_evidence_as_written(text):
    """Mask credentials in a judge prompt, reply, or problem as written."""
    # The whole text is masked first, so a form that runs over an escape (a
    # private key block, a continued or quoted value, a value that holds "\n"
    # or "\u00e4") is masked whole before the text is split at the escapes.
    redacted = _mask_judge_evidence_text(text)
    masked_lines = {}

    def mask_line(line):
        if line not in masked_lines:
            masked_lines[line] = _mask_judge_evidence_line(line)
        return masked_lines[line]

    parts = _JUDGE_EVIDENCE_ESCAPE_RE.split(redacted)
    if len(parts) > 1:
        # Text and escapes alternate.
        parts[::2] = [mask_line(part) if part else part for part in parts[::2]]
        redacted = "".join(parts)
    lines = _JUDGE_EVIDENCE_ESCAPE_RE.split(text)[::2]
    if len(lines) == 1:
        return redacted
    # An unquoted value at the end of a line reads on through the escape, so
    # the whole pass can mask the name that starts the next line with it:
    # "--password A\n--token B" becomes "--password <redacted> B", where B no
    # longer follows a name. The lines of the original text still hold the
    # name, so a value the line pass masks on such a line is masked where the
    # whole pass left it: in the rest of that line, which follows a marker.
    # Other copies of the value are left as the whole pass left them.
    sites = _judge_evidence_value_sites(lines[1:], mask_line)
    return _mask_judge_evidence_value_sites(redacted, sites) if sites else redacted


def _verifier_output_dir():
    """Directory that receives skill_evaluator_reward.json (see write_reward_outputs)."""
    if (
        SKILL_EVALUATOR_REWARD_JSON == VERIFIER_DIR / "skill_evaluator_reward.json"
        and REWARD_JSON.parent != VERIFIER_DIR
    ):
        return REWARD_JSON.parent
    return SKILL_EVALUATOR_REWARD_JSON.parent


def _record_judge_attempt(
    metric, attempt, *, prompt, reply, problem, method="llm", model=None, status=None, score=None
):
    """Save one judge attempt to judge_attempts.json while main() runs the judges.

    The file is rewritten after every attempt, so it also explains a judge that
    failed or a verifier that stopped mid-run. Saving evidence must never change
    a score, so write failures are only logged. A ``salvage`` entry records the
    usable part rebuilt from attempt *attempt*'s truncated reply.
    """
    attempts = _ACTIVE_JUDGE_EVIDENCE.get()
    if attempts is None:
        return
    if status is None:
        status = "error" if reply is None else "accepted" if problem is None else "rejected"
    entry = {
        "metric": metric,
        "attempt": attempt,
        "method": method,
        "model": model,
        "status": status,
        "problem": _truncate_for_behavior(_redact_judge_evidence(problem), 1000) if problem else None,
    }
    if prompt is not None:
        redacted_prompt = _redact_judge_evidence(prompt)
        entry["prompt_sha256"] = hashlib.sha256(redacted_prompt.encode("utf-8", "replace")).hexdigest()
        entry["prompt_chars"] = len(prompt)
        entry["prompt"] = _truncate_for_behavior(redacted_prompt, JUDGE_EVIDENCE_PROMPT_CHARS)
    if reply is not None:
        entry["reply_chars"] = len(reply)
        entry["reply"] = _truncate_for_behavior(_redact_judge_evidence(reply), JUDGE_EVIDENCE_REPLY_CHARS)
    if score is not None:
        entry["score"] = score
    attempts.append(entry)
    _write_judge_attempts(attempts)


def _write_judge_attempts(attempts):
    try:
        path = _verifier_output_dir() / JUDGE_ATTEMPTS_FILE_NAME
        path.parent.mkdir(parents=True, exist_ok=True)
        tmp_path = path.with_name(path.name + ".tmp")
        payload = {"judge_contract": JUDGE_CONTRACT, "attempts": attempts}
        tmp_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
        tmp_path.replace(path)
    except TimeoutError:
        # The required-judge deadline alarm, not a write failure.
        raise
    except (OSError, TypeError, ValueError) as error:
        logger.warning("Could not save judge evidence: %s", type(error).__name__)


def _judge_attempt_model(provenance=None, calls_before=None):
    """Return the model that answered an attempt, or the requested model when none did."""
    calls = _ACTIVE_JUDGE_CALLS.get()
    if calls is not None and calls_before is not None and len(calls) > calls_before:
        return calls[-1]["model"]
    if provenance and provenance.get("model"):
        return provenance["model"]
    return _selected_judge_model()


def _call_validated_json_judge(prompt, validate, call, extract, *, metric="judge", salvage=None, **call_kwargs):
    """Invoke a JSON judge; on an invalid reply, retry once and name the problem.

    *validate* returns ``None`` for a usable reply or a short description of the
    problem, which the retry sends back to the judge. Provider errors are not
    retried here: the transport already retried them within its own budget.
    *salvage* may rebuild a usable reply from text that never parsed, such as a
    reply cut off by the output-token cap; it is tried only after both attempts.
    Under LLM_JUDGE_RETRY_POLICY=strict the first completed reply is final, so
    an invalid one fails the judge without a retry or a salvage.
    """
    call_kwargs.setdefault("max_tokens", STRUCTURED_JUDGE_MAX_TOKENS)
    unparsed_replies = []

    def invoke(attempt, call_prompt):
        calls = _ACTIVE_JUDGE_CALLS.get()
        calls_before = len(calls) if calls is not None else 0
        content, error, *metadata = call(call_prompt, **call_kwargs)
        provenance = metadata[0] if metadata and isinstance(metadata[0], dict) else {}
        parsed = extract(content) if content else None
        model = _judge_attempt_model(provenance, calls_before)
        problem = None
        if not error:
            problem = "the reply was empty" if not content else validate(parsed)
            if content and parsed is None:
                unparsed_replies.append((attempt, content, model))
        _record_judge_attempt(
            metric,
            attempt,
            prompt=call_prompt,
            reply=None if error else content or "",
            problem=error or problem,
            model=model,
        )
        return parsed, error, provenance, problem

    parsed, error, provenance, problem = invoke(1, prompt)
    if error:
        return None, f"LLM judge error: {error}", provenance
    if problem is None:
        return parsed, None, provenance
    if _strict_judge_replies():
        return (
            None,
            f"Judge response was unparseable or invalid: {problem}; LLM_JUDGE_RETRY_POLICY=strict sends no retry",
            provenance,
        )

    parsed, error, provenance, problem = invoke(2, prompt + _judge_retry_feedback(problem))
    if not error and problem is None:
        return parsed, None, provenance
    if salvage is not None:
        # Newest first: only text that never parsed can be a reply cut off mid-object.
        for attempt, text, model in reversed(unparsed_replies):
            candidate = salvage(text)
            if candidate is not None:
                # The LLM attempts were saved with their own status (rejected,
                # or error if the retry failed in transport); this entry shows
                # that the score comes from the part of *attempt*'s reply that
                # was rebuilt.
                _record_judge_attempt(
                    metric,
                    attempt,
                    prompt=None,
                    reply=json.dumps(candidate),
                    problem=None,
                    method="salvage",
                    model=model,
                    status="accepted",
                )
                return candidate, None, provenance
    if error:
        return None, f"LLM judge retry error: {error}", provenance
    return None, f"Judge response was unparseable or invalid after retry: {problem}", provenance


# ── LLM Judge: Accuracy (5-criterion) ────────────────────────────────────────

# Accuracy grades the outcome only. Whether the agent found and used the skill is
# scored by skill_execution, so a correct answer from the no-skill baseline can
# reach 1.0 here.
_ACCURACY_CRITERIA = (
    ("ACTION_CORRECT", "Does the response describe or carry out the correct actions or commands for the task?"),
    ("FACTUALLY_ACCURATE", "Are the factual claims consistent with the expected answer?"),
    ("TASK_ADDRESSED", "Does the response directly address the user's request?"),
    ("ACTIONABLE", "Does the response give usable results or next steps, not just an acknowledgment?"),
    (
        "FORMAT_FOLLOWED",
        "If the USER QUESTION explicitly requires an output format (a template, prefix, fields, ordering, "
        "or units), does the response follow it? When the question requires no specific format, answer true "
        "if the response gives an answer and false if it gives none.",
    ),
)
_ACCURACY_CRITERIA_KEYS = frozenset(key for key, _question in _ACCURACY_CRITERIA)


def _accuracy_payload_error(parsed):
    """Describe what is wrong with an accuracy reply, or return ``None`` when it is usable.

    The score is computed from the five verdicts, so a ``score`` field in the
    reply is ignored rather than trusted.
    """
    if not isinstance(parsed, dict):
        return "the reply did not contain one JSON object"
    criteria = parsed.get("criteria")
    if not isinstance(criteria, dict):
        return 'the reply has no "criteria" object'
    missing = sorted(_ACCURACY_CRITERIA_KEYS - criteria.keys())
    if missing:
        return f"criteria is missing {', '.join(missing)}"
    unexpected = sorted(str(key)[:40] for key in criteria.keys() - _ACCURACY_CRITERIA_KEYS)
    if unexpected:
        return f"criteria has unexpected keys {', '.join(unexpected[:5])}"
    not_boolean = sorted(key for key, value in criteria.items() if not isinstance(value, bool))
    if not_boolean:
        return f"criteria values must be true or false, not {', '.join(not_boolean)}"
    if "reason" in parsed and not isinstance(parsed["reason"], str):
        return '"reason" must be a string'
    return None


def _goal_payload_error(parsed):
    """Describe what is wrong with a goal reply, or return ``None`` when it is usable.

    Goal accuracy is binary, like RAGAS AgentGoalAccuracyWithReference: the
    score is 1.0 when ``achieved`` is true and 0.0 otherwise, so a ``score``
    field in the reply is ignored.
    """
    if not isinstance(parsed, dict):
        return "the reply did not contain one JSON object"
    if not isinstance(parsed.get("achieved"), bool):
        return '"achieved" must be true or false'
    for field in ("reason", "user_goal", "end_state"):
        if field in parsed and not isinstance(parsed[field], str):
            return f'"{field}" must be a string'
    return None


ACCURACY_JSON_SCHEMA = {
    "type": "object",
    "properties": {
        "criteria": {
            "type": "object",
            "properties": {key: {"type": "boolean"} for key, _question in _ACCURACY_CRITERIA},
            "required": [key for key, _question in _ACCURACY_CRITERIA],
            "additionalProperties": False,
        },
        "reason": {"type": "string"},
    },
    "required": ["criteria", "reason"],
    "additionalProperties": False,
}

GOAL_ACCURACY_JSON_SCHEMA = {
    "type": "object",
    "properties": {
        "user_goal": {"type": "string"},
        "end_state": {"type": "string"},
        "achieved": {"type": "boolean"},
        "reason": {"type": "string"},
    },
    "required": ["user_goal", "end_state", "achieved", "reason"],
    "additionalProperties": False,
}

BEHAVIOR_CHECK_JSON_SCHEMA = {
    "type": "object",
    "properties": {
        "results": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "step": {"type": "integer"},
                    "passed": {"type": ["boolean", "null"]},
                    "reason": {"type": "string"},
                },
                "required": ["step", "passed", "reason"],
                "additionalProperties": False,
            },
        },
        "summary": {"type": "string"},
    },
    "required": ["results", "summary"],
    "additionalProperties": False,
}


def judge_accuracy(question, ground_truth, agent_text, *, skill_identification_applicable=None):
    """Judge accuracy from five outcome verdicts; the score is computed here.

    *skill_identification_applicable* is deprecated and ignored. Accuracy no
    longer has a skill criterion, so every case and both arms use the same five
    criteria. The keyword is still accepted so existing callers keep working.
    """
    del skill_identification_applicable
    if not _has_judge_reference(ground_truth):
        return _judge_not_applicable(_NO_GROUND_TRUTH_REASON)
    criteria_text = "\n".join(
        f"{index}. {key}: {criterion}" for index, (key, criterion) in enumerate(_ACCURACY_CRITERIA, 1)
    )
    prompt = f"""You are an expert evaluator for AI agent responses. Check the response against \
the expected answer on each criterion below and decide true (satisfied) or false (not satisfied) for each.

{criteria_text}

Judge the outcome only. Do not reward or penalize the response for naming, or not naming, \
a tool or skill: that is scored separately.
If the evidence holds no answer to the question (for example, the agent stopped, timed out or \
refused), every criterion is false, unless the expected answer is itself a refusal.
Be lenient on wording, but strict on factual correctness and on any output format the user \
question explicitly requires.

For FORMAT_FOLLOWED, judge the entire final response literally against only the format explicitly \
required by the USER QUESTION, independently of factual correctness.
When a FINAL RESPONSE section is supplied, its contents are the final answer; other section \
headings, tool results, history, and artifacts are context, not part of that answer.
Inspect every line of the final response, including text after an initially valid answer. \
Line breaks do not end the final response. Do not mentally remove labels or Markdown fence characters \
when checking the stated format.
Do not extract a compliant answer from surrounding noncompliant text or substitute a correct \
value from tool output or the expected answer.
If only a number is required, extra prose, a label, or a code fence violates that requirement.
Required prefixes, units, or prose are valid when they match the stated format.
Wording leniency does not relax explicit format constraints.

Respond with ONLY one JSON object with a "criteria" object holding exactly these five keys, each \
true or false, and a one-sentence "reason". Do not include a score: it is computed from the criteria.
Example of the shape (the values are only an illustration):
{{"criteria": {{"ACTION_CORRECT": true, "FACTUALLY_ACCURATE": false, "TASK_ADDRESSED": true, "ACTIONABLE": true, \
"FORMAT_FOLLOWED": true}}, "reason": "Ran the right command but reported the wrong version number."}}

USER QUESTION:
{question}

EXPECTED ANSWER:
{ground_truth}

SELECTED EVIDENCE (final response + produced artifacts; low-relevance steps may be omitted):
{agent_text}"""

    prompt = append_character_facts(prompt, question=question, ground_truth=ground_truth, agent_text=agent_text)

    parsed, error, _provenance = _call_validated_json_judge(
        prompt,
        _accuracy_payload_error,
        call_public_llm,
        extract_json,
        metric="accuracy",
        response_schema=ACCURACY_JSON_SCHEMA,
        schema_name="accuracy_judgment",
    )
    if error:
        return _judge_error(error)

    criteria = {key: parsed["criteria"][key] for key, _question in _ACCURACY_CRITERIA}
    return {
        "score": round(sum(criteria.values()) / len(criteria), 4),
        "reason": _bounded_judge_text(parsed.get("reason", "")),
        "criteria": criteria,
    }


# ── LLM Judge: Goal Accuracy ─────────────────────────────────────────────────


def judge_goal_accuracy(question, ground_truth, agent_text, tool_summary=""):
    if not _has_judge_reference(ground_truth):
        return _judge_not_applicable(_NO_GROUND_TRUTH_REASON)

    if _ragas_goal_accuracy_enabled():
        try:
            result = _judge_goal_accuracy_ragas(question, ground_truth, agent_text, tool_summary)
            score = result.get("score") if isinstance(result, dict) else None
            if isinstance(score, bool) or score not in (0.0, 1.0):
                raise ValueError("RAGAS returned a non-binary goal accuracy score")
        except Exception as e:
            # The documented scorer changed for this trial, so say why where users will see it.
            detail = _redact_configured_credentials(f"{type(e).__name__}: {e}")[:_JUDGE_ERROR_REASON_LIMIT]
            logger.warning("RAGAS goal scorer failed (%s); using the custom goal judge", detail)
            problem = f"RAGAS failed ({type(e).__name__}: {e}); used the custom judge"
            _record_judge_attempt(
                "goal_accuracy",
                1,
                prompt=None,
                reply=None,
                problem=problem,
                method="ragas",
                model=_judge_attempt_model(),
            )
        else:
            _record_judge_attempt(
                "goal_accuracy",
                1,
                prompt=None,
                reply=None,
                problem=None,
                method="ragas",
                model=result.get("model") or _judge_attempt_model(),
                status="accepted",
                score=score,
            )
            return result
    return _judge_goal_accuracy_custom(question, ground_truth, agent_text, tool_summary)


def _ragas_goal_accuracy_enabled():
    """RAGAS is an OpenAI-only optimization, never an agent-key fallback.

    Reasoning judges reject the sampling settings RAGAS sends, so they use the prompt judge.
    """
    # The prompt judge can append metadata outside the original evidence.
    if character_facts_enabled():
        return False
    # RAGAS sends its own requests, outside the strict policy's request limits,
    # and an unknown policy value must fail the judge before any request.
    if _strict_judge_replies() or not _judge_policies_valid():
        return False
    if _public_provider() != "openai" or _is_openai_reasoning_model(_selected_judge_model()):
        return False
    try:
        request_url = _resolve_url("openai")
    except ValueError:
        return False
    return _is_native_openai_chat_url("openai", request_url)


def _ragas_message_text(message):
    content = message.get("content")
    if not isinstance(content, str):
        content = json.dumps(message.get("tool_calls") if content is None else content, default=str)
    return f"[{message.get('role', 'unknown')}]\n{content}"


def _ragas_request_text(body):
    """Return the judge model and the messages of one RAGAS chat-completions request as text."""
    try:
        request = json.loads(body)
        return request.get("model"), "\n\n".join(_ragas_message_text(message) for message in request["messages"])
    except (ValueError, LookupError, TypeError, AttributeError):
        return None, body.decode("utf-8", "replace")


def _ragas_reply_text(body):
    """Return the judge's answer in one chat-completions reply: its text, or the tool-call arguments RAGAS parses.

    A reply with neither, such as a refusal or a content-filter stop, is
    returned whole, so the refusal or the finish reason is kept.
    """
    try:
        message = json.loads(body)["choices"][0]["message"]
        if message.get("content"):
            return str(message["content"])
        if message.get("tool_calls"):
            return "\n".join(str(call["function"]["arguments"]) for call in message["tool_calls"])
    except (ValueError, LookupError, TypeError, AttributeError):
        pass
    return body.decode("utf-8", "replace")


def _record_ragas_exchange(response, problem=None):
    """Save one RAGAS judge request and its reply, or the HTTP error, as a goal_accuracy attempt.

    _record_judge_attempt redacts the full texts before it shortens them, so the
    error body is not cut here.
    """
    try:
        model, prompt = _ragas_request_text(response.request.content)
        reply = None
        if problem is None and response.is_success:
            reply = _ragas_reply_text(response.content)
        elif problem is None:
            problem = f"HTTP {response.status_code}: {response.text}"
        _record_judge_attempt(
            "goal_accuracy",
            1,
            prompt=prompt,
            reply=reply,
            problem=problem,
            method="ragas",
            model=model or _judge_attempt_model(),
            status="replied" if reply is not None else None,
        )
    except TimeoutError:
        # The required-judge deadline alarm, not an evidence failure.
        raise
    except Exception as error:
        # Saving evidence must never change a score or hide a provider error.
        logger.warning("Could not save RAGAS judge evidence: %s", type(error).__name__)


async def _save_ragas_exchange(response):
    """httpx response hook: RAGAS builds its own prompts and parses its own replies, so save both here."""
    try:
        await response.aread()
    except Exception as error:
        _record_ragas_exchange(response, f"the reply was not received ({type(error).__name__})")
        raise
    _record_ragas_exchange(response)


def _ragas_evidence_http_client(openai_module):
    """Return the SDK's default async HTTP client with the evidence hook, or None to score without evidence."""
    try:
        return openai_module.DefaultAsyncHttpxClient(event_hooks={"response": [_save_ragas_exchange]})
    except TimeoutError:
        raise
    except Exception as error:
        logger.warning("Could not save RAGAS judge evidence: %s", type(error).__name__)
        return None


def _judge_goal_accuracy_ragas(question, ground_truth, agent_text, tool_summary):
    """Use RAGAS AgentGoalAccuracyWithReference for high-quality two-step evaluation."""
    import asyncio

    import openai
    from openai import AsyncOpenAI
    from ragas.llms.base import llm_factory
    from ragas.messages import AIMessage as RagasAI
    from ragas.messages import HumanMessage as RagasHuman
    from ragas.metrics.collections import AgentGoalAccuracyWithReference

    if not _ragas_goal_accuracy_enabled():
        raise RuntimeError("RAGAS goal accuracy requires the selected canonical OpenAI provider")
    api_key = os.environ.get("OPENAI_API_KEY", "")
    if not api_key:
        raise RuntimeError("No OPENAI_API_KEY")

    request_url = _resolve_url("openai").rstrip("/")
    suffix = "/chat/completions"
    if not request_url.endswith(suffix) or not _is_native_openai_chat_url("openai", request_url):
        raise RuntimeError("RAGAS goal accuracy requires the selected canonical OpenAI provider")
    # The response hook saves each RAGAS request and reply to judge_attempts.json.
    # It runs in the loop below, whose tasks copy this context, so it sees the
    # verifier's judge evidence list. Closing the client also closes this one.
    client = AsyncOpenAI(
        api_key=api_key,
        base_url=request_url[: -len(suffix)],
        http_client=_ragas_evidence_http_client(openai),
    )
    loop = asyncio.new_event_loop()
    try:
        # Build the scorer inside the try so a setup failure still closes the client.
        judge_model = _selected_judge_model()
        llm = llm_factory(judge_model, client=client)
        metric = AgentGoalAccuracyWithReference(llm=llm)
        user_input = [
            RagasHuman(content=question),
            RagasAI(content=agent_text),
        ]
        # Collections metrics take the messages and reference as keywords, not a SingleTurnSample.
        scorer_timeout = _remaining_judge_timeout(_resolve_judge_wall_time_budget())
        result = loop.run_until_complete(
            asyncio.wait_for(
                metric.ascore(user_input=user_input, reference=ground_truth),
                timeout=scorer_timeout,
            )
        )
    finally:

        def consume_cleanup_task_exception(task):
            # Tasks can fail after a cleanup timeout; never let asyncio log their exception text.
            if not task.cancelled():
                task.exception()

        try:
            # The judge deadline alarm can stop the loop mid-score; cancel that work before closing the client.
            pending = asyncio.all_tasks(loop)
            for task in pending:
                task.add_done_callback(consume_cleanup_task_exception)
                task.cancel()
            if pending:
                _finished, unfinished = loop.run_until_complete(asyncio.wait(pending, timeout=5.0))
                if unfinished:
                    logger.warning("RAGAS judge task cancellation timed out: %d unfinished tasks", len(unfinished))
        except Exception as error:
            logger.warning("RAGAS judge task cancellation failed: %s", type(error).__name__)
        finally:
            try:
                # Closing the client must still be attempted if scoring tasks could not be drained.
                close_task = loop.create_task(client.close())
                close_task.add_done_callback(consume_cleanup_task_exception)
                _finished, unfinished = loop.run_until_complete(asyncio.wait({close_task}, timeout=5.0))
                if unfinished:
                    close_task.cancel()
                    logger.warning("RAGAS judge client close timed out")
                else:
                    close_task.result()
            except (Exception, asyncio.CancelledError) as error:
                # Cleanup must never hide the score or the scorer's own failure.
                logger.warning("RAGAS judge client close failed: %s", type(error).__name__)
            finally:
                loop.close()

    score = float(result.value) if hasattr(result, "value") else float(result)
    if score not in (0.0, 1.0):
        # Also rejects NaN; the caller then runs the prompt judge.
        raise ValueError("RAGAS returned a non-binary goal accuracy score")
    provenance = {"provider": "openai", "model": judge_model}
    _record_judge_call(provenance, judge_model, judge_model)
    return {
        "score": score,
        "reason": "RAGAS AgentGoalAccuracyWithReference",
        "achieved": score == 1.0,
        "method": "ragas",
        **provenance,
    }


def _judge_goal_accuracy_custom(question, ground_truth, agent_text, tool_summary):
    """Fallback: two-step custom prompt mirroring RAGAS logic, with the same binary score."""
    tool_section = f"\nAGENT'S TOOL CALLS:\n{tool_summary}\n" if str(tool_summary or "").strip() else ""
    prompt = f"""You are an evaluation judge. Decide whether an AI agent achieved the expected goal.

Step 1: State the user's goal.
Step 2: State the end state the agent reached.
Step 3: Decide whether that end state achieves the expected outcome.

USER REQUEST:
{question}

EXPECTED OUTCOME:
{ground_truth}
{tool_section}
END-STATE EVIDENCE:
{agent_text}

Respond with ONLY one JSON object with the keys "user_goal", "end_state", "achieved" (true or \
false) and a one-sentence "reason". Do not include a score: it is 1.0 when achieved and 0.0 otherwise.
Example of the shape (the values are only an illustration):
{{"user_goal": "List the open release blockers", "end_state": "Listed two of the three blockers", \
"achieved": false, "reason": "One blocker from the expected outcome is missing."}}"""
    prompt = append_character_facts(
        prompt, question=question, ground_truth=ground_truth, tool_summary=tool_summary, agent_text=agent_text
    )

    parsed, error, provenance = _call_validated_json_judge(
        prompt,
        _goal_payload_error,
        _call_public_llm_with_provenance,
        extract_json,
        metric="goal_accuracy",
        response_schema=GOAL_ACCURACY_JSON_SCHEMA,
        schema_name="goal_accuracy_judgment",
    )
    if error:
        return _judge_error(error, **provenance)

    achieved = parsed["achieved"]
    return {
        "score": 1.0 if achieved else 0.0,
        "reason": _bounded_judge_text(parsed.get("reason", "")),
        "achieved": achieved,
        "user_goal": _bounded_judge_text(parsed.get("user_goal", "")),
        "end_state": _bounded_judge_text(parsed.get("end_state", "")),
        "method": "custom",
        **provenance,
    }


# ── LLM Judge: Behavior Check ────────────────────────────────────────────────

# Reasoning judges (e.g. openai/openai/gpt-5*) spend completion budget on hidden
# reasoning tokens before emitting the per-behavior results array; the old 1024
# cap was observed live to truncate behavior_check output to EMPTY content
# (finish_reason="length", reasoning_tokens=1024).
BEHAVIOR_JUDGE_MAX_TOKENS = STRUCTURED_JUDGE_MAX_TOKENS


def _behavior_prompt_example(expected_count):
    """One entry per expected behavior, so the example is a valid reply if a judge copies it."""
    return json.dumps(
        {
            "results": [
                {
                    "step": step,
                    "passed": None if step % 3 == 0 else step % 3 == 1,
                    "reason": (
                        "Required tool output was not captured."
                        if step % 3 == 0
                        else "Seen in the transcript."
                        if step % 3 == 1
                        else "Observed output violates the requirement."
                    ),
                }
                for step in range(1, expected_count + 1)
            ],
            "summary": "A short summary of what was and was not observed.",
        }
    )


def judge_behavior_check(conversation_text, expected_behaviors, *, evidence_omitted=None):
    """Judge expected behaviors, or refuse when required evidence did not reach the judge.

    *evidence_omitted* is the behavior_check bundle's omission accounting. When
    it reports that required evidence is incomplete, no model is called and an
    explicit evaluation error is returned with no score: grading a shortened
    final answer scores the evidence loss, not the agent.
    """
    expected_behaviors = normalize_expected_behaviors(expected_behaviors)
    if not _has_judge_reference(expected_behaviors):
        return _judge_not_applicable(_NO_EXPECTED_BEHAVIOR_REASON, results=[])

    expected_count = len(expected_behaviors)
    behaviors_text = "\n".join(f"{i + 1}. {b}" for i, b in enumerate(expected_behaviors))

    gap = behavior_evidence_gap(evidence_omitted)
    if gap:
        return _judge_error(gap, results=[], expectations=_behavior_expectations(expected_behaviors, [], gap))

    conversation = _compact_behavior_conversation(conversation_text)
    if evidence_omitted is not None and conversation != conversation_text:
        # The bundle is built to fit this budget, so a second cut here would
        # drop evidence nothing has accounted for. Refuse rather than score it.
        second_cut = (
            "behavior_check evidence was shortened again inside the judge, past the omission accounting. "
            f"{_BEHAVIOR_EVIDENCE_GAP_HINT}"
        )
        return _judge_error(
            second_cut, results=[], expectations=_behavior_expectations(expected_behaviors, [], second_cut)
        )

    prompt = f"""You are evaluating whether an AI agent showed each expected behavior during a task. \
Read the conversation and decide, for each numbered behavior, whether it was observed.

CONVERSATION:
{conversation}

EXPECTED BEHAVIORS:
{behaviors_text}

For each numbered behavior, check only what that behavior requires.
A format-only behavior does not require the answer's value to be factually correct: a wrong value \
can still satisfy its format. If a behavior also requires factual correctness, evaluate that requirement too.
For a behavior about final-response format, judge the entire final response literally against only \
the stated format requirement, independently of factual correctness.
When a FINAL RESPONSE section is supplied, its contents are the final answer; other section \
headings, tool results, history, and artifacts are context, not part of that answer.
Inspect every line of the final response, including text after an initially valid answer. \
Line breaks do not end the final response. Do not mentally remove labels or Markdown fence characters \
when checking the stated format.
Do not extract a compliant answer from surrounding noncompliant text or substitute a correct \
value from tool output or the expected answer.
If only a number is required, extra prose, a label, or a code fence violates that requirement.
Required prefixes, units, or prose are valid when they match the stated format.
When the complete final response establishes a format violation, mark that behavior false; \
keep null when missing or incomplete evidence prevents checking it.
Before returning, ensure each passed value agrees with its reason: a reason establishing a violation \
requires false, not true; an evidence gap that prevents checking requires null.

Respond with ONLY one JSON object. "results" must hold exactly {expected_count} entries, one per \
expected behavior: "step" is the behavior's number (each number from 1 to {expected_count} exactly \
once), "passed" is true (observed), false (evidence supports a violation or absence), or null \
when missing or incomplete evidence prevents checking the behavior. Missing artifact contents, \
unavailable tool output, or a truncated trace require null, NOT false, for checks that depend on \
that evidence. A missing observation alone is not proof the behavior failed. Explain that evidence gap \
in "reason" (under 15 words). An unrelated task \
can be a valid negative control: evaluate its stated behavior without requiring skill use. Add a \
one-sentence "summary". Do not include a score: it is computed from the results.
Example of the shape for this task's {expected_count} behaviors (the values are only an illustration):
{_behavior_prompt_example(expected_count)}"""

    prompt = append_character_facts(prompt, conversation=conversation, expected_behaviors=behaviors_text)

    def salvage(text):
        # Complete entries from a reply cut off before its results array closed.
        salvaged = _salvage_behavior_results(text)
        candidate = {
            "results": salvaged,
            "summary": f"Salvaged {len(salvaged)}/{expected_count} behavior results from truncated judge response",
        }
        if not salvaged or _behavior_payload_error(candidate, expected_count, allow_partial=True):
            return None
        return candidate

    try:
        parsed, error, _provenance = _call_validated_json_judge(
            prompt,
            lambda payload: _behavior_payload_error(payload, expected_count),
            call_public_llm,
            extract_json,
            metric="behavior_check",
            salvage=salvage,
            max_tokens=BEHAVIOR_JUDGE_MAX_TOKENS,
            response_schema=BEHAVIOR_CHECK_JSON_SCHEMA,
            schema_name="behavior_check_judgment",
        )
    except Exception as exc:
        error = f"Required behavior_check judge raised {type(exc).__name__}: {exc}"
    if error:
        return _judge_error(error, results=[], expectations=_behavior_expectations(expected_behaviors, [], error))

    # Keep the conservative score denominator without calling missing verdicts failures.
    results = sorted(parsed["results"], key=lambda result: result["step"])
    score = sum(1 for result in results if result["passed"]) / expected_count
    return {
        "score": round(score, 4),
        "reason": parsed.get("summary", ""),
        "results": results,
        "expectations": _behavior_expectations(expected_behaviors, results),
    }


def _behavior_expectations(expected_behaviors, results, error=""):
    by_step = {result["step"]: result for result in results}
    return [
        {
            "step": step,
            "requirement": requirement,
            "status": ("met" if by_step[step]["passed"] else "unmet")
            if step in by_step and type(by_step[step]["passed"]) is bool
            else "not_checked",
            "reason": by_step[step].get("reason", "")
            if step in by_step
            else _redact_configured_credentials(error) or "No judgment returned for this expectation",
        }
        for step, requirement in enumerate(expected_behaviors, 1)
    ]


def _behavior_payload_error(parsed, expected_count, *, allow_partial=False):
    """Describe what is wrong with a behavior reply, or return ``None`` when it is usable.

    Each expected behavior is judged exactly once, identified by its 1-based
    ``step`` number, with a boolean ``passed`` or an explicit null abstention. *allow_partial* accepts a
    salvaged prefix that judges each of its steps once. The score is computed
    from the verdicts, so a ``score`` field in the reply is ignored.
    """
    if not isinstance(parsed, dict):
        return "the reply did not contain one JSON object"
    results = parsed.get("results")
    if not isinstance(results, list):
        return 'the reply has no "results" list'
    if allow_partial:
        if not results or len(results) > expected_count:
            return f'"results" has {len(results)} entries; it needs 1 to {expected_count}'
    elif len(results) != expected_count:
        return f'"results" has {len(results)} entries; it needs exactly {expected_count}, one per behavior'
    if any(not isinstance(result, dict) for result in results):
        return 'every "results" entry must be an object'
    if any(
        "passed" not in result or (result["passed"] is not None and type(result["passed"]) is not bool)
        for result in results
    ):
        return 'every "results" entry needs "passed" set to true, false, or null'
    if any(
        result["passed"] is None and (not isinstance(result.get("reason"), str) or not result["reason"].strip())
        for result in results
    ):
        return 'unchecked entries need a nonempty "reason" explaining the missing evidence'
    steps = [result.get("step") for result in results]
    if any(isinstance(step, bool) or not isinstance(step, int) for step in steps):
        return 'every "results" entry needs an integer "step" number'
    expected_steps = set(range(1, expected_count + 1))
    duplicated = sorted({step for step in steps if steps.count(step) > 1})
    unexpected = sorted(set(steps) - expected_steps)[:10]
    missing = [] if allow_partial else sorted(expected_steps - set(steps))[:10]
    if duplicated or missing or unexpected:
        parts = []
        if duplicated:
            parts.append(f"steps judged more than once: {duplicated[:10]}")
        if missing:
            parts.append(f"steps not judged: {missing}")
        if unexpected:
            parts.append(f"steps outside 1..{expected_count}: {unexpected}")
        return "; ".join(parts)
    if "summary" in parsed and not isinstance(parsed["summary"], str):
        return '"summary" must be a string'
    return None


# ── Main ─────────────────────────────────────────────────────────────────────


def _finite_reward_number(value):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return None
    try:
        numeric = float(value)
    except (OverflowError, ValueError):
        return None
    return numeric if math.isfinite(numeric) else None


def _normalize_required_judge_result(metric, result, *, allow_not_applicable=False):
    if isinstance(result, dict):
        normalized = dict(result)
        status = str(result.get("status", "")).casefold()
        status_is_error = status == "error"
        if status == NOT_APPLICABLE_STATUS and allow_not_applicable:
            # Only the verifier decides N/A (the case has no reference input);
            # the score is always null so it can never be averaged as 0 or 1.
            normalized["score"] = None
            normalized["status"] = NOT_APPLICABLE_STATUS
            normalized["reason"] = _bounded_judge_text(result.get("reason")) or f"{metric} is not applicable"
            return normalized
        score_is_valid = _finite_reward_number(result.get("score")) is not None
        if not status_is_error and status != NOT_APPLICABLE_STATUS and score_is_valid:
            return normalized
        supplied_reason = str(result.get("reason") or "").strip()
        if status == NOT_APPLICABLE_STATUS:
            reason = f"Required {metric} judge reported not_applicable although the eval case defines its reference"
        else:
            reason = supplied_reason if status_is_error else f"Required {metric} judge returned an invalid score"
            if supplied_reason and not status_is_error:
                reason = f"{reason}: {supplied_reason}"
    else:
        normalized = {}
        reason = f"Required {metric} judge returned an invalid result"

    normalized["score"] = None
    normalized["status"] = "error"
    normalized["reason"] = _judge_error(reason)["reason"]
    return normalized


def _call_required_judge(metric, judge, *args, allow_not_applicable=False, **kwargs):
    """Run a required LLM judge under a bounded wall-time deadline and normalize its result.

    The result records the model that produced it (``judge_model_used``), the
    reasoning effort sent, and whether a fallback model answered, so lift can
    leave out cases whose two arms were judged by different models.
    """
    previous_deadline = _ACTIVE_JUDGE_DEADLINE.get()
    own_deadline = time.monotonic() + _resolve_judge_wall_time_budget()
    deadline = min(previous_deadline, own_deadline) if previous_deadline is not None else own_deadline
    token = _ACTIVE_JUDGE_DEADLINE.set(deadline)
    calls = []
    calls_token = _ACTIVE_JUDGE_CALLS.set(calls)
    alarm_armed = False
    previous_alarm_handler = None

    # The standalone Harbor verifier runs judges on its main thread. Its
    # interval timer also interrupts a response body that keeps trickling data
    # inside one socket read, where urllib's idle timeout cannot help.
    try:
        try:
            if hasattr(signal, "setitimer") and threading.current_thread() is threading.main_thread():
                active_alarm, repeat_interval = signal.getitimer(signal.ITIMER_REAL)
                if active_alarm == 0 and repeat_interval == 0:
                    previous_alarm_handler = signal.getsignal(signal.SIGALRM)

                    def _raise_judge_timeout(_signum, _frame):
                        raise TimeoutError("LLM judge time budget exhausted")

                    signal.signal(signal.SIGALRM, _raise_judge_timeout)
                    try:
                        signal.setitimer(signal.ITIMER_REAL, max(deadline - time.monotonic(), 1e-6))
                        alarm_armed = True
                    except OSError:
                        signal.signal(signal.SIGALRM, previous_alarm_handler)
            result = judge(*args, **kwargs)
            # Dependency and logging handlers can swallow the alarm exception.
            # Never accept a result returned after this call's wall-time budget.
            if time.monotonic() >= deadline:
                raise TimeoutError("LLM judge time budget exhausted")
        finally:
            if alarm_armed:
                try:
                    signal.setitimer(signal.ITIMER_REAL, 0)
                finally:
                    signal.signal(signal.SIGALRM, previous_alarm_handler)
    except Exception as exc:
        error = f"Required {metric} judge raised {type(exc).__name__}: {exc}"
        metadata = {}
        if metric == "behavior_check":
            expected_behaviors = kwargs.get("expected_behaviors", args[1] if len(args) > 1 else [])
            metadata = {
                "results": [],
                "expectations": _behavior_expectations(expected_behaviors or [], [], error),
            }
        result = _judge_error(error, **metadata)
    finally:
        _ACTIVE_JUDGE_DEADLINE.reset(token)
        _ACTIVE_JUDGE_CALLS.reset(calls_token)
    normalized = _normalize_required_judge_result(metric, result, allow_not_applicable=allow_not_applicable)
    if calls:
        normalized["judge_model_used"] = calls[-1]["model"]
        normalized["judge_reasoning_effort"] = calls[-1]["reasoning_effort"]
        normalized["judge_fallback_used"] = any(call["fallback_used"] for call in calls)
    return normalized


NOT_APPLICABLE_STATUS = "not_applicable"


_NO_GROUND_TRUTH_REASON = "N/A: no ground_truth defined for this eval case"


_NO_EXPECTED_BEHAVIOR_REASON = "N/A: no expected_behavior defined for this eval case"


_JUDGED_METRICS = {
    "accuracy": ("ground_truth", _NO_GROUND_TRUTH_REASON),
    "goal_accuracy": ("ground_truth", _NO_GROUND_TRUTH_REASON),
    "behavior_check": ("expected_behavior", _NO_EXPECTED_BEHAVIOR_REASON),
}


SKILL_METRICS_NOT_APPLICABLE_REASON = (
    "N/A: this arm has no skill under test installed, so there is no skill to discover, run or route to"
)


_SCORE_POLICY_DIMENSIONS = (
    ("security",),
    ("accuracy",),
    ("skill_execution",),
    ("goal_accuracy", "behavior_check"),
    ("skill_efficiency",),
)


def _judge_not_applicable(reason, **metadata):
    """Return a scoreless result for a judge that has nothing to judge against."""
    return {**metadata, "score": None, "status": NOT_APPLICABLE_STATUS, "reason": reason}


def _has_judge_reference(value):
    """Return whether a ground_truth / expected_behavior value gives a judge something to check."""
    if value is None:
        return False
    if isinstance(value, str):
        return bool(value.strip())
    if isinstance(value, (list, tuple)):
        return any(_has_judge_reference(item) for item in value)
    if isinstance(value, (bool, int, float)):
        # 0, 0.0 and False are real reference answers, not a missing one.
        return True
    return bool(value)


def skill_metrics_applicable(
    has_skill,
    should_trigger,
    expected_skill,
    acceptable_skills=None,
    *,
    evaluated_skill=None,
    workspace_skill_names=None,
):
    """Return whether an arm can be scored on ``skill_execution`` and ``skill_efficiency``.

    The arm that carries the skill or plugin always can. An arm without it (the
    no-skill or no-plugin baseline) can only when it stages a skill the case
    could activate: an acceptable alternate in a skill workspace. Otherwise both metrics are not
    applicable, so skill activation alone cannot earn lift.
    """
    if has_skill is not False:
        return True
    staged = {str(name).strip().lower() for name in workspace_skill_names or [] if str(name).strip()}
    if not staged:
        return False
    if should_trigger is False:
        candidates = [evaluated_skill or expected_skill]
    else:
        candidates = [expected_skill, *(acceptable_skills or [])]
    return any(str(name).strip().lower() in staged for name in candidates if name and str(name).strip())


def _skill_metric_not_applicable(reason=SKILL_METRICS_NOT_APPLICABLE_REASON):
    """Scoreless ``skill_execution`` / ``skill_efficiency`` result.

    The default reason covers an arm without the skill. An eval case that gives
    the metric nothing to score passes its own reason.
    """
    return {"score": None, "status": NOT_APPLICABLE_STATUS, "reason": reason}


def _case_skill_metric_reasons(should_trigger, expected_skill):
    """Return the skill metrics this eval case leaves N/A, each with its reason."""
    reasons = {
        "skill_execution": skill_execution_not_applicable_reason(should_trigger, expected_skill),
        "skill_efficiency": skill_efficiency_not_applicable_reason(should_trigger, expected_skill),
    }
    return {metric: reason for metric, reason in reasons.items() if reason}


def _reward_overall(result, details):
    """The score policy's mean of the five dimensions, leaving out judged metrics recorded as N/A.

    An N/A metric is left out of its dimension, and a dimension with no scored
    metric is left out of the mean.
    """

    def scored(metric):
        return not (
            metric != "security"
            and result.get(metric) is None
            and isinstance(details.get(metric), dict)
            and details[metric].get("status") == NOT_APPLICABLE_STATUS
        )

    dimensions = []
    for metrics in _SCORE_POLICY_DIMENSIONS:
        values = [float(result[metric]) for metric in metrics if scored(metric)]
        if values:
            dimensions.append(round(sum(values) / len(values), 4))
    return round(sum(dimensions) / len(dimensions), 4)


def _format_log_score(value):
    numeric = _finite_reward_number(value)
    return f"{numeric:.2f}" if numeric is not None else "N/A"


def _numeric_reward_payload(result, overall):
    payload = {}
    for key, value in result.items():
        numeric = _finite_reward_number(value)
        if numeric is not None:
            payload[key] = numeric
    numeric_overall = _finite_reward_number(overall)
    if numeric_overall is not None:
        payload["overall"] = numeric_overall
    return payload


def write_reward_outputs(result, overall):
    # Top-level result keys are the fixed verifier schema. Sanitize their values
    # recursively so credential text cannot rename Harbor's reward metrics.
    sanitized_result = {key: _sanitize_error_value(value) for key, value in result.items()}
    sanitized_overall = _sanitize_error_value(overall)
    REWARD_JSON.parent.mkdir(parents=True, exist_ok=True)
    skill_evaluator_reward_json = _verifier_output_dir() / SKILL_EVALUATOR_REWARD_JSON.name
    skill_evaluator_reward_json.parent.mkdir(parents=True, exist_ok=True)
    skill_evaluator_reward_json.write_text(json.dumps(sanitized_result, indent=2))
    REWARD_JSON.write_text(json.dumps(_numeric_reward_payload(sanitized_result, sanitized_overall), indent=2))
    REWARD_TXT.write_text(str(sanitized_overall))


_YAML_FRONTMATTER = re.compile(r"\ufeff?---[ \t]*\r?\n(.*?)^---[ \t]*\r?$", re.MULTILINE | re.DOTALL)
_YAML_LINE_PREFIX = re.compile(r"[ \t]*(?:[-?:][ \t]+)*")
# An anchor (`&a`), a tag (`!`, `!!str`, `!local`, `!<verbatim>`) or both, in either order. They belong to
# the node that follows them, so a quote after them still opens a string.
_YAML_PROPERTY = r"(?:&[^\s,\[\]{}]+|!<[^>\s]*>|![^\s,\[\]{}]*)(?=[\s,\[\]{}]|\Z)"
_YAML_PROPERTIES = re.compile(rf"(?:{_YAML_PROPERTY}[ \t]*)+")
_YAML_KEY = re.compile(
    rf"""(?:{_YAML_PROPERTY}[ \t]+)*"""
    r"""(?:"((?:[^"\\\n]|\\.)*)"|'((?:[^'\n]|'')*)'|([^\s#'"\-?:\[\]{}|>&*!%@`,][^:\n]*?))[ \t]*:(?=[ \t\r\n]|\Z)"""
)
_YAML_QUOTED_BODY = {'"': re.compile(r"(?:[^\"\\]|\\.)*", re.DOTALL), "'": re.compile(r"(?:[^']|'')*")}
_YAML_BLOCK_SCALAR = re.compile(r"([|>])[+-]?\d?[+-]?[ \t]*(?:#[^\n]*)?(?:\r?\n|\Z)")
_YAML_FLOW_TOKEN = re.compile(
    r"""(?P<space>\s+)|(?P<comment>(?<!\S)\#[^\n]*)|(?P<open>[\[{])|(?P<close>[\]}])|(?P<comma>,)"""
    r"""|(?P<colon>:(?=[\s,\[\]{}]|\Z))|(?P<explicit>\?(?=[\s,\[\]{}]|\Z))"""
    rf"""|(?P<quoted>"(?:[^"\\]|\\.)*"|'(?:[^']|'')*')|(?P<prop>{_YAML_PROPERTY})|(?P<alias>\*[^\s,\[\]{{}}]*)""",
    re.DOTALL,
)
_YAML_FLOW_PLAIN = re.compile(r"(?:[^\s,\[\]{}:]|:(?![\s,\[\]{}]|\Z))+")
_YAML_ESCAPE = re.compile(r"\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|.)", re.DOTALL)
_YAML_SIMPLE_ESCAPES = {"0": "\0", "n": "\n", "r": "\r", "t": "\t"}


def _yaml_unescape(match: re.Match[str]) -> str:
    code = match.group(1)
    if len(code) > 1:
        try:
            return chr(int(code[1:], 16))
        except (ValueError, OverflowError):
            return match.group(0)
    return _YAML_SIMPLE_ESCAPES.get(code, code)


def _yaml_line_end(text: str, position: int) -> int:
    end = text.find("\n", position)
    return len(text) if end < 0 else end


def _yaml_unquote(raw: str) -> str:
    """Return the value of the single- or double-quoted scalar ``raw`` (quotes included)."""
    body = re.sub(r"[ \t]*\r?\n[ \t]*", " ", raw[1:-1])
    return _YAML_ESCAPE.sub(_yaml_unescape, body) if raw[0] == '"' else body.replace("''", "'")


def _yaml_flow_tokens(text: str, start: int) -> Iterator[tuple[str, str, int, int]]:
    """Yield ``(kind, token, depth, end)`` for the flow collection that opens at ``text[start]``.

    A flow collection may continue over lines whose keys are not indented, so
    brackets are counted while skipping quoted strings and comments. A quote
    opens a string only where a node begins: after ``[``, ``{``, ``,``, a
    ``:`` or ``?`` indicator, or after the anchor and tag that belong to that
    node. Inside a plain scalar it is an ordinary character. ``depth`` is the
    nesting after the token.
    """
    depth, node_starts, closed, position = 0, True, False, start
    while position < len(text):
        if closed and text[position] == ":":  # JSON-style `"key":value`
            node_starts, closed, position = True, False, position + 1
            yield "colon", ":", depth, position
            continue
        token = _YAML_FLOW_TOKEN.match(text, position)
        kind = token.lastgroup if token else None
        if kind in {"quoted", "prop", "alias", "explicit"} and not node_starts:
            kind = None  # in the middle of a plain scalar these are ordinary characters
        if kind is None:
            plain = _YAML_FLOW_PLAIN.match(text, position)
            end = plain.end() if plain else position + 1
            node_starts, closed = False, False
            yield "plain", text[position:end], depth, end
            position = end
            continue
        position = token.end()
        if kind in {"space", "comment"}:
            continue
        closed = kind in {"close", "quoted"}
        if kind != "prop":  # an anchor or tag leaves the node it belongs to still to begin
            node_starts = kind in {"open", "comma", "colon", "explicit"}
        depth += {"open": 1, "close": -1}.get(kind, 0)
        yield kind, token.group(), depth, position
        if depth == 0 and kind == "close":
            return


def _yaml_flow_end(text: str, start: int) -> int:
    """Return the index just past the flow collection that opens at ``text[start]``."""
    for kind, _token, depth, end in _yaml_flow_tokens(text, start):
        if kind == "close" and depth == 0:
            return end
    return len(text)


def _yaml_flow_mapping_name(text: str, start: int) -> str:
    """Return the string ``name`` entry of the flow mapping that opens at ``text[start]``."""
    name, key, value, in_value, nested = "", [], [], False, False
    for kind, token, depth, _end in _yaml_flow_tokens(text, start):
        if kind == "open" and depth == 2:
            nested = True
        elif depth >= 2 or (kind == "close" and depth == 1):
            continue  # inside a nested collection, or its end
        elif kind in {"quoted", "plain"}:
            (value if in_value else key).append(_yaml_unquote(token) if kind == "quoted" else token)
        elif kind == "alias":
            nested = True  # the anchored value is not resolved
        elif kind == "colon":
            in_value = True
        elif kind in {"comma", "close"}:
            if " ".join(key) == "name":
                name = "" if nested else " ".join(value)
            key, value, in_value, nested = [], [], False, False
    return name


def _yaml_node(text: str, start: int, parent: int, *, lookahead: bool = False) -> tuple[str | None, int]:
    """Consume the node whose value begins at ``text[start]``.

    ``parent`` is the column of the key or ``-`` that owns the node; a plain or
    block scalar continues over the lines indented deeper than it. Returns the
    scalar value (``None`` for no value or a flow collection) and the index of
    the newline that ends the node. With ``lookahead``, an empty value takes a
    scalar written on the following lines.
    """
    while text[start : start + 1] in {" ", "\t"}:
        start += 1
    properties = _YAML_PROPERTIES.match(text, start)
    start = properties.end() if properties else start
    first = text[start : start + 1]
    if first == "*":  # an alias is a whole node
        return None, _yaml_line_end(text, start)
    if first in {'"', "'"}:
        body = _YAML_QUOTED_BODY[first].match(text, start + 1)
        end = body.end()
        if text[end : end + 1] != first:
            return None, len(text)  # unterminated: not valid YAML
        return _yaml_unquote(text[start : end + 1]), _yaml_line_end(text, end + 1)
    if first in {"[", "{"}:
        return None, _yaml_line_end(text, _yaml_flow_end(text, start))
    block = _YAML_BLOCK_SCALAR.match(text, start)
    if block:
        position, lines, last_end = block.end(), [], block.end() - 1
        while position < len(text):
            end = _yaml_line_end(text, position)
            line = text[position:end]
            if line.strip() and len(line) - len(line.lstrip(" \t")) <= parent:
                break  # the block ends at the next line that is not indented under its key
            if line.strip():
                lines.append(line.strip())
            position, last_end = end + 1, end
        return (" " if block.group(1) == ">" else "\n").join(lines), min(last_end, len(text))
    line_end = _yaml_line_end(text, start)
    head = re.split(r"(?:^|[ \t])#", text[start:line_end], maxsplit=1)
    value, commented = head[0].strip(), len(head) == 2
    if not value:
        position = line_end + 1
        while lookahead and position < len(text):  # no value here: it may be written on the next lines
            end = _yaml_line_end(text, position)
            line = text[position:end]
            if line.strip() and not line.lstrip().startswith("#"):
                indent = len(line) - len(line.lstrip(" \t"))
                if (
                    indent > parent
                    and not _YAML_KEY.match(line, indent)
                    and not re.match(r"[-?](?:[ \t]|$)", line[indent:])
                ):
                    return _yaml_node(text, position + indent, parent)
                break
            position = end + 1
        return None, line_end
    lines, end = [value], line_end
    while not commented:  # a plain scalar continues over the lines indented under its key
        position = end + 1
        while position < len(text) and not text[position : _yaml_line_end(text, position)].strip():
            position = _yaml_line_end(text, position) + 1
        if position >= len(text):
            break
        next_end = _yaml_line_end(text, position)
        line = text[position:next_end]
        if len(line) - len(line.lstrip(" \t")) <= parent or line.lstrip().startswith("#"):
            break
        head = re.split(r"(?:^|[ \t])#", line, maxsplit=1)
        lines.append(head[0].strip())
        end, commented = next_end, len(head) == 2
    return " ".join(lines), end


def _frontmatter_skill_name(content: str) -> str:
    """Read the top-level ``name`` of a SKILL.md the way ``yaml.safe_load`` does.

    The verifier image gets PyYAML only as a dependency of the RAGAS packages,
    so this does not import it. It reads just enough of the structure to tell
    a root key from text that merely sits on an unindented line: nested
    mappings and sequences, multi-line flow collections, quoted strings, and
    plain or block scalars, each with the anchor and tag that may precede it.
    A quote opens a string only where a node begins. The whole frontmatter may
    also be one flow mapping. Like ``yaml.safe_load``, a later ``name`` key
    wins. An alias (``name: *anchor``) is not resolved.
    """
    frontmatter = _YAML_FRONTMATTER.match(content)
    if not frontmatter:
        return ""
    text, name, position, first_node = frontmatter.group(1), "", 0, True
    while position < len(text):
        end = _yaml_line_end(text, position)
        line = text[position:end]
        if not line.strip() or line.lstrip().startswith("#"):
            position = end + 1
            continue
        prefix = _YAML_LINE_PREFIX.match(line).group()
        value_start = position + len(prefix)
        if first_node:  # the whole frontmatter may be one flow mapping
            properties = _YAML_PROPERTIES.match(text, value_start)
            brace = properties.end() if properties else value_start
            if not prefix and text[brace : brace + 1] == "{":
                return _yaml_flow_mapping_name(text, brace)
            first_node = False
        key = _YAML_KEY.match(text, value_start)
        marker = max(prefix.rfind(indicator) for indicator in "-?:")
        parent = len(prefix) if key else (marker if marker >= 0 else max(len(prefix) - 1, 0))
        root_name = bool(key) and not prefix and (key.group(1) or key.group(2) or key.group(3)) == "name"
        value, end = _yaml_node(text, key.end() if key else value_start, parent, lookahead=root_name)
        if root_name:
            name = (value or "").strip()
        position = end + 1
    return name


def _dependency_context(skill: str, *, skills_root: Path = Path("/workspace/skills")) -> dict[str, Any]:
    """Read bounded dependency evidence from the evaluator-staged skill."""
    context: dict[str, Any] = {
        "apt": [],
        "pip": [],
        "skill_text": "",
        "skill_name": "",
        "skill_dirs": [],
        "skill_modules": set(),
        "script_imports": set(),
    }
    if not skill or skill in {".", ".."} or Path(skill).name != skill:
        return context
    root = skills_root / skill
    if not root.is_dir():
        return context
    context["skill_dirs"] = [
        str(root),
        f"/root/.claude/skills/{skill}",
        f"/root/.agents/skills/{skill}",
        f"/root/.config/opencode/skills/{skill}",
        f"/etc/codex/skills/{skill}",
    ]
    remaining = 1024 * 1024
    for index, path in enumerate(root.rglob("*")):
        if index >= 4096 or remaining <= 0:
            break
        if path.is_symlink() or not path.is_file() or not path.resolve().is_relative_to(root.resolve()):
            continue
        relative = path.relative_to(root)
        if path.suffix == ".py":
            context["skill_modules"].add(path.stem)
            context["skill_modules"].update(relative.parts[:-1])
        if path.name == "__init__.py":
            context["skill_modules"].add(path.parent.name)
        dependency = path.parent.name == "scripts" and path.name in {"requirements.txt", "apt-packages.txt"}
        if not dependency and path.name.lower() != "skill.md" and "scripts" not in relative.parts:
            continue
        try:
            with path.open("rb") as stream:
                data = stream.read(min(remaining, 128 * 1024))
        except OSError:
            continue
        remaining -= len(data)
        content = data.decode("utf-8", errors="replace")
        if dependency:
            key = "pip" if path.name == "requirements.txt" else "apt"
            context[key].extend(
                line.split("#", 1)[0].strip()
                for line in content.splitlines()
                if line.strip() and not line.lstrip().startswith(("#", "-"))
            )
        else:
            context["skill_text"] += "\n" + content
            if relative.as_posix().lower() == "skill.md":
                context["skill_name"] = _frontmatter_skill_name(content) or context["skill_name"]
            if "scripts" in relative.parts and path.suffix == ".py":
                imports = re.finditer(r"(?m)^\s*(?:from\s+([\w.]+)\s+import\b|import\s+([\w.]+))", content)
                context["script_imports"].update((match.group(1) or match.group(2)).split(".")[0] for match in imports)
    context["skill_modules"] = sorted(context["skill_modules"])
    context["script_imports"] = sorted(context["script_imports"])
    return context


def main():
    entry = json.loads(ENTRY_PATH.read_text(encoding="utf-8"))
    traj, traj_meta = load_trajectory_with_fallback(ATIF_PATH, ATIF_PATH.parent)

    expected_skill = entry.get("expected_skill") or ""
    expected_script = normalize_optional_reference(entry.get("expected_script"))
    should_trigger = resolve_should_trigger(entry)
    evaluated_skill = entry.get("evaluated_skill") or ""
    acceptable_skills = _resolve_acceptable_skills(entry, expected_skill)
    expected_behavior = normalize_expected_behaviors(entry.get("expected_behavior", []))
    declarative_checks = entry.get("checks", [])
    question = entry.get("question", "")
    ground_truth = entry.get("ground_truth", "")
    workspace_mode = entry.get("skill_workspace_mode", "isolated")
    workspace_skill_names = entry.get("workspace_skill_names", [])
    if not isinstance(workspace_skill_names, list):
        workspace_skill_names = []

    skill_metrics_on = skill_metrics_applicable(
        entry.get("has_skill", True),
        should_trigger,
        expected_skill,
        acceptable_skills,
        evaluated_skill=evaluated_skill,
        workspace_skill_names=workspace_skill_names,
    )

    if not traj:
        # Without a trajectory every metric the case defines fails, but a judge
        # without its reference input stays N/A exactly as on the judged path,
        # so one crashed trial cannot turn an arm's N/A judge metric into 0.0.
        judge_scores = {}
        judge_details = {}
        for metric, (field, na_reason) in _JUDGED_METRICS.items():
            if _has_judge_reference(entry.get(field)):
                judge_scores[metric] = 0
            else:
                judge_scores[metric] = None
                judge_details[metric] = _judge_not_applicable(na_reason)
        skill_scores = {"skill_execution": 0, "skill_efficiency": 0}
        if not skill_metrics_on:
            skill_scores = {"skill_execution": None, "skill_efficiency": None}
            judge_details.update(
                skill_execution=_skill_metric_not_applicable(),
                skill_efficiency=_skill_metric_not_applicable(),
            )
        else:
            # A skill metric the case gives nothing to score stays N/A, as on the judged path.
            for metric, na_reason in _case_skill_metric_reasons(should_trigger, expected_skill).items():
                skill_scores[metric] = None
                judge_details[metric] = _skill_metric_not_applicable(na_reason)
        result = {
            "security": 0,
            **skill_scores,
            **judge_scores,
            "metric_set": DEFAULT_METRIC_SET,
            "score_policy": DEFAULT_SCORE_POLICY,
            "error": "No trajectory or reconstructible agent log",
            "trajectory_source": traj_meta.get("source"),
            "trajectory_detail": traj_meta.get("warning") or traj_meta.get("note"),
        }
        if declarative_checks:
            direct_results = _shared_declarative_checks.evaluate_declarative_checks(
                declarative_checks,
                tool_calls=[],
                final_response="",
                workspace_roots=_declarative_workspace_roots(),
            )
            direct_results = _shared_declarative_checks.mark_no_skill_script_checks(
                declarative_checks,
                direct_results,
                has_skill=entry.get("has_skill", True),
                skill_metrics_on=skill_metrics_on,
                evaluated_skill=evaluated_skill,
            )
            judged_count = len(expected_behavior) if _has_judge_reference(expected_behavior) else 0
            base_behavior = {
                "score": judge_scores["behavior_check"],
                "status": "accepted" if judged_count else "not_applicable",
                "reason": "No trajectory or reconstructible agent log"
                if judged_count
                else _NO_EXPECTED_BEHAVIOR_REASON,
                "results": [
                    {"step": index + 1, "passed": False, "reason": "No trajectory or reconstructible agent log"}
                    for index in range(judged_count)
                ],
            }
            behavior_result = _shared_declarative_checks.combine_behavior_check(
                base_behavior, direct_results, judged_count
            )
            judge_scores["behavior_check"] = behavior_result["score"]
            judge_details["behavior_check"] = behavior_result
            result["behavior_check"] = behavior_result["score"]
        if judge_details:
            result["details"] = judge_details
        write_reward_outputs(result, 0.0)
        return

    tool_calls = extract_tool_calls_as_dicts(traj)
    skill_tools = get_skill_tool_calls(traj)

    details: dict[str, Any] = {}
    if traj_meta.get("note") or traj_meta.get("warning") or traj_meta.get("source") != "trajectory.json":
        details["_trajectory_load"] = {
            "source": traj_meta.get("source"),
            "note": traj_meta.get("note"),
            "warning": traj_meta.get("warning"),
        }
    if len(acceptable_skills) > 1:
        details["_skill_routing_policy"] = {
            "expected_skill": expected_skill,
            "acceptable_skills": acceptable_skills,
            "acceptable_alternates": acceptable_skills[1:],
            "alternate_score": ACCEPTABLE_ALTERNATE_SCORE,
        }

    # ── Eval 1: security ─────────────────────────────────────────────────
    security_result = check_security(
        traj,
        tool_calls,
        expected_skill,
        acceptable_skills,
        agent_workdir=entry.get("agent_workdir", "/workspace"),
    )
    security_score = security_result["score"]
    details["security"] = security_result

    # ── Eval 2: skill_execution ──────────────────────────────────────────
    if skill_metrics_on:
        skill_execution_result = score_skill_execution(
            tool_calls,
            expected_skill,
            expected_script,
            should_trigger,
            evaluated_skill=evaluated_skill,
            require_evaluated_skill=True,
            skill_tool_names=skill_tools,
            acceptable_skills=acceptable_skills,
            dependency_context=_dependency_context(evaluated_skill or expected_skill),
        )
        se_score = skill_execution_result["score"]
        details["skill_execution"] = skill_execution_result["details"]
        if skill_execution_result.get("status") == "environment_invalid":
            recovery = skill_execution_result["details"]["error_recovery"]
            write_reward_outputs(
                {
                    "evaluation_status": "failed",
                    "evaluation_errors": {"environment": recovery["reason"]},
                    "environment_issues": recovery["environment_issues"],
                    "entry_id": entry.get("id"),
                    "metric_set": DEFAULT_METRIC_SET,
                    "score_policy": DEFAULT_SCORE_POLICY,
                    "details": details,
                },
                0.0,
            )
            logger.error("[environment] %s", recovery["reason"])
            raise SystemExit(1)
    else:
        se_score = None
        details["skill_execution"] = _skill_metric_not_applicable()

    # ── Eval 3: skill_efficiency ─────────────────────────────────────────
    if not skill_metrics_on:
        sef_score = None
        details["skill_efficiency"] = _skill_metric_not_applicable()
    elif not should_trigger or not expected_skill:
        sef_score = None
        details["skill_efficiency"] = _skill_metric_not_applicable(
            skill_efficiency_not_applicable_reason(should_trigger, expected_skill)
        )
    elif not tool_calls:
        sef_score = 0.0
        details["skill_efficiency"] = {"message": "No tool calls in trajectory"}
    else:
        checks = {}
        scores = []
        r = check_routing(
            tool_calls,
            expected_skill,
            skill_tool_names=skill_tools,
            workspace_skill_names=workspace_skill_names,
            workspace_mode=workspace_mode,
            acceptable_skills=acceptable_skills,
        )
        checks["routing"] = r
        scores.append(r["score"])
        r = check_tool_efficiency(tool_calls, expected_skill, expected_script)
        checks["tool_efficiency"] = r
        scores.append(r["score"])
        sef_score = round(sum(scores) / len(scores), 4)
        details["skill_efficiency"] = checks

    bundles = build_metric_evidence_bundles(
        traj, question, ground_truth=ground_truth, expected_behavior=expected_behavior
    )

    # Every judge attempt below is saved to judge_attempts.json as it happens.
    judge_attempts = []
    judge_evidence_token = _ACTIVE_JUDGE_EVIDENCE.set(judge_attempts)
    try:
        # ── Eval 4: accuracy (LLM judge) ─────────────────────────────────
        acc_result = _call_required_judge(
            "accuracy",
            judge_accuracy,
            question,
            ground_truth,
            bundles["accuracy"]["prompt_evidence"],
            allow_not_applicable=not _has_judge_reference(ground_truth),
        )
        acc_score = acc_result["score"]
        details["accuracy"] = acc_result

        # ── Eval 5: goal_accuracy (RAGAS or custom LLM judge) ────────────
        ga_result = _call_required_judge(
            "goal_accuracy",
            judge_goal_accuracy,
            question,
            ground_truth,
            bundles["goal_accuracy"]["prompt_evidence"],
            tool_summary="",
            allow_not_applicable=not _has_judge_reference(ground_truth),
        )
        ga_score = ga_result["score"]
        details["goal_accuracy"] = ga_result

        # ── Eval 6: behavior_check (LLM judge) ───────────────────────────
        if declarative_checks:
            if _has_judge_reference(expected_behavior):
                bc_result = _call_required_judge(
                    "behavior_check",
                    judge_behavior_check,
                    bundles["behavior_check"]["prompt_evidence"],
                    expected_behavior,
                    evidence_omitted=bundles["behavior_check"]["omitted"],
                )
            else:
                bc_result = _judge_not_applicable(_NO_EXPECTED_BEHAVIOR_REASON, results=[])
        else:
            bc_result = _call_required_judge(
                "behavior_check",
                judge_behavior_check,
                bundles["behavior_check"]["prompt_evidence"],
                expected_behavior,
                evidence_omitted=bundles["behavior_check"]["omitted"],
                allow_not_applicable=not _has_judge_reference(expected_behavior),
            )
        if declarative_checks:
            direct_results = _shared_declarative_checks.evaluate_declarative_checks(
                declarative_checks,
                tool_calls=tool_calls,
                final_response=_get_final_response(traj),
                workspace_roots=_declarative_workspace_roots(),
            )
            direct_results = _shared_declarative_checks.mark_no_skill_script_checks(
                declarative_checks,
                direct_results,
                has_skill=entry.get("has_skill", True),
                skill_metrics_on=skill_metrics_on,
                evaluated_skill=evaluated_skill,
            )
            judged_count = len(expected_behavior) if _has_judge_reference(expected_behavior) else 0
            bc_result = _shared_declarative_checks.combine_behavior_check(bc_result, direct_results, judged_count)
        bc_score = bc_result["score"]
        details["behavior_check"] = bc_result
    finally:
        _ACTIVE_JUDGE_EVIDENCE.reset(judge_evidence_token)
        _write_judge_attempts(judge_attempts)

    # persist refs + omission metadata onto the metric details
    attach_metric_evidence_refs(details, {m: bundles[m]["evidence_refs"] for m in bundles})
    for _m, _b in bundles.items():
        if isinstance(details.get(_m), dict):
            details[_m]["omitted"] = _b["omitted"]

    # ── Write results ────────────────────────────────────────────────────
    result: dict[str, Any] = {
        "security": security_score,
        "skill_execution": se_score,
        "skill_efficiency": sef_score,
        "accuracy": acc_score,
        "goal_accuracy": ga_score,
        "behavior_check": bc_score,
        "metric_set": DEFAULT_METRIC_SET,
        "score_policy": DEFAULT_SCORE_POLICY,
        "judge_contract": JUDGE_CONTRACT,
        "entry_id": entry.get("id"),
        "has_skill": entry.get("has_skill", True),
        "trajectory_source": traj_meta.get("source"),
        "details": details,
    }

    judge_errors = {
        metric: details[metric]["reason"]
        for metric in ("accuracy", "goal_accuracy", "behavior_check")
        if details[metric].get("status") == "error"
    }
    if judge_errors:
        result["evaluation_status"] = "failed"
        result["evaluation_errors"] = judge_errors
        # Harbor 0.22 still parses reward.json when the verifier exits nonzero.
        # Keep this artifact deliberately incomplete so the collector cannot
        # score it even if the richer diagnostic sidecar is unavailable.
        write_reward_outputs(result, 0.0)
        logger.error("Required LLM judging failed for: %s", ", ".join(sorted(judge_errors)))
        raise SystemExit(1)

    overall = _reward_overall(result, details)

    write_reward_outputs(result, overall)

    logger.info(
        "Scores: security=%s skill_exec=%s efficiency=%s accuracy=%s goal=%s behavior=%s overall=%s",
        *(_format_log_score(result[metric]) for metric in DISPLAY_METRICS),
        _format_log_score(overall),
    )


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    main()