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.

fix(tier3): narrow the behavior evidence gate and correct its accounting (#511)

Narendran Raghavan5f79aa3d8357
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1561dea9..83b60066 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -167,18 +167,28 @@ All notable changes to SkillEvaluator are documented in this file.
member verdicts, while explicitly labeling linked reports as single-skill
results and retaining their independent verdicts.
- Behavior checks no longer score a final answer that the evidence limits
- shortened. The final-response allowance rises from 800 to 8,000 characters,
- with the total behavior evidence budget reconciled to 12,000, so an ordinary
+ shortened. The final-response allowance rises from 800 to 8,000 characters
+ and the default behavior evidence budget from 8,000 to 12,000, so an ordinary
answer reaches the judge whole instead of losing its middle; the user request
- is reserved alongside it, ahead of the optional exploration output in the
- compact tool history. The `behavior_check` evidence record now reports
- whether the required evidence is complete, not only whether something was
- dropped. When the final answer still cannot fit, the judge returns an
- explicit evaluation error and no behavior score, rather than grading the
- evidence loss as a behavior failure, and that missing score stays missing
- instead of being averaged in as a zero.
+ keeps a reserved section of up to 2,000 characters ahead of the optional
+ exploration output in the compact tool history, which also repeats the
+ request at its head. The `behavior_check` evidence record now reports whether
+ the required evidence is complete, and which sections are incomplete, not
+ only whether something was dropped. When the final answer still cannot fit
+ and the deterministic verified facts do not already settle every expected
+ behavior, the judge returns an explicit evaluation error and no behavior
+ score, rather than grading the evidence loss as a behavior failure.
+ **That case then has no overall score at all**: an unscored metric that is
+ not "not applicable" leaves `overall_score` null, so such cases drop out of
+ any gate or comparison keyed on it until the limits are raised or the case is
+ shortened. A case whose expected behaviors are all confirmed by the verified
+ facts keeps its score, because the missing text cannot change the outcome.
`SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT` and
- `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET` still override both limits.
+ `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET` are both honoured exactly as set, in
+ either direction. Note that the final-response limit also caps the reserved
+ user-request section when it is set below 2,000, and that a check budget too
+ small to hold the final response beside some tool history is logged as a
+ warning rather than quietly raised — lower the final-response limit with it.
- Code Risk Analysis reports Semgrep file-level parse errors as one partial-scan
error that names up to 20 unparsed files, relative to the skill and with the
line of the first error, instead of the first three truncated messages. The
diff --git a/docs/environment-variables.mdx b/docs/environment-variables.mdx
index c9fd1cdd..5d5c4779 100644
--- a/docs/environment-variables.mdx
+++ b/docs/environment-variables.mdx
@@ -233,11 +233,21 @@ Larger budgets give judges more context and cost more prompt tokens.
| --- | --- | --- |
| `SKILL_EVAL_ACCURACY_BUDGET` | `8000` characters | Evidence budget for the `accuracy` judge: the agent's final response, files it wrote, and up to 6 recent tool results. |
| `SKILL_EVAL_GOAL_ACCURACY_BUDGET` | `12000` characters | Evidence budget for the `goal_accuracy` judge, including the RAGAS goal scorer: the final response, end-state file changes, and up to 12 recent tool results. |
-| `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET` | `8000` characters | Evidence budget for the `behavior_check` judge: file changes, the final response, the user request, and a compact tool history. The effective budget is never less than `SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT` plus 4000. |
-| `SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT` | `800` characters | Maximum length of the agent's final response within the `behavior_check` evidence. Values above 4000 can also raise the effective behavior-check budget. |
+| `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET` | `12000` characters | Evidence budget for the `behavior_check` judge: file changes, the final response, the user request, and a compact tool history. A value you set is used exactly as set, up or down. Only the default is reconciled upwards, to `SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT` plus 4000, so raising that limit alone still leaves room for the tool history. |
+| `SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT` | `8000` characters | Maximum length of the agent's final response within the `behavior_check` evidence. It also caps the reserved USER REQUEST section, which is otherwise 2000 characters. Raising it above 8000 also raises the *default* behavior-check budget, but never a budget you set yourself. |
+
+Setting `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET` below `SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT`
+plus 1600 is honoured, but logs a warning: the final response will not fit
+beside any tool history, and `behavior_check` then reports incomplete evidence
+instead of a score (see
+[behavior evidence completeness](tier3-live-evaluation.mdx#evidence-budgets)).
+Lower the final-response limit alongside the budget to cap the judge prompt
+without losing the answer.
Each value must be an integer. Values below `1` are treated as `1`, and
-non-integer values such as `8k` or `1.5` use the default. Set these variables in
+non-integer values such as `8k` or `1.5` use the default; neither is a budget
+you set, so `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET` falls back to its reconciled
+default in both cases. Set these variables in
the host environment that runs `skillevaluator`. As with the
[retry settings](#llm-retries-and-judge-time-budget), Tier 3 stages any that
are set into the generated task's `[verifier.env]`, and never into the agent's
diff --git a/docs/reports.mdx b/docs/reports.mdx
index 3fa8c4e0..b93ef1fe 100644
--- a/docs/reports.mdx
+++ b/docs/reports.mdx
@@ -560,7 +560,12 @@ completed run directly:
fit the [evidence budget](/skills/skillevaluator/tier3-live-evaluation#evidence-budgets) or, for
`behavior_check`, the final-response section limit
(`SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT`). For `behavior_check`, the
- record's `reason` names each setting that applied.
+ record's `reason` names each setting that applied, and
+ `incomplete_sections`, `required_complete` and `required_missing` say which
+ evidence did not reach the judge whole. A `behavior_check` whose required
+ evidence is incomplete is reported as an evaluation error with no score,
+ which also leaves the trial's `overall_score` null; see
+ [evidence budgets](/skills/skillevaluator/tier3-live-evaluation#evidence-budgets).
- **`<agent>/baseline_timeout_tolerance.json`** — written only for an agent
kept scored by `--tolerate-baseline-timeouts`: the baseline attempts that hit
the agent execution timeout. `result.json` carries the same record as
diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx
index 4ca55316..f69682ee 100644
--- a/docs/tier3-live-evaluation.mdx
+++ b/docs/tier3-live-evaluation.mdx
@@ -1313,11 +1313,41 @@ setting that cut evidence: `SKILL_EVAL_BEHAVIOR_CHECK_BUDGET`,
`SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT`, or both. Raise each setting it
names; raising the budget does not clear a cut made by the final-response
limit. Larger budgets send longer judge prompts and use more evaluator
-tokens. The behavior budget never falls below the final-response limit plus
-4,000 characters, so raising the limit leaves room for the tool history. Set these variables in the host environment;
+tokens. The *default* behavior budget never falls below the final-response
+limit plus 4,000 characters, so raising the limit alone leaves room for the
+tool history; a budget you set yourself is used exactly as set. Set these
+variables in the host environment;
SkillEvaluator forwards them to the verifier. Defaults and accepted values are
in [Judge evidence budgets](/skills/skillevaluator/environment-variables#judge-evidence-budgets).
+`behavior_check`'s `omitted` record carries four further keys, because
+`truncated` alone cannot say whether the judge still had what it needed:
+
+- `incomplete_sections` — the evidence sections whose complete source did not
+ reach the judge, by name: `final response`, `user request`, `file changes`,
+ `compact tool history`. Each is compared against its unclipped source, so
+ `file changes` and `compact tool history` also appear when a single write
+ body or tool result was longer than its own per-entry allowance, not only
+ when the overall budget was exceeded.
+- `required_complete` and `required_missing` — whether the *required*
+ evidence survived. Only `final response` is required: file changes and the
+ tool history grow with the run, so any finite budget shortens them on a long
+ trajectory, and their loss is reported but never withholds a score.
+- `expected_behaviors_verified` — whether the deterministic fact list already
+ settles every expected behavior, in which case the evidence that was cut
+ cannot change the judge's answer.
+
+When `required_complete` is `false`, `behavior_check` returns an evaluation
+error with no score instead of grading the evidence loss as a behavior
+failure, and **the case then has no overall score at all** — an unscored
+metric that is not "not applicable" leaves `overall_score` null, so the case
+drops out of any gate or comparison keyed on it. Raise the two settings the
+`reason` names, or shorten the case, and re-run. The one exception is
+`expected_behaviors_verified`: when every expected behavior names an artifact
+path or backtick-quoted snippet that the deterministic fact list above the
+evidence already marks observed, the missing text cannot change the answer, so
+the case is judged and scored normally.
+
### Judge requests and retries
- **Structured output.** Each judge requests a fixed JSON schema. OpenAI and
diff --git a/src/skillevaluator/tier3/eval_core/atif_helpers.py b/src/skillevaluator/tier3/eval_core/atif_helpers.py
index f1c4b187..f976327e 100644
--- a/src/skillevaluator/tier3/eval_core/atif_helpers.py
+++ b/src/skillevaluator/tier3/eval_core/atif_helpers.py
@@ -12,6 +12,7 @@ OpenHands, and Opencode.
from __future__ import annotations
import json
+import logging
import os
import re
from typing import Any
@@ -53,6 +54,8 @@ else: # Standalone helper staged beside the verifier.
from evidence import evidence_ref_identity
from secret_redaction import redact_secrets_in_log_line
+logger = logging.getLogger(__name__)
+
def get_all_tool_calls(traj: dict[str, Any]) -> list[dict[str, Any]]:
"""Extract all tool calls with function name, arguments, and observation text.
@@ -155,11 +158,21 @@ def get_output_tokens(traj: dict[str, Any]) -> int:
return last
-def build_conversation_summary(traj: dict[str, Any], question: str) -> str:
+def build_conversation_summary(traj: dict[str, Any], question: str, *, full: bool = False) -> str:
"""Build a human-readable conversation summary for LLM judges.
The summary is optimized for behavior-check and goal-accuracy prompts.
+
+ Each entry is clipped to a per-entry allowance so one noisy tool result
+ cannot crowd out the rest of the run. Pass ``full=True`` for the same
+ rendering with those per-entry clips lifted: the completeness accounting
+ compares against that, so content this function drops is not mistaken for
+ content that reached the judge.
"""
+
+ def clip(text: str, limit: int) -> str:
+ return text if full else text[:limit]
+
parts = [f"User: {question}"]
for step in traj.get("steps", []):
@@ -168,26 +181,26 @@ def build_conversation_summary(traj: dict[str, Any], question: str) -> str:
reasoning = step.get("reasoning_content") or ""
if reasoning:
- parts.append(f"Agent reasoning: {str(reasoning)[:200]}")
+ parts.append(f"Agent reasoning: {clip(str(reasoning), 200)}")
for _, tc in iter_tool_calls({"steps": [step]}):
fn = tc.get("function_name", "")
args = tc.get("arguments") or {}
- parts.append(f"Agent called: {fn}({json.dumps(args)[:200]})")
+ parts.append(f"Agent called: {fn}({clip(json.dumps(args), 200)})")
obs = step.get("observation") or {}
for r in obs.get("results") or []:
content = atif_content_text(r.get("content"))
if content:
- parts.append(f"Tool returned: {content[:400]}")
+ parts.append(f"Tool returned: {clip(content, 400)}")
msg = atif_content_text(step.get("message"))
if msg.strip() and not step.get("tool_calls"):
- parts.append(f"Agent: {msg[:1500]}")
+ parts.append(f"Agent: {clip(msg, 1500)}")
final = get_final_response(traj)
if final and not any(final[:50] in p for p in parts):
- parts.append(f"Agent final answer: {final[:1500]}")
+ parts.append(f"Agent final answer: {clip(final, 1500)}")
return "\n".join(parts)
@@ -201,6 +214,13 @@ _DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT = 8000
_DEFAULT_BEHAVIOR_CHECK_BUDGET = _DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT + 4000
_DEFAULT_TOOL_HISTORY_HEADROOM = 4000
_MIN_BEHAVIOR_HISTORY_HEADROOM = 1600
+# The user request is also repeated, in full, at the head of the compact tool
+# history, so its own section is a convenience copy rather than the only one.
+# Giving it the whole final-response allowance therefore buys a duplicate at
+# the tool history's expense, which is the one place a non-file behavior
+# ("ran the tests before finishing") is observable. Cap it well below the
+# answer's allowance instead.
+_DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT = 2000
_SECTION_COMPACT_TOOL_HISTORY = "COMPACT TOOL HISTORY"
_SECTION_FILE_CHANGES = "FILE CHANGES"
_SECTION_FINAL_RESPONSE = "FINAL RESPONSE"
@@ -223,22 +243,68 @@ def _behavior_final_response_limit() -> int:
return _env_positive_int("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", _DEFAULT_BEHAVIOR_FINAL_RESPONSE_LIMIT)
+def _env_int_or_none(name: str) -> int | None:
+ """Return environment variable *name* as an int, or ``None`` when unusable."""
+ raw = os.environ.get(name, "").strip()
+ if not raw:
+ return None
+ try:
+ return int(raw)
+ except ValueError:
+ return None
+
+
+_warned_behavior_budgets: set[tuple[int, int]] = set()
+
+
def _behavior_check_budget() -> int:
- """Return the configured behavior check evidence budget or reconciled default."""
+ """Return the behavior check evidence budget.
+
+ A usable ``SKILL_EVAL_BEHAVIOR_CHECK_BUDGET`` is honoured exactly as set.
+ Operators pin it to cap the judge prompt for a small-context model or a
+ token budget, so quietly raising it past what they asked for defeats the
+ only reason to set it. A value too small to hold the final response beside
+ some tool history is warned about rather than dropped, and the behavior
+ judge's evidence gate then reports the loss instead of scoring it. Only
+ the *default* is reconciled upwards with the final-response limit, so
+ raising that limit alone still leaves room for the tool history.
+ Unparseable and non-positive values are not budgets at all and fall back
+ to that 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)
+ configured = _env_int_or_none("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET")
+ if configured is None or configured < 1:
+ base_budget = _env_positive_int("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", _DEFAULT_BEHAVIOR_CHECK_BUDGET)
+ return max(base_budget, final_limit + _DEFAULT_TOOL_HISTORY_HEADROOM)
+ if configured < final_limit + _MIN_BEHAVIOR_HISTORY_HEADROOM:
+ key = (configured, final_limit)
+ if key not in _warned_behavior_budgets:
+ _warned_behavior_budgets.add(key)
+ logger.warning(
+ "SKILL_EVAL_BEHAVIOR_CHECK_BUDGET=%d leaves under %d characters beside a "
+ "SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT of %d. The budget is honoured as set, so behavior "
+ "evidence will be cut and behavior_check may report incomplete evidence instead of a score. "
+ "Lower SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT as well, or raise the budget to at least %d.",
+ configured,
+ _MIN_BEHAVIOR_HISTORY_HEADROOM,
+ final_limit,
+ final_limit + _MIN_BEHAVIOR_HISTORY_HEADROOM,
+ )
+ return configured
def _behavior_user_request_limit() -> int:
"""Return the behavior evidence allowance for the user request section.
- The request the agent answered is required evidence, like the answer
- itself, so it gets the same allowance instead of a fixed 800 characters.
- It is still appended before the optional exploration output in the compact
- tool history, so a long request costs history, never the final answer.
+ The old fixed 800 characters cut ordinary Tier 3 task prompts, but the
+ whole final-response allowance is too much: ``build_conversation_summary``
+ already opens the compact tool history with ``User: {question}``, so every
+ character spent here is a second copy, and the history — appended after
+ this section — absorbs the entire loss. Cap it at
+ ``_DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT``, never above the final-response
+ limit so that lowering that limit still shrinks the whole bundle.
"""
- return _behavior_final_response_limit()
+ return min(_DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT, _behavior_final_response_limit())
_BEHAVIOR_WRITE_TOOLS = {
@@ -330,7 +396,16 @@ def _tool_name_looks_like_write(fn_lower: str) -> bool:
return any(candidate in _BEHAVIOR_WRITE_TOOLS for candidate in candidates)
-def _collect_file_change_evidence(traj: dict[str, Any]) -> list[str]:
+def _collect_file_change_evidence(traj: dict[str, Any], *, full: bool = False) -> list[str]:
+ """Render one entry per write the agent made.
+
+ Each write body and tool result is clipped to a per-entry allowance. Pass
+ ``full=True`` for the same entries with those clips lifted, which is what
+ the completeness accounting compares against so a body this function
+ shortened is not reported as having reached the judge.
+ """
+ body_limit = 10**9 if full else 1800
+ observation_limit = 10**9 if full else 500
changes: list[str] = []
for step in traj.get("steps", []):
if step.get("source") != "agent":
@@ -362,9 +437,9 @@ def _collect_file_change_evidence(traj: dict[str, Any]) -> list[str]:
if file_path:
entry_parts.append(f"Path: {file_path}")
if body:
- entry_parts.append(_truncate_for_behavior(body, 1800))
+ entry_parts.append(_truncate_for_behavior(body, body_limit))
if obs:
- entry_parts.append(f"Tool returned: {_truncate_for_behavior(obs, 500)}")
+ entry_parts.append(f"Tool returned: {_truncate_for_behavior(obs, observation_limit)}")
changes.append("\n".join(entry_parts))
return changes
@@ -870,6 +945,33 @@ _VERIFIED_FACTS_MAX = 12
_VERIFIED_FACT_LINE_MAX = 200
+def _checkable_tokens(text: str, seen_claims: set[str] | None = None) -> list[tuple[str, str]]:
+ """Extract ``(claim, match_mode)`` pairs from *text*.
+
+ Modes are ``"path"`` for an artifact path and ``"ci"`` for a
+ backtick-quoted snippet of four or more characters. Claims already in
+ *seen_claims* are skipped, and new ones are added to it, so a caller can
+ deduplicate across several sources.
+ """
+ if seen_claims is None:
+ seen_claims = set()
+ tokens: list[tuple[str, str]] = []
+ body = str(text or "")
+ # a. artifact paths
+ for match in _EXPECTED_ARTIFACT_PATH_RE.finditer(body):
+ claim = match.group(0).rstrip(".,;:)]}'\"")
+ if claim and claim not in seen_claims:
+ seen_claims.add(claim)
+ tokens.append((claim, "path"))
+ # b. backtick-quoted snippets >= 4 chars (strip backticks)
+ for match in _BACKTICK_TOKEN_RE.finditer(body):
+ claim = match.group(1) # strip the backticks
+ if claim and claim not in seen_claims:
+ seen_claims.add(claim)
+ tokens.append((claim, "ci"))
+ return tokens
+
+
def build_verified_facts(
traj: dict[str, Any],
expected_behavior: list[str] | None,
@@ -890,19 +992,7 @@ def build_verified_facts(
sources = list(expected_behavior) + ([ground_truth] if ground_truth else [])
for source in sources:
- text = str(source or "")
- # a. artifact paths
- for match in _EXPECTED_ARTIFACT_PATH_RE.finditer(text):
- claim = match.group(0).rstrip(".,;:)]}'\"")
- if claim and claim not in seen_claims:
- seen_claims.add(claim)
- tokens.append((claim, "path"))
- # b. backtick-quoted snippets >= 4 chars (strip backticks)
- for match in _BACKTICK_TOKEN_RE.finditer(text):
- claim = match.group(1) # strip the backticks
- if claim and claim not in seen_claims:
- seen_claims.add(claim)
- tokens.append((claim, "ci"))
+ tokens.extend(_checkable_tokens(source, seen_claims))
if not tokens:
return []
@@ -1045,14 +1135,18 @@ def _behavior_evidence_completeness(
Every section is compared against its complete source rather than against
another budgeted rendering, so a cut the budget and the final-response cap
- both applied cannot hide behind either one. Returns
- ``(required_complete, required_missing, incomplete_sections)``.
+ both applied cannot hide behind either one. File changes and the tool
+ history are rendered with ``full=True`` for the same reason: their own
+ per-entry allowances clip write bodies and tool results before any budget
+ applies, and comparing against those clipped renderings reported a section
+ complete while thousands of characters of a written file had been dropped.
+ Returns ``(required_complete, required_missing, incomplete_sections)``.
"""
sources = {
_SECTION_FINAL_RESPONSE: get_final_response(traj),
_SECTION_USER_REQUEST: question,
- _SECTION_FILE_CHANGES: "\n\n".join(_collect_file_change_evidence(traj)),
- _SECTION_COMPACT_TOOL_HISTORY: build_conversation_summary(traj, question),
+ _SECTION_FILE_CHANGES: "\n\n".join(_collect_file_change_evidence(traj, full=True)),
+ _SECTION_COMPACT_TOOL_HISTORY: build_conversation_summary(traj, question, full=True),
}
required_missing: list[str] = []
incomplete: list[str] = []
@@ -1066,15 +1160,47 @@ def _behavior_evidence_completeness(
return not required_missing, required_missing, incomplete
+def _expected_behaviors_verified(expected_behavior: Any, facts: list[dict[str, Any]]) -> bool:
+ """Return True when deterministic facts already settle every expected behavior.
+
+ An expectation is settled when every checkable token it names — an
+ artifact path or a backtick-quoted snippet — appears in *facts* marked
+ observed. Those facts are computed from the trajectory, not from the
+ budgeted evidence, and they head the judge's prompt, so for such a case
+ the judge's answer does not depend on the final response surviving the
+ limits: withholding the score would discard a result the evidence
+ supports. An expectation that names nothing checkable (plain prose such
+ as "explains the trade-offs") is never settled this way, so prose
+ expectations keep the gate.
+ """
+ if not isinstance(expected_behavior, list) or not expected_behavior:
+ return False
+ observed = {str(fact.get("claim")) for fact in facts if fact.get("observed")}
+ for behavior in expected_behavior:
+ claims = [claim for claim, _mode in _checkable_tokens(behavior)]
+ if not claims or any(claim not in observed for claim in claims):
+ return False
+ return True
+
+
def behavior_evidence_gap(omitted: Any) -> str:
"""Describe the required behavior evidence missing from a bundle, or ``""``.
A behavior score read off evidence whose final answer was silently
shortened grades the evidence loss, not the agent, so callers use this to
withhold the score and raise an explicit evaluation error instead.
+
+ Nothing is withheld when the bundle reports
+ ``expected_behaviors_verified``: the deterministic facts at the head of
+ the evidence already settle every expectation, so the missing text cannot
+ change the outcome. The key is absent from records built before it
+ existed and from records assembled by hand, and absence means "not
+ known", which keeps the gate.
"""
if not isinstance(omitted, dict) or omitted.get("required_complete", True):
return ""
+ if omitted.get("expected_behaviors_verified", False):
+ return ""
missing = [str(item).strip() for item in omitted.get("required_missing") or [] if str(item).strip()]
names = ", ".join(missing) or "required evidence"
reason = str(omitted.get("reason") or "").strip()
@@ -1191,6 +1317,10 @@ def build_metric_evidence_bundles(
# is ordinary. Completeness says whether the evidence the judge must read
# survived, so the judge can refuse to score an evidence-loss artifact.
bc_required_ok, bc_required_missing, bc_incomplete = _behavior_evidence_completeness(traj, question, bc_evidence)
+ # Whether the gap matters is a separate question from whether there is
+ # one. When the deterministic facts above already settle every expected
+ # behavior, the judge's answer does not rest on the text the limits cut.
+ bc_behaviors_verified = _expected_behaviors_verified(expected_behavior, facts)
bundles["behavior_check"] = {
"prompt_evidence": bc_evidence,
"evidence_refs": refs["behavior_check"],
@@ -1201,6 +1331,7 @@ def build_metric_evidence_bundles(
"required_complete": bc_required_ok,
"required_missing": bc_required_missing,
"incomplete_sections": bc_incomplete,
+ "expected_behaviors_verified": bc_behaviors_verified,
},
"verified": facts,
}
diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py
index 3c70623c..422c422c 100644
--- a/src/skillevaluator/tier3/harbor/templates/eval.py
+++ b/src/skillevaluator/tier3/harbor/templates/eval.py
@@ -753,10 +753,13 @@ _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
@@ -808,6 +811,7 @@ _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
diff --git a/tests/tier3/test_behavior_evidence.py b/tests/tier3/test_behavior_evidence.py
index a31391d5..b1eb20a5 100644
--- a/tests/tier3/test_behavior_evidence.py
+++ b/tests/tier3/test_behavior_evidence.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import importlib.util
import json
+import logging
from pathlib import Path
import pytest
@@ -562,6 +563,79 @@ def test_behavior_evidence_keeps_write_when_prompt_is_long() -> None:
assert "/workspace/output/test_gpu_engine_selection.py" in evidence
+def _evidence_section(evidence: str, title: str) -> str:
+ """Return the body of *title*'s section, or ``""`` when it is absent."""
+ start = evidence.find(f"{title}\n")
+ if start == -1:
+ return ""
+ body_start = start + len(title) + 1
+ ends = [
+ evidence.find(f"\n\n{other}\n", body_start)
+ for other in ("FILE CHANGES", "FINAL RESPONSE", "USER REQUEST", "COMPACT TOOL HISTORY")
+ if other != title
+ ]
+ ends = [end for end in ends if end != -1]
+ return evidence[body_start : min(ends)] if ends else evidence[body_start:]
+
+
+def test_behavior_evidence_user_request_allowance_is_capped_above_the_old_800() -> None:
+ # The USER REQUEST section gets its own allowance of
+ # _DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT characters: enough for an ordinary
+ # Tier 3 task prompt, which the old fixed 800 cut, but not the whole
+ # final-response allowance, which would spend up to 8,000 of the budget on
+ # a second copy of a question the compact tool history already repeats and
+ # leave no room for the tool calls.
+ question = "QSTART_" + ("q" * 1000) + "_QMID_" + ("q" * 1800) + "_QEND"
+ assert len(question) == 2818
+ traj = {
+ "steps": [
+ {
+ "source": "agent",
+ "tool_calls": [
+ {"tool_call_id": f"run-{idx}", "function_name": "Bash", "arguments": {"command": f"pytest -k t{idx}"}}
+ ],
+ "observation": {"results": [{"source_call_id": f"run-{idx}", "content": f"{idx} passed"}]},
+ }
+ for idx in range(12)
+ ]
+ + [{"source": "agent", "message": "FINAL_ANSWER_BODY all tests pass."}]
+ }
+
+ evidence = build_behavior_evidence(traj, question, max_chars=12000)
+ user_section = _evidence_section(evidence, "USER REQUEST")
+
+ # Past the old 800-character cap, which dropped everything from offset 511
+ # to the last 256 characters.
+ assert "QSTART_" in user_section
+ assert "_QMID_" in user_section
+ assert "_QEND" in user_section
+ # But still capped: the section is bounded by its own allowance, not by the
+ # 8,000-character final-response allowance, which would carry all 2,818.
+ assert "...[truncated]..." in user_section
+ assert len(user_section) <= atif_helpers._DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT
+
+ # The final answer is untouched, and the tool history still carries tool
+ # calls — the evidence a non-file behavior is judged on.
+ assert "FINAL_ANSWER_BODY all tests pass." in _evidence_section(evidence, "FINAL RESPONSE")
+ assert "Agent called: Bash" in _evidence_section(evidence, "COMPACT TOOL HISTORY")
+
+ # Nothing of the request is actually lost: the compact tool history opens
+ # with the whole question.
+ assert question in evidence
+
+
+def test_behavior_evidence_user_request_limit_never_exceeds_the_final_response_limit(monkeypatch) -> None:
+ # Lowering the final-response limit must still shrink the whole bundle,
+ # so the user-request allowance follows it down.
+ assert atif_helpers._behavior_user_request_limit() == atif_helpers._DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT
+
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "500")
+ assert atif_helpers._behavior_user_request_limit() == 500
+
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "20000")
+ assert atif_helpers._behavior_user_request_limit() == atif_helpers._DEFAULT_BEHAVIOR_USER_REQUEST_LIMIT
+
+
def test_behavior_evidence_does_not_treat_read_like_tool_names_as_writes() -> None:
traj = {
"steps": [
@@ -751,29 +825,55 @@ def test_behavior_evidence_default_keeps_a_realistic_final_answer() -> None:
def test_behavior_evidence_final_response_explicit_arg() -> None:
- traj = _trajectory_with_long_final_response()
+ # The answer is 4,031 characters: under the 8,000-character default it
+ # survives whole, and a per-call limit of 3,000 cuts its middle. Without
+ # that span the explicit argument changes nothing and the test proves
+ # nothing (the defaults produce a 2,231-character answer, which fits
+ # either way).
+ traj = _trajectory_with_long_final_response(middle=2500, tail=1500)
+
+ default_evidence = build_behavior_evidence(traj, "question", max_chars=8000)
+ assert "START_MARKER_" in default_evidence
+ assert "_LATE_MARKER_" in default_evidence
+ assert "...[truncated]..." not in default_evidence
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
+ assert "_LATE_MARKER_" not in evidence
+ assert "...[truncated]..." in evidence
def test_behavior_evidence_standalone_reconciles_max_chars(monkeypatch) -> None:
- traj = _trajectory_with_long_final_response()
+ traj = _trajectory_with_long_final_response(middle=2500, tail=1500)
- # When final_response_limit is explicitly passed without max_chars, max_chars expands
- evidence = build_behavior_evidence(traj, "question", final_response_limit=3000)
+ # When final_response_limit is explicitly passed without max_chars, max_chars
+ # expands to hold it: a 6,000-character limit carries the whole 4,031-character
+ # answer even though the standalone floor is only 4,000 characters.
+ evidence = build_behavior_evidence(traj, "question", final_response_limit=6000)
assert "START_MARKER_" in evidence
assert "_LATE_MARKER_" in evidence
assert "...[truncated]..." not in evidence
+ assert len(evidence) > atif_helpers._BEHAVIOR_EVIDENCE_MAX_CHARS
+
+ # And a lower per-call limit still binds, so the expansion follows the
+ # argument rather than ignoring it.
+ tight = build_behavior_evidence(traj, "question", final_response_limit=3000)
+ assert "_LATE_MARKER_" not in tight
+ assert "...[truncated]..." in tight
# 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")
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "6000")
env_evidence = build_behavior_evidence(traj, "question")
assert "START_MARKER_" in env_evidence
assert "_LATE_MARKER_" in env_evidence
+ assert "...[truncated]..." not in env_evidence
+
+ # The env limit binds downwards too, on the same budget.
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "3000")
+ tight_env = build_behavior_evidence(traj, "question")
+ assert "_LATE_MARKER_" not in tight_env
+ assert "...[truncated]..." in tight_env
def test_behavior_check_budget_and_compactor_env_override(monkeypatch) -> None:
@@ -797,16 +897,51 @@ def test_behavior_check_budget_auto_reconciles_tool_history_headroom(monkeypatch
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)
+ # If only final response limit is set to a large value, the DEFAULT budget
+ # expands with headroom (4000).
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "16000")
+ assert atif_helpers._behavior_check_budget() == 20000
+ assert judge_budget() == 20000
+
+ # Unparseable and non-positive values are not budgets, so they fall back to
+ # that same reconciled default rather than being honoured.
+ for unusable in ("16k", "1.5", "0", "-100"):
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", unusable)
+ assert atif_helpers._behavior_check_budget() == 20000
+ assert judge_budget() == 20000
+
+
+def test_explicit_behavior_check_budget_is_honoured_below_the_default_floor(monkeypatch, caplog) -> None:
+ # An operator pins this to cap the judge prompt for a small-context model.
+ # Quietly raising it to the final-response limit plus 4,000 would defeat
+ # the only reason to set it, so it is used as set and warned about.
+ from skillevaluator.tier3.eval_core import atif_helpers
+ from skillevaluator.tier3.eval_core.llm_judge import _behavior_check_budget as judge_budget
+
monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT", "8000")
- assert atif_helpers._behavior_check_budget() == 12000
- assert judge_budget() == 12000
+ monkeypatch.setattr(atif_helpers, "_warned_behavior_budgets", set())
- # Equal explicit budget (8000) and exceeded explicit budget (6000) both reserve tool-history headroom (4000)
- for explicit_budget in ("8000", "6000"):
+ for explicit_budget, expected in (("2000", 2000), ("6000", 6000), ("8000", 8000), ("16000", 16000)):
monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", explicit_budget)
- assert atif_helpers._behavior_check_budget() == 12000
- assert judge_budget() == 12000
+ assert atif_helpers._behavior_check_budget() == expected
+ assert judge_budget() == expected
+
+ # A budget too small to hold the final response beside any tool history is
+ # warned about, naming both settings, rather than silently dropped.
+ monkeypatch.setattr(atif_helpers, "_warned_behavior_budgets", set())
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "2000")
+ with caplog.at_level(logging.WARNING, logger=atif_helpers.__name__):
+ assert atif_helpers._behavior_check_budget() == 2000
+ assert "SKILL_EVAL_BEHAVIOR_CHECK_BUDGET=2000" in caplog.text
+ assert "SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT" in caplog.text
+
+ # A budget with room for the answer and some history is not warned about.
+ caplog.clear()
+ monkeypatch.setattr(atif_helpers, "_warned_behavior_budgets", set())
+ monkeypatch.setenv("SKILL_EVAL_BEHAVIOR_CHECK_BUDGET", "9600")
+ with caplog.at_level(logging.WARNING, logger=atif_helpers.__name__):
+ assert atif_helpers._behavior_check_budget() == 9600
+ assert caplog.text == ""
def _trajectory_with_failed_verification_and_long_claim(*, include_file_changes: bool = False) -> dict:
diff --git a/tests/tier3/test_evidence_compiler.py b/tests/tier3/test_evidence_compiler.py
index 1e472684..9b151056 100644
--- a/tests/tier3/test_evidence_compiler.py
+++ b/tests/tier3/test_evidence_compiler.py
@@ -406,6 +406,43 @@ def test_behavior_bundle_keeps_a_realistic_final_answer_at_the_default_limit() -
assert bundle["omitted"]["incomplete_sections"] == []
+def test_behavior_bundle_reports_sections_cut_by_their_own_per_entry_caps() -> None:
+ # FILE CHANGES clips each write body to 1,800 characters and each tool
+ # result to 500, and the compact tool history clips arguments, results and
+ # agent messages, all before any budget applies. Completeness is compared
+ # against the unclipped rendering, so content those caps dropped is
+ # reported rather than counted as having reached the judge.
+ content = "HEAD_MARK " + "a" * 2000 + " MIDDLE_MARK " + "b" * 2000 + " TAIL_MARK"
+ assert len(content) > 1800
+ traj = {
+ "steps": [
+ {
+ "source": "agent",
+ "tool_calls": [
+ {
+ "tool_call_id": "write-1",
+ "function_name": "Write",
+ "arguments": {"file_path": "/workspace/output/x.txt", "content": content},
+ }
+ ],
+ "observation": {"results": [{"source_call_id": "write-1", "content": "ok"}]},
+ },
+ {"source": "agent", "message": "Done, wrote the file."},
+ ]
+ }
+
+ for module in (atif_helpers, _load_harbor_template_module()):
+ bundle = module.build_metric_evidence_bundles(traj, "Write x")["behavior_check"]
+ evidence = bundle["prompt_evidence"]
+ assert "HEAD_MARK" in evidence
+ assert "MIDDLE_MARK" not in evidence
+ assert "file changes" in bundle["omitted"]["incomplete_sections"]
+ # Only the final response withholds a score, so a per-entry cap is a
+ # diagnostic, not a gate: the answer itself still arrived whole.
+ assert bundle["omitted"]["required_complete"] is True
+ assert bundle["omitted"]["required_missing"] == []
+
+
def test_behavior_bundle_completeness_follows_the_final_response_limit_env_var(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -518,20 +555,21 @@ def test_behavior_bundle_final_answer_split_across_history_and_section(
@pytest.mark.parametrize(
- ("env", "reason"),
+ ("env", "reason", "incomplete"),
[
- ({}, f"{_BUDGET_REASON}; {_LIMIT_REASON}"),
- ({"SKILL_EVAL_BEHAVIOR_CHECK_BUDGET": "100000"}, _LIMIT_REASON),
- ({"SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT": "20000"}, _BUDGET_REASON),
+ ({}, f"{_BUDGET_REASON}; {_LIMIT_REASON}", ["final response", "compact tool history"]),
+ ({"SKILL_EVAL_BEHAVIOR_CHECK_BUDGET": "100000"}, _LIMIT_REASON, ["final response", "compact tool history"]),
+ ({"SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT": "20000"}, _BUDGET_REASON, ["compact tool history"]),
(
{"SKILL_EVAL_BEHAVIOR_CHECK_BUDGET": "100000", "SKILL_EVAL_BEHAVIOR_FINAL_RESPONSE_LIMIT": "20000"},
"",
+ [],
),
],
ids=["both", "limit-only", "budget-only", "neither"],
)
def test_behavior_bundle_reason_names_each_setting_that_cut_evidence(
- monkeypatch: pytest.MonkeyPatch, env: dict[str, str], reason: str
+ monkeypatch: pytest.MonkeyPatch, env: dict[str, str], reason: str, incomplete: list[str]
) -> None:
# A long tool history overflows the default behavior budget, and a final
# answer past the 8,000-character default also loses its middle to the
@@ -564,3 +602,7 @@ def test_behavior_bundle_reason_names_each_setting_that_cut_evidence(
# the final-response section, so completeness is the coverage check,
# not a contiguous substring. Only the final-response limit loses it.
assert bundle["omitted"]["required_complete"] is (_LIMIT_REASON not in reason)
+ # incomplete_sections is the diagnostic half of the same accounting and
+ # reports non-required losses too, so the budget-only case names the
+ # tool history while the required evidence is still complete.
+ assert bundle["omitted"]["incomplete_sections"] == incomplete
diff --git a/tests/tier3/test_judge_contracts.py b/tests/tier3/test_judge_contracts.py
index 5ae31f4d..28c99383 100644
--- a/tests/tier3/test_judge_contracts.py
+++ b/tests/tier3/test_judge_contracts.py
@@ -6,6 +6,8 @@
from __future__ import annotations
import json
+import random
+import string
from pathlib import Path
from types import ModuleType
from typing import Any
@@ -378,10 +380,53 @@ def _never_called(*args: Any, **kwargs: Any):
raise AssertionError("the judge must not call a model on incomplete evidence")
-def _behavior_bundle(module: ModuleType, traj: dict[str, Any]) -> dict[str, Any]:
+def _behavior_bundle(
+ module: ModuleType,
+ traj: dict[str, Any],
+ expected_behavior: list[str] | None = None,
+) -> dict[str, Any]:
"""Build the behavior_check bundle with the module the judge belongs to."""
builder = atif_helpers if module is llm_judge else module
- return builder.build_metric_evidence_bundles(traj, "Explain the migration.")["behavior_check"]
+ return builder.build_metric_evidence_bundles(
+ traj, "Explain the migration.", expected_behavior=expected_behavior
+ )["behavior_check"]
+
+
+_VERIFIED_PATH = "/workspace/output/report.md"
+_VERIFIED_BEHAVIOR = f"writes the file `{_VERIFIED_PATH}`"
+
+
+def _traj_with_verified_write_and_long_answer(answer_chars: int = 9000) -> dict[str, Any]:
+ """A run whose one expected behavior is provable from the write alone.
+
+ The final answer is long enough that the final-response limit cuts its
+ middle, which is the condition the evidence gate fires on.
+ """
+ return {
+ "steps": [
+ {
+ "source": "agent",
+ "tool_calls": [
+ {
+ "tool_call_id": "write-1",
+ "function_name": "Write",
+ "arguments": {"file_path": _VERIFIED_PATH, "content": "# Report\nAll good.\n"},
+ }
+ ],
+ "observation": {"results": [{"source_call_id": "write-1", "content": "File written"}]},
+ },
+ {"source": "agent", "message": _distinct_answer(answer_chars)},
+ ]
+ }
+
+
+def _distinct_answer(length: int) -> str:
+ """Build non-repetitive text, so a cut middle cannot be matched elsewhere."""
+ rng = random.Random(20234)
+ words: list[str] = []
+ while sum(len(word) + 1 for word in words) < length:
+ words.append("".join(rng.choice(string.ascii_lowercase) for _ in range(rng.randint(3, 9))))
+ return " ".join(words)[:length]
def test_incomplete_required_behavior_evidence_errors_without_a_model_call(judge_module, monkeypatch) -> None:
@@ -458,6 +503,85 @@ def test_oversized_final_answer_reaches_the_judge_gate_as_an_error(judge_module,
assert result["status"] == "error"
+def test_cut_answer_still_scores_when_verified_facts_settle_every_behavior(judge_module, monkeypatch) -> None:
+ # The gate exists to stop a score being read off evidence the limits cut.
+ # It must not discard a score the surviving evidence supports: here the one
+ # expected behavior is a path the deterministic fact list already marks
+ # OBSERVED, so the missing middle of the answer cannot change the answer.
+ calls: list[dict[str, Any]] = []
+ response = json.dumps({"results": [{"step": 1, "passed": True, "reason": "wrote the report"}]})
+ monkeypatch.setattr(judge_module, "call_public_llm", _script([(response, None)], calls))
+
+ bundle = _behavior_bundle(judge_module, _traj_with_verified_write_and_long_answer(), [_VERIFIED_BEHAVIOR])
+
+ # The evidence really is incomplete — the gate's own precondition holds.
+ assert bundle["omitted"]["required_complete"] is False
+ assert bundle["omitted"]["required_missing"] == ["final response"]
+ # And the deterministic facts settle the expectation regardless.
+ assert bundle["omitted"]["expected_behaviors_verified"] is True
+ assert f"[OBSERVED step 0] {_VERIFIED_PATH}" in bundle["prompt_evidence"]
+
+ result = judge_module.judge_behavior_check(
+ bundle["prompt_evidence"], [_VERIFIED_BEHAVIOR], evidence_omitted=bundle["omitted"]
+ )
+
+ assert len(calls) == 1
+ assert result.get("status") != "error"
+ assert result["score"] == 1.0
+
+ # And the case keeps an overall score, instead of dropping out of every
+ # gate and comparison keyed on one.
+ from skillevaluator.tier3.harbor.metrics import overall_score_from_metrics
+
+ scores = {
+ "security": 1.0,
+ "skill_execution": 1.0,
+ "skill_efficiency": 1.0,
+ "accuracy": 1.0,
+ "goal_accuracy": 1.0,
+ "behavior_check": result["score"],
+ }
+ assert overall_score_from_metrics(scores) == 1.0
+
+
+def test_cut_answer_is_still_gated_when_any_behavior_needs_the_answer(judge_module, monkeypatch) -> None:
+ # A prose expectation names nothing checkable, so it can only be judged
+ # from the text the limits cut. One such expectation keeps the gate, even
+ # beside a behavior the facts do settle.
+ monkeypatch.setattr(judge_module, "call_public_llm", _never_called)
+ traj = _traj_with_verified_write_and_long_answer()
+
+ for expectations in (
+ ["explains the migration trade-offs"],
+ [_VERIFIED_BEHAVIOR, "explains the migration trade-offs"],
+ ):
+ bundle = _behavior_bundle(judge_module, traj, expectations)
+ assert bundle["omitted"]["required_complete"] is False
+ assert bundle["omitted"]["expected_behaviors_verified"] is False
+
+ result = judge_module.judge_behavior_check(
+ bundle["prompt_evidence"], expectations, evidence_omitted=bundle["omitted"]
+ )
+
+ assert result["score"] is None
+ assert result["status"] == "error"
+
+
+def test_behavior_evidence_gap_treats_an_absent_verified_flag_as_unknown(judge_module, monkeypatch) -> None:
+ # Records written before the flag existed, and records assembled by hand,
+ # must keep the gate rather than skip it by default.
+ monkeypatch.setattr(judge_module, "call_public_llm", _never_called)
+ omitted = {"required_complete": False, "required_missing": ["final response"], "reason": "cut"}
+
+ assert judge_module.behavior_evidence_gap(omitted)
+ assert judge_module.behavior_evidence_gap({**omitted, "expected_behaviors_verified": False})
+ assert judge_module.behavior_evidence_gap({**omitted, "expected_behaviors_verified": True}) == ""
+
+ result = judge_module.judge_behavior_check("conversation", ["b1"], evidence_omitted=omitted)
+ assert result["score"] is None
+ assert result["status"] == "error"
+
+
def test_gated_behavior_result_never_becomes_a_zero_downstream(judge_module, monkeypatch) -> None:
from skillevaluator.tier3.eval_core.declarative_checks import combine_behavior_check
from skillevaluator.tier3.harbor.metrics import overall_score_from_metrics