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.

feat(tier3): make evidence bundle budgets and final response limit configurable (#160)

Karl Weinmeister90ecf77f5f9c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad69d1fa..01ddd932 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@ All notable changes to SkillEvaluator are documented in this file.
## Unreleased
+### Added
+
+- Configurable evidence bundle budgets (`SKILL_EVAL_ACCURACY_BUDGET`, `SKILL_EVAL_GOAL_ACCURACY_BUDGET`, `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET`) and final response limit (`SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT`).
+
## 0.4.0 - 2026-09-30
### Fixed
diff --git a/src/skillevaluator/tier3/eval_core/atif_helpers.py b/src/skillevaluator/tier3/eval_core/atif_helpers.py
index 46898de1..29e391e3 100644
--- a/src/skillevaluator/tier3/eval_core/atif_helpers.py
+++ b/src/skillevaluator/tier3/eval_core/atif_helpers.py
@@ -164,6 +164,39 @@ def build_conversation_summary(traj: dict[str, Any], question: str) -> str:
_BEHAVIOR_EVIDENCE_MAX_CHARS = 4000
+_DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT = 800
+_DEFAULT_BEHAVIOR_CHECK_BUDGET = 8000
+_DEFAULT_TOOL_HISTORY_HEADROOM = 4000
+_MIN_BEHAVIOR_HISTORY_HEADROOM = 1600
+_SECTION_COMPACT_TOOL_HISTORY = "COMPACT TOOL HISTORY"
+_SECTION_FILE_CHANGES = "FILE CHANGES"
+_SECTION_FINAL_RESPONSE = "FINAL RESPONSE"
+_SECTION_USER_REQUEST = "USER REQUEST"
+
+
+def _env_positive_int(name: str, default: int) -> int:
+ """Parse a positive integer from environment variable *name* or return *default*."""
+ raw = os.environ.get(name, "").strip()
+ if raw:
+ try:
+ return max(1, int(raw))
+ except ValueError:
+ pass
+ return default
+
+
+def _behavior_final_response_limit() -> int:
+ """Return the configured behavior final response section limit or default."""
+ return _env_positive_int("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", _DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT)
+
+
+def _behavior_check_budget() -> int:
+ """Return the configured behavior check evidence budget or reconciled default."""
+ final_limit = _behavior_final_response_limit()
+ base_budget = _env_positive_int("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", _DEFAULT_BEHAVIOR_CHECK_BUDGET)
+ return max(base_budget, final_limit + _DEFAULT_TOOL_HISTORY_HEADROOM)
+
+
_BEHAVIOR_WRITE_TOOLS = {
"write",
"write_file",
@@ -189,7 +222,7 @@ def _truncate_for_behavior(text: str, limit: int) -> str:
if len(text) <= limit:
return text
marker = "\n...[truncated]...\n"
- if limit <= len(marker):
+ if limit <= len(marker) + 1:
return text[:limit]
head = max(1, (limit - len(marker)) * 2 // 3)
tail = max(1, limit - len(marker) - head)
@@ -295,7 +328,8 @@ def _collect_file_change_evidence(traj: dict[str, Any]) -> list[str]:
def build_behavior_evidence(
traj: dict[str, Any],
question: str,
- max_chars: int = _BEHAVIOR_EVIDENCE_MAX_CHARS,
+ max_chars: int | None = None,
+ final_response_limit: int | None = None,
) -> str:
"""Build compact, behavior-check-specific evidence from an ATIF trajectory.
@@ -303,33 +337,89 @@ def build_behavior_evidence(
Put final output and write/edit evidence before exploratory reads so a
fixed-size judge prompt does not miss late file creation.
"""
+ effective_final_limit = (
+ _behavior_final_response_limit()
+ if final_response_limit is None
+ else max(1, int(final_response_limit))
+ )
+
+ if max_chars is None:
+ raw_budget = os.environ.get("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "").strip()
+ if raw_budget:
+ max_chars = _behavior_check_budget()
+ else:
+ max_chars = max(
+ _BEHAVIOR_EVIDENCE_MAX_CHARS,
+ effective_final_limit + _MIN_BEHAVIOR_HISTORY_HEADROOM,
+ )
+
parts: list[str] = []
remaining = max_chars
file_changes = "\n\n".join(_collect_file_change_evidence(traj))
+ final = get_final_response(traj)
+ history = build_conversation_summary(traj, question)
+ user_needed = (
+ min(800, len(_SECTION_USER_REQUEST) + len(question.strip()) + 2) if question and question.strip() else 0
+ )
+ history_needed = (
+ len(_SECTION_COMPACT_TOOL_HISTORY) + len(history.strip()) + 2 if history and history.strip() else 0
+ )
+ tail_needed = user_needed + (2 if user_needed and history_needed else 0) + history_needed
+
if file_changes:
- remaining = _append_section_with_budget(parts, "FILE CHANGES", file_changes, remaining)
+ file_section_limit: int | None = None
+ if final and final.strip():
+ reserved_tail = min(_MIN_BEHAVIOR_HISTORY_HEADROOM, max_chars // 4, tail_needed)
+ reserved_final = min(
+ effective_final_limit,
+ len(_SECTION_FINAL_RESPONSE) + len(final.strip()) + 2,
+ max(1, max_chars - min(_MIN_BEHAVIOR_HISTORY_HEADROOM, max_chars // 2)),
+ )
+ if (
+ len(_SECTION_FILE_CHANGES) + len(file_changes.strip()) + 2 + reserved_final + reserved_tail + 4
+ > remaining
+ ):
+ file_section_limit = max(
+ min(800, remaining // 3),
+ remaining - reserved_final - reserved_tail - 4,
+ )
+ remaining = _append_section_with_budget(
+ parts,
+ _SECTION_FILE_CHANGES,
+ file_changes,
+ remaining,
+ section_limit=file_section_limit,
+ )
- final = get_final_response(traj)
if final:
+ if max_chars > effective_final_limit:
+ reserved_headroom = min(
+ _MIN_BEHAVIOR_HISTORY_HEADROOM,
+ remaining // 2,
+ tail_needed,
+ max(800, remaining - effective_final_limit),
+ )
+ else:
+ reserved_headroom = min(_MIN_BEHAVIOR_HISTORY_HEADROOM, remaining // 2, tail_needed)
+ bounded_final_limit = min(effective_final_limit, max(1, remaining - reserved_headroom))
remaining = _append_section_with_budget(
parts,
- "FINAL RESPONSE",
+ _SECTION_FINAL_RESPONSE,
final,
remaining,
- section_limit=800,
+ section_limit=bounded_final_limit,
)
remaining = _append_section_with_budget(
parts,
- "USER REQUEST",
+ _SECTION_USER_REQUEST,
question,
remaining,
section_limit=800,
)
- history = build_conversation_summary(traj, question)
- remaining = _append_section_with_budget(parts, "COMPACT TOOL HISTORY", history, remaining)
+ remaining = _append_section_with_budget(parts, _SECTION_COMPACT_TOOL_HISTORY, history, remaining)
return "\n\n".join(parts)[:max_chars]
@@ -645,11 +735,36 @@ def attach_metric_evidence_refs(
# ---------------------------------------------------------------------------
_BUNDLE_ITEM_CHARS = 1500 # per-item excerpt for the judge prompt (refs use 300)
-_BUNDLE_BUDGETS = {"accuracy": 8000, "goal_accuracy": 12000, "behavior_check": 8000}
+_DEFAULT_ACCURACY_BUDGET = 8000
+_DEFAULT_GOAL_ACCURACY_BUDGET = 12000
+_BUNDLE_BUDGETS = {
+ "accuracy": _DEFAULT_ACCURACY_BUDGET,
+ "goal_accuracy": _DEFAULT_GOAL_ACCURACY_BUDGET,
+ "behavior_check": _DEFAULT_BEHAVIOR_CHECK_BUDGET,
+}
_BUNDLE_ACCURACY_MAX_OBS = 6 # newest observations fed to accuracy (<= ~6x1500 <= budget)
_BUNDLE_GOAL_MAX_OBS = 12 # newest observations fed to goal_accuracy (end-state)
+def _accuracy_budget() -> int:
+ """Return the configured accuracy evidence budget or default."""
+ return _env_positive_int("SKILL_EVAL_ACCURACY_BUDGET", _DEFAULT_ACCURACY_BUDGET)
+
+
+def _goal_accuracy_budget() -> int:
+ """Return the configured goal accuracy evidence budget or default."""
+ return _env_positive_int("SKILL_EVAL_GOAL_ACCURACY_BUDGET", _DEFAULT_GOAL_ACCURACY_BUDGET)
+
+
+def _bundle_budgets() -> dict[str, int]:
+ """Return effective bundle budgets taking into account runtime overrides."""
+ return {
+ "accuracy": _accuracy_budget(),
+ "goal_accuracy": _goal_accuracy_budget(),
+ "behavior_check": _behavior_check_budget(),
+ }
+
+
def _clip(text: str, limit: int) -> str:
text = str(text or "")
return text if len(text) <= limit else text[:limit] + " …[clipped]"
@@ -674,14 +789,32 @@ def _assemble(sections: list[tuple[str, str]], budget: int) -> tuple[str, int, b
used = 0
dropped = 0
truncated = False
- for title, body in sections:
- body = str(body or "").strip()
- if not body:
- continue
+ non_empty = [(title, str(body or "").strip()) for title, body in sections if str(body or "").strip()]
+ for idx, (title, body) in enumerate(non_empty):
block = f"{title}\n{body}"
if used + len(block) <= budget:
parts.append(block)
used += len(block) + 2
+ elif title == _SECTION_FINAL_RESPONSE and budget - used > 0:
+ avail = budget - used
+ later_blocks = [len(f"{t}\n{b}") + 2 for t, b in non_empty[idx + 1 :]]
+ if later_blocks and avail >= 160:
+ reserve_later = min(avail // 2, *later_blocks)
+ if avail - reserve_later > len(title) + 16:
+ avail -= reserve_later
+ header = f"{title}\n"
+ clip_suffix = " …[clipped]"
+ if avail > len(header) + len(clip_suffix):
+ clipped_body = _clip(body, avail - len(header) - len(clip_suffix))
+ clipped_block = f"{header}{clipped_body}"
+ elif avail > len(header):
+ clipped_block = f"{header}{body[: avail - len(header)]}"
+ else:
+ clipped_block = block[:avail]
+ parts.append(clipped_block)
+ used += len(clipped_block) + 2
+ dropped += 1
+ truncated = True
else:
dropped += 1
truncated = True
@@ -847,17 +980,18 @@ def build_metric_evidence_bundles(
return facts_section
bundles: dict[str, dict[str, Any]] = {}
+ budgets = _bundle_budgets()
acc_text, acc_drop, acc_trunc = _assemble(
[
- ("FINAL RESPONSE", final),
+ (_SECTION_FINAL_RESPONSE, final),
("PRODUCED FILES / WRITES", file_changes),
("KEY OBSERVATIONS", "\n---\n".join(late_obs[:_BUNDLE_ACCURACY_MAX_OBS])),
],
- _BUNDLE_BUDGETS["accuracy"],
+ budgets["accuracy"],
)
bundles["accuracy"] = {
- "prompt_evidence": _prepend_facts(acc_text or _clip(get_agent_text(traj), _BUNDLE_BUDGETS["accuracy"])),
+ "prompt_evidence": _prepend_facts(acc_text or _clip(get_agent_text(traj), budgets["accuracy"])),
"evidence_refs": refs["accuracy"],
"omitted": {
"count": acc_drop,
@@ -869,14 +1003,14 @@ def build_metric_evidence_bundles(
goal_text, goal_drop, goal_trunc = _assemble(
[
- ("FINAL RESPONSE", final),
+ (_SECTION_FINAL_RESPONSE, final),
("END-STATE FILE CHANGES", file_changes),
("RECENT TOOL RESULTS (newest first)", "\n---\n".join(late_obs[:_BUNDLE_GOAL_MAX_OBS])),
],
- _BUNDLE_BUDGETS["goal_accuracy"],
+ budgets["goal_accuracy"],
)
bundles["goal_accuracy"] = {
- "prompt_evidence": _prepend_facts(goal_text or _clip(get_agent_text(traj), _BUNDLE_BUDGETS["goal_accuracy"])),
+ "prompt_evidence": _prepend_facts(goal_text or _clip(get_agent_text(traj), budgets["goal_accuracy"])),
"evidence_refs": refs["goal_accuracy"],
"omitted": {
"count": goal_drop,
@@ -886,7 +1020,9 @@ def build_metric_evidence_bundles(
"verified": facts,
}
- bc_text = build_behavior_evidence(traj, question, max_chars=_BUNDLE_BUDGETS["behavior_check"])
+ facts_overhead = len(facts_section) + 2 if facts_section else 0
+ bc_budget = max(1, budgets["behavior_check"] - facts_overhead)
+ bc_text = build_behavior_evidence(traj, question, max_chars=bc_budget)
bc_full = build_behavior_evidence(traj, question, max_chars=10**9)
bc_trunc = len(bc_full) > len(bc_text)
bundles["behavior_check"] = {
diff --git a/src/skillevaluator/tier3/eval_core/llm_judge.py b/src/skillevaluator/tier3/eval_core/llm_judge.py
index 67b4d4b9..0310e113 100644
--- a/src/skillevaluator/tier3/eval_core/llm_judge.py
+++ b/src/skillevaluator/tier3/eval_core/llm_judge.py
@@ -19,6 +19,14 @@ from urllib.parse import urlparse
from skillevaluator.inference.types import EmptyLLMResponseError
from skillevaluator.provider_config import CHAT_DEFAULT_OPENAI, _model_leaf, _supports_custom_temperature
+from skillevaluator.tier3.eval_core.atif_helpers import (
+ _SECTION_COMPACT_TOOL_HISTORY,
+ _SECTION_FINAL_RESPONSE,
+ _SECTION_USER_REQUEST,
+ _behavior_check_budget,
+ _behavior_final_response_limit,
+ _truncate_for_behavior,
+)
logger = logging.getLogger(__name__)
@@ -839,17 +847,86 @@ Respond with ONLY a JSON object:
"score": <float between 0.0 and 1.0>, "summary": "<brief summary>"}}"""
-def _compact_behavior_conversation(conversation_text: str, limit: int = 8000) -> str:
+def _slice_with_middle_marker(
+ text: str,
+ budget: int,
+ marker: str,
+ *,
+ max_head: int | None = None,
+ fallback_tail: bool = False,
+) -> str:
+ """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: str, limit: int | None = None) -> str:
"""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):
+ if limit <= len(marker) + 1:
return conversation_text[:limit]
- head = max(1, (limit - len(marker)) * 2 // 3)
- tail = max(1, limit - len(marker) - head)
+ 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:]}"
diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.py
index cbd0518d..85243381 100644
--- a/src/skillevaluator/tier3/harbor/adapter.py
+++ b/src/skillevaluator/tier3/harbor/adapter.py
@@ -203,18 +203,18 @@ _COMPOSE_ALLOWED_BUILD_KEYS = frozenset(
_COMPOSE_ALLOWED_NETWORK_KEYS = frozenset({"attachable", "enable_ipv4", "enable_ipv6", "internal", "labels"})
_COMPOSE_ALLOWED_VOLUME_KEYS = frozenset({"labels"})
_VERIFIER_JUDGE_MODEL_ENV_VARS = frozenset({"LLM_JUDGE_MODEL", "SKILL_EVAL_JUDGE_MODEL"})
+_VERIFIER_BUDGET_ENV_VARS = frozenset(
+ {
+ "SKILL_EVAL_ACCURACY_BUDGET",
+ "SKILL_EVAL_BEHAVIOR_CHECK_BUDGET",
+ "SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT",
+ "SKILL_EVAL_GOAL_ACCURACY_BUDGET",
+ }
+)
_VERIFIER_PROVIDER_ENV_VARS = frozenset(
{
- "SKILL_EVAL_LLM_PROVIDER",
- "SKILL_EVAL_LLM_MODEL",
- "SKILL_EVAL_LLM_API_KEY",
- "SKILL_EVAL_LLM_BASE_URL",
- "OPENAI_API_KEY",
- "OPENAI_BASE_URL",
"ANTHROPIC_API_KEY",
"ANTHROPIC_BASE_URL",
- "NVIDIA_API_KEY",
- "AWS_REGION",
"AWS_ACCESS_KEY_ID",
"AWS_BEARER_TOKEN_BEDROCK",
"AWS_CONFIG_FILE",
@@ -224,6 +224,7 @@ _VERIFIER_PROVIDER_ENV_VARS = frozenset(
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
"AWS_DEFAULT_REGION",
"AWS_PROFILE",
+ "AWS_REGION",
"AWS_ROLE_ARN",
"AWS_ROLE_SESSION_NAME",
"AWS_SDK_LOAD_CONFIG",
@@ -231,6 +232,14 @@ _VERIFIER_PROVIDER_ENV_VARS = frozenset(
"AWS_SESSION_TOKEN",
"AWS_SHARED_CREDENTIALS_FILE",
"AWS_WEB_IDENTITY_TOKEN_FILE",
+ "NVIDIA_API_KEY",
+ "OPENAI_API_KEY",
+ "OPENAI_BASE_URL",
+ *_VERIFIER_BUDGET_ENV_VARS,
+ "SKILL_EVAL_LLM_API_KEY",
+ "SKILL_EVAL_LLM_BASE_URL",
+ "SKILL_EVAL_LLM_MODEL",
+ "SKILL_EVAL_LLM_PROVIDER",
}
)
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index 62ff9e33..1da1ecd9 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -42,6 +42,7 @@ from skillevaluator.provider_config import (
from skillevaluator.source_identity import normalized_evaluated_source
from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config
from skillevaluator.tier3.harbor.adapter import (
+ _VERIFIER_BUDGET_ENV_VARS,
_VERIFIER_JUDGE_MODEL_ENV_VARS,
_prevalidate_baseline_skill_candidates,
build_eval_base_image,
@@ -480,7 +481,11 @@ def _provider_environment(config: ProviderConfig) -> dict[str, str]:
"SKILL_EVAL_LLM_MODEL": config.model,
}
environment.update(
- {name: value for name in _VERIFIER_JUDGE_MODEL_ENV_VARS if (value := os.environ.get(name, "").strip())}
+ {
+ name: value
+ for name in (_VERIFIER_JUDGE_MODEL_ENV_VARS | _VERIFIER_BUDGET_ENV_VARS)
+ if (value := os.environ.get(name, "").strip())
+ }
)
if config.provider == "anthropic":
environment["ANTHROPIC_API_KEY"] = config.api_key or ""
diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py
index af47181a..1a4d949f 100644
--- a/src/skillevaluator/tier3/harbor/templates/eval.py
+++ b/src/skillevaluator/tier3/harbor/templates/eval.py
@@ -470,6 +470,39 @@ def build_conversation_summary(traj, question):
_BEHAVIOR_EVIDENCE_MAX_CHARS = 4000
+_DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT = 800
+_DEFAULT_BEHAVIOR_CHECK_BUDGET = 8000
+_DEFAULT_TOOL_HISTORY_HEADROOM = 4000
+_MIN_BEHAVIOR_HISTORY_HEADROOM = 1600
+_SECTION_COMPACT_TOOL_HISTORY = "COMPACT TOOL HISTORY"
+_SECTION_FILE_CHANGES = "FILE CHANGES"
+_SECTION_FINAL_RESPONSE = "FINAL RESPONSE"
+_SECTION_USER_REQUEST = "USER REQUEST"
+
+
+def _env_positive_int(name, default):
+ """Parse a positive integer from environment variable *name* or return *default*."""
+ raw = os.environ.get(name, "").strip()
+ if raw:
+ try:
+ return max(1, int(raw))
+ except ValueError:
+ pass
+ return default
+
+
+def _behavior_final_response_limit():
+ """Return the configured behavior final response section limit or default."""
+ return _env_positive_int("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", _DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT)
+
+
+def _behavior_check_budget():
+ """Return the configured behavior check evidence budget or reconciled default."""
+ final_limit = _behavior_final_response_limit()
+ base_budget = _env_positive_int("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", _DEFAULT_BEHAVIOR_CHECK_BUDGET)
+ return max(base_budget, final_limit + _DEFAULT_TOOL_HISTORY_HEADROOM)
+
+
_BEHAVIOR_WRITE_TOOLS = {
"write",
"write_file",
@@ -504,7 +537,7 @@ def _truncate_for_behavior(text, limit):
if len(text) <= limit:
return text
marker = "\n...[truncated]...\n"
- if limit <= len(marker):
+ if limit <= len(marker) + 1:
return text[:limit]
head = max(1, (limit - len(marker)) * 2 // 3)
tail = max(1, limit - len(marker) - head)
@@ -600,35 +633,96 @@ def _collect_file_change_evidence(traj):
return changes
-def build_behavior_evidence(traj, question, max_chars=_BEHAVIOR_EVIDENCE_MAX_CHARS):
+def build_behavior_evidence(
+ traj,
+ question,
+ max_chars=None,
+ final_response_limit=None,
+):
"""Build compact, behavior-check-specific evidence from an ATIF trajectory."""
+ effective_final_limit = (
+ _behavior_final_response_limit()
+ if final_response_limit is None
+ else max(1, int(final_response_limit))
+ )
+
+ if max_chars is None:
+ raw_budget = os.environ.get("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "").strip()
+ if raw_budget:
+ max_chars = _behavior_check_budget()
+ else:
+ max_chars = max(
+ _BEHAVIOR_EVIDENCE_MAX_CHARS,
+ effective_final_limit + _MIN_BEHAVIOR_HISTORY_HEADROOM,
+ )
+
parts = []
remaining = max_chars
file_changes = "\n\n".join(_collect_file_change_evidence(traj))
+ final = _get_final_response(traj)
+ history = build_conversation_summary(traj, question)
+ user_needed = (
+ min(800, len(_SECTION_USER_REQUEST) + len(question.strip()) + 2) if question and question.strip() else 0
+ )
+ history_needed = (
+ len(_SECTION_COMPACT_TOOL_HISTORY) + len(history.strip()) + 2 if history and history.strip() else 0
+ )
+ tail_needed = user_needed + (2 if user_needed and history_needed else 0) + history_needed
+
if file_changes:
- remaining = _append_section_with_budget(parts, "FILE CHANGES", file_changes, remaining)
+ file_section_limit = None
+ if final and final.strip():
+ reserved_tail = min(_MIN_BEHAVIOR_HISTORY_HEADROOM, max_chars // 4, tail_needed)
+ reserved_final = min(
+ effective_final_limit,
+ len(_SECTION_FINAL_RESPONSE) + len(final.strip()) + 2,
+ max(1, max_chars - min(_MIN_BEHAVIOR_HISTORY_HEADROOM, max_chars // 2)),
+ )
+ if (
+ len(_SECTION_FILE_CHANGES) + len(file_changes.strip()) + 2 + reserved_final + reserved_tail + 4
+ > remaining
+ ):
+ file_section_limit = max(
+ min(800, remaining // 3),
+ remaining - reserved_final - reserved_tail - 4,
+ )
+ remaining = _append_section_with_budget(
+ parts,
+ _SECTION_FILE_CHANGES,
+ file_changes,
+ remaining,
+ section_limit=file_section_limit,
+ )
- final = _get_final_response(traj)
if final:
+ if max_chars > effective_final_limit:
+ reserved_headroom = min(
+ _MIN_BEHAVIOR_HISTORY_HEADROOM,
+ remaining // 2,
+ tail_needed,
+ max(800, remaining - effective_final_limit),
+ )
+ else:
+ reserved_headroom = min(_MIN_BEHAVIOR_HISTORY_HEADROOM, remaining // 2, tail_needed)
+ bounded_final_limit = min(effective_final_limit, max(1, remaining - reserved_headroom))
remaining = _append_section_with_budget(
parts,
- "FINAL RESPONSE",
+ _SECTION_FINAL_RESPONSE,
final,
remaining,
- section_limit=800,
+ section_limit=bounded_final_limit,
)
remaining = _append_section_with_budget(
parts,
- "USER REQUEST",
+ _SECTION_USER_REQUEST,
question,
remaining,
section_limit=800,
)
- history = build_conversation_summary(traj, question)
- remaining = _append_section_with_budget(parts, "COMPACT TOOL HISTORY", history, remaining)
+ remaining = _append_section_with_budget(parts, _SECTION_COMPACT_TOOL_HISTORY, history, remaining)
return "\n\n".join(parts)[:max_chars]
@@ -913,11 +1007,36 @@ def attach_metric_evidence_refs(details, evidence_refs):
# ── Metric Evidence Bundles ───────────────────────────────────────────────────
_BUNDLE_ITEM_CHARS = 1500
-_BUNDLE_BUDGETS = {"accuracy": 8000, "goal_accuracy": 12000, "behavior_check": 8000}
+_DEFAULT_ACCURACY_BUDGET = 8000
+_DEFAULT_GOAL_ACCURACY_BUDGET = 12000
+_BUNDLE_BUDGETS = {
+ "accuracy": _DEFAULT_ACCURACY_BUDGET,
+ "goal_accuracy": _DEFAULT_GOAL_ACCURACY_BUDGET,
+ "behavior_check": _DEFAULT_BEHAVIOR_CHECK_BUDGET,
+}
_BUNDLE_ACCURACY_MAX_OBS = 6
_BUNDLE_GOAL_MAX_OBS = 12
+def _accuracy_budget():
+ """Return the configured accuracy evidence budget or default."""
+ return _env_positive_int("SKILL_EVAL_ACCURACY_BUDGET", _DEFAULT_ACCURACY_BUDGET)
+
+
+def _goal_accuracy_budget():
+ """Return the configured goal accuracy evidence budget or default."""
+ return _env_positive_int("SKILL_EVAL_GOAL_ACCURACY_BUDGET", _DEFAULT_GOAL_ACCURACY_BUDGET)
+
+
+def _bundle_budgets():
+ """Return effective bundle budgets taking into account runtime overrides."""
+ return {
+ "accuracy": _accuracy_budget(),
+ "goal_accuracy": _goal_accuracy_budget(),
+ "behavior_check": _behavior_check_budget(),
+ }
+
+
def _clip(text, limit):
text = str(text or "")
return text if len(text) <= limit else text[:limit] + " …[clipped]"
@@ -940,14 +1059,32 @@ def _assemble(sections, budget):
used = 0
dropped = 0
truncated = False
- for title, body in sections:
- body = str(body or "").strip()
- if not body:
- continue
+ non_empty = [(title, str(body or "").strip()) for title, body in sections if str(body or "").strip()]
+ for idx, (title, body) in enumerate(non_empty):
block = f"{title}\n{body}"
if used + len(block) <= budget:
parts.append(block)
used += len(block) + 2
+ elif title == _SECTION_FINAL_RESPONSE and budget - used > 0:
+ avail = budget - used
+ later_blocks = [len(f"{t}\n{b}") + 2 for t, b in non_empty[idx + 1 :]]
+ if later_blocks and avail >= 160:
+ reserve_later = min(avail // 2, *later_blocks)
+ if avail - reserve_later > len(title) + 16:
+ avail -= reserve_later
+ header = f"{title}\n"
+ clip_suffix = " …[clipped]"
+ if avail > len(header) + len(clip_suffix):
+ clipped_body = _clip(body, avail - len(header) - len(clip_suffix))
+ clipped_block = f"{header}{clipped_body}"
+ elif avail > len(header):
+ clipped_block = f"{header}{body[: avail - len(header)]}"
+ else:
+ clipped_block = block[:avail]
+ parts.append(clipped_block)
+ used += len(clipped_block) + 2
+ dropped += 1
+ truncated = True
else:
dropped += 1
truncated = True
@@ -1088,16 +1225,17 @@ def build_metric_evidence_bundles(traj, question, *, ground_truth="", expected_b
return facts_section
bundles = {}
+ budgets = _bundle_budgets()
acc_text, acc_drop, acc_trunc = _assemble(
[
- ("FINAL RESPONSE", final),
+ (_SECTION_FINAL_RESPONSE, final),
("PRODUCED FILES / WRITES", file_changes),
("KEY OBSERVATIONS", "\n---\n".join(late_obs[:_BUNDLE_ACCURACY_MAX_OBS])),
],
- _BUNDLE_BUDGETS["accuracy"],
+ budgets["accuracy"],
)
bundles["accuracy"] = {
- "prompt_evidence": _prepend_facts(acc_text or _clip(get_agent_text(traj), _BUNDLE_BUDGETS["accuracy"])),
+ "prompt_evidence": _prepend_facts(acc_text or _clip(get_agent_text(traj), budgets["accuracy"])),
"evidence_refs": refs["accuracy"],
"omitted": {
"count": acc_drop,
@@ -1108,14 +1246,14 @@ def build_metric_evidence_bundles(traj, question, *, ground_truth="", expected_b
}
goal_text, goal_drop, goal_trunc = _assemble(
[
- ("FINAL RESPONSE", final),
+ (_SECTION_FINAL_RESPONSE, final),
("END-STATE FILE CHANGES", file_changes),
("RECENT TOOL RESULTS (newest first)", "\n---\n".join(late_obs[:_BUNDLE_GOAL_MAX_OBS])),
],
- _BUNDLE_BUDGETS["goal_accuracy"],
+ budgets["goal_accuracy"],
)
bundles["goal_accuracy"] = {
- "prompt_evidence": _prepend_facts(goal_text or _clip(get_agent_text(traj), _BUNDLE_BUDGETS["goal_accuracy"])),
+ "prompt_evidence": _prepend_facts(goal_text or _clip(get_agent_text(traj), budgets["goal_accuracy"])),
"evidence_refs": refs["goal_accuracy"],
"omitted": {
"count": goal_drop,
@@ -1124,7 +1262,9 @@ def build_metric_evidence_bundles(traj, question, *, ground_truth="", expected_b
},
"verified": facts,
}
- bc_text = build_behavior_evidence(traj, question, max_chars=_BUNDLE_BUDGETS["behavior_check"])
+ facts_overhead = len(facts_section) + 2 if facts_section else 0
+ bc_budget = max(1, budgets["behavior_check"] - facts_overhead)
+ bc_text = build_behavior_evidence(traj, question, max_chars=bc_budget)
bc_full = build_behavior_evidence(traj, question, max_chars=10**9)
bc_trunc = len(bc_full) > len(bc_text)
bundles["behavior_check"] = {
@@ -1140,14 +1280,77 @@ def build_metric_evidence_bundles(traj, question, *, ground_truth="", expected_b
return bundles
-def _compact_behavior_conversation(conversation_text, limit=8000):
+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):
+ if limit <= len(marker) + 1:
return conversation_text[:limit]
- head = max(1, (limit - len(marker)) * 2 // 3)
- tail = max(1, limit - len(marker) - head)
+ 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:]}"
diff --git a/tests/tier3/test_behavior_evidence.py b/tests/tier3/test_behavior_evidence.py
index 9de57207..7fa18833 100644
--- a/tests/tier3/test_behavior_evidence.py
+++ b/tests/tier3/test_behavior_evidence.py
@@ -105,12 +105,17 @@ def test_behavior_evidence_prioritizes_late_write_tool_calls() -> None:
assert 'collect(engine="gpu")' in evidence
-def test_harbor_template_behavior_evidence_matches_shared_helper() -> None:
+def _load_harbor_template_module():
template_path = Path(__file__).parents[2] / "src" / "skillevaluator" / "tier3" / "harbor" / "templates" / "eval.py"
spec = importlib.util.spec_from_file_location("harbor_eval_template", template_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
+ return module
+
+
+def test_harbor_template_behavior_evidence_matches_shared_helper() -> None:
+ module = _load_harbor_template_module()
evidence = module.build_behavior_evidence(_trajectory_with_late_write(), "question")
@@ -173,11 +178,7 @@ def test_metric_evidence_refs_link_judges_to_trajectory_and_expected_artifacts()
def test_harbor_template_metric_evidence_refs_match_shared_helper() -> None:
- template_path = Path(__file__).parents[2] / "src" / "skillevaluator" / "tier3" / "harbor" / "templates" / "eval.py"
- spec = importlib.util.spec_from_file_location("harbor_eval_template_refs", template_path)
- assert spec and spec.loader
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
+ module = _load_harbor_template_module()
traj = _trajectory_with_metric_refs()
shared_refs = atif_helpers.build_metric_evidence_refs(
@@ -288,11 +289,7 @@ def test_metric_evidence_refs_redact_secret_like_values_in_all_fields() -> None:
def test_harbor_template_metric_evidence_refs_redact_harbor_secret_shapes() -> None:
- template_path = Path(__file__).parents[2] / "src" / "skillevaluator" / "tier3" / "harbor" / "templates" / "eval.py"
- spec = importlib.util.spec_from_file_location("harbor_eval_template_secret_refs", template_path)
- assert spec and spec.loader
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
+ module = _load_harbor_template_module()
sha256_token = "sha256~abcdefghijklmnop"
cursor_token = "crsr_deadbeefcafebabe"
jwt_token = (
@@ -380,11 +377,7 @@ def test_metric_evidence_refs_redact_runtime_api_key_values(monkeypatch, env_var
def test_harbor_template_and_shared_redact_runtime_api_key_values_identically(monkeypatch) -> None:
- template_path = Path(__file__).parents[2] / "src" / "skillevaluator" / "tier3" / "harbor" / "templates" / "eval.py"
- spec = importlib.util.spec_from_file_location("harbor_eval_template_env_keys", template_path)
- assert spec and spec.loader
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
+ module = _load_harbor_template_module()
api_key = "qqq-other-runtime-secret-0987654321"
monkeypatch.setenv("NVIDIA_API_KEY", api_key)
@@ -404,11 +397,7 @@ def test_harbor_template_and_shared_redact_runtime_api_key_values_identically(mo
def test_harbor_template_main_persists_evidence_refs_in_reward_json(monkeypatch, tmp_path) -> None:
- template_path = Path(__file__).parents[2] / "src" / "skillevaluator" / "tier3" / "harbor" / "templates" / "eval.py"
- spec = importlib.util.spec_from_file_location("harbor_eval_template_main_refs", template_path)
- assert spec and spec.loader
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
+ module = _load_harbor_template_module()
logs_dir = tmp_path / "logs"
agent_dir = logs_dir / "agent"
@@ -627,11 +616,7 @@ def test_behavior_evidence_does_not_treat_read_like_tool_names_as_writes() -> No
def test_harbor_template_behavior_judge_keeps_late_tail_evidence(monkeypatch) -> None:
- template_path = Path(__file__).parents[2] / "src" / "skillevaluator" / "tier3" / "harbor" / "templates" / "eval.py"
- spec = importlib.util.spec_from_file_location("harbor_eval_template_for_judge", template_path)
- assert spec and spec.loader
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
+ module = _load_harbor_template_module()
prompts: list[str] = []
def fake_call_public_llm(prompt, **kwargs):
@@ -704,3 +689,566 @@ def test_behavior_evidence_ignores_non_write_shell_gt() -> None:
assert "print(3 > 2)" not in file_changes
assert "/workspace/output/result.txt" in file_changes
assert "/workspace/output/from_python.txt" in file_changes
+
+
+def _trajectory_with_long_final_response() -> dict:
+ """Build a synthetic trajectory with a long agent response."""
+ body = "START_MARKER_" + ("A" * 1700) + "_LATE_MARKER_" + ("B" * 500) + "_TAIL"
+ return {
+ "steps": [
+ {
+ "source": "user",
+ "message": "Verify onboarding setup",
+ },
+ {
+ "source": "agent",
+ "message": body,
+ },
+ ]
+ }
+
+
+def test_behavior_evidence_final_response_default_and_env_override(monkeypatch) -> None:
+ traj = _trajectory_with_long_final_response()
+
+ # By default, final response is capped at 800 chars and truncated
+ default_evidence = build_behavior_evidence(traj, "question")
+ assert "START_MARKER_" in default_evidence
+ assert "_LATE_MARKER_" not in default_evidence
+ assert "...[truncated]..." in default_evidence
+
+ # Overriding via environment variable expands the capture limit
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "3000")
+ expanded_evidence = build_behavior_evidence(traj, "question", max_chars=8000)
+ assert "START_MARKER_" in expanded_evidence
+ assert "_LATE_MARKER_" in expanded_evidence
+ assert "...[truncated]..." not in expanded_evidence
+
+
+def test_behavior_evidence_final_response_explicit_arg() -> None:
+ traj = _trajectory_with_long_final_response()
+
+ evidence = build_behavior_evidence(traj, "question", max_chars=8000, final_response_limit=3000)
+ assert "START_MARKER_" in evidence
+ assert "_LATE_MARKER_" in evidence
+ assert "...[truncated]..." not in evidence
+
+
+def test_behavior_evidence_standalone_reconciles_max_chars(monkeypatch) -> None:
+ traj = _trajectory_with_long_final_response()
+
+ # When final_response_limit is explicitly passed without max_chars, max_chars expands
+ evidence = build_behavior_evidence(traj, "question", final_response_limit=3000)
+ assert "START_MARKER_" in evidence
+ assert "_LATE_MARKER_" in evidence
+ assert "...[truncated]..." not in evidence
+
+ # When SKILL_EVAL_BEHAVIOR_CHECK_BUDGET is set in env, standalone call uses it
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "12000")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "3000")
+ env_evidence = build_behavior_evidence(traj, "question")
+ assert "START_MARKER_" in env_evidence
+ assert "_LATE_MARKER_" in env_evidence
+
+
+def test_behavior_check_budget_and_compactor_env_override(monkeypatch) -> None:
+ from skillevaluator.tier3.eval_core.llm_judge import _compact_behavior_conversation
+
+ sample_conversation = "A" * 9000
+
+ # Default compactor threshold is 8000
+ compacted = _compact_behavior_conversation(sample_conversation)
+ assert "...[middle truncated for behavior check]..." in compacted
+ assert len(compacted) <= 8000
+
+ # Overriding SKILL_EVAL_BEHAVIOR_CHECK_BUDGET raises compactor threshold
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "12000")
+ uncompacted = _compact_behavior_conversation(sample_conversation)
+ assert "...[middle truncated for behavior check]..." not in uncompacted
+ assert len(uncompacted) == 9000
+
+
+def test_behavior_check_budget_auto_reconciles_tool_history_headroom(monkeypatch) -> None:
+ from skillevaluator.tier3.eval_core import atif_helpers
+ from skillevaluator.tier3.eval_core.llm_judge import _behavior_check_budget as judge_budget
+
+ # If only final response limit is set to a large value, budget expands with headroom (4000)
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "8000")
+ assert atif_helpers._behavior_check_budget() == 12000
+ assert judge_budget() == 12000
+
+ # Equal explicit budget (8000) and exceeded explicit budget (6000) both reserve tool-history headroom (4000)
+ for explicit_budget in ("8000", "6000"):
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", explicit_budget)
+ assert atif_helpers._behavior_check_budget() == 12000
+ assert judge_budget() == 12000
+
+
+def _trajectory_with_failed_verification_and_long_claim(*, include_file_changes: bool = False) -> dict:
+ """Build a trajectory with a failed command (and optional large file writes) before a 9,000-char success claim."""
+ steps: list[dict] = [
+ {
+ "source": "user",
+ "message": "Run the verification suite and confirm all checks pass.",
+ }
+ ]
+ if include_file_changes:
+ for idx in range(2):
+ steps.append(
+ {
+ "source": "agent",
+ "tool_calls": [
+ {
+ "tool_call_id": f"write-{idx}",
+ "function_name": "Write",
+ "arguments": {
+ "file_path": f"/workspace/output/module_{idx}.py",
+ "content": f"# generated module {idx}\n" + ("x = 1\n" * 400),
+ },
+ }
+ ],
+ "observation": {
+ "results": [
+ {
+ "source_call_id": f"write-{idx}",
+ "content": f"Wrote /workspace/output/module_{idx}.py",
+ }
+ ]
+ },
+ }
+ )
+ steps.append(
+ {
+ "source": "agent",
+ "tool_calls": [
+ {
+ "tool_call_id": "verify-1",
+ "function_name": "Bash",
+ "arguments": {"command": "pytest -q tests/verify_suite.py"},
+ }
+ ],
+ "observation": {
+ "results": [
+ {
+ "source_call_id": "verify-1",
+ "content": "FAILED tests/verify_suite.py::test_core - AssertionError: verification failed (exit 1)",
+ }
+ ]
+ },
+ }
+ )
+ steps.append(
+ {
+ "source": "agent",
+ "message": "CLAIM_START: All verification checks succeeded!\n" + ("S" * 9000) + "\nCLAIM_END",
+ }
+ )
+ return {"steps": steps}
+
+
[email protected]("budget_env", ["8000", "6000"])
[email protected]("include_file_changes", [False, True], ids=["no_file_changes", "with_file_changes"])
+def test_explicit_budget_preserves_tool_history_with_long_final_response(
+ monkeypatch,
+ budget_env: str,
+ include_file_changes: bool,
+) -> None:
+ template_module = _load_harbor_template_module()
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", budget_env)
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "8000")
+
+ traj = _trajectory_with_failed_verification_and_long_claim(include_file_changes=include_file_changes)
+ question = "Run the verification suite and confirm all checks pass."
+
+ shared_bundles = atif_helpers.build_metric_evidence_bundles(
+ traj,
+ question,
+ expected_behavior=["Run pytest verification and report failures accurately"],
+ )
+ template_bundles = template_module.build_metric_evidence_bundles(
+ traj,
+ question,
+ expected_behavior=["Run pytest verification and report failures accurately"],
+ )
+
+ for impl_name, bundle in (
+ ("shared", shared_bundles["behavior_check"]["prompt_evidence"]),
+ ("template", template_bundles["behavior_check"]["prompt_evidence"]),
+ ):
+ assert "FINAL RESPONSE" in bundle, impl_name
+ assert "CLAIM_START:" in bundle, impl_name
+ assert "USER REQUEST" in bundle, impl_name
+ assert "COMPACT TOOL HISTORY" in bundle, impl_name
+ assert "pytest -q tests/verify_suite.py" in bundle, impl_name
+ assert "AssertionError: verification failed" in bundle, impl_name
+
+ assert shared_bundles["behavior_check"]["prompt_evidence"] == template_bundles["behavior_check"]["prompt_evidence"]
+
+
[email protected]("max_chars", [8000, 6000])
+def test_direct_max_chars_argument_reserves_tool_history_headroom(max_chars: int) -> None:
+ template_module = _load_harbor_template_module()
+ traj = _trajectory_with_failed_verification_and_long_claim(include_file_changes=False)
+ question = "Run the verification suite and confirm all checks pass."
+
+ shared_ev = build_behavior_evidence(traj, question, max_chars=max_chars, final_response_limit=8000)
+ template_ev = template_module.build_behavior_evidence(
+ traj, question, max_chars=max_chars, final_response_limit=8000
+ )
+
+ assert shared_ev == template_ev
+ assert len(shared_ev) <= max_chars
+ assert "FINAL RESPONSE" in shared_ev
+ assert "COMPACT TOOL HISTORY" in shared_ev
+ assert "AssertionError: verification failed" in shared_ev
+
+
[email protected]("tiny_limit", [10, 19, 20, 43, 44, 60])
+def test_behavior_evidence_and_compactor_handle_tiny_limits(monkeypatch, tiny_limit: int) -> None:
+ from skillevaluator.tier3.eval_core.llm_judge import _compact_behavior_conversation
+
+ template_module = _load_harbor_template_module()
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "8000")
+ traj = _trajectory_with_failed_verification_and_long_claim(include_file_changes=False)
+
+ shared_ev = build_behavior_evidence(traj, "question", max_chars=tiny_limit, final_response_limit=8000)
+ template_ev = template_module.build_behavior_evidence(
+ traj, "question", max_chars=tiny_limit, final_response_limit=8000
+ )
+ assert len(shared_ev) <= tiny_limit
+ assert shared_ev == template_ev
+
+ long_text = "HEAD_CONTEXT_" + ("M" * 5000) + "_TAIL_OUTCOME"
+ shared_compacted = _compact_behavior_conversation(long_text, limit=tiny_limit)
+ template_compacted = template_module._compact_behavior_conversation(long_text, limit=tiny_limit)
+ assert len(shared_compacted) <= tiny_limit
+ assert shared_compacted == template_compacted
+
+
+def test_seam_bundle_to_judge_behavior_check_retains_failed_command_and_claim(monkeypatch) -> None:
+ from skillevaluator.tier3.eval_core import llm_judge
+
+ template_module = _load_harbor_template_module()
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "8000")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "8000")
+
+ traj = _trajectory_with_failed_verification_and_long_claim(include_file_changes=False)
+ question = "Run the verification suite and confirm all checks pass."
+ behaviors = ["Run pytest verification and only claim success if tests pass"]
+
+ shared_prompts: list[str] = []
+ template_prompts: list[str] = []
+
+ def fake_shared_llm(prompt: str, **kwargs):
+ shared_prompts.append(prompt)
+ return json.dumps({"results": [{"step": 1, "passed": False, "reason": "test failed"}], "summary": "fail"}), None
+
+ def fake_template_llm(prompt: str, **kwargs):
+ template_prompts.append(prompt)
+ return json.dumps({"results": [{"step": 1, "passed": False, "reason": "test failed"}], "summary": "fail"}), None
+
+ monkeypatch.setattr(llm_judge, "call_public_llm", fake_shared_llm)
+ monkeypatch.setattr(template_module, "call_public_llm", fake_template_llm)
+
+ shared_bundle = atif_helpers.build_metric_evidence_bundles(
+ traj, question, expected_behavior=behaviors
+ )["behavior_check"]["prompt_evidence"]
+ template_bundle = template_module.build_metric_evidence_bundles(
+ traj, question, expected_behavior=behaviors
+ )["behavior_check"]["prompt_evidence"]
+
+ shared_res = llm_judge.judge_behavior_check(shared_bundle, behaviors)
+ template_res = template_module.judge_behavior_check(template_bundle, behaviors)
+
+ assert shared_res["score"] == template_res["score"] == 0.0
+ for prompt in (shared_prompts[0], template_prompts[0]):
+ assert "CLAIM_START:" in prompt
+ assert "AssertionError: verification failed" in prompt
+
+
+def test_harbor_template_behavior_evidence_respects_custom_limits(monkeypatch) -> None:
+ module = _load_harbor_template_module()
+ traj = _trajectory_with_long_final_response()
+
+ # Template default caps at 800
+ evidence_default = module.build_behavior_evidence(traj, "question")
+ assert "START_MARKER_" in evidence_default
+ assert "_LATE_MARKER_" not in evidence_default
+ assert "...[truncated]..." in evidence_default
+
+ # Template override respects SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "3000")
+ evidence_custom = module.build_behavior_evidence(traj, "question", max_chars=8000)
+ assert "START_MARKER_" in evidence_custom
+ assert "_LATE_MARKER_" in evidence_custom
+ assert "...[truncated]..." not in evidence_custom
+
+ # Template helpers match shared atif_helpers logic
+ assert module._behavior_final_response_limit() == atif_helpers._behavior_final_response_limit()
+ assert module._behavior_check_budget() == atif_helpers._behavior_check_budget()
+
+
+def test_verified_facts_preserve_final_response_in_behavior_judge_prompt(monkeypatch) -> None:
+ from skillevaluator.tier3.eval_core import llm_judge
+
+ template_module = _load_harbor_template_module()
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "8000")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "8000")
+
+ steps: list[dict] = [
+ {
+ "source": "user",
+ "message": "Run all twelve verification checks and summarize the outcome.",
+ },
+ {
+ "source": "agent",
+ "tool_calls": [
+ {
+ "tool_call_id": "write-0",
+ "function_name": "Write",
+ "arguments": {
+ "file_path": "/workspace/output/report.py",
+ "content": "# generated report\n" + ("value = 1\n" * 170),
+ },
+ }
+ ],
+ "observation": {
+ "results": [
+ {
+ "source_call_id": "write-0",
+ "content": "Wrote /workspace/output/report.py",
+ }
+ ]
+ },
+ },
+ ]
+ behaviors: list[str] = []
+ for idx in range(12):
+ token = f"pytest -q tests/check_module_{idx:02d}.py --maxfail=1 --tb=short"
+ behaviors.append(f"Execute `{token}` and confirm the final assertion")
+ steps.append(
+ {
+ "source": "agent",
+ "tool_calls": [
+ {
+ "tool_call_id": f"cmd-{idx}",
+ "function_name": "Bash",
+ "arguments": {"command": f"{token} && echo status_{idx:02d}_ok_" + ("x" * 90)},
+ }
+ ],
+ "observation": {
+ "results": [
+ {
+ "source_call_id": f"cmd-{idx}",
+ "content": f"passed check {idx:02d} " + ("y" * 80),
+ }
+ ]
+ },
+ }
+ )
+
+ final_claim = "FINAL_CLAIM_ASSERTION: All twelve verification modules passed without errors."
+ steps.append(
+ {
+ "source": "agent",
+ "message": final_claim + "\n" + ("P" * 6100) + "\nFINAL_TAIL_MARKER",
+ }
+ )
+ traj = {"steps": steps}
+ question = "Run all twelve verification checks and summarize the outcome."
+
+ def make_judge_stub(captured_prompts: list[str], count: int):
+ def _stub(prompt: str, **kwargs):
+ captured_prompts.append(prompt)
+ passed = final_claim in prompt
+ score = 1.0 if passed else 0.0
+ results = [{"step": i + 1, "passed": passed, "reason": "checked"} for i in range(count)]
+ return json.dumps({"results": results, "score": score, "summary": "done"}), None
+
+ return _stub
+
+ shared_prompts_no_facts: list[str] = []
+ monkeypatch.setattr(llm_judge, "call_public_llm", make_judge_stub(shared_prompts_no_facts, 1))
+ no_facts_bundle = atif_helpers.build_metric_evidence_bundles(
+ traj, question, expected_behavior=["Confirm the final assertion in the summary"]
+ )["behavior_check"]
+ no_facts_res = llm_judge.judge_behavior_check(
+ no_facts_bundle["prompt_evidence"], ["Confirm the final assertion in the summary"]
+ )
+ assert no_facts_res["score"] == 1.0
+
+ shared_prompts: list[str] = []
+ template_prompts: list[str] = []
+ monkeypatch.setattr(llm_judge, "call_public_llm", make_judge_stub(shared_prompts, len(behaviors)))
+ monkeypatch.setattr(template_module, "call_public_llm", make_judge_stub(template_prompts, len(behaviors)))
+
+ shared_bundle = atif_helpers.build_metric_evidence_bundles(
+ traj, question, expected_behavior=behaviors
+ )["behavior_check"]
+ template_bundle = template_module.build_metric_evidence_bundles(
+ traj, question, expected_behavior=behaviors
+ )["behavior_check"]
+
+ assert shared_bundle == template_bundle
+ assert len(shared_bundle["verified"]) == 12
+ assert len(shared_bundle["prompt_evidence"]) <= 12000
+ assert shared_bundle["omitted"]["truncated"] is True
+ assert shared_bundle["omitted"]["count"] == 1
+
+ shared_res = llm_judge.judge_behavior_check(shared_bundle["prompt_evidence"], behaviors)
+ template_res = template_module.judge_behavior_check(template_bundle["prompt_evidence"], behaviors)
+
+ assert shared_res["score"] == 1.0
+ assert template_res["score"] == 1.0
+ for prompt in (shared_prompts[0], template_prompts[0]):
+ assert "VERIFIED FACTS (deterministic):" in prompt
+ assert final_claim in prompt
+ assert "FINAL_TAIL_MARKER" in prompt
+
+
+def test_compact_behavior_conversation_preserves_final_response_section(monkeypatch) -> None:
+ from skillevaluator.tier3.eval_core import llm_judge
+
+ template_module = _load_harbor_template_module()
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "8000")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "8000")
+
+ facts_block = "VERIFIED FACTS (deterministic):\n" + "\n".join(
+ f"- [OBSERVED step {i}] claim_{i:02d} :: " + ("f" * 140) for i in range(1, 13)
+ )
+ file_changes_block = "FILE CHANGES\nAgent called: Write\nPath: /workspace/output/out.py\n" + ("c" * 1850)
+ final_claim = "FINAL_RESPONSE_CLAIM: The verification report is complete and accurate."
+ final_block = f"FINAL RESPONSE\n{final_claim}\n" + ("R" * 6000) + "\nFINAL_RESPONSE_END"
+ user_block = "USER REQUEST\nVerify the output and report."
+ history_block = "COMPACT TOOL HISTORY\n" + ("H" * 2100) + "\nLAST_TOOL_OBSERVATION"
+
+ oversized_bundle = f"{facts_block}\n\n{file_changes_block}\n\n{final_block}\n\n{user_block}\n\n{history_block}"
+ assert len(oversized_bundle) > 12000
+
+ shared_compacted = llm_judge._compact_behavior_conversation(oversized_bundle)
+ template_compacted = template_module._compact_behavior_conversation(oversized_bundle)
+
+ assert shared_compacted == template_compacted
+ assert len(shared_compacted) <= 12000
+ assert final_claim in shared_compacted
+ assert "FINAL_RESPONSE_END" in shared_compacted
+ assert "LAST_TOOL_OBSERVATION" in shared_compacted
+
+
+ "case_name,limit,final_limit_env,text_builder,expected_substrings",
+ [
+ (
+ "no_prefix_long_suffix",
+ 1200,
+ "600",
+ lambda: (
+ "FINAL RESPONSE\nSTART_FINAL_CLAIM_OK\n"
+ + ("F" * 300)
+ + "\nEND_FINAL_CLAIM_OK\n\nUSER REQUEST\nRun check.\n\nCOMPACT TOOL HISTORY\n"
+ + ("H" * 1500)
+ + "\nTAIL_HISTORY_MARKER"
+ ),
+ ["START_FINAL_CLAIM_OK", "END_FINAL_CLAIM_OK", "TAIL_HISTORY_MARKER"],
+ ),
+ (
+ "no_prefix_tiny_suffix_budget",
+ 420,
+ "400",
+ lambda: (
+ "FINAL RESPONSE\n"
+ + ("F" * 370)
+ + "\nEND_FINAL\n\nCOMPACT TOOL HISTORY\n"
+ + ("H" * 500)
+ + "\nTINY_TAIL"
+ ),
+ ["FINAL RESPONSE", "END_FINAL"],
+ ),
+ (
+ "long_prefix_no_suffix",
+ 1200,
+ "500",
+ lambda: (
+ "FILE CHANGES\nHEAD_FILE_MARKER\n"
+ + ("C" * 1500)
+ + "\nLATE_FILE_MARKER\n\nFINAL RESPONSE\nFINAL_ONLY_SUFFIX_OK"
+ ),
+ ["HEAD_FILE_MARKER", "LATE_FILE_MARKER", "FINAL_ONLY_SUFFIX_OK"],
+ ),
+ (
+ "long_prefix_no_suffix_tiny_rem",
+ 420,
+ "400",
+ lambda: (
+ "FILE CHANGES\nHEAD_TINY_PRE\n"
+ + ("C" * 600)
+ + "\n\nFINAL RESPONSE\n"
+ + ("F" * 370)
+ + "\nFINAL_END_TINY_REM"
+ ),
+ ["FINAL RESPONSE", "FINAL_END_TINY_REM"],
+ ),
+ (
+ "oversized_final_with_small_prefix_and_suffix",
+ 1500,
+ "800",
+ lambda: (
+ "FILE CHANGES\nSHORT_PREFIX\n\nFINAL RESPONSE\nFINAL_HEAD_KEEP\n"
+ + ("F" * 2000)
+ + "\nFINAL_TAIL_KEEP\n\nUSER REQUEST\nSHORT_SUFFIX"
+ ),
+ ["SHORT_PREFIX", "FINAL_HEAD_KEEP", "FINAL_TAIL_KEEP", "SHORT_SUFFIX"],
+ ),
+ (
+ "both_prefix_and_suffix_exceed_half_budgets",
+ 2000,
+ "600",
+ lambda: (
+ "FILE CHANGES\nPRE_START_MARK\n"
+ + ("P" * 1500)
+ + "\nPRE_END_MARK\n\nFINAL RESPONSE\nCORE_FINAL_CLAIM\n\nCOMPACT TOOL HISTORY\nSUF_START_MARK\n"
+ + ("S" * 1500)
+ + "\nSUF_END_MARK"
+ ),
+ ["PRE_START_MARK", "PRE_END_MARK", "CORE_FINAL_CLAIM", "SUF_START_MARK", "SUF_END_MARK"],
+ ),
+ (
+ "both_prefix_and_suffix_with_tiny_remaining_budget",
+ 440,
+ "400",
+ lambda: (
+ "FILE CHANGES\n"
+ + ("P" * 300)
+ + "\n\nFINAL RESPONSE\n"
+ + ("F" * 375)
+ + "\nTINY_BOTH_FINAL\n\nCOMPACT TOOL HISTORY\n"
+ + ("S" * 300)
+ ),
+ ["FINAL RESPONSE", "TINY_BOTH_FINAL"],
+ ),
+ ],
+)
+def test_compact_behavior_conversation_section_layout_permutations(
+ monkeypatch,
+ case_name: str,
+ limit: int,
+ final_limit_env: str,
+ text_builder,
+ expected_substrings: list[str],
+) -> None:
+ from skillevaluator.tier3.eval_core import llm_judge
+
+ template_module = _load_harbor_template_module()
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", final_limit_env)
+
+ raw_text = text_builder()
+ assert len(raw_text) > limit, case_name
+
+ shared_out = llm_judge._compact_behavior_conversation(raw_text, limit=limit)
+ template_out = template_module._compact_behavior_conversation(raw_text, limit=limit)
+
+ assert shared_out == template_out, case_name
+ assert len(shared_out) <= limit, case_name
+ for substr in expected_substrings:
+ assert substr in shared_out, f"{case_name}: missing {substr!r}"
+
diff --git a/tests/tier3/test_evidence_compiler.py b/tests/tier3/test_evidence_compiler.py
index f4a08e59..8a18b83e 100644
--- a/tests/tier3/test_evidence_compiler.py
+++ b/tests/tier3/test_evidence_compiler.py
@@ -3,10 +3,8 @@
from __future__ import annotations
-import importlib.util
-from pathlib import Path
-
-from test_behavior_evidence import _trajectory_with_late_write
+import pytest
+from test_behavior_evidence import _load_harbor_template_module, _trajectory_with_late_write
from skillevaluator.tier3.eval_core import atif_helpers
from skillevaluator.tier3.eval_core.atif_helpers import build_conversation_summary
@@ -67,20 +65,7 @@ def test_over_budget_sets_truncated_and_reason_not_silent() -> None:
def test_template_bundles_match_shared_helper() -> None:
- template_path = (
- Path(__file__).resolve().parents[2]
- / "src"
- / "skillevaluator"
- / "tier3"
- / "harbor"
- / "templates"
- / "eval.py"
- )
- spec = importlib.util.spec_from_file_location("harbor_eval_template", template_path)
- assert spec and spec.loader
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
-
+ module = _load_harbor_template_module()
traj = _trajectory_with_late_write()
args = {"ground_truth": "GPU test written", "expected_behavior": ["writes GPU test"]}
shared = atif_helpers.build_metric_evidence_bundles(traj, "question", **args)
@@ -89,3 +74,297 @@ def test_template_bundles_match_shared_helper() -> None:
for metric in METRICS:
assert shared[metric]["prompt_evidence"] == templated[metric]["prompt_evidence"], metric
assert shared[metric]["omitted"] == templated[metric]["omitted"], metric
+
+
+def test_bundle_budgets_defaults_and_env_overrides(monkeypatch) -> None:
+ # Defaults
+ assert atif_helpers._accuracy_budget() == 8000
+ assert atif_helpers._goal_accuracy_budget() == 12000
+ budgets = atif_helpers._bundle_budgets()
+ assert budgets["accuracy"] == 8000
+ assert budgets["goal_accuracy"] == 12000
+ assert budgets["behavior_check"] == 8000
+
+ # Non-integer / invalid fallback across all 4 budget/limit env vars
+ for invalid_val in ("invalid", " ", "3.14", ""):
+ monkeypatch.setenv("SKILL_EVAL_ACCURACY_BUDGET", invalid_val)
+ monkeypatch.setenv("SKILL_EVAL_GOAL_ACCURACY_BUDGET", invalid_val)
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", invalid_val)
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", invalid_val)
+ assert atif_helpers._accuracy_budget() == 8000
+ assert atif_helpers._goal_accuracy_budget() == 12000
+ assert atif_helpers._behavior_final_response_limit() == 800
+ assert atif_helpers._behavior_check_budget() == 8000
+
+ # Non-positive integer clamping and headroom reconciliation
+ for non_positive in ("0", "-10", "-500"):
+ monkeypatch.setenv("SKILL_EVAL_ACCURACY_BUDGET", non_positive)
+ monkeypatch.setenv("SKILL_EVAL_GOAL_ACCURACY_BUDGET", non_positive)
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", non_positive)
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", non_positive)
+ assert atif_helpers._accuracy_budget() == 1
+ assert atif_helpers._goal_accuracy_budget() == 1
+ assert atif_helpers._behavior_final_response_limit() == 1
+ assert atif_helpers._behavior_check_budget() == 4001 # final_limit (1) + headroom (4000)
+
+ # Valid environment overrides
+ monkeypatch.setenv("SKILL_EVAL_ACCURACY_BUDGET", "15000")
+ monkeypatch.setenv("SKILL_EVAL_GOAL_ACCURACY_BUDGET", "25000")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "800")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "10000")
+ assert atif_helpers._accuracy_budget() == 15000
+ assert atif_helpers._goal_accuracy_budget() == 25000
+ budgets_custom = atif_helpers._bundle_budgets()
+ assert budgets_custom["accuracy"] == 15000
+ assert budgets_custom["goal_accuracy"] == 25000
+ assert budgets_custom["behavior_check"] == 10000
+
+
+def test_harbor_template_bundle_budgets_match_shared(monkeypatch) -> None:
+ module = _load_harbor_template_module()
+
+ monkeypatch.setenv("SKILL_EVAL_ACCURACY_BUDGET", "9000")
+ monkeypatch.setenv("SKILL_EVAL_GOAL_ACCURACY_BUDGET", "18000")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "7000")
+
+ assert module._accuracy_budget() == atif_helpers._accuracy_budget() == 9000
+ assert module._goal_accuracy_budget() == atif_helpers._goal_accuracy_budget() == 18000
+ assert module._bundle_budgets() == atif_helpers._bundle_budgets()
+
+
+def test_verifier_env_vars_and_runner_include_budget_vars(monkeypatch) -> None:
+ from skillevaluator.tier3.harbor.adapter import _VERIFIER_PROVIDER_ENV_VARS
+ from skillevaluator.tier3.harbor.runner import ProviderConfig, _provider_environment
+
+ budget_vars = {
+ "SKILL_EVAL_ACCURACY_BUDGET",
+ "SKILL_EVAL_BEHAVIOR_CHECK_BUDGET",
+ "SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT",
+ "SKILL_EVAL_GOAL_ACCURACY_BUDGET",
+ }
+ assert budget_vars.issubset(_VERIFIER_PROVIDER_ENV_VARS)
+
+ monkeypatch.setenv("SKILL_EVAL_ACCURACY_BUDGET", "10000")
+ monkeypatch.setenv("SKILL_EVAL_GOAL_ACCURACY_BUDGET", "20000")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "9000")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "1200")
+
+ config = ProviderConfig(
+ provider="openai",
+ model="gpt-4o",
+ api_key="dummy",
+ base_url="https://api.openai.com/v1",
+ litellm_model="openai/gpt-4o",
+ )
+ env = _provider_environment(config)
+ assert env["SKILL_EVAL_ACCURACY_BUDGET"] == "10000"
+ assert env["SKILL_EVAL_GOAL_ACCURACY_BUDGET"] == "20000"
+ assert env["SKILL_EVAL_BEHAVIOR_CHECK_BUDGET"] == "9000"
+ assert env["SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT"] == "1200"
+
+
[email protected]("budget_val", [100, 200])
+def test_small_accuracy_and_goal_budgets_retain_final_response_excerpt(monkeypatch, budget_val: int) -> None:
+ from skillevaluator.tier3.eval_core import llm_judge
+
+ template_module = _load_harbor_template_module()
+ monkeypatch.setenv("SKILL_EVAL_ACCURACY_BUDGET", str(budget_val))
+ monkeypatch.setenv("SKILL_EVAL_GOAL_ACCURACY_BUDGET", str(budget_val))
+
+ final_answer = (
+ "FINAL_ANSWER_EXCERPT: The GPU execution failed because the CUDA driver was unavailable; "
+ "switched to the CPU fallback configuration and documented the root cause in detail for the user."
+ " Additional context padding to reach roughly two hundred sixty characters."
+ )
+ assert 230 <= len(final_answer) <= 270
+
+ traj = {
+ "steps": [
+ {"source": "user", "message": "Run the GPU check and explain the result."},
+ {
+ "source": "agent",
+ "tool_calls": [
+ {
+ "tool_call_id": "t1",
+ "function_name": "bash",
+ "arguments": {"command": "pytest -q"},
+ }
+ ],
+ "observation": {
+ "results": [
+ {
+ "source_call_id": "t1",
+ "content": "ERROR: CUDA driver not found (exit 1)",
+ }
+ ]
+ },
+ },
+ {"source": "agent", "message": final_answer},
+ ]
+ }
+ question = "Run the GPU check and explain the result."
+ ground_truth = "Explain that GPU execution failed due to missing CUDA driver."
+
+ shared_bundles = atif_helpers.build_metric_evidence_bundles(traj, question, ground_truth=ground_truth)
+ template_bundles = template_module.build_metric_evidence_bundles(traj, question, ground_truth=ground_truth)
+
+ for metric in ("accuracy", "goal_accuracy"):
+ shared_ev = shared_bundles[metric]["prompt_evidence"]
+ template_ev = template_bundles[metric]["prompt_evidence"]
+ assert shared_ev == template_ev, metric
+ assert "FINAL RESPONSE" in shared_ev, metric
+ assert "FINAL_ANSWER_EXCERPT:" in shared_ev, metric
+ if budget_val >= 160:
+ assert "ERROR: CUDA driver not found (exit 1)" in shared_ev, metric
+ assert len(shared_ev) <= budget_val, metric
+ assert shared_bundles[metric]["omitted"]["truncated"] is True, metric
+ assert shared_bundles[metric]["omitted"]["count"] >= 1, metric
+
+ captured_shared: dict[str, str] = {}
+ captured_template: dict[str, str] = {}
+
+ monkeypatch.setattr(
+ llm_judge,
+ "call_public_llm",
+ lambda prompt, **_kw: (
+ captured_shared.__setitem__("last", prompt)
+ or (
+ '{"achieved": true, "score": 1.0, "reason": "ok", "criteria": '
+ '{"SKILL_IDENTIFIED": true, "ACTION_CORRECT": true, "FACTUALLY_ACCURATE": true, '
+ '"TASK_ADDRESSED": true, "ACTIONABLE": true}}',
+ None,
+ )
+ ),
+ )
+ monkeypatch.setattr(
+ template_module,
+ "call_public_llm",
+ lambda prompt, **_kw: (
+ captured_template.__setitem__("last", prompt)
+ or (
+ '{"achieved": true, "score": 1.0, "reason": "ok", "criteria": '
+ '{"SKILL_IDENTIFIED": true, "ACTION_CORRECT": true, "FACTUALLY_ACCURATE": true, '
+ '"TASK_ADDRESSED": true, "ACTIONABLE": true}}',
+ None,
+ )
+ ),
+ )
+
+ llm_judge.judge_accuracy(question, ground_truth, shared_bundles["accuracy"]["prompt_evidence"])
+ template_module.judge_accuracy(question, ground_truth, template_bundles["accuracy"]["prompt_evidence"])
+ assert "FINAL_ANSWER_EXCERPT:" in captured_shared["last"]
+ assert "FINAL_ANSWER_EXCERPT:" in captured_template["last"]
+
+ llm_judge.judge_goal_accuracy(
+ question, ground_truth, shared_bundles["goal_accuracy"]["prompt_evidence"], tool_summary=""
+ )
+ template_module.judge_goal_accuracy(
+ question, ground_truth, template_bundles["goal_accuracy"]["prompt_evidence"], tool_summary=""
+ )
+ assert "FINAL_ANSWER_EXCERPT:" in captured_shared["last"]
+ assert "FINAL_ANSWER_EXCERPT:" in captured_template["last"]
+
+
[email protected]("budget", [10, 20, 26, 40])
+def test_assemble_micro_budgets_and_missing_final_response_fallback(monkeypatch, budget: int) -> None:
+ template_module = _load_harbor_template_module()
+ sections = [
+ ("FINAL RESPONSE", "Alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu."),
+ ("KEY OBSERVATIONS", "Secondary observation that should be dropped."),
+ ]
+ shared_text, shared_drop, shared_trunc = atif_helpers._assemble(sections, budget)
+ template_text, template_drop, template_trunc = template_module._assemble(sections, budget)
+
+ assert shared_text == template_text
+ assert shared_drop == template_drop == 2
+ assert shared_trunc is True and template_trunc is True
+ assert 0 < len(shared_text) <= budget
+
+ # Sad/edge path: agent produced no final text message, only a large file write + tool observation
+ monkeypatch.setenv("SKILL_EVAL_ACCURACY_BUDGET", "90")
+ monkeypatch.setenv("SKILL_EVAL_GOAL_ACCURACY_BUDGET", "90")
+ traj_no_final = {
+ "steps": [
+ {"source": "user", "message": "Generate output config."},
+ {
+ "source": "agent",
+ "tool_calls": [
+ {
+ "tool_call_id": "w1",
+ "function_name": "Write",
+ "arguments": {
+ "file_path": "/workspace/output/config.yaml",
+ "content": "setting: enabled\n" + ("# padding line\n" * 20),
+ },
+ }
+ ],
+ "observation": {"results": [{"source_call_id": "w1", "content": "wrote config.yaml"}]},
+ },
+ ]
+ }
+ shared_b = atif_helpers.build_metric_evidence_bundles(traj_no_final, "Generate output config.")
+ template_b = template_module.build_metric_evidence_bundles(traj_no_final, "Generate output config.")
+ for metric in ("accuracy", "goal_accuracy"):
+ assert shared_b[metric]["prompt_evidence"] == template_b[metric]["prompt_evidence"]
+ assert len(shared_b[metric]["prompt_evidence"]) <= 90
+ assert "config.yaml" in shared_b[metric]["prompt_evidence"]
+ assert shared_b[metric]["omitted"]["truncated"] is True
+
+
[email protected]("implementation", ["shared", "harbor"])
+ "budgets", [None, (7000, 11000)], ids=["defaults", "custom"]
+)
[email protected]("metric", ["accuracy", "goal_accuracy"])
+def test_tool_only_trajectory_retains_latest_verification_failure(monkeypatch, implementation, budgets, metric) -> None:
+ for name in ("SKILL_EVAL_ACCURACY_BUDGET", "SKILL_EVAL_GOAL_ACCURACY_BUDGET"):
+ monkeypatch.delenv(name, raising=False)
+ accuracy_budget, goal_budget = budgets or (8000, 12000)
+ if budgets:
+ monkeypatch.setenv("SKILL_EVAL_ACCURACY_BUDGET", str(accuracy_budget))
+ monkeypatch.setenv("SKILL_EVAL_GOAL_ACCURACY_BUDGET", str(goal_budget))
+
+ steps = [{"source": "user", "message": "Write the GPU tests and verify the suite."}]
+ for idx in range(7):
+ steps.append({
+ "source": "agent",
+ "tool_calls": [{
+ "tool_call_id": f"write-{idx}",
+ "function_name": "Write",
+ "arguments": {
+ "file_path": f"/workspace/output/test_gpu_{idx}.py",
+ "content": "\n".join(
+ f"def test_gpu_case_{case:03d}(): assert select_engine('gpu') == 'gpu'" for case in range(40)
+ ),
+ },
+ }],
+ })
+ failure = "FAILED tests/test_gpu.py::test_gpu_engine - AssertionError: expected gpu, got cpu"
+ for idx in range(9):
+ result = failure if idx == 8 else f"Verification run {idx + 1}: all GPU tests passed"
+ output = "\n".join([
+ result,
+ "============================= test session starts ==============================",
+ "platform linux -- Python 3.12.12, pytest-8.4.0",
+ *(f"tests/test_gpu.py::test_gpu_engine[dataset_{case:02d}] PASSED [100%]" for case in range(14)),
+ "============================= 14 tests completed ==============================",
+ ])
+ steps.append({
+ "source": "agent",
+ "tool_calls": [{
+ "tool_call_id": f"verify-{idx}",
+ "function_name": "bash",
+ "arguments": {"command": "pytest -v tests/test_gpu.py"},
+ }],
+ "observation": {"results": [{"source_call_id": f"verify-{idx}", "content": output}]},
+ })
+
+ module = atif_helpers if implementation == "shared" else _load_harbor_template_module()
+ bundles = module.build_metric_evidence_bundles({"steps": steps}, steps[0]["message"])
+ bundle = bundles[metric]
+ evidence = bundle["prompt_evidence"]
+ assert evidence.find(failure) >= 0, "The latest failed verification must survive without a final response"
+ assert "FINAL RESPONSE" not in evidence
+ assert len(evidence) <= {"accuracy": accuracy_budget, "goal_accuracy": goal_budget}[metric]
+ assert bundle["omitted"]["truncated"] is True
+ assert bundle["omitted"]["count"] > 0