Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ All notable changes to SkillEvaluator are documented in this file.

### Fixed

- NeMo Gym now scores native multi-step tasks once using the task's `mean` or
`final` strategy. The live case grid and finished report use the same verdict.
A failed or ungraded step leaves the attempt unscored. With `final`, the last
step determines which metrics apply, even if an earlier step scored one.
Each step keeps its own verifier output and trajectory after job cleanup,
including steps completed before a failure. Gym masks configured credential
values in trajectory text, verifier output, and step failure messages.
- Reject unsafe paths in SkillSpector scope exclusions and clarify incomplete
supply-chain scans when work counters disagree with the ledger.

Expand Down
27 changes: 26 additions & 1 deletion docs/nemo-gym.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,30 @@ Its help must describe a standalone positional `TARGET`, `tasks`, `task_dir`,
be collected. The Gym implementation must execute inside Docker and resolve task
environment templates; a host-only agent harness does not meet this contract.

A native multi-step task reports its steps in order in `turns`, each with its own
`verifier_return_code` and `verifier_logs_dir`; Gym leaves the top-level pair unset.
SkillEvaluator keeps each step's rewards, verifier files and trajectory under the step's
name, as for a Harbor multi-step trial, and scores the attempt once by the task's
`multi_step_reward_strategy` as Gym reports it in `turn_reward_strategy`: `final` takes
the last step's rewards, and `mean` averages each reward key over the steps that ran,
counting a key a step did not report as 0. The attempt is unscored when a step was masked,
failed, or produced no verifier result, when Gym marked the episode failed, or when the
strategy is missing or unsupported. For a step with no verifier result, Gym's own `mean`
counts it as 0 and Harbor leaves it out; SkillEvaluator does neither, so a step the
verifier never graded is never part of a score. An episode Gym stopped after a step
missed its `min_reward` is scored over the steps that ran, as on Harbor. Gym exports
each turn's own input and new output even when `turn_sessions` is `continue`, so the
merged trajectory keeps every turn's steps in order and never treats a turn that opens
like the previous one as a repeat. The live case status shown during the run judges
every Gym attempt as the finished run does: an attempt that misses its goal under
standard grading shows as failed, and one the finished run leaves unscored, such as
one whose required judge failed or whose verifier names a different case than the
staged task, shows as an error, also after the staged tasks are removed. Judge
attribution follows `turn_reward_strategy` too, so a `final` attempt names only the last
step's judges. The published trial keeps each step's redacted trajectory and verifier
output under `steps/<name>/` after the run's job folder is removed. Tests cover this with
source-shaped Gym rollouts; a live multi-step Gym run has not been recorded yet.

</Accordion>
<Accordion title="Options, saved configuration, and retained artifacts">

Expand Down Expand Up @@ -296,7 +320,8 @@ Docker sandboxes before you run again. A finished run updates `latest` and recor
the same dataset snapshot and publication target as a Harbor run. As on Harbor
without `--harbor-keep-jobs`, the staged tasks and per-trial files are removed at
the end; Gym's own redacted `gym.log` and its `rollouts.jsonl` stay under
`_nemo-gym/` in the run folder, and the rollouts hold the raw agent responses.
`_nemo-gym/` in the run folder with each arm's `task_case_ids.json`, the case each
staged task ran as, and the rollouts hold the raw agent responses.

</Accordion>
</AccordionGroup>
4 changes: 3 additions & 1 deletion docs/reports.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -833,7 +833,9 @@ completed run directly:
per-trial artifacts: the trial's `reward.json`, Harbor's `trajectory.json`
when available, and redacted, size-capped diagnostic copies such as
`trial.log`, `exception.txt`, and agent logs (`codex.txt`, `opencode.txt`).
With standard grading, `reward.json` records `trajectory_source` (the
A multi-step trial also keeps each named step's redacted `trajectory.json`
and `test-stdout.txt` under `steps/<step>/`, so an attempt that stopped
partway still shows the steps that ran. With standard grading, `reward.json` records `trajectory_source` (the
trajectory or agent log that was graded) and, under each LLM judge's
`details`, an `omitted` record showing whether its evidence was truncated to
fit the [evidence budget](/skills/skillevaluator/tier3-grading#evidence-budgets) or, for
Expand Down
76 changes: 55 additions & 21 deletions src/skillevaluator/tier3/case_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from __future__ import annotations

import hashlib
import json
import logging
import os
Expand Down Expand Up @@ -1590,6 +1591,9 @@ def load_case_marks(run_dir: Path) -> dict[str, dict[str, dict[str, list[str]]]]


_LIVE_VARIANTS = {"with": "with_skill", "without": "without_skill"}
# Gym run folder -> mark of each rollout its last poll read, the least recently polled run first.
_GYM_LIVE_MARKS: dict[str, dict[str, str]] = {}
_MAX_GYM_LIVE_MARKS = 65536


def _harbor_job_owner(job_name: str, agents: list[str]) -> tuple[str, str] | None:
Expand Down Expand Up @@ -1617,45 +1621,75 @@ def _live_mark(trial: Path, run_dir: Path, pass_threshold: float) -> str | None:
return ERROR


def _gym_live_mark(
row: dict[str, Any],
task: str,
case_id: str,
pass_threshold: float,
judged: Mapping[str, str],
seen: dict[str, str],
) -> str:
from skillevaluator.tier3.nemo_gym.results import rollout_verdict

# Gym appends a rollout only once its verifier logs are written, so each line is judged once.
key = hashlib.sha256(json.dumps([row, task, case_id, pass_threshold], sort_keys=True).encode()).hexdigest()
mark = seen.get(key) or judged.get(key)
if mark is None:
passed = rollout_verdict(row, task, case_id, pass_threshold)
mark = ERROR if passed is None else PASS if passed else FAIL
seen[key] = mark
return mark


def _keep_gym_live_marks(run: str, seen: dict[str, str]) -> None:
"""Keep the verdicts of the rollouts a Gym run holds now for its next poll.

Past ``_MAX_GYM_LIVE_MARKS`` verdicts, the runs polled longest ago are dropped; the run just polled
keeps all of its verdicts, so a poll judges only the rollouts appended since the last one.
"""
_GYM_LIVE_MARKS.pop(run, None)
_GYM_LIVE_MARKS[run] = seen
kept = sum(len(marks) for marks in list(_GYM_LIVE_MARKS.values()))
for other in [other for other in list(_GYM_LIVE_MARKS) if other != run]:
if kept <= _MAX_GYM_LIVE_MARKS:
break
kept -= len(_GYM_LIVE_MARKS.pop(other, {}))


def _add_gym_live_marks(
run_dir: Path, agents: list[str], marks: dict[str, dict[str, dict[str, list[str]]]], pass_threshold: float
) -> bool:
"""Add the attempts a running NeMo Gym arm has appended to its ``rollouts.jsonl``; False for a non-Gym run.

Each attempt is scored from its verifier logs with the same rules the Gym result normalizer uses.
Each attempt is judged as the finished run judges it, for the case the runner staged its task as.
A task the runner recorded no case for is its own case.
"""
from skillevaluator.tier3.nemo_gym.results import (
read_rollouts,
read_verifier_rewards,
rollout_failure_text,
rollout_task_name,
)
from skillevaluator.tier3.nemo_gym.results import TASK_CASE_IDS_FILE, read_rollouts, rollout_task_name

gym_root = run_dir / "_nemo-gym"
if not gym_root.is_dir() or gym_root.is_symlink():
return False
judged = _GYM_LIVE_MARKS.get(str(gym_root), {})
seen: dict[str, str] = {}
for agent in agents:
for variant, key in _LIVE_VARIANTS.items():
arm = gym_root / f"{agent}-{variant}"
rollouts = arm / "rollouts.jsonl"
if arm.is_symlink() or rollouts.is_symlink() or not rollouts.is_file():
continue
case_ids = _load_json(arm / TASK_CASE_IDS_FILE, root=run_dir)
if not isinstance(case_ids, dict):
case_ids = {}
for row in read_rollouts(rollouts):
case_id = rollout_task_name(row)
if case_id is None or not _SAFE_TRIAL.match(case_id):
task = rollout_task_name(row)
if task is None or not _SAFE_TRIAL.match(task):
continue
logs_dir = row.get("verifier_logs_dir")
rewards = (
read_verifier_rewards(Path(logs_dir))
if not rollout_failure_text(row) and isinstance(logs_dir, str) and logs_dir
else None
)
score = rewards.get("overall", rewards.get("reward")) if rewards else None
if not isinstance(score, int | float) or isinstance(score, bool):
mark = ERROR
else:
mark = PASS if score >= pass_threshold else FAIL
marks.setdefault(agent, {}).setdefault(key, {}).setdefault(case_id, []).append(mark)
case_id = case_ids.get(task)
if not isinstance(case_id, str) or not case_id:
case_id = task
mark = _gym_live_mark(row, task, case_id, pass_threshold, judged, seen)
marks.setdefault(agent, {}).setdefault(key, {}).setdefault(task, []).append(mark)
_keep_gym_live_marks(str(gym_root), seen)
return True


Expand Down
102 changes: 96 additions & 6 deletions src/skillevaluator/tier3/harbor/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@
"_trusted_case_identity_unresolved",
)
TRIAL_DIAGNOSTIC_ARTIFACTS = ("result.json", "config.json", "exception.txt", "trial.log")
STEP_VERIFIER_ARTIFACTS = ("test-stdout.txt",)
AGENT_LOG_ARTIFACTS = (
"trajectory.json",
"cursor-cli.txt",
Expand Down Expand Up @@ -1301,6 +1302,7 @@ def _write_redacted_text_copy(
dest: Path,
*,
source_root: Path | None = None,
secret_values: set[str] | None = None,
) -> tuple[bool, dict[str, Any] | None]:
"""Copy a Harbor text artifact while masking common credential shapes."""
max_bytes = _diagnostic_artifact_max_bytes()
Expand Down Expand Up @@ -1348,6 +1350,10 @@ def _write_redacted_text_copy(
except UnicodeDecodeError as e:
logger.debug("Failed to read Harbor artifact %s: %s", src, e)
return False, {"name": src.name, "reason": "read_failed", "size_bytes": size_bytes}
if secret_values:
from skillevaluator.tier3.harbor.stream_redaction import StreamingSecretRedactor

text = StreamingSecretRedactor(secret_values).feed(text, final=True)
redacted = _redacted_artifact_text(src, text)
if redacted is None:
return False, {"name": src.name, "reason": "invalid_json", "size_bytes": size_bytes}
Expand Down Expand Up @@ -1415,6 +1421,44 @@ def _copy_trial_artifacts(
return copied


def _copy_step_artifacts(trial_dir: Path, trial_out: Path) -> list[str]:
"""Publish each named step's redacted trajectory and verifier output under ``steps/<name>/``.

A partial episode keeps the steps that ran even when its merged trajectory is incomplete.
"""
names = _expected_step_trajectory_names(trial_dir)
if names is None:
return []
trajectories = {path.parent.parent.name: path for path in _ordered_step_trajectory_paths(trial_dir)}
copied: list[str] = []
for name in names:
if _safe_trial_path_component(name) != name:
continue
step_out = trial_out / "steps" / name
trajectory_path = trajectories.get(name)
trajectory: dict[str, Any] | None = None
if trajectory_path is not None:
try:
trajectory, _reference_key = _materialize_trajectory_file(trajectory_path.parent, trajectory_path.name)
except (OSError, SecurePathError, _TrajectoryMergeError, RecursionError):
trajectory = None
safe_trajectory = _redacted_trajectory_data(trajectory) if trajectory is not None else None
if safe_trajectory is not None:
step_out.mkdir(parents=True, exist_ok=True)
(step_out / "trajectory.json").write_text(
json.dumps(safe_trajectory, separators=(",", ":"), ensure_ascii=True, allow_nan=False),
encoding="utf-8",
)
copied.append(f"steps/{name}/trajectory.json")
for artifact_name in STEP_VERIFIER_ARTIFACTS:
src = trial_dir / "steps" / name / "verifier" / artifact_name
if src.exists() or src.is_symlink():
ok, _record = _write_redacted_text_copy(src, step_out / artifact_name, source_root=trial_dir)
if ok:
copied.append(f"steps/{name}/{artifact_name}")
return copied


def _record_skipped_trajectory(trial_out: Path, reason: str) -> None:
"""Persist a value-free explanation when canonical trajectory output is omitted."""
manifest_path = trial_out / "artifact_manifest.json"
Expand Down Expand Up @@ -1613,6 +1657,7 @@ def _save_unscored_trials(
trial_out = trials_dir / persisted_names.get(trial_src.name, "unknown")
trial_out.mkdir(parents=True, exist_ok=True)
copied = _copy_trial_artifacts(trial_src, trial_out, include_root_trajectory=False)
copied.extend(_copy_step_artifacts(trial_src, trial_out))
materialized_trajectory, trajectory_reason = _materialized_trial_trajectory(trial_src, None)
safe_trajectory = (
_redacted_trajectory_data(materialized_trajectory) if materialized_trajectory is not None else None
Expand Down Expand Up @@ -1982,7 +2027,30 @@ def _merged_atif_schema_version(*trajectories: Mapping[str, Any]) -> str:
return f"ATIF-v{newest[0]}.{newest[1]}"


def _validated_trajectory_dict(data: Any) -> dict[str, Any]:
def _mask_atif_fields(value: Any, mask: Callable[[str], str]) -> Any:
"""Mask free text and free-form metadata while preserving ATIF's field names and literal tags."""
from typing import Literal, get_origin

from pydantic import BaseModel

if isinstance(value, BaseModel):
fields = {}
for name, field in type(value).model_fields.items():
item = getattr(value, name)
if item is None:
continue
masked = item if get_origin(field.annotation) is Literal else _mask_atif_fields(item, mask)
if name != "timestamp" or masked == item:
fields[name] = masked
return fields
if isinstance(value, dict):
return {key: _mask_atif_fields(item, mask) for key, item in value.items() if mask(key) == key}
if isinstance(value, list):
return [_mask_atif_fields(item, mask) for item in value]
return mask(value) if isinstance(value, str) else value


def _validated_trajectory_dict(data: Any, *, secret_values: set[str] | None = None) -> dict[str, Any]:
try:
# Bound traversal before deepcopy so hostile ATIF cannot amplify work
# before validation begins.
Expand Down Expand Up @@ -2082,7 +2150,20 @@ def _validated_trajectory_dict(data: Any) -> dict[str, Any]:
)
from harbor.models.trajectories import Trajectory

validated = Trajectory.model_validate(candidate).to_json_dict()
trajectory = Trajectory.model_validate(candidate)
if secret_values:
from skillevaluator.tier3.harbor.stream_redaction import collision_safe_redaction_marker

secrets = sorted(secret_values - {""}, key=len, reverse=True)
marker = collision_safe_redaction_marker(secrets)

def mask(text: str) -> str:
for secret in secrets:
text = text.replace(secret, marker)
return text

trajectory = Trajectory.model_validate(_mask_atif_fields(trajectory, mask))
validated = trajectory.to_json_dict()
_validate_generated_json_value(
validated,
max_depth=ATIF_JSON_MAX_DEPTH,
Expand Down Expand Up @@ -3474,7 +3555,7 @@ def _constituent_custom_metric_failure(result: dict[str, Any]) -> str:
def _restore_constituent_not_applicable(
data: dict[str, Any], result: dict[str, Any], trial_root: Path
) -> dict[str, Any]:
"""Restore absent N/A metrics only when every declared step has bounded sidecar evidence.
"""Restore absent N/A metrics from the scoring steps, after checking every sidecar.

The returned validation view preserves Harbor's authoritative numeric values.
Missing or unsafe sidecars cannot turn absent metrics into applicable scores.
Expand All @@ -3497,10 +3578,11 @@ def _restore_constituent_not_applicable(
original = root_verifier.get("rewards") if isinstance(root_verifier, dict) else None
if not isinstance(original, dict):
return result
scoring_steps = names[-1:] if _harbor_multi_step_reward_strategy(result) == "final" else names
restored = [
metric
for metric in _standard_reward_metrics(original)
if metric not in original and all(metric_is_not_applicable(by_name[name], metric) for name in names)
if metric not in original and all(metric_is_not_applicable(by_name[name], metric) for name in scoring_steps)
]
if not restored:
return result
Expand All @@ -3513,14 +3595,16 @@ def _restore_constituent_not_applicable(
return result
rewards = dict(rewards)
for metric in restored:
if not metric_is_not_applicable(by_name[name], metric):
continue
# A conflicting numeric value remains authoritative and prevents restoration.
if metric in rewards and not metric_is_not_applicable(rewards, metric):
return result
# Keep the reason the step's verifier recorded, such as a negative eval case.
mark_not_applicable(rewards, metric, recorded_not_applicable_reason(by_name[name], metric))
steps.append({**step, "verifier_result": {**verifier, "rewards": rewards}})
for metric in restored:
reason = shared_not_applicable_reason([by_name[name] for name in names], metric)
reason = shared_not_applicable_reason([by_name[name] for name in scoring_steps], metric)
mark_not_applicable(root_rewards, metric, reason)
if metric not in data:
mark_not_applicable(data, metric, reason)
Expand Down Expand Up @@ -5482,7 +5566,11 @@ def _shared_metric_pass_lift(


def _harbor_multi_step_reward_strategy(result: dict[str, Any]) -> str | None:
"""Read the task's strategy when its staged configuration is still available."""
"""Read the strategy NeMo Gym reported, else the task's when its staged configuration is still available."""
gym = result.get("nemo_gym")
if result.get("execution_backend") == "nemo-gym" and isinstance(gym, dict):
strategy = gym.get("turn_reward_strategy")
return strategy if isinstance(strategy, str) and strategy in {"final", "mean"} else None
config = result.get("config")
task = config.get("task") if isinstance(config, dict) else None
paths = {
Expand Down Expand Up @@ -6668,6 +6756,8 @@ def _save_trials(

if trial_src:
_copy_trial_artifacts(trial_src, trial_out, include_root_trajectory=False)
if not reward.get("_step_name"):
_copy_step_artifacts(trial_src, trial_out)
if safe_materialized_traj:
(trial_out / "trajectory.json").write_text(
json.dumps(
Expand Down
9 changes: 7 additions & 2 deletions src/skillevaluator/tier3/harbor/progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,15 @@ def close(self) -> None: ...

def redact_progress_detail(detail: object, *, secret_values: set[str] | None = None) -> str:
"""Return a single-line diagnostic safe enough for a progress surface."""
text = " ".join(strip_terminal_controls(str(detail)).split())
raw = str(detail)
secrets = sorted(secret_values or (), key=len, reverse=True)
for secret in secrets:
if secret and secret != " ".join(strip_terminal_controls(secret).split()):
raw = raw.replace(secret, "<redacted>")
text = " ".join(strip_terminal_controls(raw).split())
if "://" in text:
text = _CREDENTIAL_URI_USERINFO_RE.sub(r"\g<scheme><redacted>@", text)
for secret in sorted(secret_values or (), key=len, reverse=True):
for secret in secrets:
if len(secret) >= MIN_EXACT_SECRET_CHARS:
text = text.replace(secret, "<redacted>")
elif secret:
Expand Down
Loading
Loading