From 28fe43c9ee3c327b90facc6b762d5ac2f00a9f1a Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Thu, 30 Jul 2026 09:30:44 -0500 Subject: [PATCH 01/15] feat(eval-author): implement the discover command Discovery exists so a later, cheaper model can run a repo's Harbor evals without re-deriving how. That only works if every fact it records was proved rather than observed, so the command assembles a candidate JobConfig from the strongest source the repo offers and then makes Harbor's own validators judge it: schema, Job.create resolution, per-task validity, the reward-file contract, required host vars, the agent import path, backend preflight, and a round trip of the persisted bytes through the Harbor CLI. The config and the report are therefore two separate claims. discovery.md is uploaded either way so a failure is documented instead of lost, while harbor-job.yaml is withheld unless every rung passed, which keeps the fileset from ever holding a config that reads as ready to run. Exit 0 likewise means validated *and* recorded, so the command works as a gate. Harbor drops task directories it cannot parse without raising, so a per-task check alone would report every surviving task valid while one silently vanished. A coverage rung diffs the resolved tasks against what is on disk to surface that, staying quiet when the dataset filters tasks on purpose. The LLM scout is bounded by the same ladder: its proposal is revalidated from the schema rung and adopted only if Harbor then accepts it, so a wrong guess costs a round trip rather than replacing failures the user could have acted on. Anything it influenced is marked as inference in the report. Signed-off-by: Alec Khoury --- plugins/nemo-eval-author/pyproject.toml | 7 +- .../src/nemo_eval_author_plugin/cli.py | 136 +++- .../discovery/agent.py | 201 +++++ .../discovery/memory.py | 219 ++++++ .../discovery/models.py | 165 +++++ .../discovery/report.py | 321 ++++++++ .../nemo_eval_author_plugin/discovery/run.py | 293 ++++++++ .../nemo_eval_author_plugin/discovery/scan.py | 180 +++++ .../discovery/sources.py | 499 +++++++++++++ .../discovery/validate.py | 693 ++++++++++++++++++ .../tests/discovery_fixtures.py | 174 +++++ plugins/nemo-eval-author/tests/test_cli.py | 10 +- .../tests/test_discovery_cli.py | 248 +++++++ .../tests/test_discovery_memory.py | 137 ++++ .../tests/test_discovery_report.py | 186 +++++ .../tests/test_discovery_scan.py | 108 +++ .../tests/test_discovery_scout.py | 135 ++++ .../tests/test_discovery_sources.py | 150 ++++ .../tests/test_discovery_validate.py | 315 ++++++++ uv.lock | 4 +- 20 files changed, 4161 insertions(+), 20 deletions(-) create mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py create mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py create mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py create mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py create mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py create mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py create mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py create mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py create mode 100644 plugins/nemo-eval-author/tests/discovery_fixtures.py create mode 100644 plugins/nemo-eval-author/tests/test_discovery_cli.py create mode 100644 plugins/nemo-eval-author/tests/test_discovery_memory.py create mode 100644 plugins/nemo-eval-author/tests/test_discovery_report.py create mode 100644 plugins/nemo-eval-author/tests/test_discovery_scan.py create mode 100644 plugins/nemo-eval-author/tests/test_discovery_scout.py create mode 100644 plugins/nemo-eval-author/tests/test_discovery_sources.py create mode 100644 plugins/nemo-eval-author/tests/test_discovery_validate.py diff --git a/plugins/nemo-eval-author/pyproject.toml b/plugins/nemo-eval-author/pyproject.toml index 870d2dcefc8..c1f6b2aa99e 100644 --- a/plugins/nemo-eval-author/pyproject.toml +++ b/plugins/nemo-eval-author/pyproject.toml @@ -5,12 +5,17 @@ description = "Eval Author agent for NeMo Platform (hard-depends on Experimental requires-python = ">=3.12,<3.14" dependencies = [ "pydantic>=2", - "harbor>=0.16", + # Floor is 0.18 because discovery validates through Harbor's own APIs instead of + # reimplementing its rules: Task.is_valid_dir, get_required_host_vars, and the + # JobConfig schema are load-bearing, and an older Harbor fails at import rather + # than at the point of use. + "harbor>=0.18", "nooa", "nemo-experimentalist-plugin", "nemo-insights-plugin", "nemo-platform", "nemo-platform-plugin", + "pyyaml>=6.0.3", "tomlkit>=0.13.3", ] diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index d7c56674147..ed9f0e5747f 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -3,23 +3,34 @@ """Eval Author plugin CLI — ``nemo eval-author ...`` subcommands. -Scaffolding. Every verb is registered under its final name so the command tree is -discoverable and the child tickets have a landing spot, and each body exits non-zero -until its own ticket lands. Flags belong to those tickets, so nothing here declares -options yet. - -This module imports nothing from ``eval_author``: those agents build their LLM client -while the class body executes, so importing one here would make the whole CLI require -``AUTHOR_*`` credentials — including the ``doctor`` verb whose job is to report that they -are missing. Experimentalist's CLI keeps its runner behind a lazily-assigned module -global for the same reason. +Every verb is registered under its final name so the command tree is discoverable and the +child tickets have a landing spot. The ones still unimplemented exit non-zero. + +This module imports nothing from ``eval_author``: those agents build their LLM client while +the class body executes, so importing one here would make the whole CLI require ``AUTHOR_*`` +credentials — including the ``doctor`` verb whose job is to report that they are missing. +``discovery.run`` is safe to import because it defers the one module that builds a client. +Experimentalist's CLI keeps its runner behind a lazily-assigned module global for the same +reason. """ -from typing import ClassVar, NoReturn +import asyncio +from pathlib import Path +from typing import Annotated, ClassVar, NoReturn import typer +from nemo_eval_author_plugin.discovery import run as discovery +from nemo_eval_author_plugin.discovery.memory import FILESET_NAME +from nemo_eval_author_plugin.discovery.models import Finding +from nemo_eval_author_plugin.discovery.report import JOB_CONFIG_FILENAME from nemo_platform_plugin.cli import NemoCLI +_STATUS_MARK = {"pass": " ok ", "warn": " warn ", "fail": " FAIL "} + +# Order the ladder's own sequence, so the printed report reads the way validation ran +# rather than the way findings happened to accumulate. +_GROUP_ORDER = ("config", "validation", "repo", "scout", "memory") + def _not_implemented(command: str, ticket: str) -> NoReturn: """Fail loudly, so a placeholder verb can never be mistaken for a successful run.""" @@ -27,6 +38,51 @@ def _not_implemented(command: str, ticket: str) -> NoReturn: raise typer.Exit(code=1) +def _echo_finding(finding: Finding) -> None: + typer.echo(f"[{_STATUS_MARK[finding.status]}] {finding.group}/{finding.name}: {finding.message}") + + +def _report_discovery(result: discovery.DiscoverResult) -> None: + """Print the run, then the verdict, because the verdict is what the reader came for.""" + record = result.report + if result.reused: + typer.echo( + f"Nothing the previous report depended on has changed, so its verdict still holds " + f"(revalidated {record.last_validated_at.isoformat()})." + ) + else: + findings = [*record.findings, *result.memory_findings] + for group in _GROUP_ORDER: + for finding in (item for item in findings if item.group == group): + _echo_finding(finding) + + typer.echo("") + if record.runnable: + source = record.config_source + typer.echo(f"Harbor can run this repo's evals ({source.detail if source else 'unknown source'}).") + typer.echo(f"Run it from {record.repo_root}:") + typer.echo(f" harbor job start -c {JOB_CONFIG_FILENAME}") + if record.required_env_vars: + typer.echo(f" Needs: {', '.join(item.name for item in record.required_env_vars)}") + else: + typer.echo("Harbor cannot run this repo's evals. Blocking:", err=True) + for finding in record.blocking: + call = f" ({finding.harbor_call})" if finding.harbor_call else "" + typer.echo(f" - {finding.name}: {finding.message}{call}", err=True) + if finding.hint: + typer.echo(f" {finding.hint}", err=True) + + if result.dry_run: + typer.echo("") + typer.echo("Dry run: nothing was uploaded.") + elif result.persisted: + typer.echo("") + typer.echo(f"Recorded to fileset '{FILESET_NAME}' under {record.agent}/.") + else: + typer.echo("") + typer.echo("Discovery could not be recorded, so a later run has nothing to read.", err=True) + + class EvalAuthorCLI(NemoCLI): """``nemo eval-author ...`` subcommands.""" @@ -41,10 +97,60 @@ def _root() -> None: """Force subcommand dispatch even when only one verb is registered.""" @app.command("discover") - def discover() -> None: - """Discover candidate evaluation cases from agent traces.""" - # TODO(ASE-677): declare flags and wire discovery. - _not_implemented("discover", "ASE-677") + def discover( + repo: Annotated[ + Path, + typer.Option("--repo", help="Agent repository to inspect.", exists=True, file_okay=False), + ] = Path(), + agent: Annotated[ + str | None, + typer.Option("--agent", help="Agent name. Defaults to optimizer.yaml, else the directory name."), + ] = None, + workspace: Annotated[str, typer.Option("--workspace", help="Platform workspace.")] = "default", + base_url: Annotated[ + str | None, + typer.Option("--base-url", help="Platform base URL. Defaults to the active context."), + ] = None, + env_backend: Annotated[ + str | None, + typer.Option("--env-backend", help="Harbor environment type to assume when the repo names none."), + ] = None, + deep: Annotated[ + bool, + typer.Option("--deep/--no-deep", help="Let an LLM scout fill gaps that block a valid config."), + ] = True, + refresh: Annotated[ + bool, + typer.Option("--refresh", help="Revalidate even when nothing the last report depended on moved."), + ] = False, + dry_run: Annotated[ + bool, + typer.Option("--dry-run", help="Print the findings and config without uploading anything."), + ] = False, + ) -> None: + """Find and validate how this repo runs Harbor evals, then record it.""" + result = asyncio.run( + discovery.discover( + discovery.DiscoverOptions( + repo_root=repo, + agent=agent, + workspace=workspace, + base_url=base_url, + env_backend=env_backend, + deep=deep, + refresh=refresh, + dry_run=dry_run, + ) + ) + ) + _report_discovery(result) + if result.dry_run: + typer.echo("") + typer.echo(result.markdown) + if result.job_config: + typer.echo(result.job_config) + # Non-zero on an unrunnable config is what makes this usable as a gate in CI. + raise typer.Exit(code=0 if result.ok else 1) @app.command("audit") def audit() -> None: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py new file mode 100644 index 00000000000..e704cd2de50 --- /dev/null +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py @@ -0,0 +1,201 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""A bounded scout that proposes a config when the ladder cannot get one. + +Only reached when validation failed on something a look around the repo could plausibly +settle: which directory is the dataset rather than the single-task template, what the +wrapper's class is actually called, which of two plausible entrypoints is the real one. + +The scout's output is a proposal and never a result. Whatever it returns goes back through +the ladder from the schema rung, and a config it touched is persisted only if Harbor then +accepts it. That ordering is the whole reason a later, weaker model can trust the artifact: +the strong model is allowed to guess, and Harbor decides whether the guess was right. + +Importing this module builds an LLM client, because ``Agent`` binds ``llm`` while the class +body executes. The CLI therefore imports it inside the command body rather than at module +scope, so ``nemo eval-author discover`` on a repo that needs no scouting works with no +``AUTHOR_*`` credentials at all. +""" + +import json +import logging +from collections.abc import Awaitable, Callable +from pathlib import Path +from typing import Any + +# Populates EXPERIMENTALIST_* from AUTHOR_*, which the Experimentalist modules imported +# below read while their class bodies execute. Must stay ahead of them; isort keeps it there. +import nemo_eval_author_plugin._env_bridge # noqa: F401 +from nemo_eval_author_plugin.discovery.models import CandidateConfig, ConfigSource, Finding +from nemo_eval_author_plugin.discovery.validate import ValidationOutcome, run_ladder +from nemo_eval_author_plugin.model_config import get_smart_model +from nemo_experimentalist_plugin.experimentalist.components.tools import GuardedShellTools +from nooa import Agent, CodeActStrategy, strategy +from nooa.config import CodeActConfig +from pydantic import BaseModel, Field + +logger = logging.getLogger(__name__) + +_GROUP = "scout" + +# The rungs a look at the filesystem could plausibly resolve. A backend preflight failure +# means Docker is not running, and no amount of reading the repo fixes that. +_SCOUTABLE_RUNGS = frozenset({"schema", "resolution", "tasks", "agent", "config-source"}) + +ProposeFn = Callable[[CandidateConfig, list[Finding], Path], Awaitable["ScoutProposal"]] + + +class ScoutProposal(BaseModel): + """A config the scout believes will validate, plus its reasoning.""" + + config: dict[str, Any] = Field(description="A complete Harbor job config payload, not a patch.") + rationale: str = Field(description="What was inspected and why this config follows from it.") + changed: list[str] = Field(default_factory=list, description="The keys that differ from the input config.") + + +class DiscoveryScout(Agent, llm=get_smart_model()): + """Reads an agent repository to work out how its Harbor evaluations are meant to run.""" + + def __init__(self, repo_root: Path, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.repo_root = repo_root + self.shell = GuardedShellTools(cwd=repo_root) + + @strategy(CodeActStrategy(config=CodeActConfig(max_iterations=20, cell_timeout=60.0))) + async def propose_config(self, candidate: str, blocking: str) -> ScoutProposal: + """Work out the Harbor job config this repository actually intends. + + A candidate config was assembled from the repository and rejected by Harbor's own + validators. Use the shell to inspect the repository and return a config that will + pass. + + Args: + candidate: The rejected Harbor job config, as JSON. + blocking: The validation failures, each naming the Harbor call that produced it. + + Returns: + ScoutProposal: A complete config payload, the keys changed, and the reasoning. + + Ground every change in something read from the filesystem: a directory that holds + `task.toml` files, a class definition in a wrapper module, a path named in a config + or README. Do not invent dataset paths, task names, agent import paths, or model + names, and do not add fields the repository gives no evidence for. + + A config returned unchanged with the rationale explaining what is missing is a + useful answer. A plausible-looking guess is not: this proposal is revalidated + against Harbor, and a wrong guess costs another round trip while an honest "the + repository does not say" tells the user what to fix. + """ + + async def scout(self, candidate: CandidateConfig, blocking: list[Finding]) -> ScoutProposal: + summary = "\n".join( + f"- {finding.name}: {finding.message}" + (f" (from {finding.harbor_call})" if finding.harbor_call else "") + for finding in blocking + ) + return await self.propose_config(json.dumps(candidate.data, indent=2, sort_keys=True), summary) + + +def is_scoutable(outcome: ValidationOutcome) -> bool: + """Whether any failure is the kind reading the repo could plausibly settle.""" + return any(finding.name in _SCOUTABLE_RUNGS for finding in outcome.findings if finding.status == "fail") + + +async def _ask_the_scout(candidate: CandidateConfig, blocking: list[Finding], repo_root: Path) -> ScoutProposal: + return await DiscoveryScout(repo_root=repo_root).scout(candidate, blocking) + + +async def attempt_repair( + candidate: CandidateConfig, + outcome: ValidationOutcome, + repo_root: Path, + propose: ProposeFn = _ask_the_scout, +) -> tuple[CandidateConfig, ValidationOutcome, list[Finding]]: + """Let the scout propose a config, then make Harbor judge it. + + Returns the proposal and its validation only if the ladder is happier with it than + with what we had. "Happier" means runnable, not merely different: a proposal that + trades one failure for another is noise, and keeping the original at least leaves the + user with failures traceable to their own repo rather than to a language model. + + ``propose`` is a parameter so this containment logic can be tested without a model. + It is the part worth testing: nooa refuses to let a test attach a method to an agent + class, and the interesting behavior here is what happens to a proposal, not how one is + produced. + """ + blocking = [finding for finding in outcome.findings if finding.status == "fail"] + try: + proposal = await propose(candidate, blocking, repo_root) + except Exception as exc: + logger.debug("discovery scout failed", exc_info=True) + return ( + candidate, + outcome, + [ + Finding( + name="scout", + group=_GROUP, + status="warn", + message=f"The scout could not run: {type(exc).__name__}: {exc}", + hint="Set AUTHOR_API_KEY and AUTHOR_BASE_URL, or pass --no-deep to skip this step.", + provenance="inference", + ) + ], + ) + + if proposal.config == candidate.data: + return ( + candidate, + outcome, + [ + Finding( + name="scout", + group=_GROUP, + status="warn", + message=f"The scout found nothing in the repo to change: {proposal.rationale}", + provenance="inference", + ) + ], + ) + + proposed = CandidateConfig( + data=proposal.config, + source=ConfigSource( + kind=candidate.source.kind, + detail=f"{candidate.source.detail}, then adjusted by the discovery scout", + path=candidate.source.path, + ), + ) + revalidated = await run_ladder(proposed, repo_root) + changed = ", ".join(proposal.changed) if proposal.changed else "unspecified keys" + + if not revalidated.runnable: + return ( + candidate, + outcome, + [ + Finding( + name="scout", + group=_GROUP, + status="warn", + message=f"The scout proposed changes to {changed}, and Harbor still rejected the result", + hint=f"Its reasoning: {proposal.rationale}", + provenance="inference", + ) + ], + ) + + return ( + proposed, + revalidated, + [ + Finding( + name="scout", + group=_GROUP, + status="pass", + message=f"The scout changed {changed}, and Harbor accepted the result", + hint=f"Its reasoning: {proposal.rationale}", + provenance="inference", + ) + ], + ) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py new file mode 100644 index 00000000000..fd0059c1eeb --- /dev/null +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py @@ -0,0 +1,219 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Persist discovery to a fileset, and read back what a previous run concluded. + +One fixed fileset with agent-scoped paths, following the telemetry exporter's precedent of +``nemo-agent-telemetry`` plus ``{agent}/...``. Nothing is written into the user's repo: the +repo is the thing under inspection, and a command that inspects a repo should not change it. + +The read side is what makes discovery cheap to repeat. A prior report lists the files it was +derived from along with their hashes, so a re-run can re-hash exactly those paths and +compare one digest, deciding whether anything relevant moved without touching Harbor. That +is the same property that lets a later, weaker model trust the artifact instead of +rediscovering it. + +``harbor-job.yaml`` is uploaded only when it exists, and it only exists when Harbor accepted +the schema. A config that is present in the fileset is therefore a config Harbor could load, +which is the invariant the whole artifact rests on. +""" + +from datetime import datetime +from pathlib import Path +from typing import Any + +import yaml +from nemo_eval_author_plugin.discovery.models import Finding, InputFingerprint +from nemo_eval_author_plugin.discovery.report import ( + JOB_CONFIG_FILENAME, + REPORT_FILENAME, + fingerprint_inputs, +) +from pydantic import BaseModel, Field + +FILESET_NAME = "nemo-eval-author" + +_GROUP = "memory" +_FRONT_MATTER_FENCE = "---" + + +class PriorRecord(BaseModel): + """The parts of a previously persisted report that decide whether to redo the work.""" + + inputs_digest: str | None = None + runnable: bool = False + harbor_version: str | None = None + last_validated_at: str | None = None + inputs: list[InputFingerprint] = Field(default_factory=list) + text: str = Field(default="", description="The report as stored, so a fresh re-run can restamp and reupload it.") + + +def remote_report_path(agent: str) -> str: + return f"{agent}/{REPORT_FILENAME}" + + +def remote_config_path(agent: str) -> str: + return f"{agent}/{JOB_CONFIG_FILENAME}" + + +def _split_front_matter(text: str) -> tuple[str, str] | None: + """Separate the front matter from the body, or ``None`` if there is no front matter. + + One implementation for both readers, because the fence is easy to miscount: the + closing ``\\n---`` is consumed by the split, so the body it returns still carries the + blank line that followed it and can be concatenated straight back on. + """ + if not text.startswith(_FRONT_MATTER_FENCE): + return None + head, _, body = text.partition(f"\n{_FRONT_MATTER_FENCE}") + if not _: + return None + return head[len(_FRONT_MATTER_FENCE) :], body + + +def parse_front_matter(text: str) -> dict[str, Any] | None: + """Pull the YAML front matter out of a rendered report.""" + split = _split_front_matter(text) + if split is None: + return None + try: + payload = yaml.safe_load(split[0]) + except yaml.YAMLError: + return None + return payload if isinstance(payload, dict) else None + + +async def load_previous(sdk: Any, *, agent: str, workspace: str) -> PriorRecord | None: + """Fetch the last report for this agent, or ``None`` when there is nothing to compare. + + A missing file and an unreachable platform are the same answer here: rediscover. That + is why every failure mode returns ``None`` rather than raising. + """ + try: + raw = await sdk.files.download_content( + remote_path=remote_report_path(agent), + fileset=FILESET_NAME, + workspace=workspace, + ) + except Exception: + return None + + try: + text = raw.decode("utf-8") if isinstance(raw, bytes) else str(raw) + except UnicodeError: + return None + + front = parse_front_matter(text) + if front is None: + return None + + inputs = [ + InputFingerprint(path=str(item["path"]), sha256=str(item["sha256"])) + for item in front.get("inputs") or [] + if isinstance(item, dict) and "path" in item and "sha256" in item + ] + return PriorRecord( + inputs_digest=front.get("inputs_digest"), + runnable=bool(front.get("runnable")), + harbor_version=front.get("harbor_version"), + last_validated_at=front.get("last_validated_at"), + inputs=inputs, + text=text, + ) + + +def restamp(text: str, *, when: datetime, harbor_version: str) -> str | None: + """Update a stored report's validation stamp without regenerating its narrative. + + Used when nothing the report depends on has changed: the findings would come out + word for word, so re-deriving them would only spend a Harbor resolution and a Docker + preflight to reprint the same file. The stamp still has to move, because + ``last_validated_at`` answers "when did someone last confirm this", and the Harbor + version has to move with it, since confirming under a different Harbor is a different + claim. + + Returns ``None`` when the front matter cannot be re-serialized, which tells the caller + to fall back to a full re-render rather than upload something malformed. + """ + split = _split_front_matter(text) + front = parse_front_matter(text) + if split is None or front is None: + return None + front["last_validated_at"] = when.isoformat() + front["harbor_version"] = harbor_version + rendered = yaml.safe_dump(front, sort_keys=False, default_flow_style=False).rstrip() + return f"{_FRONT_MATTER_FENCE}\n{rendered}\n{_FRONT_MATTER_FENCE}{split[1]}" + + +def rehash_prior_inputs(prior: PriorRecord, repo_root: Path) -> list[InputFingerprint]: + """Re-hash the files a prior report named, so its digest can be recomputed today. + + A path the prior run recorded and that no longer exists is dropped, which changes the + digest and correctly forces revalidation: a report derived from a file someone deleted + is exactly the kind of stale claim this comparison exists to catch. + """ + return fingerprint_inputs([repo_root / item.path for item in prior.inputs], repo_root) + + +async def persist( + sdk: Any, + *, + agent: str, + workspace: str, + markdown: str, + job_config: str | None, +) -> tuple[bool, list[Finding]]: + """Upload the report, and the config when there is one worth uploading. + + Returns whether everything landed. Upload failures are reported as warnings rather + than failures, because ``runnable`` answers one question only — can Harbor run this + config — and a fileset being down does not change that answer. The caller folds the + ``False`` into its exit code. + """ + findings: list[Finding] = [] + ok = True + + for remote_path, content, label in ( + (remote_report_path(agent), markdown, REPORT_FILENAME), + *(((remote_config_path(agent), job_config, JOB_CONFIG_FILENAME),) if job_config is not None else ()), + ): + try: + await sdk.files.upload_content( + content=content.encode("utf-8"), + remote_path=remote_path, + fileset=FILESET_NAME, + workspace=workspace, + fileset_auto_create=True, + ) + except Exception as exc: + ok = False + findings.append( + Finding( + name="upload", + group=_GROUP, + status="warn", + message=f"Could not upload {label}: {type(exc).__name__}: {exc}", + hint=f"Target was fileset '{FILESET_NAME}' at {remote_path} in workspace '{workspace}'.", + ) + ) + continue + findings.append( + Finding( + name="upload", + group=_GROUP, + status="pass", + message=f"Uploaded {label} to fileset '{FILESET_NAME}' at {remote_path}", + ) + ) + + if job_config is None: + findings.append( + Finding( + name="upload", + group=_GROUP, + status="warn", + message=f"Withheld {JOB_CONFIG_FILENAME}: no config passed Harbor's schema check", + hint="A config in this fileset is always one Harbor could load, so none was written.", + ) + ) + return ok, findings diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py new file mode 100644 index 00000000000..e63908746db --- /dev/null +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py @@ -0,0 +1,165 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Result types for ``nemo eval-author discover``. + +The command exists so that a later, cheaper model can run a Harbor eval without +rediscovering anything, which only works if every claim in the output is traceable to +whoever established it. That is what ``Finding.harbor_call`` and ``Finding.provenance`` +are for: a reader can tell a verdict Harbor's own code returned from a path we merely +observed on disk, and both from something a language model guessed. A report whose +findings are all ``provenance="inference"`` is a report to distrust. + +Shaped after ``CheckResult`` in ``nemo_insights_plugin.contracts.checks`` but defined +here, because a finding carries the artifact it is about and the Harbor call that judged +it, and a readiness check carries neither. +""" + +import hashlib +import json +from datetime import datetime +from pathlib import Path +from typing import Any, Literal + +from pydantic import BaseModel, Field + +Status = Literal["pass", "warn", "fail"] + +Provenance = Literal["harbor", "filesystem", "inference"] +"""Who established a finding. + +``harbor`` a Harbor API or CLI returned this verdict, so it is as true as the run + would be. Always paired with ``harbor_call``. +``filesystem`` we observed it directly (a file exists, a name matched). +``inference`` the scout proposed it. Never load-bearing on its own: a proposal has to + come back through the validation ladder before it can be persisted. +""" + +SourceKind = Literal["config_file", "prior_job", "profile", "convention"] +"""Where a candidate job config came from. + +Ordered by how much of it Harbor already agreed to, which is what +``SOURCE_PRIORITY`` encodes: + +``config_file`` a config file in the repo; the user declared this. +``prior_job`` ``config.json`` from a job Harbor resolved and ran. Evidence, not a guess. +``profile`` assembled from ``optimizer.yaml`` plus the agent wrapper. +``convention`` assembled from directory layout alone. Weakest, so say so out loud. +""" + +SOURCE_PRIORITY: tuple[SourceKind, ...] = ("config_file", "prior_job", "profile", "convention") + + +class Finding(BaseModel): + """One thing discover learned, and who vouches for it.""" + + name: str + group: str + status: Status + message: str + path: Path | None = None + hint: str | None = None + harbor_call: str | None = Field( + default=None, + description="The Harbor API or CLI that returned this verdict, when one did.", + ) + provenance: Provenance = "filesystem" + + +class ConfigSource(BaseModel): + """The winning source, kept so a reader knows how much to trust the config.""" + + kind: SourceKind + detail: str + path: Path | None = None + + @property + def rank(self) -> int: + return SOURCE_PRIORITY.index(self.kind) + + +class CandidateConfig(BaseModel): + """An unvalidated Harbor job config payload plus where it came from. + + Deliberately a raw ``dict`` rather than a ``JobConfig``. Assembling and judging are + separate jobs here: if this held a parsed ``JobConfig`` then the schema rung of the + ladder would have already run somewhere off to the side, and "no config reaches the + artifact unless a Harbor validator accepted it" would stop being checkable. + """ + + data: dict[str, Any] + source: ConfigSource + + +class RequiredEnvVar(BaseModel): + """A host variable a task config templates as ``${VAR}`` or ``${VAR:-default}``. + + Discover records the name and where it was declared. Whether this machine has a + value for it is ``doctor``'s question, not ours. + """ + + name: str + default: str | None = None + declared_in: Path + + +class InputFingerprint(BaseModel): + """A file the report was derived from, so a re-run can tell what moved.""" + + path: str + sha256: str + + +def digest_inputs(inputs: list[InputFingerprint]) -> str: + """Hash a set of input fingerprints, order-independently. + + A free function and not just a property, because the freshness check runs it against + the inputs a *previous* report listed, before this run has a report of its own. Both + sides must hash identically or the comparison is meaningless, so there is one + implementation. Canonical JSON matches the digest style in ``materialization.py``. + """ + payload = [[item.path, item.sha256] for item in sorted(inputs, key=lambda item: item.path)] + canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return f"sha256:{hashlib.sha256(canonical.encode('utf-8')).hexdigest()}" + + +class DiscoveryReport(BaseModel): + """Everything a later run needs to trust or redo this discovery.""" + + schema_version: int = 1 + agent: str + workspace: str + repo_root: Path + harbor_version: str = Field( + description="A validation result is only as good as the Harbor that produced it, " + "which is why Harbor stamps its own version into lock.json.", + ) + config_source: ConfigSource | None = None + findings: list[Finding] = Field(default_factory=list) + required_env_vars: list[RequiredEnvVar] = Field(default_factory=list) + inputs: list[InputFingerprint] = Field(default_factory=list) + discovered_at: datetime + last_validated_at: datetime + + @property + def blocking(self) -> list[Finding]: + return [finding for finding in self.findings if finding.status == "fail"] + + @property + def inputs_digest(self) -> str: + """One hash over every input, so a re-run can skip the ladder in a single compare. + + Derived rather than stored: a digest that can disagree with the list it summarizes + is worse than no digest, because the whole point is deciding whether to trust the + file without redoing the work. + """ + return digest_inputs(self.inputs) + + @property + def runnable(self) -> bool: + """True only when a config was found and nothing about it failed. + + The whole artifact turns on this flag, so it stays conservative: no source means + not runnable even with an empty failure list, because there is nothing to run. + """ + return self.config_source is not None and not self.blocking diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py new file mode 100644 index 00000000000..e285644691c --- /dev/null +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py @@ -0,0 +1,321 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Render the two artifacts discover persists. + +``harbor-job.yaml`` is the config a later agent hands to Harbor. ``discovery.md`` is the +story around it: which source won, what every rung of the ladder concluded, what a run +needs from the host, and what is blocking when something is. + +The markdown leads with front matter rather than prose because the first reader is a +program. ``runnable`` and ``inputs_digest`` are what let a later run skip everything here: +if the digest still matches and the flag is true, nothing about the repo that produced this +verdict has moved. + +Paths in the persisted config are rewritten relative to the repo root. An absolute path +would encode this machine into an artifact meant to outlive it, so the config is written to +be run from ``repo_root``, and the front matter records where that is. +""" + +import hashlib +import json +from datetime import UTC, datetime +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from typing import Any + +import yaml +from harbor.models.job.config import JobConfig +from nemo_eval_author_plugin.discovery.models import ( + CandidateConfig, + DiscoveryReport, + Finding, + InputFingerprint, + RequiredEnvVar, +) +from nemo_eval_author_plugin.discovery.scan import display_path + +JOB_CONFIG_FILENAME = "harbor-job.yaml" +REPORT_FILENAME = "discovery.md" + +_STATUS_MARK = {"pass": "ok", "warn": "warn", "fail": "FAIL"} + + +def harbor_version() -> str: + """The Harbor that produced these verdicts. + + A validation result is only as good as the version that returned it, which is why + Harbor stamps its own version into ``lock.json``. Same reasoning here. + """ + try: + return version("harbor") + except PackageNotFoundError: + return "unknown" + + +def fingerprint_inputs(paths: list[Path], repo_root: Path) -> list[InputFingerprint]: + """Hash every file a verdict was derived from, deduped and ordered for stability.""" + seen: dict[str, str] = {} + for path in paths: + if not path.is_file(): + continue + key = display_path(path, repo_root) + if key in seen: + continue + try: + seen[key] = hashlib.sha256(path.read_bytes()).hexdigest() + except OSError: + continue + return [InputFingerprint(path=key, sha256=seen[key]) for key in sorted(seen)] + + +def build_report( + *, + agent: str, + workspace: str, + repo_root: Path, + candidate: CandidateConfig | None, + findings: list[Finding], + required_env_vars: list[RequiredEnvVar], + inputs: list[InputFingerprint], + discovered_at: datetime | None = None, + last_validated_at: datetime | None = None, +) -> DiscoveryReport: + now = discovered_at or datetime.now(UTC) + return DiscoveryReport( + agent=agent, + workspace=workspace, + repo_root=repo_root, + harbor_version=harbor_version(), + config_source=candidate.source if candidate is not None else None, + findings=findings, + required_env_vars=required_env_vars, + inputs=inputs, + discovered_at=now, + last_validated_at=last_validated_at or now, + ) + + +def render_job_config(config: JobConfig, repo_root: Path) -> str: + """Serialize the validated config, with in-repo paths made relative. + + ``exclude_defaults`` keeps the file to what was actually decided, so a reader can tell + a deliberate setting from a Harbor default. Secrets are safe to write: Harbor's own + ``AgentConfig.env`` serializer rewrites sensitive values as ``${VAR}`` templates on the + way out, so the dump carries the variable names a run needs and none of their values. + + ``job_name`` is dropped unless the source config named it. Harbor's default is a + timestamp generated at load, and freezing one into a reusable artifact would label + every future run with the moment discovery happened. + """ + generated = set() if "job_name" in config.model_fields_set else {"job_name"} + payload = _relativize(config.model_dump(mode="json", exclude_defaults=True, exclude=generated), repo_root) + return yaml.safe_dump(payload, sort_keys=True, default_flow_style=False) + + +def render_markdown(report: DiscoveryReport) -> str: + """The narrative artifact, front matter first.""" + front = yaml.safe_dump(_front_matter(report), sort_keys=False, default_flow_style=False).rstrip() + body = "\n".join(_body(report)) + return f"---\n{front}\n---\n\n{body}\n" + + +def _front_matter(report: DiscoveryReport) -> dict[str, Any]: + source = report.config_source + return { + "schema_version": report.schema_version, + "agent": report.agent, + "workspace": report.workspace, + "repo_root": str(report.repo_root), + "runnable": report.runnable, + "config_source": ( + { + "kind": source.kind, + "detail": source.detail, + "path": display_path(source.path, report.repo_root) if source.path else None, + } + if source is not None + else None + ), + "validation": {finding.name: finding.status for finding in report.findings if finding.group == "validation"}, + "harbor_version": report.harbor_version, + "required_env_vars": [ + { + "name": item.name, + "default": item.default, + "declared_in": display_path(item.declared_in, report.repo_root), + } + for item in report.required_env_vars + ], + "discovered_at": report.discovered_at.isoformat(), + "last_validated_at": report.last_validated_at.isoformat(), + "inputs_digest": report.inputs_digest, + "inputs": [{"path": item.path, "sha256": item.sha256} for item in report.inputs], + } + + +def _body(report: DiscoveryReport) -> list[str]: + lines = [f"# Harbor eval setup for `{report.agent}`", ""] + lines += _verdict_section(report) + lines += _how_to_run_section(report) + lines += _validation_section(report) + lines += _env_section(report) + lines += _repo_section(report) + lines += _inputs_section(report) + return lines + + +def _verdict_section(report: DiscoveryReport) -> list[str]: + if report.runnable: + source = report.config_source + detail = source.detail if source is not None else "unknown" + return [ + f"Harbor can run this repo's evals. The config in `{JOB_CONFIG_FILENAME}` was " + f"{detail}, and every check below was answered by Harbor {report.harbor_version} " + "rather than inferred.", + "", + ] + + lines = ["**Harbor cannot run this repo's evals yet.** Blocking:", ""] + for finding in report.blocking: + lines.append(f"- **{finding.name}** — {finding.message}") + if finding.harbor_call: + lines.append(f" - reported by `{finding.harbor_call}`") + if finding.hint: + lines.append(f" - {finding.hint}") + lines.append("") + if report.config_source is None: + lines += [ + "No config could be assembled at all, so there is nothing to fix incrementally. " + "Start with `harbor job init` and rerun discovery.", + "", + ] + else: + lines += [ + f"`{JOB_CONFIG_FILENAME}` is not part of this record: a config is only persisted " + "once Harbor accepts its schema, so its absence means do not try to run one.", + "", + ] + return lines + + +def _how_to_run_section(report: DiscoveryReport) -> list[str]: + if not report.runnable: + return [] + lines = [ + "## Running it", + "", + f"From `{report.repo_root}`, because the config uses repo-relative paths:", + "", + "```bash", + f"harbor job start -c {JOB_CONFIG_FILENAME}", + "```", + "", + ] + if report.required_env_vars: + names = " ".join(f"{item.name}=..." for item in report.required_env_vars) + lines += [f"Set the host variables first: `{names}`", ""] + lines += [ + "To confirm the tasks are solvable before trusting any agent's score, run Harbor's " + "oracle, which replays each task's own solution and should score 1.0:", + "", + "```bash", + f"harbor run -a oracle -c {JOB_CONFIG_FILENAME}", + "```", + "", + "Discovery does not run this itself, because unlike every check above it builds and starts containers.", + "", + ] + return lines + + +def _validation_section(report: DiscoveryReport) -> list[str]: + rungs = [finding for finding in report.findings if finding.group == "validation"] + if not rungs: + return [] + lines = [ + "## What Harbor checked", + "", + "Each line is a Harbor call, so a failure here is the error a real run would hit.", + "", + ] + for finding in rungs: + lines.append(f"- `{_STATUS_MARK[finding.status]}` **{finding.name}**: {finding.message}") + if finding.harbor_call: + lines.append(f" - via `{finding.harbor_call}`") + if finding.hint: + lines.append(f" - {finding.hint}") + lines.append("") + return lines + + +def _env_section(report: DiscoveryReport) -> list[str]: + if not report.required_env_vars: + return ["## Host variables", "", "The config templates no host variables.", ""] + lines = [ + "## Host variables", + "", + "Harbor resolves these from the environment at trial start and raises on a missing " + "one. Whether this machine has them is a separate question, which `nemo eval-author " + "doctor` answers.", + "", + ] + for item in report.required_env_vars: + default = f", default `{item.default}`" if item.default is not None else ", no default" + lines.append(f"- `{item.name}`{default} — declared in `{display_path(item.declared_in, report.repo_root)}`") + lines.append("") + return lines + + +def _repo_section(report: DiscoveryReport) -> list[str]: + probes = [finding for finding in report.findings if finding.group == "repo"] + if not probes: + return [] + lines = [ + "## Repo shape", + "", + "Context for authoring evals rather than running them, so nothing here blocks a run.", + "", + ] + for finding in probes: + lines.append(f"- `{_STATUS_MARK[finding.status]}` **{finding.name}**: {finding.message}") + lines.append("") + return lines + + +def _inputs_section(report: DiscoveryReport) -> list[str]: + return [ + "## Freshness", + "", + f"Derived from {len(report.inputs)} file(s), digest `{report.inputs_digest}`. Rerun " + "`nemo eval-author discover` to compare: an unchanged digest means these verdicts " + "still hold and the ladder can be skipped.", + "", + ] + + +def _relativize(payload: Any, repo_root: Path) -> Any: + """Rewrite absolute paths under *repo_root* as repo-relative posix strings. + + Applied to the whole dumped structure rather than named fields, because Harbor carries + paths in several places (datasets, tasks, skills, output dirs) and a config that only + half-relativizes is worse than one that does not try. Paths outside the repo are left + alone: they are genuinely elsewhere, and pretending otherwise would break the run. + """ + prefix = f"{repo_root}/" + if isinstance(payload, dict): + return {key: _relativize(value, repo_root) for key, value in payload.items()} + if isinstance(payload, list): + return [_relativize(item, repo_root) for item in payload] + if isinstance(payload, str): + if payload == str(repo_root): + return "." + if payload.startswith(prefix): + return Path(payload).relative_to(repo_root).as_posix() + return payload + + +def canonical_digest(value: Any) -> str: + """Hash a structure the way the rest of this plugin does, for cross-run comparison.""" + canonical = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return f"sha256:{hashlib.sha256(canonical.encode('utf-8')).hexdigest()}" diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py new file mode 100644 index 00000000000..702e4fd3431 --- /dev/null +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -0,0 +1,293 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Orchestration for ``nemo eval-author discover``. + +Assemble a candidate config, let Harbor judge it, scout only if that fails on something a +look at the repo could settle, then persist. Sequenced so the expensive and side-effecting +work happens as late and as rarely as possible: the freshness check can skip the ladder +entirely, and the scout runs only after the ladder has failed. + +Kept apart from ``cli.py`` so it can be tested without a ``CliRunner`` and so the CLI holds +nothing but flags, printing, and the exit code. ``make_client`` is a module global for the +same reason it is in ``eval_author/run.py``: tests replace it. +""" + +import logging +import re +import tempfile +from dataclasses import dataclass, field, replace +from datetime import UTC, datetime +from pathlib import Path + +from nemo_eval_author_plugin.discovery import memory, report, scan, sources, validate +from nemo_eval_author_plugin.discovery.models import ( + CandidateConfig, + DiscoveryReport, + Finding, + digest_inputs, +) +from nemo_eval_author_plugin.discovery.validate import ValidationOutcome +from nemo_experimentalist_plugin.client import make_client +from nemo_insights_plugin.contracts.profile import discover_profile +from nemo_platform import AsyncNeMoPlatform + +logger = logging.getLogger(__name__) + +_SLUG_PATTERN = re.compile(r"[^a-z0-9]+") + + +@dataclass +class DiscoverOptions: + """Everything the CLI passes through, resolved.""" + + repo_root: Path + agent: str | None = None + workspace: str = "default" + base_url: str | None = None + env_backend: str | None = None + deep: bool = True + refresh: bool = False + dry_run: bool = False + + +@dataclass +class DiscoverResult: + """The artifacts, plus what the command needs to report and exit on.""" + + report: DiscoveryReport + markdown: str + job_config: str | None = None + persisted: bool = False + reused: bool = False + dry_run: bool = False + memory_findings: list[Finding] = field(default_factory=list) + + @property + def ok(self) -> bool: + """Exit-zero condition: Harbor can run it and the record was written. + + Two independent claims, deliberately kept apart. ``runnable`` is Harbor's verdict + on the config; persistence is whether a later agent will actually find it. A run + that validates but cannot upload has not delivered what the command promises. A dry + run is exempt because it was asked not to write anything. + """ + return self.report.runnable and (self.persisted or self.dry_run) + + +async def discover(options: DiscoverOptions) -> DiscoverResult: + """Run discovery end to end.""" + repo_root = options.repo_root.resolve() + agent = options.agent or _infer_agent_name(repo_root) + client = make_client(options.base_url) + try: + return await _discover(client, options, repo_root=repo_root, agent=agent) + finally: + await client.close() + + +async def _discover( + client: AsyncNeMoPlatform, options: DiscoverOptions, *, repo_root: Path, agent: str +) -> DiscoverResult: + prior = await memory.load_previous(client, agent=agent, workspace=options.workspace) + + reuse = _reusable(prior, repo_root, refresh=options.refresh) + if reuse is not None: + return await _reuse(client, options, agent=agent, prior=reuse) + + candidate, findings = sources.find_candidate(repo_root, env_backend=options.env_backend) + outcome = ValidationOutcome() + if candidate is not None: + outcome = await validate.run_ladder(candidate, repo_root) + if not outcome.runnable and options.deep: + candidate, outcome, scout_findings = await _scout(candidate, outcome, repo_root) + findings.extend(scout_findings) + + findings.extend(outcome.findings) + findings.extend(await _probe_repo(client, repo_root, agent=agent, workspace=options.workspace)) + + job_config = None + if outcome.config is not None: + job_config = report.render_job_config(outcome.config, repo_root) + findings.append(_round_trip(job_config, repo_root)) + + record = report.build_report( + agent=agent, + workspace=options.workspace, + repo_root=repo_root, + candidate=candidate, + findings=findings, + required_env_vars=outcome.required_env_vars, + inputs=report.fingerprint_inputs(_input_paths(repo_root, candidate, outcome), repo_root), + ) + # A config only travels with a report that vouches for it. The schema rung can pass + # while a later rung fails, and shipping the config anyway would put a file in the + # fileset that reads as ready to run. + publishable = job_config if record.runnable else None + markdown = report.render_markdown(record) + + if options.dry_run: + return DiscoverResult(report=record, markdown=markdown, job_config=job_config, dry_run=True) + + persisted, memory_findings = await memory.persist( + client, + agent=agent, + workspace=options.workspace, + markdown=markdown, + job_config=publishable, + ) + return DiscoverResult( + report=record, + markdown=markdown, + job_config=job_config, + persisted=persisted, + memory_findings=memory_findings, + ) + + +def _reusable(prior: memory.PriorRecord | None, repo_root: Path, *, refresh: bool) -> memory.PriorRecord | None: + """Whether the prior report still describes this repo, so the ladder can be skipped. + + Only ever reuses a report that was runnable. A prior failure is worth re-deriving even + on identical inputs, because the reason it failed may have been the machine rather than + the repo: Docker was not running, a cloud extra was missing. + """ + if prior is None or refresh or not prior.runnable or not prior.inputs: + return None + if digest_inputs(memory.rehash_prior_inputs(prior, repo_root)) != prior.inputs_digest: + return None + return prior + + +async def _reuse( + client: AsyncNeMoPlatform, options: DiscoverOptions, *, agent: str, prior: memory.PriorRecord +) -> DiscoverResult: + """Restamp and reupload a report whose inputs have not moved.""" + now = datetime.now(UTC) + restamped = memory.restamp(prior.text, when=now, harbor_version=report.harbor_version()) + if restamped is None: + logger.debug("prior report could not be restamped; falling through to a full discovery") + return await _discover( + client, + replace(options, refresh=True), + repo_root=options.repo_root.resolve(), + agent=agent, + ) + + front = memory.parse_front_matter(restamped) or {} + record = DiscoveryReport.model_validate( + { + "agent": agent, + "workspace": options.workspace, + "repo_root": front.get("repo_root", str(options.repo_root)), + "harbor_version": front.get("harbor_version", report.harbor_version()), + "config_source": front.get("config_source"), + "discovered_at": front.get("discovered_at", now), + "last_validated_at": now, + "inputs": [item.model_dump() for item in prior.inputs], + } + ) + if options.dry_run: + return DiscoverResult(report=record, markdown=restamped, reused=True, dry_run=True) + + persisted, memory_findings = await memory.persist( + client, + agent=agent, + workspace=options.workspace, + markdown=restamped, + # The stored config is already correct and already uploaded; rewriting it would + # churn the fileset to produce identical bytes. + job_config=None, + ) + return DiscoverResult( + report=record, + markdown=restamped, + persisted=persisted, + reused=True, + memory_findings=[item for item in memory_findings if item.name != "upload" or item.status != "warn"], + ) + + +async def _scout( + candidate: CandidateConfig, outcome: ValidationOutcome, repo_root: Path +) -> tuple[CandidateConfig, ValidationOutcome, list[Finding]]: + """Hand a failed ladder to the scout, importing it only if we actually need it. + + The import builds an LLM client while the module's class body executes, so deferring it + is what keeps ``discover`` usable on a healthy repo with no ``AUTHOR_*`` credentials. + """ + from nemo_eval_author_plugin.discovery.agent import attempt_repair, is_scoutable + + if not is_scoutable(outcome): + return candidate, outcome, [] + return await attempt_repair(candidate, outcome, repo_root) + + +async def _probe_repo(client: AsyncNeMoPlatform, repo_root: Path, *, agent: str, workspace: str) -> list[Finding]: + _, doctrine = scan.find_doctrine(repo_root) + _, skills = scan.find_skills(repo_root) + traces = await scan.probe_traces(client, agent=agent, workspace=workspace) + return [doctrine, skills, traces] + + +def _round_trip(job_config: str, repo_root: Path) -> Finding: + """Validate the exact bytes we intend to persist, from a scratch directory. + + Written outside the repo on purpose: discover inspects a repo and must not leave + anything in it. Harbor loads the config relative to ``cwd``, which the round trip sets + to the repo root, so the file's own location does not matter. + """ + with tempfile.TemporaryDirectory(prefix="eval-author-discover-") as scratch: + config_path = Path(scratch) / report.JOB_CONFIG_FILENAME + config_path.write_text(job_config, encoding="utf-8") + return validate.check_persisted_config(config_path, repo_root) + + +def _input_paths(repo_root: Path, candidate: CandidateConfig | None, outcome: ValidationOutcome) -> list[Path]: + """Every file a verdict in this report was derived from. + + The freshness check is only as good as this list: a file that shaped a conclusion but + is missing here means a later run reports "nothing changed" after someone changed it. + """ + paths: list[Path] = [] + if candidate is not None and candidate.source.path is not None: + paths.append(candidate.source.path) + + profile = discover_profile(repo_root) + if profile is not None: + paths.append(profile) + + for name in ("ETHOS.md", "AGENT-SPEC.md", "README.md"): + paths.append(repo_root / name) + + for task_dir in outcome.task_dirs: + paths.append(task_dir / "task.toml") + paths.extend(sorted((task_dir / "tests").glob("test.*"))) + + if outcome.config is not None: + for agent_config in outcome.config.agents: + if agent_config.import_path: + module = agent_config.import_path.split(":", 1)[0].split(".", 1)[0] + paths.extend(sorted(repo_root.rglob(f"{module}.py"))) + return paths + + +def _infer_agent_name(repo_root: Path) -> str: + """Name from ``optimizer.yaml`` when it says, else a slug of the directory.""" + profile = discover_profile(repo_root) + if profile is not None: + try: + declared = sources.read_profile_agent(profile) + except Exception: + declared = None + if declared: + return _slug(declared) + return _slug(repo_root.name) + + +def _slug(value: str) -> str: + slug = _SLUG_PATTERN.sub("-", value.strip().lower()).strip("-") + return slug or "agent" + + +__all__ = ["DiscoverOptions", "DiscoverResult", "discover"] diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py new file mode 100644 index 00000000000..73334b074ff --- /dev/null +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py @@ -0,0 +1,180 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Repo-shape probes, plus the traversal helpers the rest of discovery shares. + +Three things matter to Eval Author but are not fields of a Harbor job config: the doctrine +document describing what the agent is for, any Harbor skill bundles the repo ships, and +whether the platform has traces for this agent to author evals from. + +None of these probes ever returns a ``fail``. ``DiscoveryReport.runnable`` is false when +any finding failed, and that flag means precisely one thing: Harbor cannot run this +config. A repo with no traces yet, or no ``ETHOS.md``, runs its evals perfectly well. Only +the ladder in ``validate`` gets to fail a report. +""" + +import os +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +from nemo_eval_author_plugin.discovery.models import Finding + +_GROUP = "repo" + +# Vendored and generated trees dwarf a repo's own content and never hold its eval setup. +_PRUNE_DIR_NAMES = frozenset( + { + ".git", + ".venv", + "venv", + "node_modules", + "__pycache__", + ".ruff_cache", + ".pytest_cache", + ".mypy_cache", + ".tox", + ".eggs", + ".cache", + "site-packages", + "dist", + "build", + } +) +_MAX_WALK_DEPTH = 6 + +# ETHOS.md is the new name and AGENT-SPEC.md the old one, so both are honored while the +# rename is in flight. README.md is the fallback every repo has. +_DOCTRINE_FILENAMES = ("ETHOS.md", "AGENT-SPEC.md", "README.md") +_SKILL_FILENAME = "SKILL.md" +_MAX_LISTED_SKILLS = 10 + + +def walk_dirs(root: Path, max_depth: int = _MAX_WALK_DEPTH) -> Iterator[Path]: + """Yield directories under *root*, pruning vendored trees and bottoming out by depth.""" + root = root.resolve() + root_depth = len(root.parts) + for current, dir_names, _ in os.walk(root): + current_path = Path(current) + if len(current_path.parts) - root_depth >= max_depth: + dir_names.clear() + else: + dir_names[:] = sorted(name for name in dir_names if name not in _PRUNE_DIR_NAMES) + yield current_path + + +def display_path(path: Path, repo_root: Path) -> str: + """Render *path* relative to the repo when it lives there, absolute when it does not. + + Not every discovered path is inside the repo: ``discover_profile`` walks upward, so an + ``optimizer.yaml`` in a parent directory is a legitimate find rather than an error to + crash on. A path that is already relative is left alone, which also covers the + ```` sentinel used for values declared inline rather than in a file. + """ + if not path.is_absolute(): + return str(path) + try: + return str(path.resolve().relative_to(repo_root.resolve())) + except ValueError: + return str(path) + + +def find_doctrine(repo_root: Path) -> tuple[Path | None, Finding]: + """Locate the document describing what the agent is supposed to do. + + Recording which name matched makes the report double as a signal for the + ``AGENT-SPEC.md`` to ``ETHOS.md`` rename: a repo still on the old name says so here. + """ + for name in _DOCTRINE_FILENAMES: + candidate = repo_root / name + if candidate.is_file(): + return candidate, Finding( + name="doctrine", + group=_GROUP, + status="pass", + message=f"Agent doctrine at {name}", + path=candidate, + hint=( + "ETHOS.md is the current name; this repo predates the rename." if name == "AGENT-SPEC.md" else None + ), + ) + return None, Finding( + name="doctrine", + group=_GROUP, + status="warn", + message=f"No {' or '.join(_DOCTRINE_FILENAMES)} at the repo root", + hint="Eval Author writes better cases when the repo states what the agent is for.", + ) + + +def find_skills(repo_root: Path) -> tuple[list[Path], Finding]: + """Find Harbor skill bundles, the directories a ``SKILL.md`` marks. + + These are what ``harbor.skills`` resolves for ``AgentConfig.skills`` and mounts at + ``[environment].skills_dir``. Not the same thing as ``framework_skills`` in + ``optimizer.yaml``: a repo can ship both, and they are handed to different consumers. + """ + skills = [directory for directory in walk_dirs(repo_root) if (directory / _SKILL_FILENAME).is_file()] + if not skills: + return [], Finding( + name="skills", + group=_GROUP, + status="warn", + message=f"No {_SKILL_FILENAME} bundles found", + hint="Only relevant if the agent under test is meant to receive Harbor skills.", + ) + + listed = ", ".join(display_path(path, repo_root) for path in skills[:_MAX_LISTED_SKILLS]) + remainder = len(skills) - _MAX_LISTED_SKILLS + return skills, Finding( + name="skills", + group=_GROUP, + status="pass", + message=f"{len(skills)} Harbor skill bundle(s): {listed}" + + (f", and {remainder} more" if remainder > 0 else ""), + path=skills[0], + hint="Pass these to a job via AgentConfig.skills; they mount at [environment].skills_dir.", + ) + + +async def probe_traces(client: Any, *, agent: str, workspace: str) -> Finding: + """Count the agent's distinct sessions in Intake, which is Eval Author's raw material. + + A "trace" is one distinct ``session_id`` among the agent's spans, because only spans + carry the agent identity. This is the rollup ``count_agent_sessions`` performs in the + insights analyst backend; the SDK call is made directly here rather than importing + that class, which would drag a backend and its persistence into a read-only probe. + """ + try: + page = await client.intake.spans.groups.list( + workspace=workspace, + by="session_id", + page=1, + page_size=1, + filter={"agent_name": agent}, + sort="-span_count", + ) + except Exception as exc: + return Finding( + name="traces", + group=_GROUP, + status="warn", + message=f"Could not read traces for '{agent}': {type(exc).__name__}: {exc}", + hint="Traces feed later Eval Author stages; Harbor runs fine without them.", + ) + + total = page.pagination.total_results if page.pagination is not None else len(page.data) + if not total: + return Finding( + name="traces", + group=_GROUP, + status="warn", + message=f"No traces recorded for agent '{agent}' in workspace '{workspace}'", + hint="Run the agent with telemetry enabled to give Eval Author something to author from.", + ) + return Finding( + name="traces", + group=_GROUP, + status="pass", + message=f"{total} trace session(s) available for '{agent}' in workspace '{workspace}'", + ) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py new file mode 100644 index 00000000000..f886c03a766 --- /dev/null +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py @@ -0,0 +1,499 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Assemble a candidate Harbor job config from whatever the repo already declares. + +Four sources, ranked in ``SOURCE_PRIORITY`` by how much of the config Harbor has already +agreed to. A config file the user wrote beats a config Harbor once ran, which beats one +we assembled from ``optimizer.yaml``, which beats one inferred from directory names. + +Nothing in this module validates anything. Every source hands back a raw mapping and a +note about where it came from, and the ladder in ``validate`` owns every verdict. Keeping +assembly apart from judgement is what turns "no config reaches the artifact unless Harbor +accepted it" into a property that can be checked rather than a promise: if this module +returned a parsed ``JobConfig``, the schema rung would already have run off to the side. + +Paths come back absolute so validation needs no working-directory tricks. Rewriting them +relative to the repo for the persisted artifact is ``report``'s job. +""" + +import ast +import json +from pathlib import Path +from typing import Any + +import yaml +from nemo_eval_author_plugin.discovery.models import ( + SOURCE_PRIORITY, + CandidateConfig, + ConfigSource, + Finding, +) +from nemo_eval_author_plugin.discovery.scan import display_path, walk_dirs +from nemo_insights_plugin.contracts.profile import ( + PROFILE_FILENAME, + ProfileError, + discover_profile, + load_profile_model, + resolve_profile_path, +) +from pydantic import BaseModel, ConfigDict, Field + +_GROUP = "config" + +# `harbor job init` writes into `configs/` unless told otherwise, so look there first. +_CONFIG_SEARCH_DIRS = ("configs", ".", "harbor", ".harbor", "evals") +_CONFIG_SUFFIXES = (".yaml", ".yml", ".json") + +_TASK_CONFIG_FILENAME = "task.toml" +_TEMPLATE_DIR_NAME = "task_template" +_WRAPPER_FILENAME = "harbor_wrapper.py" +_AGENT_BASE_CLASSES = frozenset({"BaseAgent", "BaseInstalledAgent"}) +_CONVENTIONAL_DATASET_DIRS = ("evals/validation", "evals/val", "evals/train") + + +class _ProfileDatasets(BaseModel): + model_config = ConfigDict(extra="ignore") + + train: str | None = None + validation: str | None = None + + +class _DiscoveryProfile(BaseModel): + """The ``optimizer.yaml`` fields discover needs, and nothing else. + + Lenient where Experimentalist's ``AgentProfile`` is strict. That model forbids extras + and lives behind the import boundary, so a repo written for a newer Experimentalist + would make discover fail on a key it does not even read. Ignoring extras is the point. + """ + + model_config = ConfigDict(extra="ignore") + + agent: str | None = None + task_template: str | None = None + agent_source: str = "." + datasets: _ProfileDatasets = Field(default_factory=_ProfileDatasets) + profile_dir: Path + + +def find_candidate(repo_root: Path, *, env_backend: str | None = None) -> tuple[CandidateConfig | None, list[Finding]]: + """Return the highest-priority candidate config found in *repo_root*. + + Every source is attempted even once one has won, because "we also found a prior job + directory" is worth saying: it tells a reader which evidence was passed over. + """ + # Resolved once here so every path downstream is comparable. The walk resolves as it + # goes, and on macOS a caller's /tmp is the walk's /private/tmp, which would make + # rendering a path relative to the repo fail on a symlinked root. + repo_root = repo_root.resolve() + findings: list[Finding] = [] + candidates: list[CandidateConfig] = [] + + for source in (_from_config_file, _from_prior_job, _from_profile, _from_convention): + candidate, source_findings = source(repo_root) + findings.extend(source_findings) + if candidate is not None: + candidates.append(candidate) + + if not candidates: + findings.append( + Finding( + name="config-source", + group=_GROUP, + status="fail", + message="No Harbor job config could be assembled from this repo", + hint=( + f"Add a config with `harbor job init`, or a {PROFILE_FILENAME} naming a " + "task_template and datasets, or a directory of Harbor task dirs." + ), + ) + ) + return None, findings + + winner = min(candidates, key=lambda item: item.source.rank) + if env_backend is not None: + _apply_env_backend(winner, env_backend) + + passed_over = [item.source.kind for item in candidates if item is not winner] + findings.append( + Finding( + name="config-source", + group=_GROUP, + status="pass", + message=f"Using the {winner.source.kind} source: {winner.source.detail}", + path=winner.source.path, + hint=(f"Also found, lower trust: {', '.join(passed_over)}" if passed_over else None), + ) + ) + return winner, findings + + +def _apply_env_backend(candidate: CandidateConfig, env_backend: str) -> None: + """Set ``environment.type`` only when the source did not declare one. + + A user who wrote ``type: daytona`` into their config meant it, and a CLI default + should not quietly overwrite a declaration on its way into the persisted artifact. + """ + environment = candidate.data.get("environment") + if not isinstance(environment, dict): + candidate.data["environment"] = {"type": env_backend} + elif environment.get("type") is None: + environment["type"] = env_backend + + +def _from_config_file(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: + """A config file the user wrote, which is the strongest thing a repo can offer.""" + matches: list[tuple[Path, dict[str, Any]]] = [] + for relative in _CONFIG_SEARCH_DIRS: + directory = repo_root / relative + if not directory.is_dir(): + continue + for path in sorted(directory.iterdir()): + if not path.is_file() or path.suffix.lower() not in _CONFIG_SUFFIXES: + continue + payload = _load_mapping(path) + if payload is not None and _looks_like_job_config(payload): + matches.append((path, payload)) + + if not matches: + return None, [] + + path, payload = matches[0] + shown = display_path(path, repo_root) + extra = [display_path(other, repo_root) for other, _ in matches[1:]] + findings = [ + Finding( + name="config-file", + group=_GROUP, + status="pass", + message=f"Found a Harbor job config at {shown}", + path=path, + hint=(f"Ignoring additional candidates: {', '.join(extra)}" if extra else None), + ) + ] + return ( + CandidateConfig( + data=payload, + source=ConfigSource( + kind="config_file", + detail=f"declared at {shown}", + path=path, + ), + ), + findings, + ) + + +def _from_prior_job(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: + """A ``config.json`` Harbor itself resolved and ran. + + Harbor writes ``config.json`` and ``lock.json`` into the job directory and again into + every trial directory, so matching on those filenames alone would also pick up trial + configs. ``_looks_like_job_config`` is the discriminator: a trial config names one + ``task``, never a list of ``datasets`` or ``tasks``. + """ + job_dirs: list[tuple[Path, dict[str, Any]]] = [] + for directory in walk_dirs(repo_root): + config_path = directory / "config.json" + if not config_path.is_file() or not (directory / "lock.json").is_file(): + continue + payload = _load_mapping(config_path) + if payload is not None and _looks_like_job_config(payload): + job_dirs.append((config_path, payload)) + + if not job_dirs: + return None, [] + + config_path, payload = max(job_dirs, key=lambda item: item[0].stat().st_mtime) + shown = display_path(config_path.parent, repo_root) + return ( + CandidateConfig( + data=payload, + source=ConfigSource( + kind="prior_job", + detail=f"resolved by a previous run at {shown}", + path=config_path, + ), + ), + [ + Finding( + name="prior-job", + group=_GROUP, + status="pass", + message=f"Found {len(job_dirs)} previous Harbor job config(s); using {shown}", + path=config_path, + hint="A config Harbor already ran is evidence, so it outranks anything inferred from layout.", + ) + ], + ) + + +def _from_profile(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: + """Assemble from ``optimizer.yaml`` plus the agent wrapper it implies.""" + profile_path = discover_profile(repo_root) + if profile_path is None: + return None, [] + + try: + profile = load_profile_model(profile_path, _DiscoveryProfile) + except ProfileError as exc: + return None, [ + Finding( + name="profile", + group=_GROUP, + status="warn", + message=f"Found {PROFILE_FILENAME} but could not read it: {exc}", + path=profile_path, + ) + ] + + findings = [ + Finding( + name="profile", + group=_GROUP, + status="pass", + message=f"Read {PROFILE_FILENAME}", + path=profile_path, + ) + ] + + # validation is the eval set; train exists to optimize against, so preferring it + # here would quietly evaluate on the wrong split. + declared = {"validation": profile.datasets.validation, "train": profile.datasets.train} + chosen_split = next((split for split in ("validation", "train") if declared[split]), None) + if chosen_split is None: + findings.append( + Finding( + name="profile-datasets", + group=_GROUP, + status="warn", + message=f"{PROFILE_FILENAME} declares no datasets.train or datasets.validation", + path=profile_path, + ) + ) + return None, findings + + dataset_path = _resolve_profile_path(declared[chosen_split], profile.profile_dir) + if dataset_path is None: + findings.append( + Finding( + name="profile-datasets", + group=_GROUP, + status="warn", + message=f"Could not resolve datasets.{chosen_split} from {PROFILE_FILENAME}", + path=profile_path, + ) + ) + return None, findings + + other_split = "train" if chosen_split == "validation" else "validation" + findings.append( + Finding( + name="profile-datasets", + group=_GROUP, + status="pass", + message=f"Evaluating datasets.{chosen_split} at {display_path(dataset_path, repo_root)}", + path=dataset_path, + hint=( + f"{PROFILE_FILENAME} also declares datasets.{other_split}, which is not evaluated here." + if declared[other_split] + else None + ), + ) + ) + + agent_root = _resolve_profile_path(profile.agent_source, profile.profile_dir) or repo_root + agent_entry, agent_findings = _agent_entry(agent_root, repo_root) + findings.extend(agent_findings) + + return ( + CandidateConfig( + data={"agents": [agent_entry], "datasets": [{"path": str(dataset_path)}]}, + source=ConfigSource( + kind="profile", + detail=f"assembled from {PROFILE_FILENAME} datasets.{chosen_split}", + path=profile_path, + ), + ), + findings, + ) + + +def _from_convention(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: + """Assemble from directory layout alone, which is the weakest source on offer.""" + task_dirs = [directory for directory in walk_dirs(repo_root) if (directory / _TASK_CONFIG_FILENAME).is_file()] + if not task_dirs: + return None, [] + + # Harbor takes the parent of task dirs as the dataset, and skips a child named + # task_template, so a parent whose only task child is the template is a template + # holder rather than a dataset. + by_parent: dict[Path, list[Path]] = {} + for task_dir in task_dirs: + by_parent.setdefault(task_dir.parent, []).append(task_dir) + + dataset_dirs = { + parent: children + for parent, children in by_parent.items() + if [child for child in children if child.name != _TEMPLATE_DIR_NAME] + } + if not dataset_dirs: + return None, [ + Finding( + name="convention-datasets", + group=_GROUP, + status="warn", + message=f"Found Harbor task dirs but only under a {_TEMPLATE_DIR_NAME} directory", + path=task_dirs[0], + hint="A template is a scaffold for one task, not a dataset Harbor can evaluate.", + ) + ] + + chosen = _preferred_dataset_dir(repo_root, dataset_dirs) + shown = display_path(chosen, repo_root) + findings = [ + Finding( + name="convention-datasets", + group=_GROUP, + status="pass", + message=f"Found {len(dataset_dirs[chosen])} Harbor task dir(s) under {shown}", + path=chosen, + hint="Inferred from directory layout, so confirm it is the set you meant to evaluate.", + ) + ] + + agent_entry, agent_findings = _agent_entry(repo_root, repo_root) + findings.extend(agent_findings) + + return ( + CandidateConfig( + data={"agents": [agent_entry], "datasets": [{"path": str(chosen)}]}, + source=ConfigSource( + kind="convention", + detail=f"inferred from task dirs under {shown}", + path=chosen, + ), + ), + findings, + ) + + +def _preferred_dataset_dir(repo_root: Path, dataset_dirs: dict[Path, list[Path]]) -> Path: + """Prefer a conventional eval directory, then the largest set, then a stable name.""" + for relative in _CONVENTIONAL_DATASET_DIRS: + candidate = (repo_root / relative).resolve() + if candidate in dataset_dirs: + return candidate + return max(dataset_dirs, key=lambda parent: (len(dataset_dirs[parent]), str(parent))) + + +def _agent_entry(agent_root: Path, repo_root: Path) -> tuple[dict[str, Any], list[Finding]]: + """Describe the agent to run, preferring a wrapper in the repo over Harbor's default. + + Falls back to ``oracle``, which is what Harbor itself defaults to and the only agent + that needs no model or credentials. It runs ``solution/solve.sh``, so a config that + lands here still proves the tasks work even though it evaluates nothing. + """ + wrapper = _find_wrapper(agent_root) or _find_wrapper(repo_root) + if wrapper is None: + return {"name": "oracle"}, [ + Finding( + name="agent-entrypoint", + group=_GROUP, + status="warn", + message=f"No {_WRAPPER_FILENAME} found; falling back to Harbor's oracle agent", + hint=( + "The oracle replays solution/solve.sh, so it validates the tasks but " + "evaluates no agent. Add a harbor_wrapper.py to evaluate yours." + ), + ) + ] + + path, class_name = wrapper + return {"import_path": f"{path.stem}:{class_name}"}, [ + Finding( + name="agent-entrypoint", + group=_GROUP, + status="pass", + message=f"Agent import path {path.stem}:{class_name}", + path=path, + hint=f"Read from the class definition in {display_path(path, repo_root)}, not assumed.", + ) + ] + + +def _find_wrapper(root: Path) -> tuple[Path, str] | None: + """Find ``harbor_wrapper.py`` and the agent class inside it, by parsing not importing. + + The class name is read rather than assumed: ``WrappedAgent`` is the convention in this + repo, but a wrapper is a file the user wrote and the ladder's agent rung is the thing + that gets to import it. + """ + for directory in walk_dirs(root): + path = directory / _WRAPPER_FILENAME + if not path.is_file(): + continue + class_name = _agent_class_name(path) + if class_name is not None: + return path, class_name + return None + + +def _agent_class_name(path: Path) -> str | None: + try: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + except (OSError, UnicodeError, SyntaxError): + return None + for node in ast.walk(tree): + if not isinstance(node, ast.ClassDef): + continue + for base in node.bases: + name = base.attr if isinstance(base, ast.Attribute) else getattr(base, "id", None) + if name in _AGENT_BASE_CLASSES: + return node.name + return None + + +def _resolve_profile_path(value: str | None, profile_dir: Path) -> Path | None: + if not value: + return None + try: + return resolve_profile_path(value, profile_dir) + except ProfileError: + return None + + +def _looks_like_job_config(payload: dict[str, Any]) -> bool: + """Whether a mapping declares a Harbor task source. + + Requiring ``datasets`` or ``tasks`` rather than ``agents`` does double duty: a job + config without a task source cannot run at all, and the stricter test keeps unrelated + YAML that happens to mention agents (a NAT workflow, a CI matrix) from matching. + """ + for key in ("datasets", "tasks"): + value = payload.get(key) + if isinstance(value, list) and value: + return True + return False + + +def _load_mapping(path: Path) -> dict[str, Any] | None: + try: + text = path.read_text(encoding="utf-8") + payload = json.loads(text) if path.suffix.lower() == ".json" else yaml.safe_load(text) + except (OSError, UnicodeError, json.JSONDecodeError, yaml.YAMLError): + return None + return payload if isinstance(payload, dict) else None + + +def read_profile_agent(profile_path: Path) -> str | None: + """The agent name ``optimizer.yaml`` declares, if it declares one.""" + try: + return load_profile_model(profile_path, _DiscoveryProfile).agent + except ProfileError: + return None + + +def source_priority() -> tuple[str, ...]: + """Exposed so the report can explain the ranking it applied.""" + return SOURCE_PRIORITY diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py new file mode 100644 index 00000000000..f002f66919c --- /dev/null +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py @@ -0,0 +1,693 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Prove a candidate job config runnable using Harbor's own validators. + +Every rung here is a Harbor call. That is the entire point: a later agent is meant to run +what discover recorded without re-deriving it, which is only safe if the verdicts came +from the same code the run will use. Reimplementing Harbor's rules would produce a report +that agrees with Harbor today and drifts silently tomorrow. + +The rungs, in order, and the Harbor API each one leans on: + +1. schema ``JobConfig.model_validate`` plus ``validate_agent_concurrency_limits``, + which is what ``harbor job start --print-config`` runs before it returns. +2. resolution ``Job.create``, which resolves skills, task configs, resource policies and + metrics, and starts no container. +3. tasks ``Task.is_valid_dir``, then ``Task()`` to get the reason a task failed. +4. reward the resolved test script must write ``/logs/verifier/reward.{json,txt}``. +5. credentials ``get_required_host_vars`` over the task and job env templates. +6. agent ``import_class(..., base=BaseAgent)`` or ``AgentFactory.get_agent_class``. +7. backend ``EnvironmentFactory.run_preflight``. +8. round trip ``harbor job start --print-config -c `` against the persisted bytes. + +A failing rung is recorded, not raised. A report listing every problem is worth more than +one that stops at the first, and the command's whole job is to say why a repo cannot run. + +Two side effects worth knowing. ``Job.create`` populates ``~/.cache/harbor`` when a config +names remote datasets, and rung 6 imports a module from the repo under test, which runs +that module's top level. Neither starts a container or writes into the repo. +""" + +import asyncio +import contextlib +import shutil +import subprocess +import sys +import tempfile +import tomllib +from collections.abc import Iterator +from dataclasses import dataclass, field +from pathlib import Path + +from harbor.agents.base import BaseAgent +from harbor.agents.factory import AgentFactory +from harbor.environments.factory import EnvironmentFactory +from harbor.job import Job +from harbor.models.agent.name import AgentName +from harbor.models.job.config import JobConfig +from harbor.models.task.config import TaskConfig as TaskDefinitionConfig +from harbor.models.task.paths import TaskPaths +from harbor.models.task.task import Task +from harbor.models.task.verifier_mode import resolve_effective_verifier_env_config +from harbor.utils.env import get_required_host_vars +from harbor.utils.import_path import import_class +from nemo_eval_author_plugin.discovery.models import CandidateConfig, Finding, RequiredEnvVar, Status +from pydantic import ValidationError + +_GROUP = "validation" + +# Harbor reads reward.json first and falls back to reward.txt; a test script naming +# neither fails the trial with RewardFileNotFoundError no matter how good the agent is. +_REWARD_FILENAMES = ("reward.json", "reward.txt") + +_TASK_CONFIG_FILENAME = "task.toml" +# Harbor skips a dataset child named task_template; it is a scaffold, not a task. +_TEMPLATE_DIR_NAME = "task_template" +_MAX_LISTED_DROPPED = 5 + +_PRINT_CONFIG_TIMEOUT_SEC = 120.0 + + +@dataclass +class ValidationOutcome: + """What the ladder concluded, and the evidence it gathered on the way.""" + + config: JobConfig | None = None + findings: list[Finding] = field(default_factory=list) + required_env_vars: list[RequiredEnvVar] = field(default_factory=list) + task_dirs: list[Path] = field(default_factory=list) + + @property + def runnable(self) -> bool: + return self.config is not None and not any(item.status == "fail" for item in self.findings) + + +def _harbor(name: str, status: Status, message: str, call: str, **kwargs) -> Finding: + """A finding Harbor vouches for, which is the only kind this module emits.""" + return Finding( + name=name, + group=_GROUP, + status=status, + message=message, + harbor_call=call, + provenance="harbor", + **kwargs, + ) + + +async def run_ladder(candidate: CandidateConfig, repo_root: Path) -> ValidationOutcome: + """Walk the ladder, stopping only where a later rung has nothing left to judge.""" + outcome = ValidationOutcome() + + config = _rung_schema(candidate, outcome) + if config is None: + return outcome + outcome.config = config + + job = await _rung_resolution(config, outcome) + _rung_agent(config, repo_root, outcome) + _rung_backend(config, outcome) + if job is None: + return outcome + + resolved = _resolved_local_paths(job) + task_dirs = _rung_tasks(resolved, outcome) + outcome.task_dirs = task_dirs + _rung_coverage(config, resolved, outcome) + if not task_dirs: + return outcome + + _rung_reward(task_dirs, outcome) + _rung_credentials(config, task_dirs, outcome) + return outcome + + +def _rung_schema(candidate: CandidateConfig, outcome: ValidationOutcome) -> JobConfig | None: + """Does the payload satisfy Harbor's job config schema?""" + try: + config = JobConfig.model_validate(candidate.data) + # Redundant with the model's own after-validator, and kept because it is the gate + # the CLI runs by hand at harbor/cli/jobs.py:1473 after it applies flags. If we + # ever mutate a config post-validation, this is the line that catches it. + config.validate_agent_concurrency_limits() + except ValidationError as exc: + details = "; ".join(error["msg"] for error in exc.errors(include_url=False, include_input=False)) + outcome.findings.append( + _harbor( + "schema", + "fail", + f"Job config does not satisfy Harbor's schema: {details}", + "JobConfig.model_validate", + path=candidate.source.path, + hint=f"Assembled from the {candidate.source.kind} source ({candidate.source.detail}).", + ) + ) + return None + except ValueError as exc: + outcome.findings.append( + _harbor( + "schema", + "fail", + f"Job config is internally inconsistent: {exc}", + "JobConfig.validate_agent_concurrency_limits", + path=candidate.source.path, + ) + ) + return None + + outcome.findings.append( + _harbor( + "schema", + "pass", + "Harbor accepts the job config schema", + "JobConfig.model_validate", + path=candidate.source.path, + ) + ) + return config + + +async def _rung_resolution(config: JobConfig, outcome: ValidationOutcome) -> Job | None: + """Can Harbor resolve every dataset, skill and metric the config names? + + ``Job.create`` is the deepest gate available without running anything: it expands + datasets into task configs, resolves skill sources, validates resource policies + against the chosen backend, and builds metrics. Anything it raises is an error the + real run would have hit at the same point. + """ + try: + job = await Job.create(config) + except Exception as exc: + outcome.findings.append( + _harbor( + "resolution", + "fail", + f"Harbor could not resolve the job: {type(exc).__name__}: {exc}", + "Job.create", + hint="This is the error a real run would raise before starting any container.", + ) + ) + return None + + outcome.findings.append( + _harbor( + "resolution", + "pass", + "Harbor resolved datasets, skills, metrics and resource policies", + "Job.create", + ) + ) + return job + + +def _resolved_local_paths(job: Job) -> list[Path]: + """The on-disk task directories Harbor expanded this job into. + + Harbor's own CLI reaches for this attribute at harbor/cli/jobs.py:93 for the same + reason; there is no public accessor for the resolved list. Tasks that live only in a + remote registry are skipped, since the resolution rung already spoke for whether they + could be fetched. + """ + paths: list[Path] = [] + for task_config in getattr(job, "_task_configs", []): + try: + paths.append(task_config.get_local_path()) + except ValueError: + continue + return paths + + +def _rung_tasks(resolved: list[Path], outcome: ValidationOutcome) -> list[Path]: + """Is each resolved task a valid Harbor task directory? + + Deferring to ``Task.is_valid_dir`` rather than checking for ``tests/`` and + ``environment/`` by hand is what keeps this from crying wolf on the four shapes a + naive check gets wrong: a multi-step task whose instruction lives under ``steps/``, a + Windows task carrying ``test.bat``, a task whose verifier bakes its tests into a + separate image, and a task with ``[environment].docker_image`` and no Dockerfile. + """ + valid: list[Path] = [] + invalid: list[tuple[Path, str]] = [] + for local_path in resolved: + if Task.is_valid_dir(local_path): + valid.append(local_path) + else: + invalid.append((local_path, _task_failure_reason(local_path))) + + if not resolved: + outcome.findings.append( + _harbor( + "tasks", + "fail", + "The config resolves to zero tasks", + "Job.create", + hint="Harbor raises 'Either datasets or tasks must be provided' for an empty task set.", + ) + ) + return [] + + status = "fail" if invalid else "pass" + outcome.findings.append( + _harbor( + "tasks", + status, + f"{len(valid)} of {len(valid) + len(invalid)} task dirs are valid Harbor tasks", + "Task.is_valid_dir", + ) + ) + for path, reason in invalid: + outcome.findings.append(_harbor("tasks", "fail", f"{path.name}: {reason}", "Task.is_valid_dir", path=path)) + return valid + + +def _rung_coverage(config: JobConfig, resolved: list[Path], outcome: ValidationOutcome) -> None: + """Did Harbor pick up every task the repo appears to contain? + + Harbor drops a directory it cannot parse as a task without saying so: given ten task + dirs where three are half-written, ``Job.create`` resolves seven and raises nothing. + The run then succeeds and reports a score over seven tasks, which is the most expensive + kind of wrong, because nothing about the output looks incomplete. + + A dataset that narrows itself with ``task_names``, ``exclude_task_names`` or ``n_tasks`` + is deliberately running a subset, so its unresolved directories are reported as + information rather than as a problem. + """ + resolved_set = {path.resolve() for path in resolved} + for dataset in config.datasets: + if dataset.path is None or not dataset.path.is_dir(): + continue + on_disk = [ + child + for child in sorted(dataset.path.iterdir()) + if child.is_dir() and (child / _TASK_CONFIG_FILENAME).is_file() and child.name != _TEMPLATE_DIR_NAME + ] + dropped = [child for child in on_disk if child.resolve() not in resolved_set] + if not dropped: + continue + + selective = dataset.task_names or dataset.exclude_task_names or dataset.n_tasks + listed = ", ".join(f"{child.name} ({_task_failure_reason(child)})" for child in dropped[:_MAX_LISTED_DROPPED]) + remainder = len(dropped) - _MAX_LISTED_DROPPED + message = f"{len(dropped)} of {len(on_disk)} task dir(s) under {dataset.path.name} were not picked up: {listed}" + outcome.findings.append( + _harbor( + "coverage", + "warn" if selective else "fail", + message + (f", and {remainder} more" if remainder > 0 else ""), + "Job.create", + path=dataset.path, + hint=( + "The dataset selects a subset, so this is expected." + if selective + else "Harbor skips these silently, so a run would score fewer tasks than the repo contains." + ), + ) + ) + + +def _task_failure_reason(task_dir: Path) -> str: + """Ask Harbor why a task is invalid, since ``is_valid_dir`` only says that it is.""" + try: + Task(task_dir) + except FileNotFoundError as exc: + return str(exc) + except (OSError, tomllib.TOMLDecodeError, ValidationError) as exc: + return f"task.toml could not be read: {exc}" + except Exception as exc: + return f"{type(exc).__name__}: {exc}" + return "rejected by Task.is_valid_dir" + + +def _rung_reward(task_dirs: list[Path], outcome: ValidationOutcome) -> None: + """Does each task's test script actually write a reward file? + + A task can be structurally valid and still score nothing, which is the most + expensive way to discover a problem: the trial runs, the agent works, and Harbor + raises ``RewardFileNotFoundError`` at the end. + """ + missing: list[Path] = [] + image_provided: list[Path] = [] + reward_forms: set[str] = set() + + for task_dir in task_dirs: + scripts, graded_in_image = _test_scripts(task_dir) + if graded_in_image: + image_provided.append(task_dir) + for script in scripts: + text = _executable_lines(_read_text(script)) + found = [name for name in _REWARD_FILENAMES if name in text] + if found: + reward_forms.update(found) + elif task_dir not in missing: + missing.append(task_dir) + + if missing: + outcome.findings.append( + _harbor( + "reward", + "fail", + f"{len(missing)} task(s) have a test script that never writes a reward file", + "TaskPaths.discovered_test_path_for", + path=missing[0], + hint=( + "Harbor reads /logs/verifier/reward.json then reward.txt, and raises " + "RewardFileNotFoundError when neither exists." + ), + ) + ) + return + + detail = ", ".join(sorted(reward_forms)) if reward_forms else "none read" + message = f"Every test script writes a reward file ({detail})" + if image_provided: + message += f"; {len(image_provided)} task(s) grade from a separate verifier image" + outcome.findings.append( + _harbor( + "reward", + "pass", + message, + "TaskPaths.discovered_test_path_for", + hint=( + "reward.txt yields the single key 'reward'; reward.json keys are only " + "known once a trial runs, and they decide what metrics can aggregate." + ), + ) + ) + + +def _test_scripts(task_dir: Path) -> tuple[list[Path], bool]: + """Every host test script that has to produce a reward, and whether any grades in-image. + + Mirrors ``Task._validate_tests``: one script for a single-step task, and for a + multi-step task the effective script per step, which is the step's own or the shared + one it falls back to. Checking only the first would pass a task whose later step never + scores, and that failure surfaces only after a full run. + + ``resolve_effective_verifier_env_config`` is what decides the in-image case. Asking + Harbor beats inferring it from a missing file, which cannot tell a task that grades + from its own verifier image apart from one whose author forgot to write a test. + """ + paths = TaskPaths(task_dir) + config = _task_config(task_dir) + if config is None: + return [], False + + task_os = config.environment.os + shared = paths.discovered_test_path_for(task_os) + + if not config.steps: + if resolve_effective_verifier_env_config(config, step_cfg=None) is not None: + return [], True + return ([shared] if shared is not None else []), False + + scripts: list[Path] = [] + graded_in_image = False + for step in config.steps: + if resolve_effective_verifier_env_config(config, step_cfg=step) is not None: + graded_in_image = True + continue + effective = paths.discovered_step_test_path_for(step.name, task_os) or shared + if effective is not None and effective not in scripts: + scripts.append(effective) + return scripts, graded_in_image + + +def _rung_credentials(config: JobConfig, task_dirs: list[Path], outcome: ValidationOutcome) -> None: + """Which host variables must be set for this config to run? + + Harbor resolves ``${VAR}`` and ``${VAR:-default}`` templates from the host + environment at run time and raises on a missing one, and ``harbor run`` stops to ask + the user before handing any of them to a container. Discover records the names so the + persisted artifact is honest about what a run needs. Whether this machine has values + for them is ``doctor``'s question. + """ + required: dict[str, RequiredEnvVar] = {} + + def collect(env: dict[str, str], declared_in: Path) -> None: + for name, default in get_required_host_vars(env): + required.setdefault(name, RequiredEnvVar(name=name, default=default, declared_in=declared_in)) + + for task_dir in task_dirs: + task_config = _task_config(task_dir) + if task_config is None: + continue + config_path = TaskPaths(task_dir).config_path + collect(task_config.environment.env, config_path) + collect(task_config.verifier.env, config_path) + collect(task_config.solution.env, config_path) + + job_level = Path("") + collect(config.environment.env, job_level) + collect(config.verifier.env, job_level) + for agent in config.agents: + collect(agent.env, job_level) + + outcome.required_env_vars = sorted(required.values(), key=lambda item: item.name) + names = ", ".join(item.name for item in outcome.required_env_vars) + outcome.findings.append( + _harbor( + "credentials", + "pass", + f"{len(outcome.required_env_vars)} host variable(s) required" + (f": {names}" if names else ""), + "get_required_host_vars", + hint="Set these before running; Harbor raises on a missing template at trial start." if names else None, + ) + ) + + +def _rung_agent(config: JobConfig, repo_root: Path, outcome: ValidationOutcome) -> None: + """Does the agent this config names actually exist? + + Importing the class proves what matters without constructing it. Harbor instantiates + agents at trial time, but a discovery command has no business running a user's + ``__init__``, and ``import_class`` already enforces the ``BaseAgent`` contract. + """ + for agent in config.agents: + if agent.import_path is not None: + _check_agent_import(agent.import_path, repo_root, outcome) + elif agent.name is not None: + _check_agent_name(agent.name, outcome) + + +def _check_agent_import(import_path: str, repo_root: Path, outcome: ValidationOutcome) -> None: + module_name = import_path.split(":", 1)[0] + with _module_search_path(repo_root, module_name): + try: + agent_class = import_class(import_path, base=BaseAgent, label="agent") + except Exception as exc: + outcome.findings.append( + _harbor( + "agent", + "fail", + f"Could not load agent {import_path}: {type(exc).__name__}: {exc}", + "import_class", + hint="Harbor needs the module importable and the class to subclass BaseAgent.", + ) + ) + return + outcome.findings.append( + _harbor( + "agent", + "pass", + f"Agent {import_path} imports and subclasses BaseAgent ({agent_class.__name__})", + "import_class", + ) + ) + + +def _check_agent_name(name: str, outcome: ValidationOutcome) -> None: + if name not in AgentName.values(): + outcome.findings.append( + _harbor( + "agent", + "fail", + f"'{name}' is not a Harbor agent name", + "AgentName.values", + hint=f"Valid names: {', '.join(sorted(AgentName.values()))}", + ) + ) + return + try: + AgentFactory.get_agent_class(AgentName(name)) + except Exception as exc: + outcome.findings.append( + _harbor( + "agent", + "fail", + f"Harbor knows agent '{name}' but cannot import it: {type(exc).__name__}: {exc}", + "AgentFactory.get_agent_class", + hint="Built-in agents can need an optional extra, as in `pip install 'harbor[...]'`.", + ) + ) + return + outcome.findings.append( + _harbor("agent", "pass", f"Built-in agent '{name}' is available", "AgentFactory.get_agent_class") + ) + + +def _rung_backend(config: JobConfig, outcome: ValidationOutcome) -> None: + """Is the environment backend usable here? + + Harbor's own preflight is the check. For docker that means the binary is on PATH and + the daemon answers, and it reports the problem by raising ``SystemExit``, which is + fine for a CLI and has to be caught here. + """ + label = config.environment.import_path or ( + config.environment.type.value if config.environment.type is not None else "docker" + ) + try: + EnvironmentFactory.run_preflight(config.environment.type, config.environment.import_path) + except SystemExit as exc: + outcome.findings.append( + _harbor( + "backend", + "fail", + f"Environment backend '{label}' is not ready: {exc}", + "EnvironmentFactory.run_preflight", + ) + ) + return + except Exception as exc: + outcome.findings.append( + _harbor( + "backend", + "fail", + f"Environment backend '{label}' preflight failed: {type(exc).__name__}: {exc}", + "EnvironmentFactory.run_preflight", + hint="Cloud backends need their optional extra installed and vendor credentials set.", + ) + ) + return + outcome.findings.append( + _harbor( + "backend", "pass", f"Environment backend '{label}' passed preflight", "EnvironmentFactory.run_preflight" + ) + ) + + +def check_persisted_config(config_path: Path, repo_root: Path) -> Finding: + """Load the file we are about to persist through the Harbor CLI itself. + + The only rung that judges bytes rather than an in-memory object, which matters + because bytes are what a later agent will hand to Harbor. ``--print-config`` returns + before ``Job.create``, so this re-validates the schema and resolves nothing. It runs + with ``cwd`` at the repo root because the persisted config uses repo-relative paths. + """ + harbor_bin = shutil.which("harbor") + if harbor_bin is None: + return Finding( + name="round-trip", + group=_GROUP, + status="warn", + message="Skipped the CLI round trip: no `harbor` executable on PATH", + hint="The in-process schema rung already accepted this config.", + ) + + try: + completed = subprocess.run( + [harbor_bin, "job", "start", "--print-config", "-c", str(config_path)], + cwd=repo_root, + capture_output=True, + text=True, + timeout=_PRINT_CONFIG_TIMEOUT_SEC, + check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + return Finding( + name="round-trip", + group=_GROUP, + status="warn", + message=f"Could not run the CLI round trip: {type(exc).__name__}: {exc}", + path=config_path, + ) + + if completed.returncode != 0: + detail = (completed.stderr or completed.stdout).strip().splitlines() + return _harbor( + "round-trip", + "fail", + f"`harbor job start --print-config` rejected the persisted config: {detail[-1] if detail else 'no output'}", + "harbor job start --print-config", + path=config_path, + ) + return _harbor( + "round-trip", + "pass", + "The persisted config loads through the Harbor CLI", + "harbor job start --print-config", + path=config_path, + ) + + +@contextlib.contextmanager +def _module_search_path(repo_root: Path, module_name: str) -> Iterator[None]: + """Make *module_name* importable from this repo, then undo it. + + Two things have to be arranged. A wrapper is referenced as + ``harbor_wrapper:WrappedAgent``, a bare module name that only imports if its directory + is on ``sys.path``; Harbor's callers arrange that themselves at run time. + + And the name has to be evicted from ``sys.modules`` first. ``harbor_wrapper`` is a + convention, so two different repos, or the same repo before and after an edit, claim the + same module name. Without eviction the second import silently returns the first repo's + module and the rung would validate a file that is not the one under inspection. Both + changes are reversed on the way out, since this process did not ask to be reshaped. + """ + top = module_name.split(".", 1)[0] + directories = [ + path.parent + for path in sorted(repo_root.rglob(f"{top}.py")) + if ".venv" not in path.parts and "site-packages" not in path.parts + ] + added = [str(directory) for directory in directories if str(directory) not in sys.path] + sys.path[:0] = added + displaced = sys.modules.pop(top, None) + try: + yield + finally: + for entry in added: + with contextlib.suppress(ValueError): + sys.path.remove(entry) + sys.modules.pop(top, None) + if displaced is not None: + sys.modules[top] = displaced + + +def _task_config(task_dir: Path) -> TaskDefinitionConfig | None: + try: + return TaskDefinitionConfig.model_validate_toml(TaskPaths(task_dir).config_path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, tomllib.TOMLDecodeError, ValidationError): + return None + + +def _read_text(path: Path) -> str: + try: + return path.read_text(encoding="utf-8") + except (OSError, UnicodeError): + return "" + + +def _executable_lines(text: str) -> str: + """Drop comment lines before looking for a reward file. + + Harbor's own task template ships a ``test.sh`` that writes nothing and only mentions + ``reward.txt`` in a comment telling the author to write one. Grepping raw text would + pass exactly the task most likely to be broken: a scaffold nobody finished. + """ + kept = [ + line + for line in text.splitlines() + if not line.lstrip().startswith(("#", "::")) and not line.lstrip().upper().startswith("REM ") + ] + return "\n".join(kept) + + +def validate(candidate: CandidateConfig, repo_root: Path) -> ValidationOutcome: + """Synchronous entry point, since the CLI is not async but ``Job.create`` is.""" + return asyncio.run(run_ladder(candidate, repo_root)) + + +def temp_logs_dir() -> tempfile.TemporaryDirectory: + """Exposed for tests that need a throwaway logs dir when constructing agents.""" + return tempfile.TemporaryDirectory(prefix="eval-author-discover-") diff --git a/plugins/nemo-eval-author/tests/discovery_fixtures.py b/plugins/nemo-eval-author/tests/discovery_fixtures.py new file mode 100644 index 00000000000..e7547bf39a6 --- /dev/null +++ b/plugins/nemo-eval-author/tests/discovery_fixtures.py @@ -0,0 +1,174 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Builders for real Harbor task directories, plus a stub platform client. + +The discovery tests assert against Harbor's actual validators rather than against our +reading of them, which only works if the fixtures are things Harbor genuinely accepts. So +these write the same layout ``harbor task create`` produces — ``task.toml``, +``instruction.md``, ``environment/Dockerfile``, ``tests/test.sh``, ``solution/solve.sh`` — +and the interesting cases are departures from it. + +Imported as a module rather than declared as fixtures in ``conftest.py`` because the +builders take arguments; a test that needs a Windows task with no reward script should say +so at the call site instead of composing four fixtures to get there. +""" + +import json +from pathlib import Path +from typing import Any + +WRITES_REWARD = "#!/bin/bash\necho 1 > /logs/verifier/reward.txt\n" + +# What Harbor's own template ships: a comment telling the author to write a reward, and no +# code that does. A task scaffolded and abandoned looks exactly like this. +MENTIONS_REWARD_IN_COMMENT = "#!/bin/bash\n\n# Make sure to output a reward to /logs/verifier/reward.txt.\n" + +_DOCKERFILE = "FROM ubuntu:24.04\n\nWORKDIR /app\n" +_SOLVE = "#!/bin/bash\necho solved\n" + + +def write_task( + task_dir: Path, + *, + task_toml: str = "", + instruction: str | None = "Do the thing.\n", + test_script: str | None = WRITES_REWARD, + test_name: str = "test.sh", + environment: bool = True, + steps: dict[str, dict[str, str | None]] | None = None, +) -> Path: + """Write a Harbor task directory, defaulting to one Harbor accepts. + + Args: + task_toml: TOML appended after the version line. The baseline deliberately declares + no sections, so a caller can add ``[environment]`` or ``[verifier]`` without + colliding with a duplicate table. + instruction: Root ``instruction.md`` contents; ``None`` to omit it. + test_script: Root ``tests/`` script contents; ``None`` to omit it. + test_name: Root test filename, so a Windows task can ask for ``test.bat``. + environment: Whether to write ``environment/Dockerfile``. + steps: Multi-step layout as ``{step_name: {"instruction": ..., "test": ...}}``, + where a ``None`` value omits that file. + """ + task_dir.mkdir(parents=True, exist_ok=True) + (task_dir / "task.toml").write_text(f'version = "1.0"\n{task_toml}', encoding="utf-8") + + if instruction is not None: + (task_dir / "instruction.md").write_text(instruction, encoding="utf-8") + if environment: + (task_dir / "environment").mkdir(exist_ok=True) + (task_dir / "environment" / "Dockerfile").write_text(_DOCKERFILE, encoding="utf-8") + if test_script is not None: + (task_dir / "tests").mkdir(exist_ok=True) + (task_dir / "tests" / test_name).write_text(test_script, encoding="utf-8") + + (task_dir / "solution").mkdir(exist_ok=True) + (task_dir / "solution" / "solve.sh").write_text(_SOLVE, encoding="utf-8") + + for name, files in (steps or {}).items(): + step_dir = task_dir / "steps" / name + step_dir.mkdir(parents=True, exist_ok=True) + if files.get("instruction") is not None: + (step_dir / "instruction.md").write_text(str(files["instruction"]), encoding="utf-8") + if files.get("test") is not None: + (step_dir / "tests").mkdir(exist_ok=True) + (step_dir / "tests" / "test.sh").write_text(str(files["test"]), encoding="utf-8") + return task_dir + + +def write_dataset(root: Path, *, count: int = 2, test_script: str = WRITES_REWARD) -> Path: + """A directory of sibling task dirs, which is what Harbor treats as a dataset.""" + for index in range(count): + write_task(root / f"task-{index}", test_script=test_script) + return root + + +def write_wrapper(repo_root: Path, *, class_name: str = "WrappedAgent", base: str = "BaseAgent") -> Path: + """A ``harbor_wrapper.py`` holding a real ``BaseAgent`` subclass.""" + path = repo_root / "harbor_wrapper.py" + path.write_text( + f"from harbor.agents.base import {base}\n\n\n" + f"class {class_name}({base}):\n" + " @staticmethod\n" + " def name() -> str:\n" + f" return {class_name.lower()!r}\n\n" + " async def setup(self, environment):\n" + " return None\n\n" + " async def run(self, instruction, environment):\n" + " return None\n", + encoding="utf-8", + ) + return path + + +def write_job_dir(root: Path, *, config: dict[str, Any], with_lock: bool = True) -> Path: + """A completed Harbor job directory, which is a config Harbor already resolved.""" + root.mkdir(parents=True, exist_ok=True) + (root / "config.json").write_text(json.dumps(config), encoding="utf-8") + if with_lock: + (root / "lock.json").write_text(json.dumps({"harbor_version": "0.18.0"}), encoding="utf-8") + return root + + +class StubFiles: + """Records uploads and serves whatever was uploaded before, like the real thing.""" + + def __init__(self, stored: dict[str, bytes] | None = None, fail: bool = False) -> None: + self.stored: dict[str, bytes] = dict(stored or {}) + self.uploads: list[dict[str, Any]] = [] + self.fail = fail + + async def upload_content(self, *, content: bytes, remote_path: str, **kwargs: Any) -> None: + if self.fail: + raise RuntimeError("fileset unavailable") + self.uploads.append({"remote_path": remote_path, "content": content, **kwargs}) + self.stored[remote_path] = content + + async def download_content(self, *, remote_path: str, **kwargs: Any) -> bytes: + if remote_path not in self.stored: + raise FileNotFoundError(remote_path) + return self.stored[remote_path] + + +class StubClient: + """The narrow slice of ``AsyncNeMoPlatform`` discovery touches.""" + + def __init__(self, files: StubFiles | None = None, trace_total: int | None = 3) -> None: + self.files = files or StubFiles() + self.intake = _StubIntake(trace_total) + self.closed = False + + async def close(self) -> None: + self.closed = True + + +class _StubIntake: + def __init__(self, total: int | None) -> None: + self.spans = _StubSpans(total) + + +class _StubSpans: + def __init__(self, total: int | None) -> None: + self.groups = _StubGroups(total) + + +class _StubGroups: + def __init__(self, total: int | None) -> None: + self._total = total + + async def list(self, **kwargs: Any) -> Any: + if self._total is None: + raise RuntimeError("intake unreachable") + return _StubPage(self._total) + + +class _StubPage: + def __init__(self, total: int) -> None: + self.data = [object()] * min(total, 1) + self.pagination = _StubPagination(total) + + +class _StubPagination: + def __init__(self, total: int) -> None: + self.total_results = total diff --git a/plugins/nemo-eval-author/tests/test_cli.py b/plugins/nemo-eval-author/tests/test_cli.py index 663d0f15f12..919b670ffab 100644 --- a/plugins/nemo-eval-author/tests/test_cli.py +++ b/plugins/nemo-eval-author/tests/test_cli.py @@ -1,11 +1,14 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Scaffolding tests: the command tree exists, and every verb still refuses to run. +"""Scaffolding tests: the command tree exists, and unimplemented verbs still refuse to run. The entry-point cases cover the ``pyproject.toml`` wiring that nothing else exercises. A typo in the key or the import path does not fail an import; it just makes ``nemo eval-author`` quietly missing from the CLI, which no unit test of this module would catch. + +``discover`` has shipped, so it is asserted on in ``test_discovery_cli.py`` instead. It is +listed in ``_IMPLEMENTED_VERBS`` here only so ``--help`` still has to show it. """ from importlib.metadata import EntryPoint, entry_points @@ -19,13 +22,14 @@ # Each verb is a placeholder owned by the child ticket named beside it. _PLACEHOLDER_VERBS = [ - ("discover", "ASE-677"), ("audit", "ASE-676"), ("propose", "ASE-675"), ("run", "ASE-673"), ("doctor", "ASE-678"), ] +_IMPLEMENTED_VERBS = ["discover"] + @pytest.fixture def app() -> typer.Typer: @@ -42,7 +46,7 @@ def test_help_lists_every_verb(app: typer.Typer) -> None: result = runner.invoke(app, ["--help"]) assert result.exit_code == 0, result.output - for command, _ in _PLACEHOLDER_VERBS: + for command in [*(name for name, _ in _PLACEHOLDER_VERBS), *_IMPLEMENTED_VERBS]: assert command in result.output diff --git a/plugins/nemo-eval-author/tests/test_discovery_cli.py b/plugins/nemo-eval-author/tests/test_discovery_cli.py new file mode 100644 index 00000000000..da7f5072b33 --- /dev/null +++ b/plugins/nemo-eval-author/tests/test_discovery_cli.py @@ -0,0 +1,248 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""End to end through the CLI, with the platform stubbed out. + +Every test passes ``--repo`` explicitly and replaces ``make_client``. Without both, the +command defaults to the current directory and uploads to whatever platform the developer +happens to have running, which is how a unit test quietly becomes a network call. + +The exit code is the contract these pin down: this command is meant to be usable as a gate, +so exit 0 has to mean a config was validated *and* recorded, and nothing else. +""" + +import pytest +import typer +from discovery_fixtures import ( + MENTIONS_REWARD_IN_COMMENT, + StubClient, + StubFiles, + write_dataset, + write_wrapper, +) +from nemo_eval_author_plugin import cli +from nemo_eval_author_plugin.discovery import memory +from nemo_eval_author_plugin.discovery import run as discovery +from typer.testing import CliRunner + +runner = CliRunner() + + +@pytest.fixture +def app() -> typer.Typer: + return cli.EvalAuthorCLI().get_cli() + + +@pytest.fixture +def client(monkeypatch) -> StubClient: + """A stub platform, installed where ``run`` looks it up.""" + stub = StubClient() + monkeypatch.setattr(discovery, "make_client", lambda base_url: stub) + return stub + + +@pytest.fixture +def no_scout(monkeypatch): + """Fail loudly if a test reaches the LLM scout, which would need real credentials.""" + + def _forbidden(*args, **kwargs): + raise AssertionError("the scout must not run in these tests") + + monkeypatch.setattr(discovery, "_scout", _forbidden) + + +# Pytest's tmp_path names would be slugged, so tests that assert on a remote path name the +# agent outright. Defaulting is covered on its own below. +AGENT = "ticket-triage" + + +def _invoke(app, repo, *extra): + return runner.invoke(app, ["discover", "--repo", str(repo), "--no-deep", *extra]) + + +def _invoke_named(app, repo, *extra): + return _invoke(app, repo, "--agent", AGENT, *extra) + + +def test_a_healthy_repo_exits_zero_and_records_both_artifacts(app, client, tmp_path): + write_dataset(tmp_path / "evals" / "validation") + write_wrapper(tmp_path) + + result = _invoke_named(app, tmp_path) + + assert result.exit_code == 0, result.output + assert "Harbor can run this repo's evals" in result.output + assert "harbor job start -c harbor-job.yaml" in result.output + assert sorted(client.files.stored) == [f"{AGENT}/discovery.md", f"{AGENT}/harbor-job.yaml"] + + +def test_a_repo_whose_tasks_never_score_exits_one_and_withholds_the_config(app, client, tmp_path): + write_dataset(tmp_path / "evals" / "validation", test_script=MENTIONS_REWARD_IN_COMMENT) + + result = _invoke_named(app, tmp_path) + + assert result.exit_code == 1, result.output + assert "Harbor cannot run this repo's evals" in result.output + assert "reward" in result.output + # The report still lands, so the failure is documented rather than lost. + assert sorted(client.files.stored) == [f"{AGENT}/discovery.md"] + + +def test_a_repo_with_no_harbor_setup_at_all_exits_one(app, client, tmp_path): + (tmp_path / "README.md").write_text("# Just a repo\n") + + result = _invoke(app, tmp_path) + + assert result.exit_code == 1, result.output + assert "No Harbor job config could be assembled" in result.output + + +def test_dry_run_prints_the_artifacts_and_uploads_nothing(app, client, tmp_path): + write_dataset(tmp_path / "evals" / "validation") + + result = _invoke(app, tmp_path, "--dry-run") + + assert result.exit_code == 0, result.output + assert "Dry run: nothing was uploaded." in result.output + assert "inputs_digest:" in result.output, "the report itself is printed" + assert client.files.uploads == [] + + +def test_the_agent_name_defaults_to_the_repo_directory(app, client, tmp_path): + repo = tmp_path / "Ticket Triage Agent" + write_dataset(repo / "evals" / "validation") + + result = _invoke(app, repo) + + assert result.exit_code == 0, result.output + assert "ticket-triage-agent/discovery.md" in client.files.stored + + +def test_the_name_declared_in_the_profile_beats_the_directory(app, client, tmp_path): + """The name is the fileset path, so guessing it wrong hides the artifacts from ASE-675.""" + repo = tmp_path / "some-checkout-dir" + write_dataset(repo / "evals" / "validation") + (repo / "optimizer.yaml").write_text( + "agent: Ticket Triage\ntask_template: evals/template\ndatasets:\n validation: evals/validation\n" + ) + + result = _invoke(app, repo) + + assert result.exit_code == 0, result.output + assert "ticket-triage/discovery.md" in client.files.stored + + +def test_a_profile_written_for_a_newer_experimentalist_still_names_the_directory(app, client, tmp_path): + """A profile we cannot parse costs the name, not the run.""" + repo = tmp_path / "invoice-parser" + write_dataset(repo / "evals" / "validation") + (repo / "optimizer.yaml").write_text("agent:\n name: Ticket Triage\n version: 2\n") + + result = _invoke(app, repo) + + assert result.exit_code == 0, result.output + assert "invoice-parser/discovery.md" in client.files.stored + + +def test_an_explicit_agent_name_wins(app, client, tmp_path): + write_dataset(tmp_path / "evals" / "validation") + (tmp_path / "optimizer.yaml").write_text("agent: ignored\ndatasets:\n validation: evals/validation\n") + + result = _invoke(app, tmp_path, "--agent", "invoice-parser") + + assert result.exit_code == 0, result.output + assert "invoice-parser/discovery.md" in client.files.stored + + +def test_an_unchanged_repo_is_not_revalidated(app, client, tmp_path, no_scout): + write_dataset(tmp_path / "evals" / "validation") + first = _invoke(app, tmp_path) + assert first.exit_code == 0, first.output + + second = _invoke(app, tmp_path) + + assert second.exit_code == 0, second.output + assert "Nothing the previous report depended on has changed" in second.output + assert "validation/schema" not in second.output, "the ladder should not have run again" + + +def test_refresh_forces_the_ladder_to_run_again(app, client, tmp_path): + write_dataset(tmp_path / "evals" / "validation") + assert _invoke(app, tmp_path).exit_code == 0 + + result = _invoke(app, tmp_path, "--refresh") + + assert result.exit_code == 0, result.output + assert "validation/schema" in result.output + + +def test_an_edited_task_is_revalidated(app, client, tmp_path): + dataset = write_dataset(tmp_path / "evals" / "validation") + assert _invoke(app, tmp_path).exit_code == 0 + + # Break the reward contract; the digest moves, so the prior verdict cannot be reused. + (dataset / "task-0" / "tests" / "test.sh").write_text(MENTIONS_REWARD_IN_COMMENT) + result = _invoke(app, tmp_path) + + assert result.exit_code == 1, result.output + assert "never writes a reward file" in result.output + + +def test_a_previously_failing_repo_is_always_revalidated(app, client, tmp_path, no_scout): + """A failure may have been the machine's fault, so it is never taken on trust.""" + write_dataset(tmp_path / "evals" / "validation", test_script=MENTIONS_REWARD_IN_COMMENT) + assert _invoke(app, tmp_path).exit_code == 1 + + result = _invoke(app, tmp_path) + + assert result.exit_code == 1, result.output + assert "validation/reward" in result.output + + +def test_an_unwritable_fileset_exits_one_even_though_harbor_is_happy(app, monkeypatch, tmp_path): + write_dataset(tmp_path / "evals" / "validation") + monkeypatch.setattr(discovery, "make_client", lambda base_url: StubClient(files=StubFiles(fail=True))) + + result = _invoke(app, tmp_path) + + assert result.exit_code == 1, result.output + assert "Harbor can run this repo's evals" in result.output + assert "could not be recorded" in result.output + + +def test_traces_are_reported_without_blocking_a_run(app, monkeypatch, tmp_path): + write_dataset(tmp_path / "evals" / "validation") + monkeypatch.setattr(discovery, "make_client", lambda base_url: StubClient(trace_total=None)) + + result = _invoke(app, tmp_path) + + assert result.exit_code == 0, result.output + assert "repo/traces" in result.output + + +def test_the_platform_client_is_closed(app, client, tmp_path): + write_dataset(tmp_path / "evals" / "validation") + + _invoke(app, tmp_path) + + assert client.closed is True + + +def test_a_nonexistent_repo_is_rejected_by_the_flag(app, client, tmp_path): + result = runner.invoke(app, ["discover", "--repo", str(tmp_path / "nope")]) + + assert result.exit_code != 0 + assert client.files.uploads == [] + + +def test_the_uploaded_report_carries_the_verdict_that_was_printed(app, client, tmp_path): + """A later agent reads the fileset copy, so it has to be the copy that was verified.""" + write_dataset(tmp_path / "evals" / "validation") + + assert _invoke_named(app, tmp_path).exit_code == 0 + + stored = client.files.stored[memory.remote_report_path(AGENT)].decode("utf-8") + front = memory.parse_front_matter(stored) + assert front is not None + assert front["runnable"] is True + assert front["config_source"]["kind"] == "convention" diff --git a/plugins/nemo-eval-author/tests/test_discovery_memory.py b/plugins/nemo-eval-author/tests/test_discovery_memory.py new file mode 100644 index 00000000000..88f721eb370 --- /dev/null +++ b/plugins/nemo-eval-author/tests/test_discovery_memory.py @@ -0,0 +1,137 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""What reaches the fileset, and what deliberately does not. + +The invariant worth defending: a ``harbor-job.yaml`` in the fileset is always a config +Harbor accepted. A later agent is told to run whatever it finds there, so a config uploaded +alongside a failing report would be an instruction to run something broken. +""" + +from discovery_fixtures import StubClient, StubFiles +from nemo_eval_author_plugin.discovery import memory, report + + +async def test_both_artifacts_are_uploaded_under_the_agent_prefix(): + client = StubClient() + + ok, findings = await memory.persist( + client, agent="ticket-triage", workspace="default", markdown="# report\n", job_config="datasets: []\n" + ) + + assert ok is True + assert [item["remote_path"] for item in client.files.uploads] == [ + "ticket-triage/discovery.md", + "ticket-triage/harbor-job.yaml", + ] + assert all(item["fileset"] == memory.FILESET_NAME for item in client.files.uploads) + assert all(item["fileset_auto_create"] is True for item in client.files.uploads) + assert all(item.status == "pass" for item in findings) + + +async def test_the_config_is_withheld_when_harbor_never_accepted_one(): + client = StubClient() + + ok, findings = await memory.persist( + client, agent="ticket-triage", workspace="default", markdown="# report\n", job_config=None + ) + + assert ok is True, "the report still has to land, so the failure is documented" + assert [item["remote_path"] for item in client.files.uploads] == ["ticket-triage/discovery.md"] + withheld = next(item for item in findings if "Withheld" in item.message) + assert withheld.status == "warn" + assert withheld.hint is not None and "always one Harbor could load" in withheld.hint + + +async def test_an_upload_failure_is_reported_without_claiming_the_config_is_broken(): + client = StubClient(files=StubFiles(fail=True)) + + ok, findings = await memory.persist( + client, agent="ticket-triage", workspace="default", markdown="# report\n", job_config="datasets: []\n" + ) + + assert ok is False + # A fileset outage says nothing about whether Harbor can run the config, so these are + # warnings; run.DiscoverResult.ok folds the False into the exit code instead. + assert all(item.status == "warn" for item in findings) + assert any("fileset unavailable" in item.message for item in findings) + + +async def test_a_previous_report_is_read_back_for_comparison(tmp_path): + record = report.build_report( + agent="ticket-triage", + workspace="default", + repo_root=tmp_path, + candidate=None, + findings=[], + required_env_vars=[], + inputs=report.fingerprint_inputs([_write(tmp_path / "a.md", "a\n")], tmp_path), + ) + markdown = report.render_markdown(record) + client = StubClient(files=StubFiles({"ticket-triage/discovery.md": markdown.encode("utf-8")})) + + prior = await memory.load_previous(client, agent="ticket-triage", workspace="default") + + assert prior is not None + assert prior.inputs_digest == record.inputs_digest + assert [item.path for item in prior.inputs] == ["a.md"] + assert prior.text == markdown + + +async def test_a_missing_or_unreachable_report_just_means_rediscover(): + empty = await memory.load_previous(StubClient(), agent="ticket-triage", workspace="default") + assert empty is None + + unusable = StubClient(files=StubFiles({"ticket-triage/discovery.md": b"not a report"})) + assert await memory.load_previous(unusable, agent="ticket-triage", workspace="default") is None + + +def test_rehashing_prior_inputs_notices_an_edited_file(tmp_path): + path = _write(tmp_path / "task.toml", 'version = "1.0"\n') + inputs = report.fingerprint_inputs([path], tmp_path) + prior = memory.PriorRecord(inputs=inputs, inputs_digest="sha256:whatever", runnable=True) + + assert memory.rehash_prior_inputs(prior, tmp_path) == inputs + + _write(path, 'version = "1.0"\n# edited\n') + assert memory.rehash_prior_inputs(prior, tmp_path) != inputs + + +def test_a_deleted_input_changes_the_digest(tmp_path): + """A report derived from a file someone removed must not read as still valid.""" + path = _write(tmp_path / "task.toml", 'version = "1.0"\n') + prior = memory.PriorRecord( + inputs=report.fingerprint_inputs([path], tmp_path), inputs_digest="sha256:whatever", runnable=True + ) + path.unlink() + + assert memory.rehash_prior_inputs(prior, tmp_path) == [] + + +async def test_rerunning_overwrites_rather_than_accumulating(): + """Agent-scoped fixed paths mean the fileset holds the latest answer, not a pile.""" + client = StubClient() + + for body in ("# first\n", "# second\n"): + await memory.persist( + client, agent="ticket-triage", workspace="default", markdown=body, job_config="datasets: []\n" + ) + + assert len(client.files.uploads) == 4 + assert sorted(client.files.stored) == ["ticket-triage/discovery.md", "ticket-triage/harbor-job.yaml"] + assert client.files.stored["ticket-triage/discovery.md"] == b"# second\n" + + +async def test_two_agents_do_not_share_a_path(): + client = StubClient() + + for agent in ("ticket-triage", "invoice-parser"): + await memory.persist(client, agent=agent, workspace="default", markdown="# report\n", job_config=None) + + assert sorted(client.files.stored) == ["invoice-parser/discovery.md", "ticket-triage/discovery.md"] + + +def _write(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path diff --git a/plugins/nemo-eval-author/tests/test_discovery_report.py b/plugins/nemo-eval-author/tests/test_discovery_report.py new file mode 100644 index 00000000000..07c62664420 --- /dev/null +++ b/plugins/nemo-eval-author/tests/test_discovery_report.py @@ -0,0 +1,186 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The persisted artifacts: portable, machine-readable, and honest about what failed. + +Two properties carry the weight. The front matter has to survive a round trip, because a +later agent reads it instead of redoing the work. And the config has to be free of this +machine: absolute paths, a frozen job name, or a real API key in the file would each make +the artifact wrong somewhere other than where it was produced. +""" + +from datetime import UTC, datetime + +import yaml +from discovery_fixtures import write_dataset +from harbor.models.job.config import JobConfig +from nemo_eval_author_plugin.discovery import memory, report +from nemo_eval_author_plugin.discovery.models import ( + CandidateConfig, + ConfigSource, + Finding, + RequiredEnvVar, +) + + +def _record(tmp_path, findings=(), env_vars=(), inputs=(), candidate=None): + return report.build_report( + agent="ticket-triage", + workspace="default", + repo_root=tmp_path, + candidate=candidate + or CandidateConfig(data={}, source=ConfigSource(kind="config_file", detail="declared at configs/eval.yaml")), + findings=list(findings), + required_env_vars=list(env_vars), + inputs=list(inputs), + ) + + +def test_front_matter_survives_a_round_trip(tmp_path): + record = _record( + tmp_path, + findings=[Finding(name="schema", group="validation", status="pass", message="ok", harbor_call="x")], + env_vars=[RequiredEnvVar(name="HF_TOKEN", declared_in=tmp_path / "evals/task-0/task.toml")], + inputs=report.fingerprint_inputs([_write(tmp_path / "ETHOS.md", "# Ethos\n")], tmp_path), + ) + + front = memory.parse_front_matter(report.render_markdown(record)) + + assert front is not None + assert front["runnable"] is True + assert front["agent"] == "ticket-triage" + assert front["validation"] == {"schema": "pass"} + assert front["inputs_digest"] == record.inputs_digest + assert front["harbor_version"] == report.harbor_version() + # Recorded relative, so the artifact means the same thing on another machine. + assert front["required_env_vars"][0]["declared_in"] == "evals/task-0/task.toml" + assert front["inputs"] == [{"path": "ETHOS.md", "sha256": record.inputs[0].sha256}] + + +def test_the_digest_is_stable_and_notices_a_changed_input(tmp_path): + path = _write(tmp_path / "task.toml", 'version = "1.0"\n') + first = _record(tmp_path, inputs=report.fingerprint_inputs([path], tmp_path)) + again = _record(tmp_path, inputs=report.fingerprint_inputs([path], tmp_path)) + assert first.inputs_digest == again.inputs_digest + + _write(path, 'version = "1.0"\n# edited\n') + changed = _record(tmp_path, inputs=report.fingerprint_inputs([path], tmp_path)) + assert changed.inputs_digest != first.inputs_digest + + +def test_the_digest_ignores_the_order_inputs_were_collected_in(tmp_path): + first = _write(tmp_path / "a.md", "a\n") + second = _write(tmp_path / "b.md", "b\n") + + forward = _record(tmp_path, inputs=report.fingerprint_inputs([first, second], tmp_path)) + backward = _record(tmp_path, inputs=report.fingerprint_inputs([second, first], tmp_path)) + + assert forward.inputs_digest == backward.inputs_digest + + +def test_the_persisted_config_carries_no_absolute_paths(tmp_path): + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + config = JobConfig.model_validate({"datasets": [{"path": str(dataset)}]}) + + rendered = report.render_job_config(config, tmp_path) + + assert yaml.safe_load(rendered)["datasets"] == [{"path": "evals/validation"}] + assert str(tmp_path) not in rendered + + +def test_a_path_outside_the_repo_is_left_absolute(tmp_path): + """Relativizing it would silently point the run at a directory that is not there.""" + outside = tmp_path.parent / "elsewhere" + config = JobConfig.model_validate({"datasets": [{"path": str(outside)}]}) + + rendered = report.render_job_config(config, tmp_path) + + assert yaml.safe_load(rendered)["datasets"] == [{"path": str(outside)}] + + +def test_a_generated_job_name_is_dropped_and_a_declared_one_is_kept(tmp_path): + generated = JobConfig.model_validate({"datasets": [{"path": "evals"}]}) + assert "job_name" not in yaml.safe_load(report.render_job_config(generated, tmp_path)) + + declared = JobConfig.model_validate({"datasets": [{"path": "evals"}], "job_name": "nightly-triage"}) + assert yaml.safe_load(report.render_job_config(declared, tmp_path))["job_name"] == "nightly-triage" + + +def test_a_secret_in_the_agent_env_is_templated_rather_than_written(tmp_path): + """Harbor's own serializer does this; the test pins the behavior we rely on.""" + config = JobConfig.model_validate( + { + "agents": [{"name": "oracle", "env": {"OPENAI_API_KEY": "sk-do-not-persist-me"}}], + "datasets": [{"path": "evals"}], + } + ) + + rendered = report.render_job_config(config, tmp_path) + + assert "sk-do-not-persist-me" not in rendered + + +def test_an_unrunnable_report_says_what_blocks_it_and_offers_no_command(tmp_path): + record = _record( + tmp_path, + findings=[ + Finding( + name="reward", + group="validation", + status="fail", + message="1 task(s) have a test script that never writes a reward file", + harbor_call="TaskPaths.discovered_test_path_for", + ) + ], + ) + + markdown = report.render_markdown(record) + + assert record.runnable is False + assert "cannot run" in markdown + assert "never writes a reward file" in markdown + assert "harbor job start" not in markdown, "an unrunnable report must not hand out a run command" + + +def test_a_report_with_no_config_at_all_says_where_to_start(tmp_path): + record = report.build_report( + agent="ticket-triage", + workspace="default", + repo_root=tmp_path, + candidate=None, + findings=[], + required_env_vars=[], + inputs=[], + ) + + markdown = report.render_markdown(record) + + assert record.runnable is False + assert "harbor job init" in markdown + + +def test_restamping_moves_the_stamp_and_leaves_the_narrative_alone(tmp_path): + record = _record(tmp_path, inputs=report.fingerprint_inputs([_write(tmp_path / "a.md", "a\n")], tmp_path)) + original = report.render_markdown(record) + later = datetime(2027, 1, 1, tzinfo=UTC) + + restamped = memory.restamp(original, when=later, harbor_version="9.9.9") + + assert restamped is not None + front = memory.parse_front_matter(restamped) + assert front is not None + assert front["last_validated_at"] == later.isoformat() + assert front["harbor_version"] == "9.9.9" + assert front["discovered_at"] == record.discovered_at.isoformat(), "discovery time is history, not a stamp" + assert front["inputs_digest"] == record.inputs_digest + assert original.split("\n---\n", 1)[1] == restamped.split("\n---\n", 1)[1] + + +def test_restamping_declines_a_file_without_front_matter(): + assert memory.restamp("# just markdown\n", when=datetime.now(UTC), harbor_version="1.0") is None + + +def _write(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path diff --git a/plugins/nemo-eval-author/tests/test_discovery_scan.py b/plugins/nemo-eval-author/tests/test_discovery_scan.py new file mode 100644 index 00000000000..f05886310a1 --- /dev/null +++ b/plugins/nemo-eval-author/tests/test_discovery_scan.py @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Repo-shape probes: context for authoring evals, never a reason a run cannot happen. + +The invariant these defend is the meaning of ``runnable``. It answers exactly one question, +"can Harbor run this config", so a repo with no traces yet or no doctrine document must not +be reported as unrunnable. Only the validation ladder is allowed to fail a report. +""" + +from pathlib import Path + +from discovery_fixtures import StubClient +from nemo_eval_author_plugin.discovery import scan + + +def test_ethos_is_preferred_over_the_name_it_replaced(tmp_path): + (tmp_path / "AGENT-SPEC.md").write_text("# Old\n") + (tmp_path / "ETHOS.md").write_text("# New\n") + (tmp_path / "README.md").write_text("# Readme\n") + + path, finding = scan.find_doctrine(tmp_path) + + assert path == tmp_path / "ETHOS.md" + assert finding.status == "pass" + assert finding.hint is None + + +def test_the_old_name_still_works_and_says_so(tmp_path): + """Both names are honored while the rename is in flight, so the report is the signal.""" + (tmp_path / "AGENT-SPEC.md").write_text("# Old\n") + (tmp_path / "README.md").write_text("# Readme\n") + + path, finding = scan.find_doctrine(tmp_path) + + assert path == tmp_path / "AGENT-SPEC.md" + assert finding.hint is not None and "predates the rename" in finding.hint + + +def test_readme_is_the_last_resort(tmp_path): + (tmp_path / "README.md").write_text("# Readme\n") + + path, finding = scan.find_doctrine(tmp_path) + + assert path == tmp_path / "README.md" + assert finding.status == "pass" + + +def test_no_doctrine_is_a_warning_not_a_failure(tmp_path): + path, finding = scan.find_doctrine(tmp_path) + + assert path is None + assert finding.status == "warn" + + +def test_skill_bundles_are_found_by_their_marker_file(tmp_path): + for name in ("triage", "escalate"): + (tmp_path / "skills" / name).mkdir(parents=True) + (tmp_path / "skills" / name / "SKILL.md").write_text(f"# {name}\n") + + skills, finding = scan.find_skills(tmp_path) + + assert len(skills) == 2 + assert finding.status == "pass" + assert finding.hint is not None and "AgentConfig.skills" in finding.hint + + +def test_vendored_trees_are_not_searched(tmp_path): + """A dependency's skills are not the repo's, and .venv dwarfs everything else.""" + vendored = tmp_path / ".venv" / "lib" / "pkg" + vendored.mkdir(parents=True) + (vendored / "SKILL.md").write_text("# not ours\n") + + skills, finding = scan.find_skills(tmp_path) + + assert skills == [] + assert finding.status == "warn" + + +async def test_available_traces_are_counted(): + finding = await scan.probe_traces(StubClient(trace_total=7), agent="ticket-triage", workspace="default") + + assert finding.status == "pass" + assert "7 trace session(s)" in finding.message + + +async def test_no_traces_is_a_warning_with_a_next_step(): + finding = await scan.probe_traces(StubClient(trace_total=0), agent="ticket-triage", workspace="default") + + assert finding.status == "warn" + assert finding.hint is not None and "telemetry" in finding.hint + + +async def test_an_unreachable_platform_never_blocks_a_run(): + finding = await scan.probe_traces(StubClient(trace_total=None), agent="ticket-triage", workspace="default") + + assert finding.status == "warn" + assert finding.hint is not None and "Harbor runs fine without them" in finding.hint + + +def test_a_path_above_the_repo_is_rendered_absolute_rather_than_crashing(tmp_path): + """``discover_profile`` walks upward, so this is a real case and not a defensive guess.""" + outside = tmp_path.parent / "optimizer.yaml" + + assert scan.display_path(outside, tmp_path) == str(outside) + assert scan.display_path(tmp_path / "evals" / "task", tmp_path) == "evals/task" + # The sentinel used for values declared inline rather than in a file. + assert scan.display_path(Path(""), tmp_path) == "" diff --git a/plugins/nemo-eval-author/tests/test_discovery_scout.py b/plugins/nemo-eval-author/tests/test_discovery_scout.py new file mode 100644 index 00000000000..397d3e6f231 --- /dev/null +++ b/plugins/nemo-eval-author/tests/test_discovery_scout.py @@ -0,0 +1,135 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The scout proposes; Harbor decides. + +This is the seam where a language model's guess enters an artifact a later agent is told to +trust, so the tests here are about containment rather than about the model. The scout's +output is pushed back through the same ladder, a proposal Harbor rejects changes nothing, +and anything it did influence is marked as inference so a reader can tell it apart from a +verdict Harbor returned. + +No model is ever called: ``attempt_repair`` takes the proposal function as a parameter and +these tests pass a fixed one. A test that reached a real model would need credentials and +would assert on something nondeterministic. +""" + +from discovery_fixtures import MENTIONS_REWARD_IN_COMMENT, write_dataset +from nemo_eval_author_plugin.discovery import validate +from nemo_eval_author_plugin.discovery.agent import ProposeFn, ScoutProposal, attempt_repair, is_scoutable +from nemo_eval_author_plugin.discovery.models import CandidateConfig, ConfigSource, Finding + + +def _candidate(data: dict) -> CandidateConfig: + return CandidateConfig(data=data, source=ConfigSource(kind="convention", detail="inferred from task dirs")) + + +def _outcome(*failures: str) -> validate.ValidationOutcome: + return validate.ValidationOutcome( + findings=[ + Finding(name=name, group="validation", status="fail", message="broken", provenance="harbor") + for name in failures + ] + ) + + +def _proposes(proposal: ScoutProposal | Exception) -> ProposeFn: + async def propose(candidate, blocking, repo_root): + if isinstance(proposal, Exception): + raise proposal + return proposal + + return propose + + +def test_only_failures_a_look_at_the_repo_could_settle_are_scoutable(): + assert is_scoutable(_outcome("resolution")) is True + assert is_scoutable(_outcome("agent")) is True + # Docker not running is a fact about the machine; no amount of reading the repo helps. + assert is_scoutable(_outcome("backend")) is False + assert is_scoutable(_outcome("reward")) is False + + +async def test_a_proposal_harbor_accepts_is_adopted_and_labelled(tmp_path): + good = write_dataset(tmp_path / "evals" / "validation", count=1) + broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) + outcome = await validate.run_ladder(broken, tmp_path) + assert not outcome.runnable + propose = _proposes( + ScoutProposal( + config={"datasets": [{"path": str(good)}]}, + rationale="evals/validation holds the task.toml dirs", + changed=["datasets"], + ) + ) + + candidate, revalidated, findings = await attempt_repair(broken, outcome, tmp_path, propose) + + assert candidate.data["datasets"] == [{"path": str(good)}] + assert revalidated.runnable + # The config's provenance has to admit a model touched it. + assert "adjusted by the discovery scout" in candidate.source.detail + assert findings[0].status == "pass" + assert findings[0].provenance == "inference" + + +async def test_a_proposal_harbor_rejects_changes_nothing(tmp_path): + """Otherwise a plausible guess could replace failures the user could act on.""" + broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) + outcome = await validate.run_ladder(broken, tmp_path) + propose = _proposes( + ScoutProposal( + config={"datasets": [{"path": str(tmp_path / "also-wrong")}]}, + rationale="guessing", + changed=["datasets"], + ) + ) + + candidate, revalidated, findings = await attempt_repair(broken, outcome, tmp_path, propose) + + assert candidate is broken + assert revalidated is outcome + assert findings[0].status == "warn" + assert "still rejected" in findings[0].message + + +async def test_a_proposal_that_only_fixes_one_of_two_failures_is_not_adopted(tmp_path): + """Runnable is the bar, not merely different: a partial fix is still not runnable.""" + dataset = write_dataset(tmp_path / "evals" / "validation", count=1, test_script=MENTIONS_REWARD_IN_COMMENT) + broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) + outcome = await validate.run_ladder(broken, tmp_path) + propose = _proposes( + ScoutProposal(config={"datasets": [{"path": str(dataset)}]}, rationale="found the dir", changed=["datasets"]) + ) + + candidate, _, findings = await attempt_repair(broken, outcome, tmp_path, propose) + + assert candidate is broken, "the reward contract is still broken, so nothing is adopted" + assert findings[0].status == "warn" + + +async def test_a_scout_with_nothing_to_change_says_so(tmp_path): + broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) + outcome = await validate.run_ladder(broken, tmp_path) + propose = _proposes(ScoutProposal(config=broken.data, rationale="the repo names no dataset anywhere", changed=[])) + + candidate, revalidated, findings = await attempt_repair(broken, outcome, tmp_path, propose) + + assert candidate is broken + assert revalidated is outcome + assert "nothing in the repo to change" in findings[0].message + assert "names no dataset" in findings[0].message + + +async def test_a_scout_that_cannot_run_degrades_to_a_warning(tmp_path): + """Missing credentials must not turn a reportable failure into a crash.""" + broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) + outcome = await validate.run_ladder(broken, tmp_path) + propose = _proposes(RuntimeError("no model credentials")) + + candidate, revalidated, findings = await attempt_repair(broken, outcome, tmp_path, propose) + + assert candidate is broken + assert revalidated is outcome + assert findings[0].status == "warn" + assert findings[0].hint is not None and "--no-deep" in findings[0].hint diff --git a/plugins/nemo-eval-author/tests/test_discovery_sources.py b/plugins/nemo-eval-author/tests/test_discovery_sources.py new file mode 100644 index 00000000000..24d6d655714 --- /dev/null +++ b/plugins/nemo-eval-author/tests/test_discovery_sources.py @@ -0,0 +1,150 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Which source wins, and what gets read rather than assumed. + +Priority is the load-bearing behavior here: the whole artifact is a trust claim, so a repo +offering both a config its author wrote and a layout we could guess at must resolve to the +former, and the report must say which it used. +""" + +import json + +import yaml +from discovery_fixtures import write_dataset, write_job_dir, write_task, write_wrapper +from nemo_eval_author_plugin.discovery import sources + + +def _job_config(dataset: str) -> dict: + return {"agents": [{"name": "oracle"}], "datasets": [{"path": dataset}]} + + +def test_config_file_outranks_every_inferred_source(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + write_job_dir(tmp_path / "jobs" / "run-1", config=_job_config("evals/validation")) + (tmp_path / "configs").mkdir() + (tmp_path / "configs" / "eval.yaml").write_text(yaml.safe_dump(_job_config("evals/validation"))) + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "config_file" + chosen = next(item for item in findings if item.name == "config-source") + assert "config_file" in chosen.message + # The passed-over sources are named, so a reader can tell what was available. + assert chosen.hint is not None and "prior_job" in chosen.hint + + +def test_prior_job_outranks_convention(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + write_job_dir(tmp_path / "jobs" / "run-1", config=_job_config("evals/validation")) + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "prior_job" + + +def test_trial_config_is_not_mistaken_for_a_job_config(tmp_path): + """Harbor writes config.json and lock.json into trial dirs too, not just job dirs.""" + write_dataset(tmp_path / "evals" / "validation") + write_job_dir( + tmp_path / "jobs" / "run-1" / "trial-0", + config={"task": {"path": "evals/validation/task-0"}, "trial_name": "trial-0"}, + ) + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "convention" + + +def test_profile_outranks_convention_and_reads_the_validation_split(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + write_dataset(tmp_path / "evals" / "train", count=3) + (tmp_path / "optimizer.yaml").write_text( + yaml.safe_dump( + {"agent": "ticket-triage", "datasets": {"train": "evals/train", "validation": "evals/validation"}} + ) + ) + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "profile" + assert candidate.data["datasets"] == [{"path": str(tmp_path / "evals" / "validation")}] + split = next(item for item in findings if item.name == "profile-datasets") + assert "validation" in split.message + # Evaluating the train split would silently score the set used to optimize. + assert split.hint is not None and "train" in split.hint + + +def test_convention_prefers_a_conventional_eval_dir_over_a_larger_one(tmp_path): + write_dataset(tmp_path / "evals" / "validation", count=2) + write_dataset(tmp_path / "experiments" / "scratch", count=5) + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.data["datasets"] == [{"path": str(tmp_path / "evals" / "validation")}] + + +def test_a_lone_task_template_is_not_a_dataset(tmp_path): + write_task(tmp_path / "evals" / "task_template") + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is None + assert any(item.name == "convention-datasets" and item.status == "warn" for item in findings) + assert any(item.name == "config-source" and item.status == "fail" for item in findings) + + +def test_wrapper_class_name_is_read_from_the_file(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + write_wrapper(tmp_path, class_name="TicketTriageAgent") + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.data["agents"] == [{"import_path": "harbor_wrapper:TicketTriageAgent"}] + entry = next(item for item in findings if item.name == "agent-entrypoint") + assert entry.hint is not None and "not assumed" in entry.hint + + +def test_missing_wrapper_falls_back_to_the_oracle_and_says_what_that_means(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.data["agents"] == [{"name": "oracle"}] + entry = next(item for item in findings if item.name == "agent-entrypoint") + assert entry.status == "warn" + assert entry.hint is not None and "evaluates no agent" in entry.hint + + +def test_env_backend_fills_a_gap_but_never_overrides_a_declaration(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + + filled, _ = sources.find_candidate(tmp_path, env_backend="docker") + assert filled is not None + assert filled.data["environment"] == {"type": "docker"} + + (tmp_path / "configs").mkdir() + declared = {**_job_config("evals/validation"), "environment": {"type": "daytona"}} + (tmp_path / "configs" / "eval.json").write_text(json.dumps(declared)) + + respected, _ = sources.find_candidate(tmp_path, env_backend="docker") + assert respected is not None + assert respected.data["environment"]["type"] == "daytona" + + +def test_unreadable_yaml_is_skipped_rather_than_raising(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + (tmp_path / "configs").mkdir() + (tmp_path / "configs" / "broken.yaml").write_text("datasets: [oops\n") + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "convention" diff --git a/plugins/nemo-eval-author/tests/test_discovery_validate.py b/plugins/nemo-eval-author/tests/test_discovery_validate.py new file mode 100644 index 00000000000..77fa7604b97 --- /dev/null +++ b/plugins/nemo-eval-author/tests/test_discovery_validate.py @@ -0,0 +1,315 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The validation ladder, against real Harbor task directories. + +Every fixture here is a layout Harbor itself accepts or rejects, so these tests assert +against Harbor's validators rather than against our reading of them. That matters most for +the shapes a hand-rolled "does tests/test.sh exist" check gets wrong: a multi-step task, a +Windows task, a task graded from a separate verifier image, and a task that names a +prebuilt image instead of shipping a Dockerfile. Each of those is legitimate, and each one +a naive check would fail. + +The backend rung is excluded from pass assertions because it runs Docker's preflight, and +whether a daemon is up is a fact about the machine rather than about the repo under test. +Tests that care about the backend assert on that finding directly. +""" + +import sys + +from discovery_fixtures import ( + MENTIONS_REWARD_IN_COMMENT, + WRITES_REWARD, + write_dataset, + write_task, + write_wrapper, +) +from nemo_eval_author_plugin.discovery import sources, validate +from nemo_eval_author_plugin.discovery.models import CandidateConfig, ConfigSource + + +def _candidate(data: dict) -> CandidateConfig: + return CandidateConfig(data=data, source=ConfigSource(kind="config_file", detail="test fixture")) + + +def _finding(outcome, name): + matches = [item for item in outcome.findings if item.name == name] + assert matches, f"no {name!r} finding in {[item.name for item in outcome.findings]}" + return matches[0] + + +def _repo_failures(outcome): + """Failures the repo is responsible for, so Docker's absence does not fail a test.""" + return [item for item in outcome.findings if item.status == "fail" and item.name != "backend"] + + +async def test_a_well_formed_repo_passes_every_rung(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + candidate = _candidate({"agents": [{"name": "oracle"}], "datasets": [{"path": str(tmp_path / "evals/validation")}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _repo_failures(outcome) == [] + assert _finding(outcome, "tasks").message.startswith("2 of 2") + assert _finding(outcome, "schema").harbor_call == "JobConfig.model_validate" + assert _finding(outcome, "resolution").harbor_call == "Job.create" + # Every verdict must be attributable to Harbor, or the artifact is not trustworthy. + assert all(item.provenance == "harbor" for item in outcome.findings) + + +async def test_schema_failure_names_the_harbor_validator(tmp_path): + outcome = await validate.run_ladder(_candidate({"datasets": "not-a-list"}), tmp_path) + + schema = _finding(outcome, "schema") + assert schema.status == "fail" + assert schema.harbor_call == "JobConfig.model_validate" + # Nothing downstream can be judged once the schema is wrong. + assert [item.name for item in outcome.findings] == ["schema"] + assert outcome.config is None + + +async def test_resolution_failure_reports_the_error_a_real_run_would_hit(tmp_path): + candidate = _candidate({"datasets": [{"path": str(tmp_path / "nope")}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + resolution = _finding(outcome, "resolution") + assert resolution.status == "fail" + assert resolution.harbor_call == "Job.create" + assert resolution.hint is not None and "before starting any container" in resolution.hint + + +async def test_a_task_harbor_silently_skips_is_reported(tmp_path): + """Harbor drops a directory it cannot parse without raising, so a run would score fewer + tasks than the repo holds and nothing about the result would look incomplete.""" + dataset = tmp_path / "evals" / "validation" + write_task(dataset / "task-0") + write_task(dataset / "task-1", instruction=None) + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + # Harbor resolved only the good one, so the tasks rung sees nothing wrong. + assert _finding(outcome, "tasks").message.startswith("1 of 1") + coverage = _finding(outcome, "coverage") + assert coverage.status == "fail" + assert "task-1" in coverage.message + assert "instruction.md" in coverage.message + assert coverage.hint is not None and "silently" in coverage.hint + + +async def test_a_dataset_that_selects_a_subset_is_not_accused_of_dropping_tasks(tmp_path): + dataset = write_dataset(tmp_path / "evals" / "validation", count=3) + candidate = _candidate({"datasets": [{"path": str(dataset), "task_names": ["task-0"]}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + coverage = _finding(outcome, "coverage") + assert coverage.status == "warn" + assert coverage.hint is not None and "selects a subset" in coverage.hint + assert _repo_failures(outcome) == [] + + +async def test_a_scaffolded_task_that_never_writes_a_reward_is_caught(tmp_path): + """Harbor's own template mentions the reward file only in a comment.""" + dataset = write_dataset(tmp_path / "evals" / "validation", count=1, test_script=MENTIONS_REWARD_IN_COMMENT) + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + reward = _finding(outcome, "reward") + assert reward.status == "fail" + assert _finding(outcome, "tasks").status == "pass", "the task is structurally fine; only its scoring is broken" + assert reward.hint is not None and "RewardFileNotFoundError" in reward.hint + + +async def test_a_multi_step_task_is_valid_without_a_root_instruction(tmp_path): + dataset = tmp_path / "evals" / "validation" + write_task( + dataset / "task-0", + task_toml='\n[[steps]]\nname = "first"\n\n[[steps]]\nname = "second"\n', + instruction=None, + steps={"first": {"instruction": "Step one.\n"}, "second": {"instruction": "Step two.\n"}}, + ) + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _finding(outcome, "tasks").status == "pass" + assert _repo_failures(outcome) == [] + + +async def test_a_multi_step_task_is_checked_for_a_reward_in_every_step(tmp_path): + """A shared script covers a step with none of its own; a step's own script must score.""" + dataset = tmp_path / "evals" / "validation" + write_task( + dataset / "task-0", + task_toml='\n[[steps]]\nname = "first"\n\n[[steps]]\nname = "second"\n', + instruction=None, + test_script=WRITES_REWARD, + steps={ + "first": {"instruction": "Step one.\n"}, + "second": {"instruction": "Step two.\n", "test": MENTIONS_REWARD_IN_COMMENT}, + }, + ) + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _finding(outcome, "tasks").status == "pass" + assert _finding(outcome, "reward").status == "fail" + + +async def test_a_windows_task_needing_test_bat_is_not_a_failure(tmp_path): + dataset = tmp_path / "evals" / "validation" + write_task( + dataset / "task-0", + task_toml='\n[environment]\nos = "windows"\n', + test_script="@echo off\r\necho 1 > /logs/verifier/reward.txt\r\n", + test_name="test.bat", + ) + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _finding(outcome, "tasks").status == "pass" + assert _finding(outcome, "reward").status == "pass" + + +async def test_a_task_graded_in_a_separate_verifier_image_needs_no_host_script(tmp_path): + dataset = tmp_path / "evals" / "validation" + write_task(dataset / "task-0", task_toml='\n[verifier]\nenvironment_mode = "separate"\n', test_script=None) + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _finding(outcome, "tasks").status == "pass" + reward = _finding(outcome, "reward") + assert reward.status == "pass" + assert "separate verifier image" in reward.message + + +async def test_a_task_naming_a_prebuilt_image_needs_no_dockerfile(tmp_path): + dataset = tmp_path / "evals" / "validation" + task = write_task(dataset / "task-0", task_toml='\n[environment]\ndocker_image = "ubuntu:24.04"\n') + (task / "environment" / "Dockerfile").unlink() + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _finding(outcome, "tasks").status == "pass" + + +async def test_required_host_variables_are_recorded_with_their_defaults(tmp_path): + dataset = tmp_path / "evals" / "validation" + write_task( + dataset / "task-0", + task_toml='\n[environment.env]\nHF_TOKEN = "${HF_TOKEN}"\nREGION = "${AWS_REGION:-us-west-2}"\n', + ) + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + recorded = {item.name: item.default for item in outcome.required_env_vars} + assert recorded == {"HF_TOKEN": None, "AWS_REGION": "us-west-2"} + # Discover records what the repo demands; whether this host has it is doctor's job. + assert _finding(outcome, "credentials").status == "pass" + + +async def test_a_repo_wrapper_is_imported_and_sys_path_is_left_alone(tmp_path): + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + write_wrapper(tmp_path, class_name="TicketTriageAgent") + candidate = _candidate( + { + "agents": [{"import_path": "harbor_wrapper:TicketTriageAgent"}], + "datasets": [{"path": str(dataset)}], + } + ) + before = list(sys.path) + + outcome = await validate.run_ladder(candidate, tmp_path) + + agent = _finding(outcome, "agent") + assert agent.status == "pass" + assert "subclasses BaseAgent" in agent.message + assert sys.path == before, "the wrapper's directory must not be left on sys.path" + + +async def test_a_second_repos_wrapper_is_not_shadowed_by_the_first(tmp_path): + """``harbor_wrapper`` is a convention, so two repos claim the same module name.""" + first, second = tmp_path / "first", tmp_path / "second" + for repo, class_name in ((first, "FirstAgent"), (second, "SecondAgent")): + write_dataset(repo / "evals" / "validation", count=1) + write_wrapper(repo, class_name=class_name) + + for repo, class_name in ((first, "FirstAgent"), (second, "SecondAgent")): + candidate = _candidate( + { + "agents": [{"import_path": f"harbor_wrapper:{class_name}"}], + "datasets": [{"path": str(repo / "evals/validation")}], + } + ) + outcome = await validate.run_ladder(candidate, repo) + assert _finding(outcome, "agent").status == "pass", f"{class_name} was shadowed by a cached module" + + +async def test_a_wrapper_that_is_not_an_agent_fails_the_agent_rung(tmp_path): + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + (tmp_path / "harbor_wrapper.py").write_text("class NotAnAgent:\n pass\n") + candidate = _candidate( + {"agents": [{"import_path": "harbor_wrapper:NotAnAgent"}], "datasets": [{"path": str(dataset)}]} + ) + + outcome = await validate.run_ladder(candidate, tmp_path) + + agent = _finding(outcome, "agent") + assert agent.status == "fail" + assert agent.harbor_call == "import_class" + + +async def test_an_unknown_builtin_agent_name_lists_the_valid_ones(tmp_path): + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + candidate = _candidate({"agents": [{"name": "not-an-agent"}], "datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + agent = _finding(outcome, "agent") + assert agent.status == "fail" + assert agent.hint is not None and "oracle" in agent.hint + + +async def test_the_persisted_config_is_checked_through_the_harbor_cli(tmp_path): + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + config_path = tmp_path / "harbor-job.yaml" + config_path.write_text(f"datasets:\n- path: {dataset}\n") + + finding = validate.check_persisted_config(config_path, tmp_path) + + assert finding.status in {"pass", "warn"} + if finding.status == "pass": + assert finding.harbor_call == "harbor job start --print-config" + + +async def test_a_config_the_cli_rejects_fails_the_round_trip(tmp_path): + config_path = tmp_path / "harbor-job.yaml" + config_path.write_text("datasets: not-a-list\n") + + finding = validate.check_persisted_config(config_path, tmp_path) + + if finding.status != "warn": # warn means no harbor executable on PATH + assert finding.status == "fail" + assert finding.path == config_path + + +async def test_the_full_pipeline_agrees_with_the_source_it_chose(tmp_path): + """Sources and the ladder have to compose: what was assembled is what gets validated.""" + write_dataset(tmp_path / "evals" / "validation") + write_wrapper(tmp_path) + + candidate, _ = sources.find_candidate(tmp_path, env_backend="docker") + assert candidate is not None + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _repo_failures(outcome) == [] + assert outcome.config is not None + assert outcome.config.agents[0].import_path == "harbor_wrapper:WrappedAgent" diff --git a/uv.lock b/uv.lock index 1ebcda6cd50..f561d4dcadf 100644 --- a/uv.lock +++ b/uv.lock @@ -4208,18 +4208,20 @@ dependencies = [ { name = "nemo-platform-plugin", marker = "(platform_machine == 'arm64' and sys_platform == 'darwin') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, { name = "nooa", marker = "(platform_machine == 'arm64' and sys_platform == 'darwin') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, { name = "pydantic", extra = ["email"], marker = "(platform_machine == 'arm64' and sys_platform == 'darwin') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "pyyaml", marker = "(platform_machine == 'arm64' and sys_platform == 'darwin') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, { name = "tomlkit", marker = "(platform_machine == 'arm64' and sys_platform == 'darwin') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] [package.metadata] requires-dist = [ - { name = "harbor", specifier = ">=0.16" }, + { name = "harbor", specifier = ">=0.18" }, { name = "nemo-experimentalist-plugin", editable = "plugins/nemo-experimentalist" }, { name = "nemo-insights-plugin", editable = "plugins/nemo-insights" }, { name = "nemo-platform", editable = "packages/nemo_platform" }, { name = "nemo-platform-plugin", editable = "packages/nemo_platform_plugin" }, { name = "nooa", git = "https://github.com/NVIDIA-NeMo/labs-OO-Agents.git?rev=bea4614a0e2a6cf88f76225466159af883da80a0" }, { name = "pydantic", specifier = ">=2" }, + { name = "pyyaml", specifier = ">=6.0.3" }, { name = "tomlkit", specifier = ">=0.13.3" }, ] From 4a49ab2e7667f463e7fb4f47e83e719efde66373 Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Thu, 30 Jul 2026 09:58:32 -0500 Subject: [PATCH 02/15] test(eval-author): group the discover tests under tests/discover Each file was named for the module it covers with a test_discovery_ prefix repeating what the directory can say instead, so the prefix is now the directory. Two names could not follow the modules they test. The CLI file is test_command.py rather than test_cli.py because the plugin already has a tests/test_cli.py, and running the plugin's suite on its own leaves pytest in prepend import mode, where two test files sharing a basename abort collection. The fixtures module has to stay at the tests/ root. The repo-root conftest forces importmode = importlib, under which pytest puts no test directory on sys.path; tests/ is there only because pytest loads that directory's conftest during startup, while prepend mode still applies. A helper inside discover/ imports fine from within the plugin and then fails the moment CI runs from the repo root, so both configs are now part of what gets checked. It keeps the harbor_ prefix for the same class of reason: every plugin's tests/ shares sys.path in that run, so a bare fixtures module would bind to whichever copy loaded first. Signed-off-by: Alec Khoury --- .../test_command.py} | 7 ++++++- .../test_memory.py} | 2 +- .../test_report.py} | 2 +- .../{test_discovery_scan.py => discover/test_scan.py} | 2 +- .../test_scout.py} | 2 +- .../test_sources.py} | 2 +- .../test_validate.py} | 2 +- .../{discovery_fixtures.py => harbor_fixtures.py} | 11 +++++++++++ plugins/nemo-eval-author/tests/test_cli.py | 4 ++-- 9 files changed, 25 insertions(+), 9 deletions(-) rename plugins/nemo-eval-author/tests/{test_discovery_cli.py => discover/test_command.py} (96%) rename plugins/nemo-eval-author/tests/{test_discovery_memory.py => discover/test_memory.py} (99%) rename plugins/nemo-eval-author/tests/{test_discovery_report.py => discover/test_report.py} (99%) rename plugins/nemo-eval-author/tests/{test_discovery_scan.py => discover/test_scan.py} (98%) rename plugins/nemo-eval-author/tests/{test_discovery_scout.py => discover/test_scout.py} (98%) rename plugins/nemo-eval-author/tests/{test_discovery_sources.py => discover/test_sources.py} (98%) rename plugins/nemo-eval-author/tests/{test_discovery_validate.py => discover/test_validate.py} (99%) rename plugins/nemo-eval-author/tests/{discovery_fixtures.py => harbor_fixtures.py} (91%) diff --git a/plugins/nemo-eval-author/tests/test_discovery_cli.py b/plugins/nemo-eval-author/tests/discover/test_command.py similarity index 96% rename from plugins/nemo-eval-author/tests/test_discovery_cli.py rename to plugins/nemo-eval-author/tests/discover/test_command.py index da7f5072b33..d1e1eb17e5b 100644 --- a/plugins/nemo-eval-author/tests/test_discovery_cli.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -9,11 +9,16 @@ The exit code is the contract these pin down: this command is meant to be usable as a gate, so exit 0 has to mean a config was validated *and* recorded, and nothing else. + +Named for the command rather than ``test_cli.py`` because ``tests/test_cli.py`` already +covers the plugin's command surface. Running the plugin's suite on its own picks up the +plugin's pytest config, which leaves the default prepend import mode in place, and two test +files sharing a basename abort collection there. """ import pytest import typer -from discovery_fixtures import ( +from harbor_fixtures import ( MENTIONS_REWARD_IN_COMMENT, StubClient, StubFiles, diff --git a/plugins/nemo-eval-author/tests/test_discovery_memory.py b/plugins/nemo-eval-author/tests/discover/test_memory.py similarity index 99% rename from plugins/nemo-eval-author/tests/test_discovery_memory.py rename to plugins/nemo-eval-author/tests/discover/test_memory.py index 88f721eb370..0e9f3ae8e41 100644 --- a/plugins/nemo-eval-author/tests/test_discovery_memory.py +++ b/plugins/nemo-eval-author/tests/discover/test_memory.py @@ -8,7 +8,7 @@ alongside a failing report would be an instruction to run something broken. """ -from discovery_fixtures import StubClient, StubFiles +from harbor_fixtures import StubClient, StubFiles from nemo_eval_author_plugin.discovery import memory, report diff --git a/plugins/nemo-eval-author/tests/test_discovery_report.py b/plugins/nemo-eval-author/tests/discover/test_report.py similarity index 99% rename from plugins/nemo-eval-author/tests/test_discovery_report.py rename to plugins/nemo-eval-author/tests/discover/test_report.py index 07c62664420..fa1a4e75336 100644 --- a/plugins/nemo-eval-author/tests/test_discovery_report.py +++ b/plugins/nemo-eval-author/tests/discover/test_report.py @@ -12,8 +12,8 @@ from datetime import UTC, datetime import yaml -from discovery_fixtures import write_dataset from harbor.models.job.config import JobConfig +from harbor_fixtures import write_dataset from nemo_eval_author_plugin.discovery import memory, report from nemo_eval_author_plugin.discovery.models import ( CandidateConfig, diff --git a/plugins/nemo-eval-author/tests/test_discovery_scan.py b/plugins/nemo-eval-author/tests/discover/test_scan.py similarity index 98% rename from plugins/nemo-eval-author/tests/test_discovery_scan.py rename to plugins/nemo-eval-author/tests/discover/test_scan.py index f05886310a1..c904c27c9fe 100644 --- a/plugins/nemo-eval-author/tests/test_discovery_scan.py +++ b/plugins/nemo-eval-author/tests/discover/test_scan.py @@ -10,7 +10,7 @@ from pathlib import Path -from discovery_fixtures import StubClient +from harbor_fixtures import StubClient from nemo_eval_author_plugin.discovery import scan diff --git a/plugins/nemo-eval-author/tests/test_discovery_scout.py b/plugins/nemo-eval-author/tests/discover/test_scout.py similarity index 98% rename from plugins/nemo-eval-author/tests/test_discovery_scout.py rename to plugins/nemo-eval-author/tests/discover/test_scout.py index 397d3e6f231..5440dda45a9 100644 --- a/plugins/nemo-eval-author/tests/test_discovery_scout.py +++ b/plugins/nemo-eval-author/tests/discover/test_scout.py @@ -14,7 +14,7 @@ would assert on something nondeterministic. """ -from discovery_fixtures import MENTIONS_REWARD_IN_COMMENT, write_dataset +from harbor_fixtures import MENTIONS_REWARD_IN_COMMENT, write_dataset from nemo_eval_author_plugin.discovery import validate from nemo_eval_author_plugin.discovery.agent import ProposeFn, ScoutProposal, attempt_repair, is_scoutable from nemo_eval_author_plugin.discovery.models import CandidateConfig, ConfigSource, Finding diff --git a/plugins/nemo-eval-author/tests/test_discovery_sources.py b/plugins/nemo-eval-author/tests/discover/test_sources.py similarity index 98% rename from plugins/nemo-eval-author/tests/test_discovery_sources.py rename to plugins/nemo-eval-author/tests/discover/test_sources.py index 24d6d655714..ed3f84d318a 100644 --- a/plugins/nemo-eval-author/tests/test_discovery_sources.py +++ b/plugins/nemo-eval-author/tests/discover/test_sources.py @@ -11,7 +11,7 @@ import json import yaml -from discovery_fixtures import write_dataset, write_job_dir, write_task, write_wrapper +from harbor_fixtures import write_dataset, write_job_dir, write_task, write_wrapper from nemo_eval_author_plugin.discovery import sources diff --git a/plugins/nemo-eval-author/tests/test_discovery_validate.py b/plugins/nemo-eval-author/tests/discover/test_validate.py similarity index 99% rename from plugins/nemo-eval-author/tests/test_discovery_validate.py rename to plugins/nemo-eval-author/tests/discover/test_validate.py index 77fa7604b97..daceccb71f4 100644 --- a/plugins/nemo-eval-author/tests/test_discovery_validate.py +++ b/plugins/nemo-eval-author/tests/discover/test_validate.py @@ -17,7 +17,7 @@ import sys -from discovery_fixtures import ( +from harbor_fixtures import ( MENTIONS_REWARD_IN_COMMENT, WRITES_REWARD, write_dataset, diff --git a/plugins/nemo-eval-author/tests/discovery_fixtures.py b/plugins/nemo-eval-author/tests/harbor_fixtures.py similarity index 91% rename from plugins/nemo-eval-author/tests/discovery_fixtures.py rename to plugins/nemo-eval-author/tests/harbor_fixtures.py index e7547bf39a6..7831489ec5f 100644 --- a/plugins/nemo-eval-author/tests/discovery_fixtures.py +++ b/plugins/nemo-eval-author/tests/harbor_fixtures.py @@ -12,6 +12,17 @@ Imported as a module rather than declared as fixtures in ``conftest.py`` because the builders take arguments; a test that needs a Windows task with no reward script should say so at the call site instead of composing four fixtures to get there. + +Lives here rather than beside its tests in ``discover/`` because the repo-root +``conftest.py`` forces ``importmode = "importlib"``, under which pytest puts no test +directory on ``sys.path``. Only ``tests/`` ends up there, and only because pytest loads that +directory's ``conftest.py`` during startup while prepend mode is still in effect. A helper +one level down imports fine from within the plugin and fails the moment CI runs from the +repo root. + +Nor is it named ``fixtures.py``, tempting as that is: every plugin's ``tests/`` is on +``sys.path`` in that same root-config run, so a bare ``fixtures`` would bind to whichever +plugin's copy imported first, silently and with no collision error. """ import json diff --git a/plugins/nemo-eval-author/tests/test_cli.py b/plugins/nemo-eval-author/tests/test_cli.py index 919b670ffab..34249d87586 100644 --- a/plugins/nemo-eval-author/tests/test_cli.py +++ b/plugins/nemo-eval-author/tests/test_cli.py @@ -7,8 +7,8 @@ typo in the key or the import path does not fail an import; it just makes ``nemo eval-author`` quietly missing from the CLI, which no unit test of this module would catch. -``discover`` has shipped, so it is asserted on in ``test_discovery_cli.py`` instead. It is -listed in ``_IMPLEMENTED_VERBS`` here only so ``--help`` still has to show it. +``discover`` has shipped, so it is asserted on in ``discover/test_command.py`` instead. It +is listed in ``_IMPLEMENTED_VERBS`` here only so ``--help`` still has to show it. """ from importlib.metadata import EntryPoint, entry_points From d7978da4aa5b36d1b9cbbd3093599b19c2f88875 Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 09:57:48 -0500 Subject: [PATCH 03/15] fix(eval-author): point discovery at the repo's own Harbor config A repo that maintains its own job config had that file copied into the fileset, leaving two configs describing one run and no owner for the second. Discovery now publishes a config only when it authored one; when the repo owns the file, the report points at it and validates that path directly. Front matter carries a run_config block so a consumer reads one field instead of guessing which case it is in, and the report says why a config file is involved at all: -c is Harbor's only interface for local task directories. Ownership ends the moment we change the payload, so --env-backend injection and scout proposals mark the source adjusted and fall back to publishing our copy. Two bugs surfaced while testing the repo-owned path. The in-process ladder judged relative dataset paths against the process directory, so a repo config saying `path: evals/validation` failed resolution while `harbor job start -c` from the repo root would have run it; the ladder now runs with cwd at the repo root, like the subprocess round trip already did. That exposed Job.create opening a job.log under a relative jobs/ dir, which resolution now redirects to scratch space so discovery leaves the repo untouched. Signed-off-by: Alec Khoury --- .../src/nemo_eval_author_plugin/cli.py | 17 +++-- .../discovery/agent.py | 3 + .../discovery/memory.py | 26 +++---- .../discovery/models.py | 40 +++++++++++ .../discovery/report.py | 69 ++++++++++++++++--- .../nemo_eval_author_plugin/discovery/run.py | 26 +++++-- .../discovery/sources.py | 6 ++ .../discovery/validate.py | 43 ++++++++++-- .../tests/discover/test_command.py | 38 ++++++++++ .../tests/discover/test_memory.py | 9 ++- .../tests/discover/test_report.py | 62 +++++++++++++++++ .../tests/discover/test_sources.py | 43 ++++++++++++ .../tests/discover/test_validate.py | 4 +- .../nemo-eval-author/tests/harbor_fixtures.py | 10 +++ 14 files changed, 345 insertions(+), 51 deletions(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index ed9f0e5747f..cf9b07307ac 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -20,9 +20,8 @@ import typer from nemo_eval_author_plugin.discovery import run as discovery -from nemo_eval_author_plugin.discovery.memory import FILESET_NAME -from nemo_eval_author_plugin.discovery.models import Finding -from nemo_eval_author_plugin.discovery.report import JOB_CONFIG_FILENAME +from nemo_eval_author_plugin.discovery.models import FILESET_NAME, JOB_CONFIG_FILENAME, Finding +from nemo_eval_author_plugin.discovery.report import run_target from nemo_platform_plugin.cli import NemoCLI _STATUS_MARK = {"pass": " ok ", "warn": " warn ", "fail": " FAIL "} @@ -57,11 +56,17 @@ def _report_discovery(result: discovery.DiscoverResult) -> None: _echo_finding(finding) typer.echo("") - if record.runnable: + target = run_target(record) + if target is not None: source = record.config_source typer.echo(f"Harbor can run this repo's evals ({source.detail if source else 'unknown source'}).") - typer.echo(f"Run it from {record.repo_root}:") - typer.echo(f" harbor job start -c {JOB_CONFIG_FILENAME}") + if target.location == "repo": + typer.echo(f"Run it from {record.repo_root}, using the config this repo already maintains:") + typer.echo(f" harbor job start -c {target.path}") + else: + typer.echo(f"Discovery wrote the config to fileset '{FILESET_NAME}' at {target.path}.") + typer.echo(f"Fetch it into {record.repo_root}, then:") + typer.echo(f" harbor job start -c {JOB_CONFIG_FILENAME}") if record.required_env_vars: typer.echo(f" Needs: {', '.join(item.name for item in record.required_env_vars)}") else: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py index e704cd2de50..0d9126c5071 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py @@ -164,6 +164,9 @@ async def attempt_repair( kind=candidate.source.kind, detail=f"{candidate.source.detail}, then adjusted by the discovery scout", path=candidate.source.path, + # Even when the source was the repo's own config file, the artifact can no + # longer point at it: what Harbor accepted is the scout's version. + adjusted=True, ), ) revalidated = await run_ladder(proposed, repo_root) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py index fd0059c1eeb..e3ef1d605ba 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py @@ -23,16 +23,16 @@ from typing import Any import yaml -from nemo_eval_author_plugin.discovery.models import Finding, InputFingerprint -from nemo_eval_author_plugin.discovery.report import ( +from nemo_eval_author_plugin.discovery.models import ( + FILESET_NAME, JOB_CONFIG_FILENAME, REPORT_FILENAME, - fingerprint_inputs, + Finding, + InputFingerprint, ) +from nemo_eval_author_plugin.discovery.report import fingerprint_inputs from pydantic import BaseModel, Field -FILESET_NAME = "nemo-eval-author" - _GROUP = "memory" _FRONT_MATTER_FENCE = "---" @@ -163,7 +163,11 @@ async def persist( markdown: str, job_config: str | None, ) -> tuple[bool, list[Finding]]: - """Upload the report, and the config when there is one worth uploading. + """Upload the report, and the config when the caller passed one. + + Reports only what it did. Why a config might be absent is the caller's to explain — + withheld because nothing validated, not needed because the repo maintains its own, + already stored by an earlier run — and a message here could only guess between them. Returns whether everything landed. Upload failures are reported as warnings rather than failures, because ``runnable`` answers one question only — can Harbor run this @@ -206,14 +210,4 @@ async def persist( ) ) - if job_config is None: - findings.append( - Finding( - name="upload", - group=_GROUP, - status="warn", - message=f"Withheld {JOB_CONFIG_FILENAME}: no config passed Harbor's schema check", - hint="A config in this fileset is always one Harbor could load, so none was written.", - ) - ) return ok, findings diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py index e63908746db..7e7d8a816fd 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py @@ -23,6 +23,12 @@ from pydantic import BaseModel, Field +FILESET_NAME = "nemo-eval-author" +"""One fixed fileset with agent-scoped paths, following the telemetry precedent.""" + +JOB_CONFIG_FILENAME = "harbor-job.yaml" +REPORT_FILENAME = "discovery.md" + Status = Literal["pass", "warn", "fail"] Provenance = Literal["harbor", "filesystem", "inference"] @@ -72,11 +78,28 @@ class ConfigSource(BaseModel): kind: SourceKind detail: str path: Path | None = None + adjusted: bool = Field( + default=False, + description="Whether the validated payload has diverged from the file at ``path``.", + ) @property def rank(self) -> int: return SOURCE_PRIORITY.index(self.kind) + @property + def owns_file(self) -> bool: + """Whether the repo maintains the config file we validated, unchanged. + + The one case where discovery has nothing of its own to persist: the file already + exists, someone maintains it, and Harbor accepted exactly its contents. Shipping a + second copy would create a config nobody owns and that drifts the moment the real + one is edited. ``prior_job`` is excluded even though it has a path, because that + path is a record Harbor wrote inside a job's output directory rather than an input + anyone maintains. + """ + return self.kind == "config_file" and self.path is not None and not self.adjusted + class CandidateConfig(BaseModel): """An unvalidated Harbor job config payload plus where it came from. @@ -91,6 +114,23 @@ class CandidateConfig(BaseModel): source: ConfigSource +class RunTarget(BaseModel): + """The config a later run passes to ``harbor job start -c``, and where to get it. + + Harbor runs local task directories through ``-c`` and no other way: ``--dataset`` and + ``--task`` name registry packages, so a filesystem path handed to either is read as a + package reference. A repo full of task dirs and no config file therefore cannot be run + as-is, which is why discovery writes one when the repo does not. + + ``location`` spares the reader from deciding which case they are in: ``repo`` means the + path is relative to ``repo_root`` and already on disk, ``fileset`` means it is a remote + path in ``FILESET_NAME`` to fetch first. + """ + + location: Literal["repo", "fileset"] + path: str + + class RequiredEnvVar(BaseModel): """A host variable a task config templates as ``${VAR}`` or ``${VAR:-default}``. diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py index e285644691c..3cf838dcb9c 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py @@ -27,17 +27,17 @@ import yaml from harbor.models.job.config import JobConfig from nemo_eval_author_plugin.discovery.models import ( + FILESET_NAME, + JOB_CONFIG_FILENAME, CandidateConfig, DiscoveryReport, Finding, InputFingerprint, RequiredEnvVar, + RunTarget, ) from nemo_eval_author_plugin.discovery.scan import display_path -JOB_CONFIG_FILENAME = "harbor-job.yaml" -REPORT_FILENAME = "discovery.md" - _STATUS_MARK = {"pass": "ok", "warn": "warn", "fail": "FAIL"} @@ -96,6 +96,22 @@ def build_report( ) +def run_target(report: DiscoveryReport) -> RunTarget | None: + """Which config a later run should pass to ``-c``, or ``None`` when there is none. + + A repo that maintains its own config keeps it: Harbor accepted exactly that file, so the + artifact points at it rather than shipping a copy that starts drifting the moment + someone edits the original. Every other source has no such file — the payload is + discovery's own synthesis — so the fileset is the only place it exists. + """ + if not report.runnable: + return None + source = report.config_source + if source is not None and source.owns_file and source.path is not None: + return RunTarget(location="repo", path=display_path(source.path, report.repo_root)) + return RunTarget(location="fileset", path=f"{report.agent}/{JOB_CONFIG_FILENAME}") + + def render_job_config(config: JobConfig, repo_root: Path) -> str: """Serialize the validated config, with in-repo paths made relative. @@ -133,10 +149,14 @@ def _front_matter(report: DiscoveryReport) -> dict[str, Any]: "kind": source.kind, "detail": source.detail, "path": display_path(source.path, report.repo_root) if source.path else None, + # Carried so a reused report resolves to the same run_config. Without it, a + # repo whose config we had to adjust would read back as ours to run. + "adjusted": source.adjusted, } if source is not None else None ), + "run_config": (target.model_dump() if (target := run_target(report)) is not None else None), "validation": {finding.name: finding.status for finding in report.findings if finding.group == "validation"}, "harbor_version": report.harbor_version, "required_env_vars": [ @@ -166,13 +186,13 @@ def _body(report: DiscoveryReport) -> list[str]: def _verdict_section(report: DiscoveryReport) -> list[str]: - if report.runnable: + target = run_target(report) + if target is not None: source = report.config_source detail = source.detail if source is not None else "unknown" return [ - f"Harbor can run this repo's evals. The config in `{JOB_CONFIG_FILENAME}` was " - f"{detail}, and every check below was answered by Harbor {report.harbor_version} " - "rather than inferred.", + f"Harbor can run this repo's evals. The config was {detail}, and every check below " + f"was answered by Harbor {report.harbor_version} rather than inferred.", "", ] @@ -200,15 +220,42 @@ def _verdict_section(report: DiscoveryReport) -> list[str]: def _how_to_run_section(report: DiscoveryReport) -> list[str]: - if not report.runnable: + target = run_target(report) + if target is None: return [] lines = [ "## Running it", "", - f"From `{report.repo_root}`, because the config uses repo-relative paths:", + "Harbor runs local task directories through `-c` and no other way: `--dataset` and " + "`--task` name registry packages, so a filesystem path given to either is read as a " + "package reference. The config below is that file.", "", + ] + if target.location == "repo": + config_arg = target.path + lines += [ + f"This repo maintains its own config at `{config_arg}`, and that file is what Harbor " + f"accepted here, so run it rather than a copy of it. From `{report.repo_root}`, " + "because its paths are relative to the repo:", + "", + ] + else: + config_arg = JOB_CONFIG_FILENAME + lines += [ + "Nothing in this repo declares a Harbor job config, so discovery wrote the one it " + f"validated. Fetch it into `{report.repo_root}`, the directory its relative paths " + "assume:", + "", + "```bash", + f"nemo files download {FILESET_NAME} --workspace {report.workspace} --remote-path {target.path} -o .", + "```", + "", + "Then, from that same directory:", + "", + ] + lines += [ "```bash", - f"harbor job start -c {JOB_CONFIG_FILENAME}", + f"harbor job start -c {config_arg}", "```", "", ] @@ -220,7 +267,7 @@ def _how_to_run_section(report: DiscoveryReport) -> list[str]: "oracle, which replays each task's own solution and should score 1.0:", "", "```bash", - f"harbor run -a oracle -c {JOB_CONFIG_FILENAME}", + f"harbor run -a oracle -c {config_arg}", "```", "", "Discovery does not run this itself, because unlike every check above it builds and starts containers.", diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py index 702e4fd3431..daf93fc8496 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -22,6 +22,7 @@ from nemo_eval_author_plugin.discovery import memory, report, scan, sources, validate from nemo_eval_author_plugin.discovery.models import ( + JOB_CONFIG_FILENAME, CandidateConfig, DiscoveryReport, Finding, @@ -106,8 +107,15 @@ async def _discover( findings.extend(outcome.findings) findings.extend(await _probe_repo(client, repo_root, agent=agent, workspace=options.workspace)) + # When the repo maintains the config Harbor accepted, that file is what a later run will + # pass to -c, so it is the thing worth round-tripping and there is nothing of ours to + # persist. Rendering a copy anyway would put a second config in the fileset that no one + # owns and that goes stale the moment the real one is edited. + repo_config = candidate.source.path if candidate is not None and candidate.source.owns_file else None job_config = None - if outcome.config is not None: + if repo_config is not None: + findings.append(validate.check_config_file(repo_config, repo_root)) + elif outcome.config is not None: job_config = report.render_job_config(outcome.config, repo_root) findings.append(_round_trip(job_config, repo_root)) @@ -136,6 +144,16 @@ async def _discover( markdown=markdown, job_config=publishable, ) + if job_config is not None and publishable is None: + memory_findings.append( + Finding( + name="upload", + group="memory", + status="warn", + message=f"Withheld {JOB_CONFIG_FILENAME}: the config did not clear every check", + hint="A config in this fileset is always one Harbor could run, so none was written.", + ) + ) return DiscoverResult( report=record, markdown=markdown, @@ -204,7 +222,7 @@ async def _reuse( markdown=restamped, persisted=persisted, reused=True, - memory_findings=[item for item in memory_findings if item.name != "upload" or item.status != "warn"], + memory_findings=memory_findings, ) @@ -238,9 +256,9 @@ def _round_trip(job_config: str, repo_root: Path) -> Finding: to the repo root, so the file's own location does not matter. """ with tempfile.TemporaryDirectory(prefix="eval-author-discover-") as scratch: - config_path = Path(scratch) / report.JOB_CONFIG_FILENAME + config_path = Path(scratch) / JOB_CONFIG_FILENAME config_path.write_text(job_config, encoding="utf-8") - return validate.check_persisted_config(config_path, repo_root) + return validate.check_config_file(config_path, repo_root) def _input_paths(repo_root: Path, candidate: CandidateConfig | None, outcome: ValidationOutcome) -> list[Path]: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py index f886c03a766..0f55ce91a2d 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py @@ -133,12 +133,18 @@ def _apply_env_backend(candidate: CandidateConfig, env_backend: str) -> None: A user who wrote ``type: daytona`` into their config meant it, and a CLI default should not quietly overwrite a declaration on its way into the persisted artifact. + + Filling the gap counts as adjusting the payload, because it now says something the + source file does not: a reader pointed at that file would run a different backend. """ environment = candidate.data.get("environment") if not isinstance(environment, dict): candidate.data["environment"] = {"type": env_backend} elif environment.get("type") is None: environment["type"] = env_backend + else: + return + candidate.source.adjusted = True def _from_config_file(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py index f002f66919c..697e732af7f 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py @@ -97,6 +97,21 @@ def _harbor(name: str, status: Status, message: str, call: str, **kwargs) -> Fin async def run_ladder(candidate: CandidateConfig, repo_root: Path) -> ValidationOutcome: + """Judge the config from the directory a real run would be started in. + + Harbor resolves a config's relative paths against the process directory, and a config a + repo maintains says ``path: evals/validation`` meaning "from the repo root". Validating + it from anywhere else reports a dataset Harbor cannot find while ``harbor job start -c`` + from the repo root would run it — a false verdict on the case that matters most. The + subprocess round trip already passes ``cwd``; this gives the in-process rungs the same + footing. A process-wide chdir is only defensible because the CLI awaits one ladder and + nothing else. + """ + with contextlib.chdir(repo_root): + return await _ladder(candidate, repo_root) + + +async def _ladder(candidate: CandidateConfig, repo_root: Path) -> ValidationOutcome: """Walk the ladder, stopping only where a later rung has nothing left to judge.""" outcome = ValidationOutcome() @@ -175,9 +190,16 @@ async def _rung_resolution(config: JobConfig, outcome: ValidationOutcome) -> Job datasets into task configs, resolves skill sources, validates resource policies against the chosen backend, and builds metrics. Anything it raises is an error the real run would have hit at the same point. + + It does have one side effect: it opens its output directory and starts a ``job.log`` + there. ``jobs_dir`` defaults to a relative ``jobs/``, which the ladder's chdir would put + inside the repo, so resolution runs against a copy pointed at scratch space. A copy + because the original is what gets persisted, and a real run's output belongs wherever + that run decides, not in a temp dir that no longer exists. """ try: - job = await Job.create(config) + with tempfile.TemporaryDirectory(prefix="eval-author-jobs-") as scratch: + job = await Job.create(config.model_copy(update={"jobs_dir": Path(scratch)})) except Exception as exc: outcome.findings.append( _harbor( @@ -208,11 +230,15 @@ def _resolved_local_paths(job: Job) -> list[Path]: reason; there is no public accessor for the resolved list. Tasks that live only in a remote registry are skipped, since the resolution rung already spoke for whether they could be fetched. + + Absolute on the way out. Harbor hands back whatever the config said, and a relative path + means the repo root only while the ladder's chdir is in effect; these outlive it as the + task list the report fingerprints. """ paths: list[Path] = [] for task_config in getattr(job, "_task_configs", []): try: - paths.append(task_config.get_local_path()) + paths.append(task_config.get_local_path().resolve()) except ValueError: continue return paths @@ -566,13 +592,16 @@ def _rung_backend(config: JobConfig, outcome: ValidationOutcome) -> None: ) -def check_persisted_config(config_path: Path, repo_root: Path) -> Finding: - """Load the file we are about to persist through the Harbor CLI itself. +def check_config_file(config_path: Path, repo_root: Path) -> Finding: + """Load the file a later run will pass to ``-c`` through the Harbor CLI itself. The only rung that judges bytes rather than an in-memory object, which matters because bytes are what a later agent will hand to Harbor. ``--print-config`` returns before ``Job.create``, so this re-validates the schema and resolves nothing. It runs - with ``cwd`` at the repo root because the persisted config uses repo-relative paths. + with ``cwd`` at the repo root because these configs use repo-relative paths. + + The file is either one discovery wrote or the repo's own, whichever the artifact ends + up pointing at; the check is the same either way. """ harbor_bin = shutil.which("harbor") if harbor_bin is None: @@ -607,14 +636,14 @@ def check_persisted_config(config_path: Path, repo_root: Path) -> Finding: return _harbor( "round-trip", "fail", - f"`harbor job start --print-config` rejected the persisted config: {detail[-1] if detail else 'no output'}", + f"`harbor job start --print-config` rejected the config file: {detail[-1] if detail else 'no output'}", "harbor job start --print-config", path=config_path, ) return _harbor( "round-trip", "pass", - "The persisted config loads through the Harbor CLI", + "The config file loads through the Harbor CLI", "harbor job start --print-config", path=config_path, ) diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index d1e1eb17e5b..e8d561edf27 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -23,6 +23,7 @@ StubClient, StubFiles, write_dataset, + write_job_config, write_wrapper, ) from nemo_eval_author_plugin import cli @@ -81,6 +82,31 @@ def test_a_healthy_repo_exits_zero_and_records_both_artifacts(app, client, tmp_p assert sorted(client.files.stored) == [f"{AGENT}/discovery.md", f"{AGENT}/harbor-job.yaml"] +def test_a_repo_that_maintains_its_own_config_keeps_it_and_records_only_the_report(app, client, tmp_path): + """The repo's file is what Harbor validated, so a copy in the fileset could only drift from it.""" + write_dataset(tmp_path / "evals" / "validation") + write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/validation") + + result = _invoke_named(app, tmp_path) + + assert result.exit_code == 0, result.output + assert "harbor job start -c configs/eval.yaml" in result.output + assert client.files.stored.keys() == {f"{AGENT}/discovery.md"} + assert "Withheld" not in result.output, "nothing was withheld; there was nothing of ours to publish" + + +def test_an_env_backend_that_the_config_omits_makes_discovery_publish_its_own(app, client, tmp_path): + """The payload now names a backend the repo's file does not, so that file is not what to run.""" + write_dataset(tmp_path / "evals" / "validation") + write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/validation") + + result = _invoke_named(app, tmp_path, "--env-backend", "docker") + + assert result.exit_code == 0, result.output + assert "harbor job start -c harbor-job.yaml" in result.output + assert sorted(client.files.stored) == [f"{AGENT}/discovery.md", f"{AGENT}/harbor-job.yaml"] + + def test_a_repo_whose_tasks_never_score_exits_one_and_withholds_the_config(app, client, tmp_path): write_dataset(tmp_path / "evals" / "validation", test_script=MENTIONS_REWARD_IN_COMMENT) @@ -89,6 +115,7 @@ def test_a_repo_whose_tasks_never_score_exits_one_and_withholds_the_config(app, assert result.exit_code == 1, result.output assert "Harbor cannot run this repo's evals" in result.output assert "reward" in result.output + assert "Withheld harbor-job.yaml" in result.output, "an absent config has to be explained, not just missing" # The report still lands, so the failure is documented rather than lost. assert sorted(client.files.stored) == [f"{AGENT}/discovery.md"] @@ -225,6 +252,17 @@ def test_traces_are_reported_without_blocking_a_run(app, monkeypatch, tmp_path): assert "repo/traces" in result.output +def test_nothing_is_written_into_the_repo_being_inspected(app, client, tmp_path): + """The ladder runs with cwd inside the repo, so a Harbor side effect would land here.""" + write_dataset(tmp_path / "evals" / "validation") + write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/validation") + before = {path.name for path in tmp_path.rglob("*")} + + assert _invoke_named(app, tmp_path).exit_code == 0 + + assert {path.name for path in tmp_path.rglob("*")} == before + + def test_the_platform_client_is_closed(app, client, tmp_path): write_dataset(tmp_path / "evals" / "validation") diff --git a/plugins/nemo-eval-author/tests/discover/test_memory.py b/plugins/nemo-eval-author/tests/discover/test_memory.py index 0e9f3ae8e41..18393aedfa3 100644 --- a/plugins/nemo-eval-author/tests/discover/test_memory.py +++ b/plugins/nemo-eval-author/tests/discover/test_memory.py @@ -29,18 +29,17 @@ async def test_both_artifacts_are_uploaded_under_the_agent_prefix(): assert all(item.status == "pass" for item in findings) -async def test_the_config_is_withheld_when_harbor_never_accepted_one(): +async def test_no_config_uploads_the_report_alone_and_says_nothing_about_why(): + """Absent for several reasons — withheld, repo-owned, already stored — and only the caller knows which.""" client = StubClient() ok, findings = await memory.persist( client, agent="ticket-triage", workspace="default", markdown="# report\n", job_config=None ) - assert ok is True, "the report still has to land, so the failure is documented" + assert ok is True, "the report still has to land, so the verdict is documented either way" assert [item["remote_path"] for item in client.files.uploads] == ["ticket-triage/discovery.md"] - withheld = next(item for item in findings if "Withheld" in item.message) - assert withheld.status == "warn" - assert withheld.hint is not None and "always one Harbor could load" in withheld.hint + assert all(item.status == "pass" for item in findings) async def test_an_upload_failure_is_reported_without_claiming_the_config_is_broken(): diff --git a/plugins/nemo-eval-author/tests/discover/test_report.py b/plugins/nemo-eval-author/tests/discover/test_report.py index fa1a4e75336..6901b983560 100644 --- a/plugins/nemo-eval-author/tests/discover/test_report.py +++ b/plugins/nemo-eval-author/tests/discover/test_report.py @@ -16,8 +16,10 @@ from harbor_fixtures import write_dataset from nemo_eval_author_plugin.discovery import memory, report from nemo_eval_author_plugin.discovery.models import ( + FILESET_NAME, CandidateConfig, ConfigSource, + DiscoveryReport, Finding, RequiredEnvVar, ) @@ -57,6 +59,66 @@ def test_front_matter_survives_a_round_trip(tmp_path): assert front["inputs"] == [{"path": "ETHOS.md", "sha256": record.inputs[0].sha256}] +def _owned_config(tmp_path, *, adjusted=False): + return CandidateConfig( + data={}, + source=ConfigSource( + kind="config_file", + detail="declared at configs/eval.yaml", + path=tmp_path / "configs" / "eval.yaml", + adjusted=adjusted, + ), + ) + + +def test_a_repo_that_maintains_its_own_config_is_told_to_run_that_file(tmp_path): + """Publishing a second copy would leave a config in the fileset that nobody edits.""" + record = _record(tmp_path, candidate=_owned_config(tmp_path)) + + markdown = report.render_markdown(record) + front = memory.parse_front_matter(markdown) + + assert front is not None + assert front["run_config"] == {"location": "repo", "path": "configs/eval.yaml"} + assert "harbor job start -c configs/eval.yaml" in markdown + assert "harbor-job.yaml" not in markdown + # Why a config file is involved at all, since a reader may only have task directories. + assert "package reference" in markdown + + +def test_a_config_we_had_to_adjust_points_at_the_copy_discovery_wrote(tmp_path): + record = _record(tmp_path, candidate=_owned_config(tmp_path, adjusted=True)) + + markdown = report.render_markdown(record) + front = memory.parse_front_matter(markdown) + + assert front is not None + assert front["run_config"] == {"location": "fileset", "path": "ticket-triage/harbor-job.yaml"} + assert "harbor job start -c harbor-job.yaml" in markdown + assert f"nemo files download {FILESET_NAME}" in markdown, "the config is not on disk yet" + + +def test_a_reused_report_resolves_the_target_it_was_written_with(tmp_path): + """Reuse rebuilds the record from front matter alone, so what decided the target must be in it.""" + record = _record(tmp_path, candidate=_owned_config(tmp_path, adjusted=True)) + front = memory.parse_front_matter(report.render_markdown(record)) + + assert front is not None + rebuilt = DiscoveryReport.model_validate( + { + "agent": record.agent, + "workspace": record.workspace, + "repo_root": front["repo_root"], + "harbor_version": front["harbor_version"], + "config_source": front["config_source"], + "discovered_at": front["discovered_at"], + "last_validated_at": front["last_validated_at"], + } + ) + + assert report.run_target(rebuilt) == report.run_target(record) + + def test_the_digest_is_stable_and_notices_a_changed_input(tmp_path): path = _write(tmp_path / "task.toml", 'version = "1.0"\n') first = _record(tmp_path, inputs=report.fingerprint_inputs([path], tmp_path)) diff --git a/plugins/nemo-eval-author/tests/discover/test_sources.py b/plugins/nemo-eval-author/tests/discover/test_sources.py index ed3f84d318a..a1eb801317d 100644 --- a/plugins/nemo-eval-author/tests/discover/test_sources.py +++ b/plugins/nemo-eval-author/tests/discover/test_sources.py @@ -139,6 +139,49 @@ def test_env_backend_fills_a_gap_but_never_overrides_a_declaration(tmp_path): assert respected.data["environment"]["type"] == "daytona" +def test_a_config_file_is_only_owned_by_the_repo_while_we_leave_it_alone(tmp_path): + """Ownership decides whether the artifact can point at the repo's file instead of a copy.""" + write_dataset(tmp_path / "evals" / "validation") + (tmp_path / "configs").mkdir() + (tmp_path / "configs" / "eval.yaml").write_text(yaml.safe_dump(_job_config("evals/validation"))) + + untouched, _ = sources.find_candidate(tmp_path) + assert untouched is not None + assert untouched.source.owns_file is True + + # Filling in a backend the file never named makes our payload the only runnable one. + injected, _ = sources.find_candidate(tmp_path, env_backend="docker") + assert injected is not None + assert injected.source.adjusted is True + assert injected.source.owns_file is False + + +def test_a_declared_backend_leaves_the_config_owned_by_the_repo(tmp_path): + """Nothing changed, so nothing stops a run from using the file that is already there.""" + write_dataset(tmp_path / "evals" / "validation") + (tmp_path / "configs").mkdir() + declared = {**_job_config("evals/validation"), "environment": {"type": "docker"}} + (tmp_path / "configs" / "eval.yaml").write_text(yaml.safe_dump(declared)) + + candidate, _ = sources.find_candidate(tmp_path, env_backend="docker") + + assert candidate is not None + assert candidate.source.adjusted is False + assert candidate.source.owns_file is True + + +def test_an_inferred_source_never_claims_a_file_it_could_be_run_from(tmp_path): + """A prior job's config.json is Harbor's own output record, not an input anyone maintains.""" + write_dataset(tmp_path / "evals" / "validation") + write_job_dir(tmp_path / "jobs" / "run-1", config=_job_config("evals/validation")) + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.path is not None + assert candidate.source.owns_file is False + + def test_unreadable_yaml_is_skipped_rather_than_raising(tmp_path): write_dataset(tmp_path / "evals" / "validation") (tmp_path / "configs").mkdir() diff --git a/plugins/nemo-eval-author/tests/discover/test_validate.py b/plugins/nemo-eval-author/tests/discover/test_validate.py index daceccb71f4..5480ba933f5 100644 --- a/plugins/nemo-eval-author/tests/discover/test_validate.py +++ b/plugins/nemo-eval-author/tests/discover/test_validate.py @@ -283,7 +283,7 @@ async def test_the_persisted_config_is_checked_through_the_harbor_cli(tmp_path): config_path = tmp_path / "harbor-job.yaml" config_path.write_text(f"datasets:\n- path: {dataset}\n") - finding = validate.check_persisted_config(config_path, tmp_path) + finding = validate.check_config_file(config_path, tmp_path) assert finding.status in {"pass", "warn"} if finding.status == "pass": @@ -294,7 +294,7 @@ async def test_a_config_the_cli_rejects_fails_the_round_trip(tmp_path): config_path = tmp_path / "harbor-job.yaml" config_path.write_text("datasets: not-a-list\n") - finding = validate.check_persisted_config(config_path, tmp_path) + finding = validate.check_config_file(config_path, tmp_path) if finding.status != "warn": # warn means no harbor executable on PATH assert finding.status == "fail" diff --git a/plugins/nemo-eval-author/tests/harbor_fixtures.py b/plugins/nemo-eval-author/tests/harbor_fixtures.py index 7831489ec5f..d414de9f417 100644 --- a/plugins/nemo-eval-author/tests/harbor_fixtures.py +++ b/plugins/nemo-eval-author/tests/harbor_fixtures.py @@ -29,6 +29,8 @@ from pathlib import Path from typing import Any +import yaml + WRITES_REWARD = "#!/bin/bash\necho 1 > /logs/verifier/reward.txt\n" # What Harbor's own template ships: a comment telling the author to write a reward, and no @@ -113,6 +115,14 @@ def write_wrapper(repo_root: Path, *, class_name: str = "WrappedAgent", base: st return path +def write_job_config(path: Path, *, dataset: str, agent: dict[str, Any] | None = None) -> Path: + """A job config of the kind a repo maintains itself, which is what ``-c`` takes.""" + path.parent.mkdir(parents=True, exist_ok=True) + payload = {"agents": [agent or {"name": "oracle"}], "datasets": [{"path": dataset}]} + path.write_text(yaml.safe_dump(payload), encoding="utf-8") + return path + + def write_job_dir(root: Path, *, config: dict[str, Any], with_lock: bool = True) -> Path: """A completed Harbor job directory, which is a config Harbor already resolved.""" root.mkdir(parents=True, exist_ok=True) From 72549f78d8183345eab4d070f696ff6c9278adaf Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 09:59:31 -0500 Subject: [PATCH 04/15] refactor(eval-author): drop two unused entry points from the validation ladder `validate` wrapped run_ladder in asyncio.run for a CLI that turned out to be async, and `temp_logs_dir` was exposed for tests that never used it. Nothing imports either. Signed-off-by: Alec Khoury --- .../src/nemo_eval_author_plugin/discovery/validate.py | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py index 697e732af7f..9124c3b77df 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py @@ -29,7 +29,6 @@ that module's top level. Neither starts a container or writes into the repo. """ -import asyncio import contextlib import shutil import subprocess @@ -710,13 +709,3 @@ def _executable_lines(text: str) -> str: if not line.lstrip().startswith(("#", "::")) and not line.lstrip().upper().startswith("REM ") ] return "\n".join(kept) - - -def validate(candidate: CandidateConfig, repo_root: Path) -> ValidationOutcome: - """Synchronous entry point, since the CLI is not async but ``Job.create`` is.""" - return asyncio.run(run_ladder(candidate, repo_root)) - - -def temp_logs_dir() -> tempfile.TemporaryDirectory: - """Exposed for tests that need a throwaway logs dir when constructing agents.""" - return tempfile.TemporaryDirectory(prefix="eval-author-discover-") From 53c9ed6916430c01e7c41d3b05ee4c310fcc0f94 Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 11:46:28 -0500 Subject: [PATCH 05/15] feat(eval-author): make the discovery scout opt-in as --fix --deep said how hard the command tries; --fix says what it does, which is edit the config until Harbor accepts it. Now off by default, so the plain command reads a repo and reports, and reaching a model is something the caller asks for. Signed-off-by: Alec Khoury --- .../src/nemo_eval_author_plugin/cli.py | 8 ++++---- .../src/nemo_eval_author_plugin/discovery/agent.py | 2 +- .../src/nemo_eval_author_plugin/discovery/run.py | 4 ++-- .../tests/discover/test_command.py | 14 +++++++++++++- .../nemo-eval-author/tests/discover/test_scout.py | 2 +- 5 files changed, 21 insertions(+), 9 deletions(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index cf9b07307ac..90a54a26b1c 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -120,10 +120,10 @@ def discover( str | None, typer.Option("--env-backend", help="Harbor environment type to assume when the repo names none."), ] = None, - deep: Annotated[ + fix: Annotated[ bool, - typer.Option("--deep/--no-deep", help="Let an LLM scout fill gaps that block a valid config."), - ] = True, + typer.Option("--fix/--no-fix", help="Let an LLM scout propose fixes for a config that failed."), + ] = False, refresh: Annotated[ bool, typer.Option("--refresh", help="Revalidate even when nothing the last report depended on moved."), @@ -142,7 +142,7 @@ def discover( workspace=workspace, base_url=base_url, env_backend=env_backend, - deep=deep, + fix=fix, refresh=refresh, dry_run=dry_run, ) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py index 0d9126c5071..ac1d0396dbc 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py @@ -137,7 +137,7 @@ async def attempt_repair( group=_GROUP, status="warn", message=f"The scout could not run: {type(exc).__name__}: {exc}", - hint="Set AUTHOR_API_KEY and AUTHOR_BASE_URL, or pass --no-deep to skip this step.", + hint="Set AUTHOR_API_KEY and AUTHOR_BASE_URL, or drop --fix to skip this step.", provenance="inference", ) ], diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py index daf93fc8496..7faed0c5653 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -47,7 +47,7 @@ class DiscoverOptions: workspace: str = "default" base_url: str | None = None env_backend: str | None = None - deep: bool = True + fix: bool = False refresh: bool = False dry_run: bool = False @@ -100,7 +100,7 @@ async def _discover( outcome = ValidationOutcome() if candidate is not None: outcome = await validate.run_ladder(candidate, repo_root) - if not outcome.runnable and options.deep: + if not outcome.runnable and options.fix: candidate, outcome, scout_findings = await _scout(candidate, outcome, repo_root) findings.extend(scout_findings) diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index e8d561edf27..f06871a9481 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -63,7 +63,9 @@ def _forbidden(*args, **kwargs): def _invoke(app, repo, *extra): - return runner.invoke(app, ["discover", "--repo", str(repo), "--no-deep", *extra]) + # --no-fix is the default; passed anyway so a later default flip cannot make this suite + # start calling a model. + return runner.invoke(app, ["discover", "--repo", str(repo), "--no-fix", *extra]) def _invoke_named(app, repo, *extra): @@ -120,6 +122,16 @@ def test_a_repo_whose_tasks_never_score_exits_one_and_withholds_the_config(app, assert sorted(client.files.stored) == [f"{AGENT}/discovery.md"] +def test_the_scout_is_opt_in(app, client, tmp_path, no_scout): + """A config Harbor rejects must not reach a model unless --fix asked for it.""" + write_dataset(tmp_path / "evals" / "validation", test_script=MENTIONS_REWARD_IN_COMMENT) + + result = runner.invoke(app, ["discover", "--repo", str(tmp_path), "--agent", AGENT]) + + assert result.exit_code == 1, result.output + assert "Harbor cannot run this repo's evals" in result.output, "the verdict was reached without a model" + + def test_a_repo_with_no_harbor_setup_at_all_exits_one(app, client, tmp_path): (tmp_path / "README.md").write_text("# Just a repo\n") diff --git a/plugins/nemo-eval-author/tests/discover/test_scout.py b/plugins/nemo-eval-author/tests/discover/test_scout.py index 5440dda45a9..366abd6da43 100644 --- a/plugins/nemo-eval-author/tests/discover/test_scout.py +++ b/plugins/nemo-eval-author/tests/discover/test_scout.py @@ -132,4 +132,4 @@ async def test_a_scout_that_cannot_run_degrades_to_a_warning(tmp_path): assert candidate is broken assert revalidated is outcome assert findings[0].status == "warn" - assert findings[0].hint is not None and "--no-deep" in findings[0].hint + assert findings[0].hint is not None and "--fix" in findings[0].hint From 383ae39c8a1fe4407f40e1b02daf51b054f9cd08 Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 12:18:18 -0500 Subject: [PATCH 06/15] refactor(eval-author): drop the platform and backend flags from discover --workspace, --base-url and --env-backend let one invocation contradict the configuration every other nemo command obeys. The cluster, credentials and workspace now come from the active context, and the Harbor environment backend is left to the repo's own config or Harbor's default. The report still records which workspace it wrote to, since a reader needs to name one to download the artifact. Dropping the backend injection also leaves the scout as the only thing that can mark a config source adjusted, which is the case that genuinely changes what a later run should pass to -c. Signed-off-by: Alec Khoury --- .../src/nemo_eval_author_plugin/cli.py | 12 ----- .../nemo_eval_author_plugin/discovery/run.py | 50 ++++++++++++------ .../discovery/sources.py | 24 +-------- .../tests/discover/test_command.py | 31 +++++++++-- .../tests/discover/test_scout.py | 4 +- .../tests/discover/test_sources.py | 52 ++++++------------- .../tests/discover/test_validate.py | 2 +- 7 files changed, 81 insertions(+), 94 deletions(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index 90a54a26b1c..ebde03ac395 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -111,15 +111,6 @@ def discover( str | None, typer.Option("--agent", help="Agent name. Defaults to optimizer.yaml, else the directory name."), ] = None, - workspace: Annotated[str, typer.Option("--workspace", help="Platform workspace.")] = "default", - base_url: Annotated[ - str | None, - typer.Option("--base-url", help="Platform base URL. Defaults to the active context."), - ] = None, - env_backend: Annotated[ - str | None, - typer.Option("--env-backend", help="Harbor environment type to assume when the repo names none."), - ] = None, fix: Annotated[ bool, typer.Option("--fix/--no-fix", help="Let an LLM scout propose fixes for a config that failed."), @@ -139,9 +130,6 @@ def discover( discovery.DiscoverOptions( repo_root=repo, agent=agent, - workspace=workspace, - base_url=base_url, - env_backend=env_backend, fix=fix, refresh=refresh, dry_run=dry_run, diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py index 7faed0c5653..bd250ae97db 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -32,6 +32,7 @@ from nemo_experimentalist_plugin.client import make_client from nemo_insights_plugin.contracts.profile import discover_profile from nemo_platform import AsyncNeMoPlatform +from nemo_platform.config.config import Config logger = logging.getLogger(__name__) @@ -40,13 +41,16 @@ @dataclass class DiscoverOptions: - """Everything the CLI passes through, resolved.""" + """Everything the CLI passes through, resolved. + + Deliberately holds nothing about where the platform is. Which cluster, which + credentials and which workspace are settled by the active ``nemo`` context, and a repo's + Harbor environment backend is settled by its own config or Harbor's default. Accepting + flags for those would let one invocation contradict the config every other command obeys. + """ repo_root: Path agent: str | None = None - workspace: str = "default" - base_url: str | None = None - env_backend: str | None = None fix: bool = False refresh: bool = False dry_run: bool = False @@ -80,23 +84,36 @@ async def discover(options: DiscoverOptions) -> DiscoverResult: """Run discovery end to end.""" repo_root = options.repo_root.resolve() agent = options.agent or _infer_agent_name(repo_root) - client = make_client(options.base_url) + workspace = _active_workspace() + # No base_url: the active context supplies the cluster and the credentials for it. + client = make_client(None) try: - return await _discover(client, options, repo_root=repo_root, agent=agent) + return await _discover(client, options, repo_root=repo_root, agent=agent, workspace=workspace) finally: await client.close() +def _active_workspace() -> str: + """The workspace the platform context resolves to. + + Read rather than accepted as a flag, so the artifact lands where every other ``nemo`` + command in this context looks. The report records the answer, since a later agent needs + to name a workspace to fetch from. ``NMP_WORKSPACE`` still overrides, because that is the + platform's own escape hatch rather than one of ours. + """ + return Config.load().resolve().workspace + + async def _discover( - client: AsyncNeMoPlatform, options: DiscoverOptions, *, repo_root: Path, agent: str + client: AsyncNeMoPlatform, options: DiscoverOptions, *, repo_root: Path, agent: str, workspace: str ) -> DiscoverResult: - prior = await memory.load_previous(client, agent=agent, workspace=options.workspace) + prior = await memory.load_previous(client, agent=agent, workspace=workspace) reuse = _reusable(prior, repo_root, refresh=options.refresh) if reuse is not None: - return await _reuse(client, options, agent=agent, prior=reuse) + return await _reuse(client, options, agent=agent, workspace=workspace, prior=reuse) - candidate, findings = sources.find_candidate(repo_root, env_backend=options.env_backend) + candidate, findings = sources.find_candidate(repo_root) outcome = ValidationOutcome() if candidate is not None: outcome = await validate.run_ladder(candidate, repo_root) @@ -105,7 +122,7 @@ async def _discover( findings.extend(scout_findings) findings.extend(outcome.findings) - findings.extend(await _probe_repo(client, repo_root, agent=agent, workspace=options.workspace)) + findings.extend(await _probe_repo(client, repo_root, agent=agent, workspace=workspace)) # When the repo maintains the config Harbor accepted, that file is what a later run will # pass to -c, so it is the thing worth round-tripping and there is nothing of ours to @@ -121,7 +138,7 @@ async def _discover( record = report.build_report( agent=agent, - workspace=options.workspace, + workspace=workspace, repo_root=repo_root, candidate=candidate, findings=findings, @@ -140,7 +157,7 @@ async def _discover( persisted, memory_findings = await memory.persist( client, agent=agent, - workspace=options.workspace, + workspace=workspace, markdown=markdown, job_config=publishable, ) @@ -178,7 +195,7 @@ def _reusable(prior: memory.PriorRecord | None, repo_root: Path, *, refresh: boo async def _reuse( - client: AsyncNeMoPlatform, options: DiscoverOptions, *, agent: str, prior: memory.PriorRecord + client: AsyncNeMoPlatform, options: DiscoverOptions, *, agent: str, workspace: str, prior: memory.PriorRecord ) -> DiscoverResult: """Restamp and reupload a report whose inputs have not moved.""" now = datetime.now(UTC) @@ -190,13 +207,14 @@ async def _reuse( replace(options, refresh=True), repo_root=options.repo_root.resolve(), agent=agent, + workspace=workspace, ) front = memory.parse_front_matter(restamped) or {} record = DiscoveryReport.model_validate( { "agent": agent, - "workspace": options.workspace, + "workspace": workspace, "repo_root": front.get("repo_root", str(options.repo_root)), "harbor_version": front.get("harbor_version", report.harbor_version()), "config_source": front.get("config_source"), @@ -211,7 +229,7 @@ async def _reuse( persisted, memory_findings = await memory.persist( client, agent=agent, - workspace=options.workspace, + workspace=workspace, markdown=restamped, # The stored config is already correct and already uploaded; rewriting it would # churn the fileset to produce identical bytes. diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py index 0f55ce91a2d..03fceee3ae9 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py @@ -76,7 +76,7 @@ class _DiscoveryProfile(BaseModel): profile_dir: Path -def find_candidate(repo_root: Path, *, env_backend: str | None = None) -> tuple[CandidateConfig | None, list[Finding]]: +def find_candidate(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: """Return the highest-priority candidate config found in *repo_root*. Every source is attempted even once one has won, because "we also found a prior job @@ -111,9 +111,6 @@ def find_candidate(repo_root: Path, *, env_backend: str | None = None) -> tuple[ return None, findings winner = min(candidates, key=lambda item: item.source.rank) - if env_backend is not None: - _apply_env_backend(winner, env_backend) - passed_over = [item.source.kind for item in candidates if item is not winner] findings.append( Finding( @@ -128,25 +125,6 @@ def find_candidate(repo_root: Path, *, env_backend: str | None = None) -> tuple[ return winner, findings -def _apply_env_backend(candidate: CandidateConfig, env_backend: str) -> None: - """Set ``environment.type`` only when the source did not declare one. - - A user who wrote ``type: daytona`` into their config meant it, and a CLI default - should not quietly overwrite a declaration on its way into the persisted artifact. - - Filling the gap counts as adjusting the payload, because it now says something the - source file does not: a reader pointed at that file would run a different backend. - """ - environment = candidate.data.get("environment") - if not isinstance(environment, dict): - candidate.data["environment"] = {"type": env_backend} - elif environment.get("type") is None: - environment["type"] = env_backend - else: - return - candidate.source.adjusted = True - - def _from_config_file(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: """A config file the user wrote, which is the strongest thing a repo can offer.""" matches: list[tuple[Path, dict[str, Any]]] = [] diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index f06871a9481..4ed0766910b 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -27,7 +27,7 @@ write_wrapper, ) from nemo_eval_author_plugin import cli -from nemo_eval_author_plugin.discovery import memory +from nemo_eval_author_plugin.discovery import memory, validate from nemo_eval_author_plugin.discovery import run as discovery from typer.testing import CliRunner @@ -47,6 +47,16 @@ def client(monkeypatch) -> StubClient: return stub +@pytest.fixture(autouse=True) +def workspace(monkeypatch): + """Pin the workspace, which the command reads from the platform context rather than a flag. + + Without this, these assertions would depend on whichever context the developer running + them happens to have selected. + """ + monkeypatch.setenv("NMP_WORKSPACE", "default") + + @pytest.fixture def no_scout(monkeypatch): """Fail loudly if a test reaches the LLM scout, which would need real credentials.""" @@ -97,12 +107,23 @@ def test_a_repo_that_maintains_its_own_config_keeps_it_and_records_only_the_repo assert "Withheld" not in result.output, "nothing was withheld; there was nothing of ours to publish" -def test_an_env_backend_that_the_config_omits_makes_discovery_publish_its_own(app, client, tmp_path): - """The payload now names a backend the repo's file does not, so that file is not what to run.""" +def test_a_config_the_scout_adjusted_is_published_instead_of_the_repo_file(app, client, monkeypatch, tmp_path): + """Once a payload diverges from the file it came from, that file is no longer what to run. + + Stands in for the scout so the ownership branch is exercised without a model: the repo's + config names a dataset that is not there, and the repair points it at the one that is. + """ write_dataset(tmp_path / "evals" / "validation") - write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/validation") + write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/missing") + + async def _repair(candidate, outcome, repo_root): + candidate.data["datasets"] = [{"path": "evals/validation"}] + candidate.source.adjusted = True + return candidate, await validate.run_ladder(candidate, repo_root), [] + + monkeypatch.setattr(discovery, "_scout", _repair) - result = _invoke_named(app, tmp_path, "--env-backend", "docker") + result = runner.invoke(app, ["discover", "--repo", str(tmp_path), "--agent", AGENT, "--fix"]) assert result.exit_code == 0, result.output assert "harbor job start -c harbor-job.yaml" in result.output diff --git a/plugins/nemo-eval-author/tests/discover/test_scout.py b/plugins/nemo-eval-author/tests/discover/test_scout.py index 366abd6da43..a006498366d 100644 --- a/plugins/nemo-eval-author/tests/discover/test_scout.py +++ b/plugins/nemo-eval-author/tests/discover/test_scout.py @@ -67,8 +67,10 @@ async def test_a_proposal_harbor_accepts_is_adopted_and_labelled(tmp_path): assert candidate.data["datasets"] == [{"path": str(good)}] assert revalidated.runnable - # The config's provenance has to admit a model touched it. + # The config's provenance has to admit a model touched it, which is also what stops the + # artifact from telling a later run to use the repo's own file. assert "adjusted by the discovery scout" in candidate.source.detail + assert candidate.source.adjusted is True assert findings[0].status == "pass" assert findings[0].provenance == "inference" diff --git a/plugins/nemo-eval-author/tests/discover/test_sources.py b/plugins/nemo-eval-author/tests/discover/test_sources.py index a1eb801317d..33668e0023c 100644 --- a/plugins/nemo-eval-author/tests/discover/test_sources.py +++ b/plugins/nemo-eval-author/tests/discover/test_sources.py @@ -8,8 +8,6 @@ former, and the report must say which it used. """ -import json - import yaml from harbor_fixtures import write_dataset, write_job_dir, write_task, write_wrapper from nemo_eval_author_plugin.discovery import sources @@ -123,51 +121,33 @@ def test_missing_wrapper_falls_back_to_the_oracle_and_says_what_that_means(tmp_p assert entry.hint is not None and "evaluates no agent" in entry.hint -def test_env_backend_fills_a_gap_but_never_overrides_a_declaration(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - - filled, _ = sources.find_candidate(tmp_path, env_backend="docker") - assert filled is not None - assert filled.data["environment"] == {"type": "docker"} - - (tmp_path / "configs").mkdir() - declared = {**_job_config("evals/validation"), "environment": {"type": "daytona"}} - (tmp_path / "configs" / "eval.json").write_text(json.dumps(declared)) - - respected, _ = sources.find_candidate(tmp_path, env_backend="docker") - assert respected is not None - assert respected.data["environment"]["type"] == "daytona" - +def test_a_config_file_is_read_as_written_and_stays_owned_by_the_repo(tmp_path): + """Nothing is injected into a config someone maintains, so the artifact can point at it. -def test_a_config_file_is_only_owned_by_the_repo_while_we_leave_it_alone(tmp_path): - """Ownership decides whether the artifact can point at the repo's file instead of a copy.""" + The environment backend is the case that tempts a default: assembly leaves it alone and + lets Harbor apply its own, rather than writing a value into a payload the repo's file + does not contain. + """ write_dataset(tmp_path / "evals" / "validation") (tmp_path / "configs").mkdir() - (tmp_path / "configs" / "eval.yaml").write_text(yaml.safe_dump(_job_config("evals/validation"))) + declared = {**_job_config("evals/validation"), "environment": {"type": "daytona"}} + (tmp_path / "configs" / "eval.yaml").write_text(yaml.safe_dump(declared)) - untouched, _ = sources.find_candidate(tmp_path) - assert untouched is not None - assert untouched.source.owns_file is True + candidate, _ = sources.find_candidate(tmp_path) - # Filling in a backend the file never named makes our payload the only runnable one. - injected, _ = sources.find_candidate(tmp_path, env_backend="docker") - assert injected is not None - assert injected.source.adjusted is True - assert injected.source.owns_file is False + assert candidate is not None + assert candidate.data["environment"] == {"type": "daytona"} + assert candidate.source.adjusted is False + assert candidate.source.owns_file is True -def test_a_declared_backend_leaves_the_config_owned_by_the_repo(tmp_path): - """Nothing changed, so nothing stops a run from using the file that is already there.""" +def test_an_undeclared_backend_is_left_for_harbor_to_default(tmp_path): write_dataset(tmp_path / "evals" / "validation") - (tmp_path / "configs").mkdir() - declared = {**_job_config("evals/validation"), "environment": {"type": "docker"}} - (tmp_path / "configs" / "eval.yaml").write_text(yaml.safe_dump(declared)) - candidate, _ = sources.find_candidate(tmp_path, env_backend="docker") + candidate, _ = sources.find_candidate(tmp_path) assert candidate is not None - assert candidate.source.adjusted is False - assert candidate.source.owns_file is True + assert "environment" not in candidate.data def test_an_inferred_source_never_claims_a_file_it_could_be_run_from(tmp_path): diff --git a/plugins/nemo-eval-author/tests/discover/test_validate.py b/plugins/nemo-eval-author/tests/discover/test_validate.py index 5480ba933f5..bb126343b30 100644 --- a/plugins/nemo-eval-author/tests/discover/test_validate.py +++ b/plugins/nemo-eval-author/tests/discover/test_validate.py @@ -306,7 +306,7 @@ async def test_the_full_pipeline_agrees_with_the_source_it_chose(tmp_path): write_dataset(tmp_path / "evals" / "validation") write_wrapper(tmp_path) - candidate, _ = sources.find_candidate(tmp_path, env_backend="docker") + candidate, _ = sources.find_candidate(tmp_path) assert candidate is not None outcome = await validate.run_ladder(candidate, tmp_path) From 2726e7d760161bb1b714c007dbf1aeffb36bde4f Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 14:27:37 -0500 Subject: [PATCH 07/15] fix(eval-author): harden discover's reuse gate and sharpen its findings Addresses review feedback on #988. The freshness gate that lets a repeat run skip the Harbor validation ladder was the weak point. load_previous could raise on a foreign report instead of declining it, contradicting its own docstring, and any truthy runnable value counted as permission to skip, so a run could exit zero having validated nothing. The input digest also hashed module copies found under .venv, tying a valid report's lifetime to a dependency reinstall. Beyond the gate: a reused report keeps the host variables a run needs, the reuse path explains an upload failure instead of only reporting one, a missing Job._task_configs is reported as our Harbor incompatibility rather than as the user's empty repo, and the verdict no longer claims Harbor answered checks that came from the filesystem or the scout. Also pins NMP_CONFIG_FILE in the discover fixture so the suite stops reading whichever platform context the developer happens to have, names the withheld-config finding for what it is rather than reusing "upload", records that discover takes one call per process because the ladder chdirs and mutates sys.path, points the doctor placeholder at ASE-769, and brings both READMEs in line with the command as it now stands. Signed-off-by: Alec Khoury --- plugins/nemo-eval-author/README.md | 3 +- .../src/nemo_eval_author_plugin/cli.py | 11 +- .../discovery/agent.py | 5 +- .../discovery/memory.py | 24 ++- .../discovery/report.py | 5 +- .../nemo_eval_author_plugin/discovery/run.py | 31 +++- .../discovery/validate.py | 33 +++- .../eval_author/README.md | 166 +++++++----------- .../tests/discover/test_command.py | 97 +++++++++- .../tests/discover/test_memory.py | 16 ++ .../tests/discover/test_validate.py | 52 ++++++ plugins/nemo-eval-author/tests/test_cli.py | 2 +- 12 files changed, 315 insertions(+), 130 deletions(-) diff --git a/plugins/nemo-eval-author/README.md b/plugins/nemo-eval-author/README.md index 7f22176cac3..a8eb748b429 100644 --- a/plugins/nemo-eval-author/README.md +++ b/plugins/nemo-eval-author/README.md @@ -63,4 +63,5 @@ Experimentalist import, both tagged `TODO(eval-author-standalone)`: ahead of any Experimentalist agent, because those agents read the environment when their class body executes. -A `nemo eval-author` CLI that auto-loads this `.env` is not wired yet. +The `nemo eval-author` CLI exists now, but nothing loads this `.env`: export the +variables in your shell instead. diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index ebde03ac395..522da0c163e 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -49,6 +49,13 @@ def _report_discovery(result: discovery.DiscoverResult) -> None: f"Nothing the previous report depended on has changed, so its verdict still holds " f"(revalidated {record.last_validated_at.isoformat()})." ) + # This branch is deliberately terse, but a failed re-upload is the one thing it + # cannot stay quiet about: without the warning, the exit code says the record was + # not written and nothing says why. Passes are skipped because the "Recorded to + # fileset ..." line below already reports them. + for finding in result.memory_findings: + if finding.status != "pass": + _echo_finding(finding) else: findings = [*record.findings, *result.memory_findings] for group in _GROUP_ORDER: @@ -166,7 +173,7 @@ def run() -> None: @app.command("doctor") def doctor() -> None: """Diagnose Eval Author setup: credentials, platform, runtime.""" - # TODO(ASE-678): report the prerequisites the other verbs gate on. - _not_implemented("doctor", "ASE-678") + # TODO(ASE-769): report the prerequisites the other verbs gate on. + _not_implemented("doctor", "ASE-769") return app diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py index ac1d0396dbc..5c5f985d212 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py @@ -43,8 +43,6 @@ # means Docker is not running, and no amount of reading the repo fixes that. _SCOUTABLE_RUNGS = frozenset({"schema", "resolution", "tasks", "agent", "config-source"}) -ProposeFn = Callable[[CandidateConfig, list[Finding], Path], Awaitable["ScoutProposal"]] - class ScoutProposal(BaseModel): """A config the scout believes will validate, plus its reasoning.""" @@ -54,6 +52,9 @@ class ScoutProposal(BaseModel): changed: list[str] = Field(default_factory=list, description="The keys that differ from the input config.") +ProposeFn = Callable[[CandidateConfig, list[Finding], Path], Awaitable[ScoutProposal]] + + class DiscoveryScout(Agent, llm=get_smart_model()): """Reads an agent repository to work out how its Harbor evaluations are meant to run.""" diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py index e3ef1d605ba..d599eb3d615 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py @@ -31,7 +31,7 @@ InputFingerprint, ) from nemo_eval_author_plugin.discovery.report import fingerprint_inputs -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, ValidationError _GROUP = "memory" _FRONT_MATTER_FENCE = "---" @@ -112,14 +112,20 @@ async def load_previous(sdk: Any, *, agent: str, workspace: str) -> PriorRecord for item in front.get("inputs") or [] if isinstance(item, dict) and "path" in item and "sha256" in item ] - return PriorRecord( - inputs_digest=front.get("inputs_digest"), - runnable=bool(front.get("runnable")), - harbor_version=front.get("harbor_version"), - last_validated_at=front.get("last_validated_at"), - inputs=inputs, - text=text, - ) + try: + return PriorRecord( + inputs_digest=front.get("inputs_digest"), + # Identity rather than truthiness: only a real YAML boolean may switch off + # revalidation. An unquoted timestamp or version loads as a datetime or a float + # and would fail validation, so a hand-edited report is rediscovered, not trusted. + runnable=front.get("runnable") is True, + harbor_version=front.get("harbor_version"), + last_validated_at=front.get("last_validated_at"), + inputs=inputs, + text=text, + ) + except ValidationError: + return None def restamp(text: str, *, when: datetime, harbor_version: str) -> str | None: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py index 3cf838dcb9c..dfaa51468ed 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py @@ -191,8 +191,9 @@ def _verdict_section(report: DiscoveryReport) -> list[str]: source = report.config_source detail = source.detail if source is not None else "unknown" return [ - f"Harbor can run this repo's evals. The config was {detail}, and every check below " - f"was answered by Harbor {report.harbor_version} rather than inferred.", + f"Harbor can run this repo's evals. The config was {detail}, and every check in " + f"*What Harbor checked* below was answered by Harbor {report.harbor_version} rather " + "than inferred.", "", ] diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py index bd250ae97db..2e62458646a 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -81,7 +81,12 @@ def ok(self) -> bool: async def discover(options: DiscoverOptions) -> DiscoverResult: - """Run discovery end to end.""" + """Run discovery end to end. + + One call at a time per process. The validation ladder chdirs into the repo and puts it on + ``sys.path``, both process-wide, so a second concurrent call would judge the wrong tree. A + caller that needs several repos at once has to run them in separate processes. + """ repo_root = options.repo_root.resolve() agent = options.agent or _infer_agent_name(repo_root) workspace = _active_workspace() @@ -164,7 +169,10 @@ async def _discover( if job_config is not None and publishable is None: memory_findings.append( Finding( - name="upload", + # Not "upload": withholding is a decision, and memory.persist uses that name + # for an upload that actually broke. One name for both invites a filter that + # silences real failures. + name="config-withheld", group="memory", status="warn", message=f"Withheld {JOB_CONFIG_FILENAME}: the config did not clear every check", @@ -218,6 +226,10 @@ async def _reuse( "repo_root": front.get("repo_root", str(options.repo_root)), "harbor_version": front.get("harbor_version", report.harbor_version()), "config_source": front.get("config_source"), + # Restored because the CLI prints "Needs: ..." from it, and a repeat run that + # dropped it would tell the user to start a job without naming the variables + # Harbor raises on. ``or []`` degrades an explicit null rather than failing. + "required_env_vars": front.get("required_env_vars") or [], "discovered_at": front.get("discovered_at", now), "last_validated_at": now, "inputs": [item.model_dump() for item in prior.inputs], @@ -304,10 +316,23 @@ def _input_paths(repo_root: Path, candidate: CandidateConfig | None, outcome: Va for agent_config in outcome.config.agents: if agent_config.import_path: module = agent_config.import_path.split(":", 1)[0].split(".", 1)[0] - paths.extend(sorted(repo_root.rglob(f"{module}.py"))) + paths.extend(_module_files(repo_root, module)) return paths +def _module_files(repo_root: Path, module: str) -> list[Path]: + """Every ``{module}.py`` the repo itself holds, located the way ``sources`` finds a wrapper. + + Through ``scan.walk_dirs`` rather than ``rglob`` because this list is hashed into the + digest that decides whether a later run may skip the ladder. An unfiltered walk would + fingerprint a copy inside ``.venv`` or ``node_modules``, so reinstalling a dependency + would invalidate a report that is still perfectly good, and the digest would quietly + cover bytes the repo does not own. + """ + candidates = (directory / f"{module}.py" for directory in scan.walk_dirs(repo_root)) + return sorted(path for path in candidates if path.is_file()) + + def _infer_agent_name(repo_root: Path) -> str: """Name from ``optimizer.yaml`` when it says, else a slug of the directory.""" profile = discover_profile(repo_root) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py index 9124c3b77df..344f48c5b26 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py @@ -126,6 +126,24 @@ async def _ladder(candidate: CandidateConfig, repo_root: Path) -> ValidationOutc return outcome resolved = _resolved_local_paths(job) + if resolved is None: + # Not a `_harbor` finding: Harbor did not return this verdict, we reached for one of + # its attributes and found it gone. Same shape as the round trip's "no harbor + # executable on PATH" — the honest report is that Harbor could not be asked. + outcome.findings.append( + Finding( + name="compatibility", + group=_GROUP, + status="fail", + message="This Harbor version no longer exposes the resolved task list through Job._task_configs", + hint=( + "Discovery reads the same private attribute Harbor's own CLI does, so this is an " + "incompatibility with the installed Harbor rather than a problem with this repo." + ), + ) + ) + return outcome + task_dirs = _rung_tasks(resolved, outcome) outcome.task_dirs = task_dirs _rung_coverage(config, resolved, outcome) @@ -222,20 +240,29 @@ async def _rung_resolution(config: JobConfig, outcome: ValidationOutcome) -> Job return job -def _resolved_local_paths(job: Job) -> list[Path]: - """The on-disk task directories Harbor expanded this job into. +def _resolved_local_paths(job: Job) -> list[Path] | None: + """The on-disk task directories Harbor expanded this job into, or ``None`` if it cannot say. Harbor's own CLI reaches for this attribute at harbor/cli/jobs.py:93 for the same reason; there is no public accessor for the resolved list. Tasks that live only in a remote registry are skipped, since the resolution rung already spoke for whether they could be fetched. + A missing attribute is ``None`` rather than an empty list, because the two mean opposite + things. Empty is a repo Harbor found no tasks in; absent is a Harbor that no longer + answers the question, and collapsing them would report "the config resolves to zero + tasks" about a repo whose tasks are fine. + Absolute on the way out. Harbor hands back whatever the config said, and a relative path means the repo root only while the ladder's chdir is in effect; these outlive it as the task list the report fingerprints. """ + task_configs = getattr(job, "_task_configs", None) + if task_configs is None: + return None + paths: list[Path] = [] - for task_config in getattr(job, "_task_configs", []): + for task_config in task_configs: try: paths.append(task_config.get_local_path().resolve()) except ValueError: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md index 59a33c09f57..dcbfe0c2d5e 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md @@ -5,112 +5,70 @@ SPDX-License-Identifier: Apache-2.0 # Eval Author -The top-level `nemo_eval_author_plugin.eval_author` package is the canonical Eval Author -implementation. It turns an Experimentalist Insight and its production trace refs into +The Eval Author plugin is a NeMo OO Agent specialized in auditing and improving the +eval suite of a target agent. + +It turns an Experimentalist Insight and its production trace refs into evaluator dataset changes, creating or augmenting regression signals that capture the failure mode before optimization begins. This package hard-depends on Experimentalist for evaluator, staging, and trace helpers. Experimentalist insight mode imports and runs this Eval Author before -beginning optimization (both packages are installed via the `experimentalist` -uv group). - -## Current Files - -- `agent.py` defines the canonical `EvalAuthor` agent. -- `materialization.py` stages, validates, and persists Insight suites locally. -- `models.py` defines the lightweight `EvalAuthorConfig` and `EvalAuthorResult` models. -- `REFERENCE.md` documents the Python return contract. -- `run.py` defines `run_eval_author(...)`, a reusable orchestration function for - Python callers. -- `config.yaml` is a default run preset for future CLI or job wiring. - -## Configuration - -`config.yaml` is not loaded automatically yet. A future entrypoint should read -the file, overlay caller-provided values, and validate the nested `eval_author` -block with `EvalAuthorConfig`. - -The preset includes the run inputs needed by `run_eval_author(...)`: - -- `insight`: local Insight file path or platform Insight id. -- `agent`: optional agent source override. If omitted, the Insight's agent is used. -- `train_dataset`: evaluator training dataset URI. -- `validation_dataset`: evaluator validation dataset URI. -- `task_template`: local or `fileset://` evaluator task template URI for production traces. -- `experiment_dir`: local Eval Author working directory. -- `workspace`, `base_url`, `mode`, and `evaluator_type`: platform and evaluator routing. -- `eval_author.max_summary_tokens` and `eval_author.max_traces`: agent tuning parameters. - -## Materialized Insight Suite - -For an Insight with trace references, Eval Author copies and fills one local Harbor -task template per trace beneath its experiment working directory: - -```text -eval-and-optimize/eval_author//insight-suite/ -``` - -Each Eval Author invocation fills a fresh candidate suite from the current template -and traces. The complete suite is Harbor-validated locally, promoted to the -experiment-local working copy with backup-and-restore failure handling, and -analyzed for the Insight's root cause. Eval Author then adds normalized -Insight-specific verifier metric keys to every materialized task while -preserving the template's existing task metrics. The metric authoring step is -scoped to the Insight suite; the user's train and validation datasets remain -unchanged. The authored verifiers must pass static Harbor validation before the -local suite is returned to the optimization loop. - -After authoring and validation, Eval Author hashes every task file and verifier -file and persists deterministic suite and scorer identities in the local suite's -manifest. The returned dataset continues to point at the single experiment-local -suite. Candidate Insight results persist the suite identity, and resume reuses -those results only when the identity still matches; changed task or verifier -content is re-evaluated. - -Task-template inputs may be local paths, `file://` URIs, or NeMo Platform -`fileset:///` references. Fileset-backed templates are -downloaded into the experiment-local staging directory before Harbor parses -them. The staged template is refreshed on every invocation rather than reused. - -The returned Python contract is documented in the -[Eval Author Python Reference](REFERENCE.md#evalauthorresult). - -Insight metrics remain adaptive development feedback. They may steer round -analysis, goal-tree updates, and proposals, but validation remains the direct -Pareto and winner-selection criterion. Promotion suggestions require complete -repeated baseline-to-winner improvement evidence, remain advisory, and never -mutate the canonical validation dataset. - -## Intended Invocation - -Until a CLI or platform job is wired, Python callers can invoke the runner -directly: - -```python -import asyncio -from pathlib import Path - -from nemo_eval_author_plugin.eval_author.models import EvalAuthorConfig -from nemo_eval_author_plugin.eval_author.run import run_eval_author -from nemo_experimentalist_plugin.experimentalist.components.evaluator.models import DatasetRef - - -async def main() -> None: - result = await run_eval_author( - insight="insight-id", - train_dataset=DatasetRef(uri="path/to/train"), - validation_dataset=DatasetRef(uri="path/to/validation"), - task_template=DatasetRef(uri="path/to/template"), - experiment_dir=Path("tmp/eval_author"), - workspace="default", - base_url="http://localhost:8080", - config=EvalAuthorConfig(), - ) - print(result.summary) - - -asyncio.run(main()) -``` - -No standalone Eval Author CLI is implemented yet. +beginning optimization. + +## Current state + +`nemo eval-author discover` is the only implemented command. It answers whether +Harbor can run a repository's evals and records the answer, so a later run does +not have to derive it again. + +The command assembles a candidate Harbor `JobConfig` from the strongest source +the repository offers: a Harbor config file it already maintains, a `config.json` +from a prior job Harbor resolved and ran, an Experimentalist `optimizer.yaml` +profile plus the agent wrapper, or the Harbor task directory layout alone. + +It validates that candidate through a ladder of Harbor's own calls rather than +reimplemented rules: schema, job resolution, task validity and coverage, reward +files, required host variables, the agent class, the environment backend, and a +round trip of the persisted bytes through `harbor job start --print-config`. +[`discovery/validate.py`](../discovery/validate.py) names the Harbor API behind +each rung. + +The result is recorded to the `nemo-eval-author` fileset as +`/discovery.md`. A `/harbor-job.yaml` is published alongside the +report only when discovery authored or adjusted the config; when the repository +maintains its own valid config file, the report points at that file instead. +Nothing is written into the repository under inspection. + +Exit code 0 means a config was validated and recorded. Every other outcome exits +non-zero, including a config Harbor accepted but that could not be uploaded, +which is what makes the command usable as a gate. + +`discover` takes these flags: + +- `--repo`: agent repository to inspect. Defaults to the current directory. +- `--agent`: name the artifacts are stored under. Defaults to the agent named in + `optimizer.yaml`, else a slug of the directory name. +- `--fix` / `--no-fix`: let an LLM scout propose fixes for a config Harbor + rejected. Defaults to `--no-fix`, and the scout is the only part of `discover` + that needs `AUTHOR_*` credentials. +- `--refresh`: revalidate even when nothing the last report depended on moved. +- `--dry-run`: print the findings and the config without uploading anything. + +There are no flags for platform state. The workspace and cluster come from the +active `nemo` context, `NMP_WORKSPACE` still overrides the workspace, and the +Harbor environment backend comes from the repository's own config or Harbor's +default. + +The other verbs are registered in [`cli.py`](../cli.py) so the command tree is +discoverable. Each one exits non-zero with a not-implemented message. + +## Planned commands + +- `nemo eval-author audit`: report coverage gaps in an existing Harbor suite + against `ETHOS.md`, without changing the suite. +- `nemo eval-author propose`: draft reviewable Harbor tasks and verifier patches + for the gaps the audit found. +- `nemo eval-author run`: run `discover`, `audit`, and `propose` as one pipeline. +- `nemo eval-author doctor`: check the credentials, platform access, and runtime + the other commands need. diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index 4ed0766910b..085c11d8051 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -24,6 +24,7 @@ StubFiles, write_dataset, write_job_config, + write_task, write_wrapper, ) from nemo_eval_author_plugin import cli @@ -48,13 +49,18 @@ def client(monkeypatch) -> StubClient: @pytest.fixture(autouse=True) -def workspace(monkeypatch): +def workspace(monkeypatch, tmp_path): """Pin the workspace, which the command reads from the platform context rather than a flag. - Without this, these assertions would depend on whichever context the developer running - them happens to have selected. + Both variables are needed. ``NMP_WORKSPACE`` fixes the value, but resolving a context still + reads the config file and raises on a dangling cluster or user reference, so this points the + platform at an empty one. Empty rather than absent, because an explicit ``NMP_CONFIG_FILE`` + that does not exist is an error rather than a fallback. """ + config = tmp_path / "nmp-config.yaml" + config.touch() monkeypatch.setenv("NMP_WORKSPACE", "default") + monkeypatch.setenv("NMP_CONFIG_FILE", str(config)) @pytest.fixture @@ -231,6 +237,91 @@ def test_an_unchanged_repo_is_not_revalidated(app, client, tmp_path, no_scout): assert "validation/schema" not in second.output, "the ladder should not have run again" +def test_a_runnable_flag_that_is_not_a_boolean_does_not_switch_off_revalidation(app, client, tmp_path): + """Reuse skips the entire ladder, so only a real YAML ``true`` may switch revalidation off. + + The string ``"false"`` is the cruel case: it is truthy, and a reused record carries no + findings, so the command would exit zero having validated nothing and claiming a verdict + the stored report explicitly denies. + """ + write_dataset(tmp_path / "evals" / "validation") + assert _invoke_named(app, tmp_path).exit_code == 0 + stored = client.files.stored[memory.remote_report_path(AGENT)].decode("utf-8") + assert "runnable: true" in stored + client.files.stored[memory.remote_report_path(AGENT)] = stored.replace( + "runnable: true", "runnable: 'false'" + ).encode("utf-8") + + result = _invoke_named(app, tmp_path) + + assert result.exit_code == 0, result.output + assert "validation/schema" in result.output, "the ladder had to run again" + assert "Nothing the previous report depended on has changed" not in result.output + + +def test_a_wrapper_copy_inside_a_virtualenv_is_not_fingerprinted(app, client, tmp_path): + """The digest decides whether a later run may skip the ladder, so it covers the repo's own source only. + + A vendored module whose basename matches the agent's import path would otherwise tie this + report's freshness to a dependency: reinstalling the package invalidates a verdict that + still holds, and the digest quietly covers bytes the repo does not own. + """ + write_dataset(tmp_path / "evals" / "validation") + write_wrapper(tmp_path) + vendored = tmp_path / ".venv" / "lib" / "python3.12" / "site-packages" + vendored.mkdir(parents=True) + write_wrapper(vendored, class_name="VendoredAgent") + + assert _invoke_named(app, tmp_path).exit_code == 0 + + front = memory.parse_front_matter(client.files.stored[memory.remote_report_path(AGENT)].decode("utf-8")) + assert front is not None + recorded = [item["path"] for item in front["inputs"]] + assert "harbor_wrapper.py" in recorded, "the repo's own wrapper shaped the verdict, so it is an input" + assert [path for path in recorded if path.startswith(".venv")] == [] + + +def test_a_reused_report_still_names_the_host_variables_a_run_needs(app, client, tmp_path): + """A repeat run is the common case, so losing ``Needs:`` there hides it nearly always. + + Harbor raises on an unresolved template at trial start. A record that stops naming + ``HF_TOKEN`` hands out a run command that cannot work and says nothing about why. + """ + write_task( + tmp_path / "evals" / "validation" / "task-0", + task_toml='\n[environment.env]\nHF_TOKEN = "${HF_TOKEN}"\n', + ) + first = _invoke_named(app, tmp_path) + assert first.exit_code == 0, first.output + assert "Needs: HF_TOKEN" in first.output + + result = _invoke_named(app, tmp_path) + + assert result.exit_code == 0, result.output + assert "Nothing the previous report depended on has changed" in result.output + assert "Needs: HF_TOKEN" in result.output + + +def test_a_reused_report_that_cannot_be_reuploaded_says_what_went_wrong(app, client, monkeypatch, tmp_path): + """The exit code says the record was not written; only the finding says why. + + This branch prints almost nothing by design, but the upload warning carries the exception, + the fileset and the remote path — the whole diagnosis, and it is on every other path. + """ + write_dataset(tmp_path / "evals" / "validation") + assert _invoke_named(app, tmp_path).exit_code == 0 + offline = StubClient(files=StubFiles(client.files.stored, fail=True)) + monkeypatch.setattr(discovery, "make_client", lambda base_url: offline) + + result = _invoke_named(app, tmp_path) + + assert result.exit_code == 1, result.output + assert "Nothing the previous report depended on has changed" in result.output, "this is the reuse path" + assert "Could not upload discovery.md" in result.output + assert "fileset unavailable" in result.output + assert "could not be recorded" in result.output + + def test_refresh_forces_the_ladder_to_run_again(app, client, tmp_path): write_dataset(tmp_path / "evals" / "validation") assert _invoke(app, tmp_path).exit_code == 0 diff --git a/plugins/nemo-eval-author/tests/discover/test_memory.py b/plugins/nemo-eval-author/tests/discover/test_memory.py index 18393aedfa3..e38190eece7 100644 --- a/plugins/nemo-eval-author/tests/discover/test_memory.py +++ b/plugins/nemo-eval-author/tests/discover/test_memory.py @@ -85,6 +85,22 @@ async def test_a_missing_or_unreachable_report_just_means_rediscover(): assert await memory.load_previous(unusable, agent="ticket-triage", workspace="default") is None +async def test_a_hand_edited_report_is_rediscovered_rather_than_raising(): + """Nothing above this catches an exception, so a report someone edited would be a traceback. + + YAML reads a bare timestamp as a ``datetime`` and a bare version as a ``float``, neither of + which Pydantic coerces into the strings ``PriorRecord`` declares. An unusable file is the + same situation as no file at all, and the answer to both is to rediscover. + """ + for line in ("last_validated_at: 2026-07-31T16:32:41.123456+00:00", "harbor_version: 0.18"): + stored = f"---\nrunnable: true\n{line}\n---\n\n# report\n" + client = StubClient(files=StubFiles({"ticket-triage/discovery.md": stored.encode("utf-8")})) + + prior = await memory.load_previous(client, agent="ticket-triage", workspace="default") + + assert prior is None, f"`{line}` should have been declined rather than raised on" + + def test_rehashing_prior_inputs_notices_an_edited_file(tmp_path): path = _write(tmp_path / "task.toml", 'version = "1.0"\n') inputs = report.fingerprint_inputs([path], tmp_path) diff --git a/plugins/nemo-eval-author/tests/discover/test_validate.py b/plugins/nemo-eval-author/tests/discover/test_validate.py index bb126343b30..7a41a422f75 100644 --- a/plugins/nemo-eval-author/tests/discover/test_validate.py +++ b/plugins/nemo-eval-author/tests/discover/test_validate.py @@ -16,6 +16,7 @@ """ import sys +from typing import ClassVar from harbor_fixtures import ( MENTIONS_REWARD_IN_COMMENT, @@ -79,6 +80,57 @@ async def test_resolution_failure_reports_the_error_a_real_run_would_hit(tmp_pat assert resolution.hint is not None and "before starting any container" in resolution.hint +async def test_a_harbor_that_stopped_exposing_its_resolved_tasks_does_not_blame_the_repo(tmp_path, monkeypatch): + """``Job._task_configs`` is private, so a Harbor upgrade is allowed to rename it. + + Reading an absent attribute as zero tasks would report "the config resolves to zero tasks" + under a hint quoting a Harbor error Harbor never raised, about a repo whose tasks are fine. + An incompatibility of ours has to read as ours. + """ + write_dataset(tmp_path / "evals" / "validation", count=1) + candidate = _candidate({"datasets": [{"path": str(tmp_path / "evals/validation")}]}) + + class _JobWithoutTaskConfigs: + @classmethod + async def create(cls, config): + return cls() + + monkeypatch.setattr(validate, "Job", _JobWithoutTaskConfigs) + + outcome = await validate.run_ladder(candidate, tmp_path) + + compatibility = _finding(outcome, "compatibility") + assert compatibility.status == "fail" + assert "Job._task_configs" in compatibility.message + assert not any(item.name == "tasks" for item in outcome.findings), "no verdict on tasks was available" + assert not any("zero tasks" in item.message for item in outcome.findings) + + +async def test_a_config_that_really_resolves_no_tasks_is_still_the_repo_s_failure(tmp_path, monkeypatch): + """The companion case: present but empty is a repo Harbor found nothing in, and it must still fail. + + Absent and empty mean opposite things, so this pins the distinction from the side that + would be lost if the attribute check were ever relaxed back to a falsy one. + """ + candidate = _candidate({"datasets": [{"path": str(write_dataset(tmp_path / "evals" / "validation", count=1))}]}) + + class _JobWithNoTasks: + _task_configs: ClassVar[list] = [] + + @classmethod + async def create(cls, config): + return cls() + + monkeypatch.setattr(validate, "Job", _JobWithNoTasks) + + outcome = await validate.run_ladder(candidate, tmp_path) + + tasks = _finding(outcome, "tasks") + assert tasks.status == "fail" + assert "zero tasks" in tasks.message + assert not any(item.name == "compatibility" for item in outcome.findings) + + async def test_a_task_harbor_silently_skips_is_reported(tmp_path): """Harbor drops a directory it cannot parse without raising, so a run would score fewer tasks than the repo holds and nothing about the result would look incomplete.""" diff --git a/plugins/nemo-eval-author/tests/test_cli.py b/plugins/nemo-eval-author/tests/test_cli.py index 34249d87586..76adf436460 100644 --- a/plugins/nemo-eval-author/tests/test_cli.py +++ b/plugins/nemo-eval-author/tests/test_cli.py @@ -25,7 +25,7 @@ ("audit", "ASE-676"), ("propose", "ASE-675"), ("run", "ASE-673"), - ("doctor", "ASE-678"), + ("doctor", "ASE-769"), ] _IMPLEMENTED_VERBS = ["discover"] From 66f5efe6b65f94a44930d4d081f1061b47f1ef7c Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 14:40:09 -0500 Subject: [PATCH 08/15] refactor(eval-author): rename --fix to --dangerously-fix and warn in the README The scout this flag enables runs shell commands in the repo under inspection with no sandbox, and it chooses those commands by reading files from that same repo, so hostile content there can steer it. A flag called --fix reads as routine maintenance. The name should carry the risk. The negative form is dropped rather than renamed, since --no-dangerously-fix is noise when the default is already off; test_the_scout_is_opt_in still pins that default. The README now leads with active development and not for production use, and names the hazard rather than leaving a reader to assume it means bugs: validating a config imports the target repo's agent module into the running process, so pointing Eval Author at a repository is equivalent to running that repository's code. Sandboxing is not implemented yet. Signed-off-by: Alec Khoury --- .../src/nemo_eval_author_plugin/cli.py | 8 +++++++- .../nemo_eval_author_plugin/discovery/agent.py | 2 +- .../eval_author/README.md | 18 +++++++++++++++--- .../tests/discover/test_command.py | 10 +++++----- .../tests/discover/test_scout.py | 2 +- 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index 522da0c163e..e3e5cda9a72 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -120,7 +120,13 @@ def discover( ] = None, fix: Annotated[ bool, - typer.Option("--fix/--no-fix", help="Let an LLM scout propose fixes for a config that failed."), + typer.Option( + "--dangerously-fix", + help=( + "Let an LLM scout propose fixes for a config Harbor rejected. The scout runs shell " + "commands in the repo under inspection with no sandbox. Only use it on a repo you trust." + ), + ), ] = False, refresh: Annotated[ bool, diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py index 5c5f985d212..58337e96558 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py @@ -138,7 +138,7 @@ async def attempt_repair( group=_GROUP, status="warn", message=f"The scout could not run: {type(exc).__name__}: {exc}", - hint="Set AUTHOR_API_KEY and AUTHOR_BASE_URL, or drop --fix to skip this step.", + hint="Set AUTHOR_API_KEY and AUTHOR_BASE_URL, or drop --dangerously-fix to skip this step.", provenance="inference", ) ], diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md index dcbfe0c2d5e..0125d673052 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md @@ -5,6 +5,15 @@ SPDX-License-Identifier: Apache-2.0 # Eval Author +> **Active development. Not intended for external use.** +> +> This plugin is incomplete and its interfaces will change without notice. It also +> runs code from the repository you point it at: validating a config imports that +> repository's agent module into the running process, and `--dangerously-fix` gives a +> language model a shell in that directory with no sandbox. Treat pointing Eval Author +> at a repository as equivalent to running that repository's code yourself, and only +> do it for code you already trust. Sandboxing is not implemented yet. + The Eval Author plugin is a NeMo OO Agent specialized in auditing and improving the eval suite of a target agent. @@ -49,9 +58,12 @@ which is what makes the command usable as a gate. - `--repo`: agent repository to inspect. Defaults to the current directory. - `--agent`: name the artifacts are stored under. Defaults to the agent named in `optimizer.yaml`, else a slug of the directory name. -- `--fix` / `--no-fix`: let an LLM scout propose fixes for a config Harbor - rejected. Defaults to `--no-fix`, and the scout is the only part of `discover` - that needs `AUTHOR_*` credentials. +- `--dangerously-fix`: let an LLM scout propose fixes for a config Harbor + rejected. Off unless passed. The scout runs shell commands in the repository + under inspection with no sandbox, and it decides what to run by reading files + from that same repository, so hostile content there can steer it. It is also + the only part of `discover` that needs `AUTHOR_*` credentials, which are in + its environment while it runs. - `--refresh`: revalidate even when nothing the last report depended on moved. - `--dry-run`: print the findings and the config without uploading anything. diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index 085c11d8051..9a0ab202fb5 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -79,9 +79,9 @@ def _forbidden(*args, **kwargs): def _invoke(app, repo, *extra): - # --no-fix is the default; passed anyway so a later default flip cannot make this suite - # start calling a model. - return runner.invoke(app, ["discover", "--repo", str(repo), "--no-fix", *extra]) + # The scout is opt-in and there is no way to ask for it here, so no test that goes through + # this helper can reach a model. test_the_scout_is_opt_in pins that default. + return runner.invoke(app, ["discover", "--repo", str(repo), *extra]) def _invoke_named(app, repo, *extra): @@ -129,7 +129,7 @@ async def _repair(candidate, outcome, repo_root): monkeypatch.setattr(discovery, "_scout", _repair) - result = runner.invoke(app, ["discover", "--repo", str(tmp_path), "--agent", AGENT, "--fix"]) + result = runner.invoke(app, ["discover", "--repo", str(tmp_path), "--agent", AGENT, "--dangerously-fix"]) assert result.exit_code == 0, result.output assert "harbor job start -c harbor-job.yaml" in result.output @@ -150,7 +150,7 @@ def test_a_repo_whose_tasks_never_score_exits_one_and_withholds_the_config(app, def test_the_scout_is_opt_in(app, client, tmp_path, no_scout): - """A config Harbor rejects must not reach a model unless --fix asked for it.""" + """A config Harbor rejects must not reach a model unless --dangerously-fix asked for it.""" write_dataset(tmp_path / "evals" / "validation", test_script=MENTIONS_REWARD_IN_COMMENT) result = runner.invoke(app, ["discover", "--repo", str(tmp_path), "--agent", AGENT]) diff --git a/plugins/nemo-eval-author/tests/discover/test_scout.py b/plugins/nemo-eval-author/tests/discover/test_scout.py index a006498366d..5e78dc06ec9 100644 --- a/plugins/nemo-eval-author/tests/discover/test_scout.py +++ b/plugins/nemo-eval-author/tests/discover/test_scout.py @@ -134,4 +134,4 @@ async def test_a_scout_that_cannot_run_degrades_to_a_warning(tmp_path): assert candidate is broken assert revalidated is outcome assert findings[0].status == "warn" - assert findings[0].hint is not None and "--fix" in findings[0].hint + assert findings[0].hint is not None and "--dangerously-fix" in findings[0].hint From d1b1e2fce8e0a19b8b44ceb2acbadf7e6f1b6f9b Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 15:16:45 -0500 Subject: [PATCH 09/15] refactor(eval-author): cut discover back to what it can prove Review found the command over-scoped. What comes out here was either untrustworthy, never read, or big enough to deserve a change of its own. The --dangerously-fix scout is gone. Handing a language model an unsandboxed shell in the repo under inspection is a decision that needs its own argument and its own review, not a flag riding along with discovery. ConfigSource .adjusted and the "inference" provenance go with it, since only the scout could ever set either. The report freshness layer is gone. It fingerprinted an explicit list of files, so adding a new eval task was invisible to it: a second run printed that the previous verdict still holds and exited zero without ever validating the new task. It also gave DiscoveryReport a second constructor, assembled from front matter, free to drift from build_report. memory.py is now write-only, every run revalidates from scratch, and build_report is the only way a report comes into being. Finding.provenance is gone. Every producer set it and nothing read it: it reached no artifact and no output. harbor_call already carries the same signal and is rendered by both the CLI and the report, so the absence of a call is now what marks a finding we observed rather than one Harbor judged. One behavior change, and the reason a repo's exit code can move: the reward rung is now advisory. It was a substring search over test scripts wearing a harbor_call that only locates the script path, and it was wrong in both directions. A script writing the reward through a shell variable was reported as a hard failure, blocking discovery and withholding the config for a repo whose evals are fine; a script that wrote nothing but echoed the string "reward.json" passed. It now warns, carries no harbor_call, and says the script never names a reward file. Two tests pin that, including the false negative. It is not a commit of its own because the hunks that update its tests are the same hunks that delete the scout's. _rung_coverage stays, after being cut and put back: writing a replacement test showed Harbor silently drops a task dir with a malformed task.toml while the ladder reports one of one valid and exits zero. Nothing else catches it. Also: the markdown body loses the essays on what -c means and how to run the oracle, leaving verdict, run command, findings and host variables, while the front matter stands as the machine-readable contract apart from the dropped inputs keys. sources.source_priority() and report.canonical_digest() were never called. scan.find_doctrine and find_skills returned tuples whose first element the only call site discarded. The discover help now says that validating a config imports the inspected repo's agent module into this process, which with the scout gone is the last code-execution hazard and was named nowhere in the CLI. Signed-off-by: Alec Khoury --- .../src/nemo_eval_author_plugin/cli.py | 50 +--- .../discovery/agent.py | 205 ----------------- .../discovery/memory.py | 135 +---------- .../discovery/models.py | 85 +------ .../discovery/report.py | 216 ++++-------------- .../nemo_eval_author_plugin/discovery/run.py | 163 +------------ .../nemo_eval_author_plugin/discovery/scan.py | 12 +- .../discovery/sources.py | 6 - .../discovery/validate.py | 102 ++++----- .../eval_author/README.md | 38 ++- .../tests/discover/test_command.py | 182 ++------------- .../tests/discover/test_memory.py | 152 ------------ .../tests/discover/test_report.py | 125 ++-------- .../tests/discover/test_scan.py | 24 +- .../tests/discover/test_scout.py | 137 ----------- .../tests/discover/test_sources.py | 1 - .../tests/discover/test_validate.py | 64 ++++-- .../nemo-eval-author/tests/harbor_fixtures.py | 15 ++ 18 files changed, 275 insertions(+), 1437 deletions(-) delete mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py delete mode 100644 plugins/nemo-eval-author/tests/discover/test_memory.py delete mode 100644 plugins/nemo-eval-author/tests/discover/test_scout.py diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index e3e5cda9a72..596792f3615 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -9,9 +9,8 @@ This module imports nothing from ``eval_author``: those agents build their LLM client while the class body executes, so importing one here would make the whole CLI require ``AUTHOR_*`` credentials — including the ``doctor`` verb whose job is to report that they are missing. -``discovery.run`` is safe to import because it defers the one module that builds a client. -Experimentalist's CLI keeps its runner behind a lazily-assigned module global for the same -reason. +``discovery.run`` builds no client at import, so it is safe. Experimentalist's CLI keeps its +runner behind a lazily-assigned module global for the same reason. """ import asyncio @@ -28,7 +27,7 @@ # Order the ladder's own sequence, so the printed report reads the way validation ran # rather than the way findings happened to accumulate. -_GROUP_ORDER = ("config", "validation", "repo", "scout", "memory") +_GROUP_ORDER = ("config", "validation", "repo", "memory") def _not_implemented(command: str, ticket: str) -> NoReturn: @@ -44,23 +43,10 @@ def _echo_finding(finding: Finding) -> None: def _report_discovery(result: discovery.DiscoverResult) -> None: """Print the run, then the verdict, because the verdict is what the reader came for.""" record = result.report - if result.reused: - typer.echo( - f"Nothing the previous report depended on has changed, so its verdict still holds " - f"(revalidated {record.last_validated_at.isoformat()})." - ) - # This branch is deliberately terse, but a failed re-upload is the one thing it - # cannot stay quiet about: without the warning, the exit code says the record was - # not written and nothing says why. Passes are skipped because the "Recorded to - # fileset ..." line below already reports them. - for finding in result.memory_findings: - if finding.status != "pass": - _echo_finding(finding) - else: - findings = [*record.findings, *result.memory_findings] - for group in _GROUP_ORDER: - for finding in (item for item in findings if item.group == group): - _echo_finding(finding) + findings = [*record.findings, *result.memory_findings] + for group in _GROUP_ORDER: + for finding in (item for item in findings if item.group == group): + _echo_finding(finding) typer.echo("") target = run_target(record) @@ -118,33 +104,21 @@ def discover( str | None, typer.Option("--agent", help="Agent name. Defaults to optimizer.yaml, else the directory name."), ] = None, - fix: Annotated[ - bool, - typer.Option( - "--dangerously-fix", - help=( - "Let an LLM scout propose fixes for a config Harbor rejected. The scout runs shell " - "commands in the repo under inspection with no sandbox. Only use it on a repo you trust." - ), - ), - ] = False, - refresh: Annotated[ - bool, - typer.Option("--refresh", help="Revalidate even when nothing the last report depended on moved."), - ] = False, dry_run: Annotated[ bool, typer.Option("--dry-run", help="Print the findings and config without uploading anything."), ] = False, ) -> None: - """Find and validate how this repo runs Harbor evals, then record it.""" + """Find and validate how this repo runs Harbor evals, then record it. + + Validating a config imports the repo's agent module into this process, which runs + that module's top level. Only point this at a repo you trust. + """ result = asyncio.run( discovery.discover( discovery.DiscoverOptions( repo_root=repo, agent=agent, - fix=fix, - refresh=refresh, dry_run=dry_run, ) ) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py deleted file mode 100644 index 58337e96558..00000000000 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/agent.py +++ /dev/null @@ -1,205 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""A bounded scout that proposes a config when the ladder cannot get one. - -Only reached when validation failed on something a look around the repo could plausibly -settle: which directory is the dataset rather than the single-task template, what the -wrapper's class is actually called, which of two plausible entrypoints is the real one. - -The scout's output is a proposal and never a result. Whatever it returns goes back through -the ladder from the schema rung, and a config it touched is persisted only if Harbor then -accepts it. That ordering is the whole reason a later, weaker model can trust the artifact: -the strong model is allowed to guess, and Harbor decides whether the guess was right. - -Importing this module builds an LLM client, because ``Agent`` binds ``llm`` while the class -body executes. The CLI therefore imports it inside the command body rather than at module -scope, so ``nemo eval-author discover`` on a repo that needs no scouting works with no -``AUTHOR_*`` credentials at all. -""" - -import json -import logging -from collections.abc import Awaitable, Callable -from pathlib import Path -from typing import Any - -# Populates EXPERIMENTALIST_* from AUTHOR_*, which the Experimentalist modules imported -# below read while their class bodies execute. Must stay ahead of them; isort keeps it there. -import nemo_eval_author_plugin._env_bridge # noqa: F401 -from nemo_eval_author_plugin.discovery.models import CandidateConfig, ConfigSource, Finding -from nemo_eval_author_plugin.discovery.validate import ValidationOutcome, run_ladder -from nemo_eval_author_plugin.model_config import get_smart_model -from nemo_experimentalist_plugin.experimentalist.components.tools import GuardedShellTools -from nooa import Agent, CodeActStrategy, strategy -from nooa.config import CodeActConfig -from pydantic import BaseModel, Field - -logger = logging.getLogger(__name__) - -_GROUP = "scout" - -# The rungs a look at the filesystem could plausibly resolve. A backend preflight failure -# means Docker is not running, and no amount of reading the repo fixes that. -_SCOUTABLE_RUNGS = frozenset({"schema", "resolution", "tasks", "agent", "config-source"}) - - -class ScoutProposal(BaseModel): - """A config the scout believes will validate, plus its reasoning.""" - - config: dict[str, Any] = Field(description="A complete Harbor job config payload, not a patch.") - rationale: str = Field(description="What was inspected and why this config follows from it.") - changed: list[str] = Field(default_factory=list, description="The keys that differ from the input config.") - - -ProposeFn = Callable[[CandidateConfig, list[Finding], Path], Awaitable[ScoutProposal]] - - -class DiscoveryScout(Agent, llm=get_smart_model()): - """Reads an agent repository to work out how its Harbor evaluations are meant to run.""" - - def __init__(self, repo_root: Path, **kwargs: Any) -> None: - super().__init__(**kwargs) - self.repo_root = repo_root - self.shell = GuardedShellTools(cwd=repo_root) - - @strategy(CodeActStrategy(config=CodeActConfig(max_iterations=20, cell_timeout=60.0))) - async def propose_config(self, candidate: str, blocking: str) -> ScoutProposal: - """Work out the Harbor job config this repository actually intends. - - A candidate config was assembled from the repository and rejected by Harbor's own - validators. Use the shell to inspect the repository and return a config that will - pass. - - Args: - candidate: The rejected Harbor job config, as JSON. - blocking: The validation failures, each naming the Harbor call that produced it. - - Returns: - ScoutProposal: A complete config payload, the keys changed, and the reasoning. - - Ground every change in something read from the filesystem: a directory that holds - `task.toml` files, a class definition in a wrapper module, a path named in a config - or README. Do not invent dataset paths, task names, agent import paths, or model - names, and do not add fields the repository gives no evidence for. - - A config returned unchanged with the rationale explaining what is missing is a - useful answer. A plausible-looking guess is not: this proposal is revalidated - against Harbor, and a wrong guess costs another round trip while an honest "the - repository does not say" tells the user what to fix. - """ - - async def scout(self, candidate: CandidateConfig, blocking: list[Finding]) -> ScoutProposal: - summary = "\n".join( - f"- {finding.name}: {finding.message}" + (f" (from {finding.harbor_call})" if finding.harbor_call else "") - for finding in blocking - ) - return await self.propose_config(json.dumps(candidate.data, indent=2, sort_keys=True), summary) - - -def is_scoutable(outcome: ValidationOutcome) -> bool: - """Whether any failure is the kind reading the repo could plausibly settle.""" - return any(finding.name in _SCOUTABLE_RUNGS for finding in outcome.findings if finding.status == "fail") - - -async def _ask_the_scout(candidate: CandidateConfig, blocking: list[Finding], repo_root: Path) -> ScoutProposal: - return await DiscoveryScout(repo_root=repo_root).scout(candidate, blocking) - - -async def attempt_repair( - candidate: CandidateConfig, - outcome: ValidationOutcome, - repo_root: Path, - propose: ProposeFn = _ask_the_scout, -) -> tuple[CandidateConfig, ValidationOutcome, list[Finding]]: - """Let the scout propose a config, then make Harbor judge it. - - Returns the proposal and its validation only if the ladder is happier with it than - with what we had. "Happier" means runnable, not merely different: a proposal that - trades one failure for another is noise, and keeping the original at least leaves the - user with failures traceable to their own repo rather than to a language model. - - ``propose`` is a parameter so this containment logic can be tested without a model. - It is the part worth testing: nooa refuses to let a test attach a method to an agent - class, and the interesting behavior here is what happens to a proposal, not how one is - produced. - """ - blocking = [finding for finding in outcome.findings if finding.status == "fail"] - try: - proposal = await propose(candidate, blocking, repo_root) - except Exception as exc: - logger.debug("discovery scout failed", exc_info=True) - return ( - candidate, - outcome, - [ - Finding( - name="scout", - group=_GROUP, - status="warn", - message=f"The scout could not run: {type(exc).__name__}: {exc}", - hint="Set AUTHOR_API_KEY and AUTHOR_BASE_URL, or drop --dangerously-fix to skip this step.", - provenance="inference", - ) - ], - ) - - if proposal.config == candidate.data: - return ( - candidate, - outcome, - [ - Finding( - name="scout", - group=_GROUP, - status="warn", - message=f"The scout found nothing in the repo to change: {proposal.rationale}", - provenance="inference", - ) - ], - ) - - proposed = CandidateConfig( - data=proposal.config, - source=ConfigSource( - kind=candidate.source.kind, - detail=f"{candidate.source.detail}, then adjusted by the discovery scout", - path=candidate.source.path, - # Even when the source was the repo's own config file, the artifact can no - # longer point at it: what Harbor accepted is the scout's version. - adjusted=True, - ), - ) - revalidated = await run_ladder(proposed, repo_root) - changed = ", ".join(proposal.changed) if proposal.changed else "unspecified keys" - - if not revalidated.runnable: - return ( - candidate, - outcome, - [ - Finding( - name="scout", - group=_GROUP, - status="warn", - message=f"The scout proposed changes to {changed}, and Harbor still rejected the result", - hint=f"Its reasoning: {proposal.rationale}", - provenance="inference", - ) - ], - ) - - return ( - proposed, - revalidated, - [ - Finding( - name="scout", - group=_GROUP, - status="pass", - message=f"The scout changed {changed}, and Harbor accepted the result", - hint=f"Its reasoning: {proposal.rationale}", - provenance="inference", - ) - ], - ) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py index d599eb3d615..bbbe9f96283 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py @@ -1,51 +1,27 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Persist discovery to a fileset, and read back what a previous run concluded. +"""Persist discovery to a fileset. One fixed fileset with agent-scoped paths, following the telemetry exporter's precedent of ``nemo-agent-telemetry`` plus ``{agent}/...``. Nothing is written into the user's repo: the repo is the thing under inspection, and a command that inspects a repo should not change it. -The read side is what makes discovery cheap to repeat. A prior report lists the files it was -derived from along with their hashes, so a re-run can re-hash exactly those paths and -compare one digest, deciding whether anything relevant moved without touching Harbor. That -is the same property that lets a later, weaker model trust the artifact instead of -rediscovering it. - ``harbor-job.yaml`` is uploaded only when it exists, and it only exists when Harbor accepted the schema. A config that is present in the fileset is therefore a config Harbor could load, which is the invariant the whole artifact rests on. """ -from datetime import datetime -from pathlib import Path from typing import Any -import yaml from nemo_eval_author_plugin.discovery.models import ( FILESET_NAME, JOB_CONFIG_FILENAME, REPORT_FILENAME, Finding, - InputFingerprint, ) -from nemo_eval_author_plugin.discovery.report import fingerprint_inputs -from pydantic import BaseModel, Field, ValidationError _GROUP = "memory" -_FRONT_MATTER_FENCE = "---" - - -class PriorRecord(BaseModel): - """The parts of a previously persisted report that decide whether to redo the work.""" - - inputs_digest: str | None = None - runnable: bool = False - harbor_version: str | None = None - last_validated_at: str | None = None - inputs: list[InputFingerprint] = Field(default_factory=list) - text: str = Field(default="", description="The report as stored, so a fresh re-run can restamp and reupload it.") def remote_report_path(agent: str) -> str: @@ -56,111 +32,6 @@ def remote_config_path(agent: str) -> str: return f"{agent}/{JOB_CONFIG_FILENAME}" -def _split_front_matter(text: str) -> tuple[str, str] | None: - """Separate the front matter from the body, or ``None`` if there is no front matter. - - One implementation for both readers, because the fence is easy to miscount: the - closing ``\\n---`` is consumed by the split, so the body it returns still carries the - blank line that followed it and can be concatenated straight back on. - """ - if not text.startswith(_FRONT_MATTER_FENCE): - return None - head, _, body = text.partition(f"\n{_FRONT_MATTER_FENCE}") - if not _: - return None - return head[len(_FRONT_MATTER_FENCE) :], body - - -def parse_front_matter(text: str) -> dict[str, Any] | None: - """Pull the YAML front matter out of a rendered report.""" - split = _split_front_matter(text) - if split is None: - return None - try: - payload = yaml.safe_load(split[0]) - except yaml.YAMLError: - return None - return payload if isinstance(payload, dict) else None - - -async def load_previous(sdk: Any, *, agent: str, workspace: str) -> PriorRecord | None: - """Fetch the last report for this agent, or ``None`` when there is nothing to compare. - - A missing file and an unreachable platform are the same answer here: rediscover. That - is why every failure mode returns ``None`` rather than raising. - """ - try: - raw = await sdk.files.download_content( - remote_path=remote_report_path(agent), - fileset=FILESET_NAME, - workspace=workspace, - ) - except Exception: - return None - - try: - text = raw.decode("utf-8") if isinstance(raw, bytes) else str(raw) - except UnicodeError: - return None - - front = parse_front_matter(text) - if front is None: - return None - - inputs = [ - InputFingerprint(path=str(item["path"]), sha256=str(item["sha256"])) - for item in front.get("inputs") or [] - if isinstance(item, dict) and "path" in item and "sha256" in item - ] - try: - return PriorRecord( - inputs_digest=front.get("inputs_digest"), - # Identity rather than truthiness: only a real YAML boolean may switch off - # revalidation. An unquoted timestamp or version loads as a datetime or a float - # and would fail validation, so a hand-edited report is rediscovered, not trusted. - runnable=front.get("runnable") is True, - harbor_version=front.get("harbor_version"), - last_validated_at=front.get("last_validated_at"), - inputs=inputs, - text=text, - ) - except ValidationError: - return None - - -def restamp(text: str, *, when: datetime, harbor_version: str) -> str | None: - """Update a stored report's validation stamp without regenerating its narrative. - - Used when nothing the report depends on has changed: the findings would come out - word for word, so re-deriving them would only spend a Harbor resolution and a Docker - preflight to reprint the same file. The stamp still has to move, because - ``last_validated_at`` answers "when did someone last confirm this", and the Harbor - version has to move with it, since confirming under a different Harbor is a different - claim. - - Returns ``None`` when the front matter cannot be re-serialized, which tells the caller - to fall back to a full re-render rather than upload something malformed. - """ - split = _split_front_matter(text) - front = parse_front_matter(text) - if split is None or front is None: - return None - front["last_validated_at"] = when.isoformat() - front["harbor_version"] = harbor_version - rendered = yaml.safe_dump(front, sort_keys=False, default_flow_style=False).rstrip() - return f"{_FRONT_MATTER_FENCE}\n{rendered}\n{_FRONT_MATTER_FENCE}{split[1]}" - - -def rehash_prior_inputs(prior: PriorRecord, repo_root: Path) -> list[InputFingerprint]: - """Re-hash the files a prior report named, so its digest can be recomputed today. - - A path the prior run recorded and that no longer exists is dropped, which changes the - digest and correctly forces revalidation: a report derived from a file someone deleted - is exactly the kind of stale claim this comparison exists to catch. - """ - return fingerprint_inputs([repo_root / item.path for item in prior.inputs], repo_root) - - async def persist( sdk: Any, *, @@ -172,8 +43,8 @@ async def persist( """Upload the report, and the config when the caller passed one. Reports only what it did. Why a config might be absent is the caller's to explain — - withheld because nothing validated, not needed because the repo maintains its own, - already stored by an earlier run — and a message here could only guess between them. + withheld because nothing validated, or not needed because the repo maintains its own — + and a message here could only guess between them. Returns whether everything landed. Upload failures are reported as warnings rather than failures, because ``runnable`` answers one question only — can Harbor run this diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py index 7e7d8a816fd..472178dc402 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py @@ -3,20 +3,12 @@ """Result types for ``nemo eval-author discover``. -The command exists so that a later, cheaper model can run a Harbor eval without -rediscovering anything, which only works if every claim in the output is traceable to -whoever established it. That is what ``Finding.harbor_call`` and ``Finding.provenance`` -are for: a reader can tell a verdict Harbor's own code returned from a path we merely -observed on disk, and both from something a language model guessed. A report whose -findings are all ``provenance="inference"`` is a report to distrust. - -Shaped after ``CheckResult`` in ``nemo_insights_plugin.contracts.checks`` but defined -here, because a finding carries the artifact it is about and the Harbor call that judged -it, and a readiness check carries neither. +``Finding.harbor_call`` names the Harbor API or CLI that returned a verdict. A finding +without one was observed directly rather than judged by Harbor, which is the difference +between "Harbor rejected this config" and "we read this off the filesystem". Both the CLI +and the report render the call, so the distinction reaches the reader. """ -import hashlib -import json from datetime import datetime from pathlib import Path from typing import Any, Literal @@ -31,16 +23,6 @@ Status = Literal["pass", "warn", "fail"] -Provenance = Literal["harbor", "filesystem", "inference"] -"""Who established a finding. - -``harbor`` a Harbor API or CLI returned this verdict, so it is as true as the run - would be. Always paired with ``harbor_call``. -``filesystem`` we observed it directly (a file exists, a name matched). -``inference`` the scout proposed it. Never load-bearing on its own: a proposal has to - come back through the validation ladder before it can be persisted. -""" - SourceKind = Literal["config_file", "prior_job", "profile", "convention"] """Where a candidate job config came from. @@ -69,7 +51,6 @@ class Finding(BaseModel): default=None, description="The Harbor API or CLI that returned this verdict, when one did.", ) - provenance: Provenance = "filesystem" class ConfigSource(BaseModel): @@ -78,10 +59,6 @@ class ConfigSource(BaseModel): kind: SourceKind detail: str path: Path | None = None - adjusted: bool = Field( - default=False, - description="Whether the validated payload has diverged from the file at ``path``.", - ) @property def rank(self) -> int: @@ -89,16 +66,14 @@ def rank(self) -> int: @property def owns_file(self) -> bool: - """Whether the repo maintains the config file we validated, unchanged. + """Whether the repo maintains the config file we validated. The one case where discovery has nothing of its own to persist: the file already - exists, someone maintains it, and Harbor accepted exactly its contents. Shipping a - second copy would create a config nobody owns and that drifts the moment the real - one is edited. ``prior_job`` is excluded even though it has a path, because that - path is a record Harbor wrote inside a job's output directory rather than an input - anyone maintains. + exists, someone maintains it, and Harbor accepted exactly its contents. ``prior_job`` + is excluded even though it has a path, because that path is a record Harbor wrote + inside a job's output directory rather than an input anyone maintains. """ - return self.kind == "config_file" and self.path is not None and not self.adjusted + return self.kind == "config_file" and self.path is not None class CandidateConfig(BaseModel): @@ -121,10 +96,6 @@ class RunTarget(BaseModel): ``--task`` name registry packages, so a filesystem path handed to either is read as a package reference. A repo full of task dirs and no config file therefore cannot be run as-is, which is why discovery writes one when the repo does not. - - ``location`` spares the reader from deciding which case they are in: ``repo`` means the - path is relative to ``repo_root`` and already on disk, ``fileset`` means it is a remote - path in ``FILESET_NAME`` to fetch first. """ location: Literal["repo", "fileset"] @@ -132,37 +103,13 @@ class RunTarget(BaseModel): class RequiredEnvVar(BaseModel): - """A host variable a task config templates as ``${VAR}`` or ``${VAR:-default}``. - - Discover records the name and where it was declared. Whether this machine has a - value for it is ``doctor``'s question, not ours. - """ + """A host variable a task config templates as ``${VAR}`` or ``${VAR:-default}``.""" name: str default: str | None = None declared_in: Path -class InputFingerprint(BaseModel): - """A file the report was derived from, so a re-run can tell what moved.""" - - path: str - sha256: str - - -def digest_inputs(inputs: list[InputFingerprint]) -> str: - """Hash a set of input fingerprints, order-independently. - - A free function and not just a property, because the freshness check runs it against - the inputs a *previous* report listed, before this run has a report of its own. Both - sides must hash identically or the comparison is meaningless, so there is one - implementation. Canonical JSON matches the digest style in ``materialization.py``. - """ - payload = [[item.path, item.sha256] for item in sorted(inputs, key=lambda item: item.path)] - canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False) - return f"sha256:{hashlib.sha256(canonical.encode('utf-8')).hexdigest()}" - - class DiscoveryReport(BaseModel): """Everything a later run needs to trust or redo this discovery.""" @@ -177,24 +124,12 @@ class DiscoveryReport(BaseModel): config_source: ConfigSource | None = None findings: list[Finding] = Field(default_factory=list) required_env_vars: list[RequiredEnvVar] = Field(default_factory=list) - inputs: list[InputFingerprint] = Field(default_factory=list) discovered_at: datetime - last_validated_at: datetime @property def blocking(self) -> list[Finding]: return [finding for finding in self.findings if finding.status == "fail"] - @property - def inputs_digest(self) -> str: - """One hash over every input, so a re-run can skip the ladder in a single compare. - - Derived rather than stored: a digest that can disagree with the list it summarizes - is worse than no digest, because the whole point is deciding whether to trust the - file without redoing the work. - """ - return digest_inputs(self.inputs) - @property def runnable(self) -> bool: """True only when a config was found and nothing about it failed. diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py index dfaa51468ed..97aafe8421d 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py @@ -4,21 +4,18 @@ """Render the two artifacts discover persists. ``harbor-job.yaml`` is the config a later agent hands to Harbor. ``discovery.md`` is the -story around it: which source won, what every rung of the ladder concluded, what a run +record around it: which source won, what every rung of the ladder concluded, what a run needs from the host, and what is blocking when something is. -The markdown leads with front matter rather than prose because the first reader is a -program. ``runnable`` and ``inputs_digest`` are what let a later run skip everything here: -if the digest still matches and the flag is true, nothing about the repo that produced this -verdict has moved. +The markdown leads with front matter because the first reader is a program: ``runnable`` +and ``run_config`` are the whole machine-readable contract, and the body below them is a +short human summary of the same thing. Paths in the persisted config are rewritten relative to the repo root. An absolute path would encode this machine into an artifact meant to outlive it, so the config is written to be run from ``repo_root``, and the front matter records where that is. """ -import hashlib -import json from datetime import UTC, datetime from importlib.metadata import PackageNotFoundError, version from pathlib import Path @@ -27,12 +24,10 @@ import yaml from harbor.models.job.config import JobConfig from nemo_eval_author_plugin.discovery.models import ( - FILESET_NAME, JOB_CONFIG_FILENAME, CandidateConfig, DiscoveryReport, Finding, - InputFingerprint, RequiredEnvVar, RunTarget, ) @@ -53,22 +48,6 @@ def harbor_version() -> str: return "unknown" -def fingerprint_inputs(paths: list[Path], repo_root: Path) -> list[InputFingerprint]: - """Hash every file a verdict was derived from, deduped and ordered for stability.""" - seen: dict[str, str] = {} - for path in paths: - if not path.is_file(): - continue - key = display_path(path, repo_root) - if key in seen: - continue - try: - seen[key] = hashlib.sha256(path.read_bytes()).hexdigest() - except OSError: - continue - return [InputFingerprint(path=key, sha256=seen[key]) for key in sorted(seen)] - - def build_report( *, agent: str, @@ -77,11 +56,8 @@ def build_report( candidate: CandidateConfig | None, findings: list[Finding], required_env_vars: list[RequiredEnvVar], - inputs: list[InputFingerprint], discovered_at: datetime | None = None, - last_validated_at: datetime | None = None, ) -> DiscoveryReport: - now = discovered_at or datetime.now(UTC) return DiscoveryReport( agent=agent, workspace=workspace, @@ -90,9 +66,7 @@ def build_report( config_source=candidate.source if candidate is not None else None, findings=findings, required_env_vars=required_env_vars, - inputs=inputs, - discovered_at=now, - last_validated_at=last_validated_at or now, + discovered_at=discovered_at or datetime.now(UTC), ) @@ -138,6 +112,7 @@ def render_markdown(report: DiscoveryReport) -> str: def _front_matter(report: DiscoveryReport) -> dict[str, Any]: source = report.config_source + target = run_target(report) return { "schema_version": report.schema_version, "agent": report.agent, @@ -149,14 +124,11 @@ def _front_matter(report: DiscoveryReport) -> dict[str, Any]: "kind": source.kind, "detail": source.detail, "path": display_path(source.path, report.repo_root) if source.path else None, - # Carried so a reused report resolves to the same run_config. Without it, a - # repo whose config we had to adjust would read back as ours to run. - "adjusted": source.adjusted, } if source is not None else None ), - "run_config": (target.model_dump() if (target := run_target(report)) is not None else None), + "run_config": target.model_dump() if target is not None else None, "validation": {finding.name: finding.status for finding in report.findings if finding.group == "validation"}, "harbor_version": report.harbor_version, "required_env_vars": [ @@ -168,93 +140,43 @@ def _front_matter(report: DiscoveryReport) -> dict[str, Any]: for item in report.required_env_vars ], "discovered_at": report.discovered_at.isoformat(), - "last_validated_at": report.last_validated_at.isoformat(), - "inputs_digest": report.inputs_digest, - "inputs": [{"path": item.path, "sha256": item.sha256} for item in report.inputs], } def _body(report: DiscoveryReport) -> list[str]: lines = [f"# Harbor eval setup for `{report.agent}`", ""] lines += _verdict_section(report) - lines += _how_to_run_section(report) - lines += _validation_section(report) + lines += _findings_section(report) lines += _env_section(report) - lines += _repo_section(report) - lines += _inputs_section(report) return lines def _verdict_section(report: DiscoveryReport) -> list[str]: - target = run_target(report) - if target is not None: - source = report.config_source - detail = source.detail if source is not None else "unknown" - return [ - f"Harbor can run this repo's evals. The config was {detail}, and every check in " - f"*What Harbor checked* below was answered by Harbor {report.harbor_version} rather " - "than inferred.", - "", - ] - - lines = ["**Harbor cannot run this repo's evals yet.** Blocking:", ""] - for finding in report.blocking: - lines.append(f"- **{finding.name}** — {finding.message}") - if finding.harbor_call: - lines.append(f" - reported by `{finding.harbor_call}`") - if finding.hint: - lines.append(f" - {finding.hint}") - lines.append("") - if report.config_source is None: - lines += [ - "No config could be assembled at all, so there is nothing to fix incrementally. " - "Start with `harbor job init` and rerun discovery.", - "", - ] - else: - lines += [ - f"`{JOB_CONFIG_FILENAME}` is not part of this record: a config is only persisted " - "once Harbor accepts its schema, so its absence means do not try to run one.", - "", - ] - return lines - - -def _how_to_run_section(report: DiscoveryReport) -> list[str]: target = run_target(report) if target is None: - return [] - lines = [ - "## Running it", - "", - "Harbor runs local task directories through `-c` and no other way: `--dataset` and " - "`--task` name registry packages, so a filesystem path given to either is read as a " - "package reference. The config below is that file.", - "", - ] + lines = ["**Harbor cannot run this repo's evals yet.** Blocking:", ""] + for finding in report.blocking: + lines.append(f"- **{finding.name}** — {finding.message}") + if finding.harbor_call: + lines.append(f" - reported by `{finding.harbor_call}`") + if finding.hint: + lines.append(f" - {finding.hint}") + return [*lines, ""] + + source = report.config_source if target.location == "repo": config_arg = target.path - lines += [ - f"This repo maintains its own config at `{config_arg}`, and that file is what Harbor " - f"accepted here, so run it rather than a copy of it. From `{report.repo_root}`, " - "because its paths are relative to the repo:", - "", - ] + where = f"From `{report.repo_root}`, because the config's paths are relative to it:" else: config_arg = JOB_CONFIG_FILENAME - lines += [ - "Nothing in this repo declares a Harbor job config, so discovery wrote the one it " - f"validated. Fetch it into `{report.repo_root}`, the directory its relative paths " - "assume:", - "", - "```bash", - f"nemo files download {FILESET_NAME} --workspace {report.workspace} --remote-path {target.path} -o .", - "```", - "", - "Then, from that same directory:", - "", - ] - lines += [ + where = f"Fetch `{target.path}` from the `{report.workspace}` workspace into `{report.repo_root}`, then:" + + lines = [ + f"Harbor {report.harbor_version} can run this repo's evals. The config was " + f"{source.detail if source is not None else 'unknown'}.", + "", + where, + "", "```bash", f"harbor job start -c {config_arg}", "```", @@ -263,83 +185,39 @@ def _how_to_run_section(report: DiscoveryReport) -> list[str]: if report.required_env_vars: names = " ".join(f"{item.name}=..." for item in report.required_env_vars) lines += [f"Set the host variables first: `{names}`", ""] - lines += [ - "To confirm the tasks are solvable before trusting any agent's score, run Harbor's " - "oracle, which replays each task's own solution and should score 1.0:", - "", - "```bash", - f"harbor run -a oracle -c {config_arg}", - "```", - "", - "Discovery does not run this itself, because unlike every check above it builds and starts containers.", - "", - ] return lines -def _validation_section(report: DiscoveryReport) -> list[str]: - rungs = [finding for finding in report.findings if finding.group == "validation"] - if not rungs: - return [] - lines = [ - "## What Harbor checked", - "", - "Each line is a Harbor call, so a failure here is the error a real run would hit.", - "", - ] - for finding in rungs: - lines.append(f"- `{_STATUS_MARK[finding.status]}` **{finding.name}**: {finding.message}") - if finding.harbor_call: - lines.append(f" - via `{finding.harbor_call}`") - if finding.hint: - lines.append(f" - {finding.hint}") - lines.append("") +def _findings_section(report: DiscoveryReport) -> list[str]: + groups = [("validation", "What Harbor checked"), ("repo", "Repo shape")] + lines: list[str] = [] + for group, heading in groups: + items = [finding for finding in report.findings if finding.group == group] + if not items: + continue + lines += [f"## {heading}", ""] + for finding in items: + call = f" (`{finding.harbor_call}`)" if finding.harbor_call else "" + lines.append(f"- `{_STATUS_MARK[finding.status]}` **{finding.name}**: {finding.message}{call}") + if finding.hint: + lines.append(f" - {finding.hint}") + lines.append("") return lines def _env_section(report: DiscoveryReport) -> list[str]: if not report.required_env_vars: - return ["## Host variables", "", "The config templates no host variables.", ""] + return [] lines = [ "## Host variables", "", - "Harbor resolves these from the environment at trial start and raises on a missing " - "one. Whether this machine has them is a separate question, which `nemo eval-author " - "doctor` answers.", + "Harbor resolves these from the environment at trial start and raises on a missing one.", "", ] for item in report.required_env_vars: default = f", default `{item.default}`" if item.default is not None else ", no default" lines.append(f"- `{item.name}`{default} — declared in `{display_path(item.declared_in, report.repo_root)}`") - lines.append("") - return lines - - -def _repo_section(report: DiscoveryReport) -> list[str]: - probes = [finding for finding in report.findings if finding.group == "repo"] - if not probes: - return [] - lines = [ - "## Repo shape", - "", - "Context for authoring evals rather than running them, so nothing here blocks a run.", - "", - ] - for finding in probes: - lines.append(f"- `{_STATUS_MARK[finding.status]}` **{finding.name}**: {finding.message}") - lines.append("") - return lines - - -def _inputs_section(report: DiscoveryReport) -> list[str]: - return [ - "## Freshness", - "", - f"Derived from {len(report.inputs)} file(s), digest `{report.inputs_digest}`. Rerun " - "`nemo eval-author discover` to compare: an unchanged digest means these verdicts " - "still hold and the ladder can be skipped.", - "", - ] + return [*lines, ""] def _relativize(payload: Any, repo_root: Path) -> Any: @@ -361,9 +239,3 @@ def _relativize(payload: Any, repo_root: Path) -> Any: if payload.startswith(prefix): return Path(payload).relative_to(repo_root).as_posix() return payload - - -def canonical_digest(value: Any) -> str: - """Hash a structure the way the rest of this plugin does, for cross-run comparison.""" - canonical = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False) - return f"sha256:{hashlib.sha256(canonical.encode('utf-8')).hexdigest()}" diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py index 2e62458646a..512551e2a86 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -3,30 +3,23 @@ """Orchestration for ``nemo eval-author discover``. -Assemble a candidate config, let Harbor judge it, scout only if that fails on something a -look at the repo could settle, then persist. Sequenced so the expensive and side-effecting -work happens as late and as rarely as possible: the freshness check can skip the ladder -entirely, and the scout runs only after the ladder has failed. +Assemble a candidate config, let Harbor judge it, then persist what it concluded. Kept apart from ``cli.py`` so it can be tested without a ``CliRunner`` and so the CLI holds nothing but flags, printing, and the exit code. ``make_client`` is a module global for the same reason it is in ``eval_author/run.py``: tests replace it. """ -import logging import re import tempfile -from dataclasses import dataclass, field, replace -from datetime import UTC, datetime +from dataclasses import dataclass, field from pathlib import Path from nemo_eval_author_plugin.discovery import memory, report, scan, sources, validate from nemo_eval_author_plugin.discovery.models import ( JOB_CONFIG_FILENAME, - CandidateConfig, DiscoveryReport, Finding, - digest_inputs, ) from nemo_eval_author_plugin.discovery.validate import ValidationOutcome from nemo_experimentalist_plugin.client import make_client @@ -34,8 +27,6 @@ from nemo_platform import AsyncNeMoPlatform from nemo_platform.config.config import Config -logger = logging.getLogger(__name__) - _SLUG_PATTERN = re.compile(r"[^a-z0-9]+") @@ -51,8 +42,6 @@ class DiscoverOptions: repo_root: Path agent: str | None = None - fix: bool = False - refresh: bool = False dry_run: bool = False @@ -64,7 +53,6 @@ class DiscoverResult: markdown: str job_config: str | None = None persisted: bool = False - reused: bool = False dry_run: bool = False memory_findings: list[Finding] = field(default_factory=list) @@ -112,19 +100,10 @@ def _active_workspace() -> str: async def _discover( client: AsyncNeMoPlatform, options: DiscoverOptions, *, repo_root: Path, agent: str, workspace: str ) -> DiscoverResult: - prior = await memory.load_previous(client, agent=agent, workspace=workspace) - - reuse = _reusable(prior, repo_root, refresh=options.refresh) - if reuse is not None: - return await _reuse(client, options, agent=agent, workspace=workspace, prior=reuse) - candidate, findings = sources.find_candidate(repo_root) outcome = ValidationOutcome() if candidate is not None: outcome = await validate.run_ladder(candidate, repo_root) - if not outcome.runnable and options.fix: - candidate, outcome, scout_findings = await _scout(candidate, outcome, repo_root) - findings.extend(scout_findings) findings.extend(outcome.findings) findings.extend(await _probe_repo(client, repo_root, agent=agent, workspace=workspace)) @@ -148,7 +127,6 @@ async def _discover( candidate=candidate, findings=findings, required_env_vars=outcome.required_env_vars, - inputs=report.fingerprint_inputs(_input_paths(repo_root, candidate, outcome), repo_root), ) # A config only travels with a report that vouches for it. The schema rung can pass # while a later rung fails, and shipping the config anyway would put a file in the @@ -170,8 +148,7 @@ async def _discover( memory_findings.append( Finding( # Not "upload": withholding is a decision, and memory.persist uses that name - # for an upload that actually broke. One name for both invites a filter that - # silences real failures. + # for an upload that actually broke. name="config-withheld", group="memory", status="warn", @@ -188,94 +165,12 @@ async def _discover( ) -def _reusable(prior: memory.PriorRecord | None, repo_root: Path, *, refresh: bool) -> memory.PriorRecord | None: - """Whether the prior report still describes this repo, so the ladder can be skipped. - - Only ever reuses a report that was runnable. A prior failure is worth re-deriving even - on identical inputs, because the reason it failed may have been the machine rather than - the repo: Docker was not running, a cloud extra was missing. - """ - if prior is None or refresh or not prior.runnable or not prior.inputs: - return None - if digest_inputs(memory.rehash_prior_inputs(prior, repo_root)) != prior.inputs_digest: - return None - return prior - - -async def _reuse( - client: AsyncNeMoPlatform, options: DiscoverOptions, *, agent: str, workspace: str, prior: memory.PriorRecord -) -> DiscoverResult: - """Restamp and reupload a report whose inputs have not moved.""" - now = datetime.now(UTC) - restamped = memory.restamp(prior.text, when=now, harbor_version=report.harbor_version()) - if restamped is None: - logger.debug("prior report could not be restamped; falling through to a full discovery") - return await _discover( - client, - replace(options, refresh=True), - repo_root=options.repo_root.resolve(), - agent=agent, - workspace=workspace, - ) - - front = memory.parse_front_matter(restamped) or {} - record = DiscoveryReport.model_validate( - { - "agent": agent, - "workspace": workspace, - "repo_root": front.get("repo_root", str(options.repo_root)), - "harbor_version": front.get("harbor_version", report.harbor_version()), - "config_source": front.get("config_source"), - # Restored because the CLI prints "Needs: ..." from it, and a repeat run that - # dropped it would tell the user to start a job without naming the variables - # Harbor raises on. ``or []`` degrades an explicit null rather than failing. - "required_env_vars": front.get("required_env_vars") or [], - "discovered_at": front.get("discovered_at", now), - "last_validated_at": now, - "inputs": [item.model_dump() for item in prior.inputs], - } - ) - if options.dry_run: - return DiscoverResult(report=record, markdown=restamped, reused=True, dry_run=True) - - persisted, memory_findings = await memory.persist( - client, - agent=agent, - workspace=workspace, - markdown=restamped, - # The stored config is already correct and already uploaded; rewriting it would - # churn the fileset to produce identical bytes. - job_config=None, - ) - return DiscoverResult( - report=record, - markdown=restamped, - persisted=persisted, - reused=True, - memory_findings=memory_findings, - ) - - -async def _scout( - candidate: CandidateConfig, outcome: ValidationOutcome, repo_root: Path -) -> tuple[CandidateConfig, ValidationOutcome, list[Finding]]: - """Hand a failed ladder to the scout, importing it only if we actually need it. - - The import builds an LLM client while the module's class body executes, so deferring it - is what keeps ``discover`` usable on a healthy repo with no ``AUTHOR_*`` credentials. - """ - from nemo_eval_author_plugin.discovery.agent import attempt_repair, is_scoutable - - if not is_scoutable(outcome): - return candidate, outcome, [] - return await attempt_repair(candidate, outcome, repo_root) - - async def _probe_repo(client: AsyncNeMoPlatform, repo_root: Path, *, agent: str, workspace: str) -> list[Finding]: - _, doctrine = scan.find_doctrine(repo_root) - _, skills = scan.find_skills(repo_root) - traces = await scan.probe_traces(client, agent=agent, workspace=workspace) - return [doctrine, skills, traces] + return [ + scan.find_doctrine(repo_root), + scan.find_skills(repo_root), + await scan.probe_traces(client, agent=agent, workspace=workspace), + ] def _round_trip(job_config: str, repo_root: Path) -> Finding: @@ -291,48 +186,6 @@ def _round_trip(job_config: str, repo_root: Path) -> Finding: return validate.check_config_file(config_path, repo_root) -def _input_paths(repo_root: Path, candidate: CandidateConfig | None, outcome: ValidationOutcome) -> list[Path]: - """Every file a verdict in this report was derived from. - - The freshness check is only as good as this list: a file that shaped a conclusion but - is missing here means a later run reports "nothing changed" after someone changed it. - """ - paths: list[Path] = [] - if candidate is not None and candidate.source.path is not None: - paths.append(candidate.source.path) - - profile = discover_profile(repo_root) - if profile is not None: - paths.append(profile) - - for name in ("ETHOS.md", "AGENT-SPEC.md", "README.md"): - paths.append(repo_root / name) - - for task_dir in outcome.task_dirs: - paths.append(task_dir / "task.toml") - paths.extend(sorted((task_dir / "tests").glob("test.*"))) - - if outcome.config is not None: - for agent_config in outcome.config.agents: - if agent_config.import_path: - module = agent_config.import_path.split(":", 1)[0].split(".", 1)[0] - paths.extend(_module_files(repo_root, module)) - return paths - - -def _module_files(repo_root: Path, module: str) -> list[Path]: - """Every ``{module}.py`` the repo itself holds, located the way ``sources`` finds a wrapper. - - Through ``scan.walk_dirs`` rather than ``rglob`` because this list is hashed into the - digest that decides whether a later run may skip the ladder. An unfiltered walk would - fingerprint a copy inside ``.venv`` or ``node_modules``, so reinstalling a dependency - would invalidate a report that is still perfectly good, and the digest would quietly - cover bytes the repo does not own. - """ - candidates = (directory / f"{module}.py" for directory in scan.walk_dirs(repo_root)) - return sorted(path for path in candidates if path.is_file()) - - def _infer_agent_name(repo_root: Path) -> str: """Name from ``optimizer.yaml`` when it says, else a slug of the directory.""" profile = discover_profile(repo_root) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py index 73334b074ff..71ce920940d 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py @@ -79,7 +79,7 @@ def display_path(path: Path, repo_root: Path) -> str: return str(path) -def find_doctrine(repo_root: Path) -> tuple[Path | None, Finding]: +def find_doctrine(repo_root: Path) -> Finding: """Locate the document describing what the agent is supposed to do. Recording which name matched makes the report double as a signal for the @@ -88,7 +88,7 @@ def find_doctrine(repo_root: Path) -> tuple[Path | None, Finding]: for name in _DOCTRINE_FILENAMES: candidate = repo_root / name if candidate.is_file(): - return candidate, Finding( + return Finding( name="doctrine", group=_GROUP, status="pass", @@ -98,7 +98,7 @@ def find_doctrine(repo_root: Path) -> tuple[Path | None, Finding]: "ETHOS.md is the current name; this repo predates the rename." if name == "AGENT-SPEC.md" else None ), ) - return None, Finding( + return Finding( name="doctrine", group=_GROUP, status="warn", @@ -107,7 +107,7 @@ def find_doctrine(repo_root: Path) -> tuple[Path | None, Finding]: ) -def find_skills(repo_root: Path) -> tuple[list[Path], Finding]: +def find_skills(repo_root: Path) -> Finding: """Find Harbor skill bundles, the directories a ``SKILL.md`` marks. These are what ``harbor.skills`` resolves for ``AgentConfig.skills`` and mounts at @@ -116,7 +116,7 @@ def find_skills(repo_root: Path) -> tuple[list[Path], Finding]: """ skills = [directory for directory in walk_dirs(repo_root) if (directory / _SKILL_FILENAME).is_file()] if not skills: - return [], Finding( + return Finding( name="skills", group=_GROUP, status="warn", @@ -126,7 +126,7 @@ def find_skills(repo_root: Path) -> tuple[list[Path], Finding]: listed = ", ".join(display_path(path, repo_root) for path in skills[:_MAX_LISTED_SKILLS]) remainder = len(skills) - _MAX_LISTED_SKILLS - return skills, Finding( + return Finding( name="skills", group=_GROUP, status="pass", diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py index 03fceee3ae9..15755a07190 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py @@ -24,7 +24,6 @@ import yaml from nemo_eval_author_plugin.discovery.models import ( - SOURCE_PRIORITY, CandidateConfig, ConfigSource, Finding, @@ -476,8 +475,3 @@ def read_profile_agent(profile_path: Path) -> str | None: return load_profile_model(profile_path, _DiscoveryProfile).agent except ProfileError: return None - - -def source_priority() -> tuple[str, ...]: - """Exposed so the report can explain the ranking it applied.""" - return SOURCE_PRIORITY diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py index 344f48c5b26..780d8611ece 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py @@ -15,12 +15,18 @@ 2. resolution ``Job.create``, which resolves skills, task configs, resource policies and metrics, and starts no container. 3. tasks ``Task.is_valid_dir``, then ``Task()`` to get the reason a task failed. -4. reward the resolved test script must write ``/logs/verifier/reward.{json,txt}``. +4. coverage every task dir on disk against the set ``Job.create`` actually resolved, + because Harbor drops one it cannot parse without raising. 5. credentials ``get_required_host_vars`` over the task and job env templates. 6. agent ``import_class(..., base=BaseAgent)`` or ``AgentFactory.get_agent_class``. 7. backend ``EnvironmentFactory.run_preflight``. 8. round trip ``harbor job start --print-config -c `` against the persisted bytes. +The one exception is the reward advisory, which reads the test scripts itself because +Harbor has no API that answers the question before a trial runs. It carries no +``harbor_call`` and can only warn, since a text search cannot tell a script that writes a +reward through a variable from one that never writes a reward at all. + A failing rung is recorded, not raised. A report listing every problem is worth more than one that stops at the first, and the command's whole job is to say why a repo cannot run. @@ -75,7 +81,6 @@ class ValidationOutcome: config: JobConfig | None = None findings: list[Finding] = field(default_factory=list) required_env_vars: list[RequiredEnvVar] = field(default_factory=list) - task_dirs: list[Path] = field(default_factory=list) @property def runnable(self) -> bool: @@ -83,14 +88,13 @@ def runnable(self) -> bool: def _harbor(name: str, status: Status, message: str, call: str, **kwargs) -> Finding: - """A finding Harbor vouches for, which is the only kind this module emits.""" + """A finding Harbor returned, which is what ``harbor_call`` claims on the way out.""" return Finding( name=name, group=_GROUP, status=status, message=message, harbor_call=call, - provenance="harbor", **kwargs, ) @@ -145,7 +149,6 @@ async def _ladder(candidate: CandidateConfig, repo_root: Path) -> ValidationOutc return outcome task_dirs = _rung_tasks(resolved, outcome) - outcome.task_dirs = task_dirs _rung_coverage(config, resolved, outcome) if not task_dirs: return outcome @@ -254,8 +257,8 @@ def _resolved_local_paths(job: Job) -> list[Path] | None: tasks" about a repo whose tasks are fine. Absolute on the way out. Harbor hands back whatever the config said, and a relative path - means the repo root only while the ladder's chdir is in effect; these outlive it as the - task list the report fingerprints. + means the repo root only while the ladder's chdir is in effect, so the coverage rung + would compare it against the wrong directory. """ task_configs = getattr(job, "_task_configs", None) if task_configs is None: @@ -318,8 +321,9 @@ def _rung_coverage(config: JobConfig, resolved: list[Path], outcome: ValidationO Harbor drops a directory it cannot parse as a task without saying so: given ten task dirs where three are half-written, ``Job.create`` resolves seven and raises nothing. - The run then succeeds and reports a score over seven tasks, which is the most expensive - kind of wrong, because nothing about the output looks incomplete. + The tasks rung then reports seven of seven valid, the run scores seven, and nothing + about the output looks incomplete. Without this rung the whole ladder returns a clean + verdict on a suite that is quietly missing a third of itself. A dataset that narrows itself with ``task_names``, ``exclude_task_names`` or ``n_tasks`` is deliberately running a subset, so its unresolved directories are reported as @@ -372,97 +376,91 @@ def _task_failure_reason(task_dir: Path) -> str: def _rung_reward(task_dirs: list[Path], outcome: ValidationOutcome) -> None: - """Does each task's test script actually write a reward file? + """Advisory: does each task's test script look like it writes a reward file? + + A task can be structurally valid and still score nothing, and Harbor only says so by + raising ``RewardFileNotFoundError`` after a full trial. There is no Harbor API that + answers earlier, so this reads the scripts and searches for a reward filename. - A task can be structurally valid and still score nothing, which is the most - expensive way to discover a problem: the trial runs, the agent works, and Harbor - raises ``RewardFileNotFoundError`` at the end. + That makes it a heuristic and it is reported as one: no ``harbor_call``, and never + worse than a warning. A script that builds the path in a variable writes a reward this + search cannot see, and failing the run over that would block a repo whose evals are + fine. """ - missing: list[Path] = [] - image_provided: list[Path] = [] + silent: list[Path] = [] reward_forms: set[str] = set() for task_dir in task_dirs: - scripts, graded_in_image = _test_scripts(task_dir) - if graded_in_image: - image_provided.append(task_dir) - for script in scripts: + for script in _test_scripts(task_dir): text = _executable_lines(_read_text(script)) found = [name for name in _REWARD_FILENAMES if name in text] if found: reward_forms.update(found) - elif task_dir not in missing: - missing.append(task_dir) + elif task_dir not in silent: + silent.append(task_dir) - if missing: + if silent: outcome.findings.append( - _harbor( - "reward", - "fail", - f"{len(missing)} task(s) have a test script that never writes a reward file", - "TaskPaths.discovered_test_path_for", - path=missing[0], + Finding( + name="reward", + group=_GROUP, + status="warn", + message=f"{len(silent)} task(s) have a test script that never names a reward file", + path=silent[0], hint=( "Harbor reads /logs/verifier/reward.json then reward.txt, and raises " - "RewardFileNotFoundError when neither exists." + "RewardFileNotFoundError when neither exists. Read as text, so a script that " + "builds the path dynamically looks the same as one that writes nothing." ), ) ) return detail = ", ".join(sorted(reward_forms)) if reward_forms else "none read" - message = f"Every test script writes a reward file ({detail})" - if image_provided: - message += f"; {len(image_provided)} task(s) grade from a separate verifier image" outcome.findings.append( - _harbor( - "reward", - "pass", - message, - "TaskPaths.discovered_test_path_for", - hint=( - "reward.txt yields the single key 'reward'; reward.json keys are only " - "known once a trial runs, and they decide what metrics can aggregate." - ), + Finding( + name="reward", + group=_GROUP, + status="pass", + message=f"Every test script names a reward file ({detail})", ) ) -def _test_scripts(task_dir: Path) -> tuple[list[Path], bool]: - """Every host test script that has to produce a reward, and whether any grades in-image. +def _test_scripts(task_dir: Path) -> list[Path]: + """Every host test script that has to produce a reward. Mirrors ``Task._validate_tests``: one script for a single-step task, and for a multi-step task the effective script per step, which is the step's own or the shared one it falls back to. Checking only the first would pass a task whose later step never scores, and that failure surfaces only after a full run. - ``resolve_effective_verifier_env_config`` is what decides the in-image case. Asking - Harbor beats inferring it from a missing file, which cannot tell a task that grades - from its own verifier image apart from one whose author forgot to write a test. + A step that grades from its own verifier image contributes no host script, which + ``resolve_effective_verifier_env_config`` is what decides. Asking Harbor beats + inferring it from a missing file, which cannot tell a task that grades from an image + apart from one whose author forgot to write a test. """ paths = TaskPaths(task_dir) config = _task_config(task_dir) if config is None: - return [], False + return [] task_os = config.environment.os shared = paths.discovered_test_path_for(task_os) if not config.steps: if resolve_effective_verifier_env_config(config, step_cfg=None) is not None: - return [], True - return ([shared] if shared is not None else []), False + return [] + return [shared] if shared is not None else [] scripts: list[Path] = [] - graded_in_image = False for step in config.steps: if resolve_effective_verifier_env_config(config, step_cfg=step) is not None: - graded_in_image = True continue effective = paths.discovered_step_test_path_for(step.name, task_os) or shared if effective is not None and effective not in scripts: scripts.append(effective) - return scripts, graded_in_image + return scripts def _rung_credentials(config: JobConfig, task_dirs: list[Path], outcome: ValidationOutcome) -> None: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md index 0125d673052..c929090c465 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md @@ -9,10 +9,10 @@ SPDX-License-Identifier: Apache-2.0 > > This plugin is incomplete and its interfaces will change without notice. It also > runs code from the repository you point it at: validating a config imports that -> repository's agent module into the running process, and `--dangerously-fix` gives a -> language model a shell in that directory with no sandbox. Treat pointing Eval Author -> at a repository as equivalent to running that repository's code yourself, and only -> do it for code you already trust. Sandboxing is not implemented yet. +> repository's agent module into the running process, which executes that module's +> top level. Treat pointing Eval Author at a repository as equivalent to running that +> repository's code yourself, and only do it for code you already trust. Sandboxing is +> not implemented yet. The Eval Author plugin is a NeMo OO Agent specialized in auditing and improving the eval suite of a target agent. @@ -28,8 +28,7 @@ beginning optimization. ## Current state `nemo eval-author discover` is the only implemented command. It answers whether -Harbor can run a repository's evals and records the answer, so a later run does -not have to derive it again. +Harbor can run a repository's evals and records the answer. The command assembles a candidate Harbor `JobConfig` from the strongest source the repository offers: a Harbor config file it already maintains, a `config.json` @@ -37,17 +36,23 @@ from a prior job Harbor resolved and ran, an Experimentalist `optimizer.yaml` profile plus the agent wrapper, or the Harbor task directory layout alone. It validates that candidate through a ladder of Harbor's own calls rather than -reimplemented rules: schema, job resolution, task validity and coverage, reward -files, required host variables, the agent class, the environment backend, and a -round trip of the persisted bytes through `harbor job start --print-config`. +reimplemented rules: schema, job resolution, task validity and coverage, +required host variables, the agent class, the environment backend, and a round +trip of the persisted bytes through `harbor job start --print-config`. [`discovery/validate.py`](../discovery/validate.py) names the Harbor API behind -each rung. +each rung. Findings that Harbor returned carry a `harbor_call`; the one check +that reads the repository directly — whether each test script names a reward +file — carries none and can only warn, because a script that builds the path in +a variable is indistinguishable from one that writes nothing. The result is recorded to the `nemo-eval-author` fileset as `/discovery.md`. A `/harbor-job.yaml` is published alongside the -report only when discovery authored or adjusted the config; when the repository -maintains its own valid config file, the report points at that file instead. -Nothing is written into the repository under inspection. +report only when discovery authored the config; when the repository maintains +its own valid config file, the report points at that file instead. Nothing is +written into the repository under inspection. + +Every run revalidates from scratch. The report is a record of what was true when +it was written, not a cache that a later run consults. Exit code 0 means a config was validated and recorded. Every other outcome exits non-zero, including a config Harbor accepted but that could not be uploaded, @@ -58,13 +63,6 @@ which is what makes the command usable as a gate. - `--repo`: agent repository to inspect. Defaults to the current directory. - `--agent`: name the artifacts are stored under. Defaults to the agent named in `optimizer.yaml`, else a slug of the directory name. -- `--dangerously-fix`: let an LLM scout propose fixes for a config Harbor - rejected. Off unless passed. The scout runs shell commands in the repository - under inspection with no sandbox, and it decides what to run by reading files - from that same repository, so hostile content there can steer it. It is also - the only part of `discover` that needs `AUTHOR_*` credentials, which are in - its environment while it runs. -- `--refresh`: revalidate even when nothing the last report depended on moved. - `--dry-run`: print the findings and the config without uploading anything. There are no flags for platform state. The workspace and cluster come from the diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index 9a0ab202fb5..c733e9242eb 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -19,17 +19,18 @@ import pytest import typer from harbor_fixtures import ( - MENTIONS_REWARD_IN_COMMENT, StubClient, StubFiles, + read_front_matter, write_dataset, write_job_config, write_task, write_wrapper, ) from nemo_eval_author_plugin import cli -from nemo_eval_author_plugin.discovery import memory, validate +from nemo_eval_author_plugin.discovery import memory from nemo_eval_author_plugin.discovery import run as discovery +from nemo_eval_author_plugin.discovery.models import JOB_CONFIG_FILENAME from typer.testing import CliRunner runner = CliRunner() @@ -63,24 +64,12 @@ def workspace(monkeypatch, tmp_path): monkeypatch.setenv("NMP_CONFIG_FILE", str(config)) -@pytest.fixture -def no_scout(monkeypatch): - """Fail loudly if a test reaches the LLM scout, which would need real credentials.""" - - def _forbidden(*args, **kwargs): - raise AssertionError("the scout must not run in these tests") - - monkeypatch.setattr(discovery, "_scout", _forbidden) - - # Pytest's tmp_path names would be slugged, so tests that assert on a remote path name the # agent outright. Defaulting is covered on its own below. AGENT = "ticket-triage" def _invoke(app, repo, *extra): - # The scout is opt-in and there is no way to ask for it here, so no test that goes through - # this helper can reach a model. test_the_scout_is_opt_in pins that default. return runner.invoke(app, ["discover", "--repo", str(repo), *extra]) @@ -113,50 +102,29 @@ def test_a_repo_that_maintains_its_own_config_keeps_it_and_records_only_the_repo assert "Withheld" not in result.output, "nothing was withheld; there was nothing of ours to publish" -def test_a_config_the_scout_adjusted_is_published_instead_of_the_repo_file(app, client, monkeypatch, tmp_path): - """Once a payload diverges from the file it came from, that file is no longer what to run. - - Stands in for the scout so the ownership branch is exercised without a model: the repo's - config names a dataset that is not there, and the repair points it at the one that is. - """ +def test_a_repo_harbor_rejects_exits_one_and_withholds_the_config(app, client, tmp_path): + """The config names a dataset that is not there, so Harbor cannot resolve the job.""" write_dataset(tmp_path / "evals" / "validation") write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/missing") - async def _repair(candidate, outcome, repo_root): - candidate.data["datasets"] = [{"path": "evals/validation"}] - candidate.source.adjusted = True - return candidate, await validate.run_ladder(candidate, repo_root), [] - - monkeypatch.setattr(discovery, "_scout", _repair) - - result = runner.invoke(app, ["discover", "--repo", str(tmp_path), "--agent", AGENT, "--dangerously-fix"]) - - assert result.exit_code == 0, result.output - assert "harbor job start -c harbor-job.yaml" in result.output - assert sorted(client.files.stored) == [f"{AGENT}/discovery.md", f"{AGENT}/harbor-job.yaml"] - - -def test_a_repo_whose_tasks_never_score_exits_one_and_withholds_the_config(app, client, tmp_path): - write_dataset(tmp_path / "evals" / "validation", test_script=MENTIONS_REWARD_IN_COMMENT) - result = _invoke_named(app, tmp_path) assert result.exit_code == 1, result.output assert "Harbor cannot run this repo's evals" in result.output - assert "reward" in result.output - assert "Withheld harbor-job.yaml" in result.output, "an absent config has to be explained, not just missing" + assert "resolution" in result.output # The report still lands, so the failure is documented rather than lost. assert sorted(client.files.stored) == [f"{AGENT}/discovery.md"] -def test_the_scout_is_opt_in(app, client, tmp_path, no_scout): - """A config Harbor rejects must not reach a model unless --dangerously-fix asked for it.""" - write_dataset(tmp_path / "evals" / "validation", test_script=MENTIONS_REWARD_IN_COMMENT) +def test_a_config_harbor_rejects_is_never_published(app, client, tmp_path): + """A config in this fileset is always one Harbor could run, so an absent one is explained.""" + write_task(tmp_path / "evals" / "validation" / "task-0", task_toml='\n[[steps]]\nname = "nowhere"\n') - result = runner.invoke(app, ["discover", "--repo", str(tmp_path), "--agent", AGENT]) + result = _invoke_named(app, tmp_path) assert result.exit_code == 1, result.output - assert "Harbor cannot run this repo's evals" in result.output, "the verdict was reached without a model" + assert "Withheld harbor-job.yaml" in result.output, "an absent config has to be explained, not just missing" + assert sorted(client.files.stored) == [f"{AGENT}/discovery.md"] def test_a_repo_with_no_harbor_setup_at_all_exits_one(app, client, tmp_path): @@ -175,7 +143,7 @@ def test_dry_run_prints_the_artifacts_and_uploads_nothing(app, client, tmp_path) assert result.exit_code == 0, result.output assert "Dry run: nothing was uploaded." in result.output - assert "inputs_digest:" in result.output, "the report itself is printed" + assert "runnable: true" in result.output, "the report itself is printed" assert client.files.uploads == [] @@ -225,134 +193,31 @@ def test_an_explicit_agent_name_wins(app, client, tmp_path): assert "invoice-parser/discovery.md" in client.files.stored -def test_an_unchanged_repo_is_not_revalidated(app, client, tmp_path, no_scout): - write_dataset(tmp_path / "evals" / "validation") - first = _invoke(app, tmp_path) - assert first.exit_code == 0, first.output - - second = _invoke(app, tmp_path) - - assert second.exit_code == 0, second.output - assert "Nothing the previous report depended on has changed" in second.output - assert "validation/schema" not in second.output, "the ladder should not have run again" - - -def test_a_runnable_flag_that_is_not_a_boolean_does_not_switch_off_revalidation(app, client, tmp_path): - """Reuse skips the entire ladder, so only a real YAML ``true`` may switch revalidation off. - - The string ``"false"`` is the cruel case: it is truthy, and a reused record carries no - findings, so the command would exit zero having validated nothing and claiming a verdict - the stored report explicitly denies. - """ - write_dataset(tmp_path / "evals" / "validation") - assert _invoke_named(app, tmp_path).exit_code == 0 - stored = client.files.stored[memory.remote_report_path(AGENT)].decode("utf-8") - assert "runnable: true" in stored - client.files.stored[memory.remote_report_path(AGENT)] = stored.replace( - "runnable: true", "runnable: 'false'" - ).encode("utf-8") - - result = _invoke_named(app, tmp_path) - - assert result.exit_code == 0, result.output - assert "validation/schema" in result.output, "the ladder had to run again" - assert "Nothing the previous report depended on has changed" not in result.output - - -def test_a_wrapper_copy_inside_a_virtualenv_is_not_fingerprinted(app, client, tmp_path): - """The digest decides whether a later run may skip the ladder, so it covers the repo's own source only. - - A vendored module whose basename matches the agent's import path would otherwise tie this - report's freshness to a dependency: reinstalling the package invalidates a verdict that - still holds, and the digest quietly covers bytes the repo does not own. - """ - write_dataset(tmp_path / "evals" / "validation") - write_wrapper(tmp_path) - vendored = tmp_path / ".venv" / "lib" / "python3.12" / "site-packages" - vendored.mkdir(parents=True) - write_wrapper(vendored, class_name="VendoredAgent") - - assert _invoke_named(app, tmp_path).exit_code == 0 - - front = memory.parse_front_matter(client.files.stored[memory.remote_report_path(AGENT)].decode("utf-8")) - assert front is not None - recorded = [item["path"] for item in front["inputs"]] - assert "harbor_wrapper.py" in recorded, "the repo's own wrapper shaped the verdict, so it is an input" - assert [path for path in recorded if path.startswith(".venv")] == [] - - -def test_a_reused_report_still_names_the_host_variables_a_run_needs(app, client, tmp_path): - """A repeat run is the common case, so losing ``Needs:`` there hides it nearly always. - - Harbor raises on an unresolved template at trial start. A record that stops naming - ``HF_TOKEN`` hands out a run command that cannot work and says nothing about why. - """ +def test_a_run_that_needs_host_variables_names_them(app, client, tmp_path): + """Harbor raises on an unresolved template at trial start, so a run command that does + not name ``HF_TOKEN`` cannot work and says nothing about why.""" write_task( tmp_path / "evals" / "validation" / "task-0", task_toml='\n[environment.env]\nHF_TOKEN = "${HF_TOKEN}"\n', ) - first = _invoke_named(app, tmp_path) - assert first.exit_code == 0, first.output - assert "Needs: HF_TOKEN" in first.output result = _invoke_named(app, tmp_path) assert result.exit_code == 0, result.output - assert "Nothing the previous report depended on has changed" in result.output assert "Needs: HF_TOKEN" in result.output -def test_a_reused_report_that_cannot_be_reuploaded_says_what_went_wrong(app, client, monkeypatch, tmp_path): - """The exit code says the record was not written; only the finding says why. - - This branch prints almost nothing by design, but the upload warning carries the exception, - the fileset and the remote path — the whole diagnosis, and it is on every other path. - """ - write_dataset(tmp_path / "evals" / "validation") - assert _invoke_named(app, tmp_path).exit_code == 0 - offline = StubClient(files=StubFiles(client.files.stored, fail=True)) - monkeypatch.setattr(discovery, "make_client", lambda base_url: offline) - - result = _invoke_named(app, tmp_path) - - assert result.exit_code == 1, result.output - assert "Nothing the previous report depended on has changed" in result.output, "this is the reuse path" - assert "Could not upload discovery.md" in result.output - assert "fileset unavailable" in result.output - assert "could not be recorded" in result.output - - -def test_refresh_forces_the_ladder_to_run_again(app, client, tmp_path): - write_dataset(tmp_path / "evals" / "validation") - assert _invoke(app, tmp_path).exit_code == 0 - - result = _invoke(app, tmp_path, "--refresh") - - assert result.exit_code == 0, result.output - assert "validation/schema" in result.output - - -def test_an_edited_task_is_revalidated(app, client, tmp_path): +def test_every_run_revalidates_from_scratch(app, client, tmp_path): + """No verdict is taken on trust from a previous run: the repo may have moved under it.""" dataset = write_dataset(tmp_path / "evals" / "validation") assert _invoke(app, tmp_path).exit_code == 0 - # Break the reward contract; the digest moves, so the prior verdict cannot be reused. - (dataset / "task-0" / "tests" / "test.sh").write_text(MENTIONS_REWARD_IN_COMMENT) - result = _invoke(app, tmp_path) - - assert result.exit_code == 1, result.output - assert "never writes a reward file" in result.output - - -def test_a_previously_failing_repo_is_always_revalidated(app, client, tmp_path, no_scout): - """A failure may have been the machine's fault, so it is never taken on trust.""" - write_dataset(tmp_path / "evals" / "validation", test_script=MENTIONS_REWARD_IN_COMMENT) - assert _invoke(app, tmp_path).exit_code == 1 - + # A task Harbor cannot parse at all, added after the first run recorded a clean verdict. + (dataset / "task-1" / "task.toml").write_text("not = [valid\n") result = _invoke(app, tmp_path) assert result.exit_code == 1, result.output - assert "validation/reward" in result.output + assert "validation/schema" in result.output, "the ladder ran again" def test_an_unwritable_fileset_exits_one_even_though_harbor_is_happy(app, monkeypatch, tmp_path): @@ -408,8 +273,7 @@ def test_the_uploaded_report_carries_the_verdict_that_was_printed(app, client, t assert _invoke_named(app, tmp_path).exit_code == 0 - stored = client.files.stored[memory.remote_report_path(AGENT)].decode("utf-8") - front = memory.parse_front_matter(stored) - assert front is not None + front = read_front_matter(client.files.stored[memory.remote_report_path(AGENT)]) assert front["runnable"] is True assert front["config_source"]["kind"] == "convention" + assert front["run_config"] == {"location": "fileset", "path": f"{AGENT}/{JOB_CONFIG_FILENAME}"} diff --git a/plugins/nemo-eval-author/tests/discover/test_memory.py b/plugins/nemo-eval-author/tests/discover/test_memory.py deleted file mode 100644 index e38190eece7..00000000000 --- a/plugins/nemo-eval-author/tests/discover/test_memory.py +++ /dev/null @@ -1,152 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""What reaches the fileset, and what deliberately does not. - -The invariant worth defending: a ``harbor-job.yaml`` in the fileset is always a config -Harbor accepted. A later agent is told to run whatever it finds there, so a config uploaded -alongside a failing report would be an instruction to run something broken. -""" - -from harbor_fixtures import StubClient, StubFiles -from nemo_eval_author_plugin.discovery import memory, report - - -async def test_both_artifacts_are_uploaded_under_the_agent_prefix(): - client = StubClient() - - ok, findings = await memory.persist( - client, agent="ticket-triage", workspace="default", markdown="# report\n", job_config="datasets: []\n" - ) - - assert ok is True - assert [item["remote_path"] for item in client.files.uploads] == [ - "ticket-triage/discovery.md", - "ticket-triage/harbor-job.yaml", - ] - assert all(item["fileset"] == memory.FILESET_NAME for item in client.files.uploads) - assert all(item["fileset_auto_create"] is True for item in client.files.uploads) - assert all(item.status == "pass" for item in findings) - - -async def test_no_config_uploads_the_report_alone_and_says_nothing_about_why(): - """Absent for several reasons — withheld, repo-owned, already stored — and only the caller knows which.""" - client = StubClient() - - ok, findings = await memory.persist( - client, agent="ticket-triage", workspace="default", markdown="# report\n", job_config=None - ) - - assert ok is True, "the report still has to land, so the verdict is documented either way" - assert [item["remote_path"] for item in client.files.uploads] == ["ticket-triage/discovery.md"] - assert all(item.status == "pass" for item in findings) - - -async def test_an_upload_failure_is_reported_without_claiming_the_config_is_broken(): - client = StubClient(files=StubFiles(fail=True)) - - ok, findings = await memory.persist( - client, agent="ticket-triage", workspace="default", markdown="# report\n", job_config="datasets: []\n" - ) - - assert ok is False - # A fileset outage says nothing about whether Harbor can run the config, so these are - # warnings; run.DiscoverResult.ok folds the False into the exit code instead. - assert all(item.status == "warn" for item in findings) - assert any("fileset unavailable" in item.message for item in findings) - - -async def test_a_previous_report_is_read_back_for_comparison(tmp_path): - record = report.build_report( - agent="ticket-triage", - workspace="default", - repo_root=tmp_path, - candidate=None, - findings=[], - required_env_vars=[], - inputs=report.fingerprint_inputs([_write(tmp_path / "a.md", "a\n")], tmp_path), - ) - markdown = report.render_markdown(record) - client = StubClient(files=StubFiles({"ticket-triage/discovery.md": markdown.encode("utf-8")})) - - prior = await memory.load_previous(client, agent="ticket-triage", workspace="default") - - assert prior is not None - assert prior.inputs_digest == record.inputs_digest - assert [item.path for item in prior.inputs] == ["a.md"] - assert prior.text == markdown - - -async def test_a_missing_or_unreachable_report_just_means_rediscover(): - empty = await memory.load_previous(StubClient(), agent="ticket-triage", workspace="default") - assert empty is None - - unusable = StubClient(files=StubFiles({"ticket-triage/discovery.md": b"not a report"})) - assert await memory.load_previous(unusable, agent="ticket-triage", workspace="default") is None - - -async def test_a_hand_edited_report_is_rediscovered_rather_than_raising(): - """Nothing above this catches an exception, so a report someone edited would be a traceback. - - YAML reads a bare timestamp as a ``datetime`` and a bare version as a ``float``, neither of - which Pydantic coerces into the strings ``PriorRecord`` declares. An unusable file is the - same situation as no file at all, and the answer to both is to rediscover. - """ - for line in ("last_validated_at: 2026-07-31T16:32:41.123456+00:00", "harbor_version: 0.18"): - stored = f"---\nrunnable: true\n{line}\n---\n\n# report\n" - client = StubClient(files=StubFiles({"ticket-triage/discovery.md": stored.encode("utf-8")})) - - prior = await memory.load_previous(client, agent="ticket-triage", workspace="default") - - assert prior is None, f"`{line}` should have been declined rather than raised on" - - -def test_rehashing_prior_inputs_notices_an_edited_file(tmp_path): - path = _write(tmp_path / "task.toml", 'version = "1.0"\n') - inputs = report.fingerprint_inputs([path], tmp_path) - prior = memory.PriorRecord(inputs=inputs, inputs_digest="sha256:whatever", runnable=True) - - assert memory.rehash_prior_inputs(prior, tmp_path) == inputs - - _write(path, 'version = "1.0"\n# edited\n') - assert memory.rehash_prior_inputs(prior, tmp_path) != inputs - - -def test_a_deleted_input_changes_the_digest(tmp_path): - """A report derived from a file someone removed must not read as still valid.""" - path = _write(tmp_path / "task.toml", 'version = "1.0"\n') - prior = memory.PriorRecord( - inputs=report.fingerprint_inputs([path], tmp_path), inputs_digest="sha256:whatever", runnable=True - ) - path.unlink() - - assert memory.rehash_prior_inputs(prior, tmp_path) == [] - - -async def test_rerunning_overwrites_rather_than_accumulating(): - """Agent-scoped fixed paths mean the fileset holds the latest answer, not a pile.""" - client = StubClient() - - for body in ("# first\n", "# second\n"): - await memory.persist( - client, agent="ticket-triage", workspace="default", markdown=body, job_config="datasets: []\n" - ) - - assert len(client.files.uploads) == 4 - assert sorted(client.files.stored) == ["ticket-triage/discovery.md", "ticket-triage/harbor-job.yaml"] - assert client.files.stored["ticket-triage/discovery.md"] == b"# second\n" - - -async def test_two_agents_do_not_share_a_path(): - client = StubClient() - - for agent in ("ticket-triage", "invoice-parser"): - await memory.persist(client, agent=agent, workspace="default", markdown="# report\n", job_config=None) - - assert sorted(client.files.stored) == ["invoice-parser/discovery.md", "ticket-triage/discovery.md"] - - -def _write(path, text): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding="utf-8") - return path diff --git a/plugins/nemo-eval-author/tests/discover/test_report.py b/plugins/nemo-eval-author/tests/discover/test_report.py index 6901b983560..0a937116904 100644 --- a/plugins/nemo-eval-author/tests/discover/test_report.py +++ b/plugins/nemo-eval-author/tests/discover/test_report.py @@ -9,23 +9,19 @@ the artifact wrong somewhere other than where it was produced. """ -from datetime import UTC, datetime - import yaml from harbor.models.job.config import JobConfig -from harbor_fixtures import write_dataset -from nemo_eval_author_plugin.discovery import memory, report +from harbor_fixtures import read_front_matter, write_dataset +from nemo_eval_author_plugin.discovery import report from nemo_eval_author_plugin.discovery.models import ( - FILESET_NAME, CandidateConfig, ConfigSource, - DiscoveryReport, Finding, RequiredEnvVar, ) -def _record(tmp_path, findings=(), env_vars=(), inputs=(), candidate=None): +def _record(tmp_path, findings=(), env_vars=(), candidate=None): return report.build_report( agent="ticket-triage", workspace="default", @@ -34,7 +30,6 @@ def _record(tmp_path, findings=(), env_vars=(), inputs=(), candidate=None): or CandidateConfig(data={}, source=ConfigSource(kind="config_file", detail="declared at configs/eval.yaml")), findings=list(findings), required_env_vars=list(env_vars), - inputs=list(inputs), ) @@ -43,30 +38,25 @@ def test_front_matter_survives_a_round_trip(tmp_path): tmp_path, findings=[Finding(name="schema", group="validation", status="pass", message="ok", harbor_call="x")], env_vars=[RequiredEnvVar(name="HF_TOKEN", declared_in=tmp_path / "evals/task-0/task.toml")], - inputs=report.fingerprint_inputs([_write(tmp_path / "ETHOS.md", "# Ethos\n")], tmp_path), ) - front = memory.parse_front_matter(report.render_markdown(record)) + front = read_front_matter(report.render_markdown(record)) - assert front is not None assert front["runnable"] is True assert front["agent"] == "ticket-triage" assert front["validation"] == {"schema": "pass"} - assert front["inputs_digest"] == record.inputs_digest assert front["harbor_version"] == report.harbor_version() # Recorded relative, so the artifact means the same thing on another machine. assert front["required_env_vars"][0]["declared_in"] == "evals/task-0/task.toml" - assert front["inputs"] == [{"path": "ETHOS.md", "sha256": record.inputs[0].sha256}] -def _owned_config(tmp_path, *, adjusted=False): +def _owned_config(tmp_path): return CandidateConfig( data={}, source=ConfigSource( kind="config_file", detail="declared at configs/eval.yaml", path=tmp_path / "configs" / "eval.yaml", - adjusted=adjusted, ), ) @@ -76,68 +66,28 @@ def test_a_repo_that_maintains_its_own_config_is_told_to_run_that_file(tmp_path) record = _record(tmp_path, candidate=_owned_config(tmp_path)) markdown = report.render_markdown(record) - front = memory.parse_front_matter(markdown) + front = read_front_matter(markdown) - assert front is not None assert front["run_config"] == {"location": "repo", "path": "configs/eval.yaml"} assert "harbor job start -c configs/eval.yaml" in markdown assert "harbor-job.yaml" not in markdown - # Why a config file is involved at all, since a reader may only have task directories. - assert "package reference" in markdown -def test_a_config_we_had_to_adjust_points_at_the_copy_discovery_wrote(tmp_path): - record = _record(tmp_path, candidate=_owned_config(tmp_path, adjusted=True)) +def test_a_config_discovery_authored_points_at_the_fileset_copy(tmp_path): + """Nothing in the repo declares a config, so the fileset is the only place it exists.""" + record = _record( + tmp_path, + candidate=CandidateConfig( + data={}, source=ConfigSource(kind="convention", detail="inferred from task dirs under evals/validation") + ), + ) markdown = report.render_markdown(record) - front = memory.parse_front_matter(markdown) + front = read_front_matter(markdown) - assert front is not None assert front["run_config"] == {"location": "fileset", "path": "ticket-triage/harbor-job.yaml"} assert "harbor job start -c harbor-job.yaml" in markdown - assert f"nemo files download {FILESET_NAME}" in markdown, "the config is not on disk yet" - - -def test_a_reused_report_resolves_the_target_it_was_written_with(tmp_path): - """Reuse rebuilds the record from front matter alone, so what decided the target must be in it.""" - record = _record(tmp_path, candidate=_owned_config(tmp_path, adjusted=True)) - front = memory.parse_front_matter(report.render_markdown(record)) - - assert front is not None - rebuilt = DiscoveryReport.model_validate( - { - "agent": record.agent, - "workspace": record.workspace, - "repo_root": front["repo_root"], - "harbor_version": front["harbor_version"], - "config_source": front["config_source"], - "discovered_at": front["discovered_at"], - "last_validated_at": front["last_validated_at"], - } - ) - - assert report.run_target(rebuilt) == report.run_target(record) - - -def test_the_digest_is_stable_and_notices_a_changed_input(tmp_path): - path = _write(tmp_path / "task.toml", 'version = "1.0"\n') - first = _record(tmp_path, inputs=report.fingerprint_inputs([path], tmp_path)) - again = _record(tmp_path, inputs=report.fingerprint_inputs([path], tmp_path)) - assert first.inputs_digest == again.inputs_digest - - _write(path, 'version = "1.0"\n# edited\n') - changed = _record(tmp_path, inputs=report.fingerprint_inputs([path], tmp_path)) - assert changed.inputs_digest != first.inputs_digest - - -def test_the_digest_ignores_the_order_inputs_were_collected_in(tmp_path): - first = _write(tmp_path / "a.md", "a\n") - second = _write(tmp_path / "b.md", "b\n") - - forward = _record(tmp_path, inputs=report.fingerprint_inputs([first, second], tmp_path)) - backward = _record(tmp_path, inputs=report.fingerprint_inputs([second, first], tmp_path)) - - assert forward.inputs_digest == backward.inputs_digest + assert "Fetch `ticket-triage/harbor-job.yaml`" in markdown, "the config is not on disk yet" def test_the_persisted_config_carries_no_absolute_paths(tmp_path): @@ -187,11 +137,11 @@ def test_an_unrunnable_report_says_what_blocks_it_and_offers_no_command(tmp_path tmp_path, findings=[ Finding( - name="reward", + name="resolution", group="validation", status="fail", - message="1 task(s) have a test script that never writes a reward file", - harbor_call="TaskPaths.discovered_test_path_for", + message="Harbor could not resolve the job", + harbor_call="Job.create", ) ], ) @@ -200,11 +150,11 @@ def test_an_unrunnable_report_says_what_blocks_it_and_offers_no_command(tmp_path assert record.runnable is False assert "cannot run" in markdown - assert "never writes a reward file" in markdown + assert "could not resolve the job" in markdown assert "harbor job start" not in markdown, "an unrunnable report must not hand out a run command" -def test_a_report_with_no_config_at_all_says_where_to_start(tmp_path): +def test_a_report_with_no_config_at_all_is_not_runnable(tmp_path): record = report.build_report( agent="ticket-triage", workspace="default", @@ -212,37 +162,10 @@ def test_a_report_with_no_config_at_all_says_where_to_start(tmp_path): candidate=None, findings=[], required_env_vars=[], - inputs=[], ) - markdown = report.render_markdown(record) + front = read_front_matter(report.render_markdown(record)) assert record.runnable is False - assert "harbor job init" in markdown - - -def test_restamping_moves_the_stamp_and_leaves_the_narrative_alone(tmp_path): - record = _record(tmp_path, inputs=report.fingerprint_inputs([_write(tmp_path / "a.md", "a\n")], tmp_path)) - original = report.render_markdown(record) - later = datetime(2027, 1, 1, tzinfo=UTC) - - restamped = memory.restamp(original, when=later, harbor_version="9.9.9") - - assert restamped is not None - front = memory.parse_front_matter(restamped) - assert front is not None - assert front["last_validated_at"] == later.isoformat() - assert front["harbor_version"] == "9.9.9" - assert front["discovered_at"] == record.discovered_at.isoformat(), "discovery time is history, not a stamp" - assert front["inputs_digest"] == record.inputs_digest - assert original.split("\n---\n", 1)[1] == restamped.split("\n---\n", 1)[1] - - -def test_restamping_declines_a_file_without_front_matter(): - assert memory.restamp("# just markdown\n", when=datetime.now(UTC), harbor_version="1.0") is None - - -def _write(path, text): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding="utf-8") - return path + assert front["config_source"] is None + assert front["run_config"] is None diff --git a/plugins/nemo-eval-author/tests/discover/test_scan.py b/plugins/nemo-eval-author/tests/discover/test_scan.py index c904c27c9fe..43d7ecb6215 100644 --- a/plugins/nemo-eval-author/tests/discover/test_scan.py +++ b/plugins/nemo-eval-author/tests/discover/test_scan.py @@ -19,9 +19,9 @@ def test_ethos_is_preferred_over_the_name_it_replaced(tmp_path): (tmp_path / "ETHOS.md").write_text("# New\n") (tmp_path / "README.md").write_text("# Readme\n") - path, finding = scan.find_doctrine(tmp_path) + finding = scan.find_doctrine(tmp_path) - assert path == tmp_path / "ETHOS.md" + assert finding.path == tmp_path / "ETHOS.md" assert finding.status == "pass" assert finding.hint is None @@ -31,25 +31,25 @@ def test_the_old_name_still_works_and_says_so(tmp_path): (tmp_path / "AGENT-SPEC.md").write_text("# Old\n") (tmp_path / "README.md").write_text("# Readme\n") - path, finding = scan.find_doctrine(tmp_path) + finding = scan.find_doctrine(tmp_path) - assert path == tmp_path / "AGENT-SPEC.md" + assert finding.path == tmp_path / "AGENT-SPEC.md" assert finding.hint is not None and "predates the rename" in finding.hint def test_readme_is_the_last_resort(tmp_path): (tmp_path / "README.md").write_text("# Readme\n") - path, finding = scan.find_doctrine(tmp_path) + finding = scan.find_doctrine(tmp_path) - assert path == tmp_path / "README.md" + assert finding.path == tmp_path / "README.md" assert finding.status == "pass" def test_no_doctrine_is_a_warning_not_a_failure(tmp_path): - path, finding = scan.find_doctrine(tmp_path) + finding = scan.find_doctrine(tmp_path) - assert path is None + assert finding.path is None assert finding.status == "warn" @@ -58,10 +58,10 @@ def test_skill_bundles_are_found_by_their_marker_file(tmp_path): (tmp_path / "skills" / name).mkdir(parents=True) (tmp_path / "skills" / name / "SKILL.md").write_text(f"# {name}\n") - skills, finding = scan.find_skills(tmp_path) + finding = scan.find_skills(tmp_path) - assert len(skills) == 2 assert finding.status == "pass" + assert "2 Harbor skill bundle(s)" in finding.message assert finding.hint is not None and "AgentConfig.skills" in finding.hint @@ -71,10 +71,10 @@ def test_vendored_trees_are_not_searched(tmp_path): vendored.mkdir(parents=True) (vendored / "SKILL.md").write_text("# not ours\n") - skills, finding = scan.find_skills(tmp_path) + finding = scan.find_skills(tmp_path) - assert skills == [] assert finding.status == "warn" + assert finding.path is None async def test_available_traces_are_counted(): diff --git a/plugins/nemo-eval-author/tests/discover/test_scout.py b/plugins/nemo-eval-author/tests/discover/test_scout.py deleted file mode 100644 index 5e78dc06ec9..00000000000 --- a/plugins/nemo-eval-author/tests/discover/test_scout.py +++ /dev/null @@ -1,137 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""The scout proposes; Harbor decides. - -This is the seam where a language model's guess enters an artifact a later agent is told to -trust, so the tests here are about containment rather than about the model. The scout's -output is pushed back through the same ladder, a proposal Harbor rejects changes nothing, -and anything it did influence is marked as inference so a reader can tell it apart from a -verdict Harbor returned. - -No model is ever called: ``attempt_repair`` takes the proposal function as a parameter and -these tests pass a fixed one. A test that reached a real model would need credentials and -would assert on something nondeterministic. -""" - -from harbor_fixtures import MENTIONS_REWARD_IN_COMMENT, write_dataset -from nemo_eval_author_plugin.discovery import validate -from nemo_eval_author_plugin.discovery.agent import ProposeFn, ScoutProposal, attempt_repair, is_scoutable -from nemo_eval_author_plugin.discovery.models import CandidateConfig, ConfigSource, Finding - - -def _candidate(data: dict) -> CandidateConfig: - return CandidateConfig(data=data, source=ConfigSource(kind="convention", detail="inferred from task dirs")) - - -def _outcome(*failures: str) -> validate.ValidationOutcome: - return validate.ValidationOutcome( - findings=[ - Finding(name=name, group="validation", status="fail", message="broken", provenance="harbor") - for name in failures - ] - ) - - -def _proposes(proposal: ScoutProposal | Exception) -> ProposeFn: - async def propose(candidate, blocking, repo_root): - if isinstance(proposal, Exception): - raise proposal - return proposal - - return propose - - -def test_only_failures_a_look_at_the_repo_could_settle_are_scoutable(): - assert is_scoutable(_outcome("resolution")) is True - assert is_scoutable(_outcome("agent")) is True - # Docker not running is a fact about the machine; no amount of reading the repo helps. - assert is_scoutable(_outcome("backend")) is False - assert is_scoutable(_outcome("reward")) is False - - -async def test_a_proposal_harbor_accepts_is_adopted_and_labelled(tmp_path): - good = write_dataset(tmp_path / "evals" / "validation", count=1) - broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) - outcome = await validate.run_ladder(broken, tmp_path) - assert not outcome.runnable - propose = _proposes( - ScoutProposal( - config={"datasets": [{"path": str(good)}]}, - rationale="evals/validation holds the task.toml dirs", - changed=["datasets"], - ) - ) - - candidate, revalidated, findings = await attempt_repair(broken, outcome, tmp_path, propose) - - assert candidate.data["datasets"] == [{"path": str(good)}] - assert revalidated.runnable - # The config's provenance has to admit a model touched it, which is also what stops the - # artifact from telling a later run to use the repo's own file. - assert "adjusted by the discovery scout" in candidate.source.detail - assert candidate.source.adjusted is True - assert findings[0].status == "pass" - assert findings[0].provenance == "inference" - - -async def test_a_proposal_harbor_rejects_changes_nothing(tmp_path): - """Otherwise a plausible guess could replace failures the user could act on.""" - broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) - outcome = await validate.run_ladder(broken, tmp_path) - propose = _proposes( - ScoutProposal( - config={"datasets": [{"path": str(tmp_path / "also-wrong")}]}, - rationale="guessing", - changed=["datasets"], - ) - ) - - candidate, revalidated, findings = await attempt_repair(broken, outcome, tmp_path, propose) - - assert candidate is broken - assert revalidated is outcome - assert findings[0].status == "warn" - assert "still rejected" in findings[0].message - - -async def test_a_proposal_that_only_fixes_one_of_two_failures_is_not_adopted(tmp_path): - """Runnable is the bar, not merely different: a partial fix is still not runnable.""" - dataset = write_dataset(tmp_path / "evals" / "validation", count=1, test_script=MENTIONS_REWARD_IN_COMMENT) - broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) - outcome = await validate.run_ladder(broken, tmp_path) - propose = _proposes( - ScoutProposal(config={"datasets": [{"path": str(dataset)}]}, rationale="found the dir", changed=["datasets"]) - ) - - candidate, _, findings = await attempt_repair(broken, outcome, tmp_path, propose) - - assert candidate is broken, "the reward contract is still broken, so nothing is adopted" - assert findings[0].status == "warn" - - -async def test_a_scout_with_nothing_to_change_says_so(tmp_path): - broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) - outcome = await validate.run_ladder(broken, tmp_path) - propose = _proposes(ScoutProposal(config=broken.data, rationale="the repo names no dataset anywhere", changed=[])) - - candidate, revalidated, findings = await attempt_repair(broken, outcome, tmp_path, propose) - - assert candidate is broken - assert revalidated is outcome - assert "nothing in the repo to change" in findings[0].message - assert "names no dataset" in findings[0].message - - -async def test_a_scout_that_cannot_run_degrades_to_a_warning(tmp_path): - """Missing credentials must not turn a reportable failure into a crash.""" - broken = _candidate({"datasets": [{"path": str(tmp_path / "wrong-place")}]}) - outcome = await validate.run_ladder(broken, tmp_path) - propose = _proposes(RuntimeError("no model credentials")) - - candidate, revalidated, findings = await attempt_repair(broken, outcome, tmp_path, propose) - - assert candidate is broken - assert revalidated is outcome - assert findings[0].status == "warn" - assert findings[0].hint is not None and "--dangerously-fix" in findings[0].hint diff --git a/plugins/nemo-eval-author/tests/discover/test_sources.py b/plugins/nemo-eval-author/tests/discover/test_sources.py index 33668e0023c..314375a1702 100644 --- a/plugins/nemo-eval-author/tests/discover/test_sources.py +++ b/plugins/nemo-eval-author/tests/discover/test_sources.py @@ -137,7 +137,6 @@ def test_a_config_file_is_read_as_written_and_stays_owned_by_the_repo(tmp_path): assert candidate is not None assert candidate.data["environment"] == {"type": "daytona"} - assert candidate.source.adjusted is False assert candidate.source.owns_file is True diff --git a/plugins/nemo-eval-author/tests/discover/test_validate.py b/plugins/nemo-eval-author/tests/discover/test_validate.py index 7a41a422f75..97e748fa8a4 100644 --- a/plugins/nemo-eval-author/tests/discover/test_validate.py +++ b/plugins/nemo-eval-author/tests/discover/test_validate.py @@ -54,8 +54,22 @@ async def test_a_well_formed_repo_passes_every_rung(tmp_path): assert _finding(outcome, "tasks").message.startswith("2 of 2") assert _finding(outcome, "schema").harbor_call == "JobConfig.model_validate" assert _finding(outcome, "resolution").harbor_call == "Job.create" - # Every verdict must be attributable to Harbor, or the artifact is not trustworthy. - assert all(item.provenance == "harbor" for item in outcome.findings) + + +async def test_only_a_verdict_harbor_returned_claims_a_harbor_call(tmp_path): + """``harbor_call`` is what tells a reader a finding is as true as the run would be. + + The reward advisory reads the test scripts itself, so it must not carry one. Naming a + Harbor API there would dress a text search up as something Harbor vouched for. + """ + write_dataset(tmp_path / "evals" / "validation", count=1) + candidate = _candidate({"datasets": [{"path": str(tmp_path / "evals/validation")}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _finding(outcome, "reward").harbor_call is None + judged_by_harbor = [item for item in outcome.findings if item.name != "reward"] + assert judged_by_harbor and all(item.harbor_call for item in judged_by_harbor) async def test_schema_failure_names_the_harbor_validator(tmp_path): @@ -132,8 +146,12 @@ async def create(cls, config): async def test_a_task_harbor_silently_skips_is_reported(tmp_path): - """Harbor drops a directory it cannot parse without raising, so a run would score fewer - tasks than the repo holds and nothing about the result would look incomplete.""" + """Harbor drops a directory it cannot parse without raising. + + Nothing else in the ladder catches this: the tasks rung only sees what Harbor + resolved, so it reports one of one valid while the repo holds two. The run would then + score half the suite and look complete doing it. + """ dataset = tmp_path / "evals" / "validation" write_task(dataset / "task-0") write_task(dataset / "task-1", instruction=None) @@ -141,8 +159,7 @@ async def test_a_task_harbor_silently_skips_is_reported(tmp_path): outcome = await validate.run_ladder(candidate, tmp_path) - # Harbor resolved only the good one, so the tasks rung sees nothing wrong. - assert _finding(outcome, "tasks").message.startswith("1 of 1") + assert _finding(outcome, "tasks").message.startswith("1 of 1"), "the tasks rung cannot see the dropped one" coverage = _finding(outcome, "coverage") assert coverage.status == "fail" assert "task-1" in coverage.message @@ -162,19 +179,40 @@ async def test_a_dataset_that_selects_a_subset_is_not_accused_of_dropping_tasks( assert _repo_failures(outcome) == [] -async def test_a_scaffolded_task_that_never_writes_a_reward_is_caught(tmp_path): - """Harbor's own template mentions the reward file only in a comment.""" +async def test_a_scaffolded_task_that_never_names_a_reward_is_flagged_without_blocking(tmp_path): + """Harbor's own template mentions the reward file only in a comment. + + Worth saying, because the trial would run and then raise. Not worth failing over: the + check is a text search, and a script that builds the path in a variable looks identical + to one that writes nothing. + """ dataset = write_dataset(tmp_path / "evals" / "validation", count=1, test_script=MENTIONS_REWARD_IN_COMMENT) candidate = _candidate({"datasets": [{"path": str(dataset)}]}) outcome = await validate.run_ladder(candidate, tmp_path) reward = _finding(outcome, "reward") - assert reward.status == "fail" - assert _finding(outcome, "tasks").status == "pass", "the task is structurally fine; only its scoring is broken" + assert reward.status == "warn" + assert _repo_failures(outcome) == [], "a heuristic must not block a repo Harbor accepted" + assert _finding(outcome, "tasks").status == "pass", "the task is structurally fine; only its scoring is doubtful" assert reward.hint is not None and "RewardFileNotFoundError" in reward.hint +async def test_a_reward_written_through_a_variable_is_not_called_a_failure(tmp_path): + """The false negative that makes this check unfit to gate on: the script does score.""" + dataset = write_dataset( + tmp_path / "evals" / "validation", + count=1, + test_script='#!/bin/bash\nOUT=/logs/verifier\nprintf 1 > "$OUT/reward.$(echo txt)"\n', + ) + candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _finding(outcome, "reward").status == "warn" + assert _repo_failures(outcome) == [] + + async def test_a_multi_step_task_is_valid_without_a_root_instruction(tmp_path): dataset = tmp_path / "evals" / "validation" write_task( @@ -209,7 +247,7 @@ async def test_a_multi_step_task_is_checked_for_a_reward_in_every_step(tmp_path) outcome = await validate.run_ladder(candidate, tmp_path) assert _finding(outcome, "tasks").status == "pass" - assert _finding(outcome, "reward").status == "fail" + assert _finding(outcome, "reward").status == "warn" async def test_a_windows_task_needing_test_bat_is_not_a_failure(tmp_path): @@ -236,9 +274,7 @@ async def test_a_task_graded_in_a_separate_verifier_image_needs_no_host_script(t outcome = await validate.run_ladder(candidate, tmp_path) assert _finding(outcome, "tasks").status == "pass" - reward = _finding(outcome, "reward") - assert reward.status == "pass" - assert "separate verifier image" in reward.message + assert _finding(outcome, "reward").status == "pass", "an image-graded task ships no host script to read" async def test_a_task_naming_a_prebuilt_image_needs_no_dockerfile(tmp_path): diff --git a/plugins/nemo-eval-author/tests/harbor_fixtures.py b/plugins/nemo-eval-author/tests/harbor_fixtures.py index d414de9f417..ae31df5e7ca 100644 --- a/plugins/nemo-eval-author/tests/harbor_fixtures.py +++ b/plugins/nemo-eval-author/tests/harbor_fixtures.py @@ -31,6 +31,21 @@ import yaml + +def read_front_matter(text: str | bytes) -> dict[str, Any]: + """Parse the YAML front matter of a rendered report. + + Lives here rather than in the plugin because only tests read a report back; the + artifact's consumer is a later agent outside this codebase. + """ + if isinstance(text, bytes): + text = text.decode("utf-8") + assert text.startswith("---\n"), f"no front matter in {text[:40]!r}" + payload = yaml.safe_load(text[4:].partition("\n---\n")[0]) + assert isinstance(payload, dict) + return payload + + WRITES_REWARD = "#!/bin/bash\necho 1 > /logs/verifier/reward.txt\n" # What Harbor's own template ships: a comment telling the author to write a reward, and no From bbd37af45f4fd1f7877a057113b7db08c81ff7b6 Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 16:40:43 -0500 Subject: [PATCH 10/15] fix(eval-author): stop discover from reading the optimizer's own job dirs Experimentalist writes config.json and lock.json into its job directory, which is exactly the pair _from_prior_job matches on, and prior_job outranks the profile. So running the optimizer and then discover in the same repo selected a config whose agent import path is rooted at the package Experimentalist synthesizes in sys.modules for the duration of its own run. No separate harbor process can import that, so discover reported "Harbor cannot run this repo's evals" about a repo that had just been evaluated successfully. Two guards, neither of which reshuffles SOURCE_PRIORITY. Pruning eval-and-optimize and .nemo-optimizer keeps every probe that walks the tree out of Experimentalist's output, including find_skills and _from_convention, which were picking up candidate agent copies. Discarding a config whose agent import path starts at _AGENT_IMPORT_ROOT covers the same config found anywhere else: a package synthesized in one process is by construction not runnable from a file. The constant is imported rather than copied so a rename in Experimentalist breaks the build, not the verdict. Signed-off-by: Alec Khoury --- .../nemo_eval_author_plugin/discovery/scan.py | 7 +++ .../discovery/sources.py | 24 +++++++- .../tests/discover/test_scan.py | 20 +++++++ .../tests/discover/test_sources.py | 60 +++++++++++++++++++ 4 files changed, 110 insertions(+), 1 deletion(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py index 71ce920940d..4af70e8670f 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py @@ -23,6 +23,11 @@ _GROUP = "repo" # Vendored and generated trees dwarf a repo's own content and never hold its eval setup. +# +# `eval-and-optimize` and `.nemo-optimizer` are Experimentalist's output, and pruning them is +# what keeps discover from reading the optimizer's own results as the repo's declared setup: +# they hold Harbor job dirs from the optimizer's runs and working copies of the agent, which +# every probe here would otherwise treat as candidates the repo maintains. _PRUNE_DIR_NAMES = frozenset( { ".git", @@ -39,6 +44,8 @@ "site-packages", "dist", "build", + "eval-and-optimize", + ".nemo-optimizer", } ) _MAX_WALK_DEPTH = 6 diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py index 15755a07190..df20a5cdafb 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py @@ -29,6 +29,7 @@ Finding, ) from nemo_eval_author_plugin.discovery.scan import display_path, walk_dirs +from nemo_experimentalist_plugin.experimentalist.components.evaluator.harbor import _AGENT_IMPORT_ROOT from nemo_insights_plugin.contracts.profile import ( PROFILE_FILENAME, ProfileError, @@ -181,7 +182,7 @@ def _from_prior_job(repo_root: Path) -> tuple[CandidateConfig | None, list[Findi if not config_path.is_file() or not (directory / "lock.json").is_file(): continue payload = _load_mapping(config_path) - if payload is not None and _looks_like_job_config(payload): + if payload is not None and _looks_like_job_config(payload) and not _has_synthetic_agent(payload): job_dirs.append((config_path, payload)) if not job_dirs: @@ -446,6 +447,27 @@ def _resolve_profile_path(value: str | None, profile_dir: Path) -> Path | None: return None +def _has_synthetic_agent(payload: dict[str, Any]) -> bool: + """Whether a config's agent only exists inside the process that wrote the config. + + Experimentalist's Harbor evaluator rewrites the agent's import path under a package it + synthesizes in ``sys.modules`` for the duration of its own run, so the config it leaves + behind names a module no separate ``harbor`` process can import. Harbor resolved and ran + it, which is exactly what makes it tempting: without this guard, running the optimizer + and then discover in the same repo reports "Harbor cannot run this repo's evals" about a + repo that was just evaluated successfully. + """ + agents = payload.get("agents") + if not isinstance(agents, list): + return False + return any( + isinstance(agent, dict) + and isinstance(agent.get("import_path"), str) + and agent["import_path"].startswith(f"{_AGENT_IMPORT_ROOT}.") + for agent in agents + ) + + def _looks_like_job_config(payload: dict[str, Any]) -> bool: """Whether a mapping declares a Harbor task source. diff --git a/plugins/nemo-eval-author/tests/discover/test_scan.py b/plugins/nemo-eval-author/tests/discover/test_scan.py index 43d7ecb6215..d0c516d49bc 100644 --- a/plugins/nemo-eval-author/tests/discover/test_scan.py +++ b/plugins/nemo-eval-author/tests/discover/test_scan.py @@ -77,6 +77,26 @@ def test_vendored_trees_are_not_searched(tmp_path): assert finding.path is None +def test_the_optimizer_s_own_output_is_not_part_of_the_repo(tmp_path): + """Experimentalist writes into ``.nemo-optimizer`` and ``eval-and-optimize``. + + What it leaves there is candidate agent copies and its own Harbor job dirs: results of + evaluating this repo, not declarations of how to evaluate it. Every probe that walks the + tree would otherwise read them as the repo's own setup. + """ + for relative in ( + Path(".nemo-optimizer") / "experiments" / "run-1" / "candidate", + Path("eval-and-optimize") / "results" / "job-1", + ): + (tmp_path / relative).mkdir(parents=True) + (tmp_path / relative / "SKILL.md").write_text("# a candidate's copy\n") + + walked = list(scan.walk_dirs(tmp_path)) + + assert walked == [tmp_path] + assert scan.find_skills(tmp_path).status == "warn" + + async def test_available_traces_are_counted(): finding = await scan.probe_traces(StubClient(trace_total=7), agent="ticket-triage", workspace="default") diff --git a/plugins/nemo-eval-author/tests/discover/test_sources.py b/plugins/nemo-eval-author/tests/discover/test_sources.py index 314375a1702..b81eacdbe19 100644 --- a/plugins/nemo-eval-author/tests/discover/test_sources.py +++ b/plugins/nemo-eval-author/tests/discover/test_sources.py @@ -11,6 +11,7 @@ import yaml from harbor_fixtures import write_dataset, write_job_dir, write_task, write_wrapper from nemo_eval_author_plugin.discovery import sources +from nemo_experimentalist_plugin.experimentalist.components.evaluator.harbor import _AGENT_IMPORT_ROOT def _job_config(dataset: str) -> dict: @@ -57,6 +58,65 @@ def test_trial_config_is_not_mistaken_for_a_job_config(tmp_path): assert candidate.source.kind == "convention" +def test_an_optimizer_job_dir_is_not_read_as_the_repo_s_own_setup(tmp_path): + """Experimentalist writes config.json and lock.json into its own results directory. + + Harbor really did resolve and run that config, which is what makes it outrank the profile. + But its agent import path names a package Experimentalist synthesizes in ``sys.modules`` + for the duration of its run, so no separate ``harbor`` process can import it: running the + optimizer and then discover reported "Harbor cannot run this repo's evals" about a repo + that had just been evaluated successfully. + """ + write_dataset(tmp_path / "evals" / "validation") + write_job_dir( + tmp_path / ".nemo-optimizer" / "experiments" / "run-1" / "eval-and-optimize" / "results" / "job-1", + config={ + "agents": [{"import_path": "_nemo_experimentalist_eval_agents.agent_abc123:WrappedAgent"}], + "datasets": [{"path": "evals/validation"}], + }, + ) + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "convention" + assert not any(item.name == "prior-job" for item in findings) + + +def test_a_synthetic_agent_import_path_is_rejected_wherever_it_is_found(tmp_path): + """The pruned directories are Experimentalist's defaults, not a promise about the layout.""" + write_dataset(tmp_path / "evals" / "validation") + write_job_dir( + tmp_path / "elsewhere" / "job-1", + config={ + "agents": [{"import_path": f"{_AGENT_IMPORT_ROOT}.src_agent_deadbeef:WrappedAgent"}], + "datasets": [{"path": "evals/validation"}], + }, + ) + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "convention" + + +def test_a_real_prior_job_is_still_the_stronger_source(tmp_path): + """The guard is about synthetic import paths, not about distrusting prior jobs.""" + write_dataset(tmp_path / "evals" / "validation") + write_job_dir( + tmp_path / "jobs" / "run-1", + config={ + "agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], + "datasets": [{"path": "evals/validation"}], + }, + ) + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "prior_job" + + def test_profile_outranks_convention_and_reads_the_validation_split(tmp_path): write_dataset(tmp_path / "evals" / "validation") write_dataset(tmp_path / "evals" / "train", count=3) From 695de10bfc3b51e472b81c618fca11cabdb17f36 Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 16:42:07 -0500 Subject: [PATCH 11/15] fix(eval-author): run the round trip through the Harbor the ladder used shutil.which("harbor") finds whatever PATH resolves first, which on a machine with a uv tool or pipx install is not the environment's own console script: 0.6.4 was observed on PATH against 0.18.0 imported in process. Every other rung is an in-process Harbor call and the report stamps only the in-process version, so the one rung that shells out could return a verdict from a different Harbor and say nothing about it. Prefer the script beside sys.executable, which is the one that imports the Harbor these verdicts came from, and keep PATH as the fallback for an interpreter whose scripts live elsewhere. Signed-off-by: Alec Khoury --- .../discovery/validate.py | 17 ++++++++++++++++- .../tests/discover/test_validate.py | 17 +++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py index 780d8611ece..2a362e3d1b5 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py @@ -627,7 +627,7 @@ def check_config_file(config_path: Path, repo_root: Path) -> Finding: The file is either one discovery wrote or the repo's own, whichever the artifact ends up pointing at; the check is the same either way. """ - harbor_bin = shutil.which("harbor") + harbor_bin = _harbor_executable() if harbor_bin is None: return Finding( name="round-trip", @@ -734,3 +734,18 @@ def _executable_lines(text: str) -> str: if not line.lstrip().startswith(("#", "::")) and not line.lstrip().upper().startswith("REM ") ] return "\n".join(kept) + + +def _harbor_executable() -> str | None: + """The ``harbor`` console script from the same environment as the in-process Harbor. + + ``PATH`` is not good enough here. A ``uv tool`` or ``pipx`` install shadows the + environment's own script, so a plain lookup can hand the round trip a different Harbor than + every other rung used, while the report stamps only the in-process version. The script + beside ``sys.executable`` is the one that imports the Harbor these verdicts came from. + ``PATH`` remains the fallback, for an interpreter whose scripts live elsewhere. + """ + beside = Path(sys.executable).parent / "harbor" + if beside.is_file(): + return str(beside) + return shutil.which("harbor") diff --git a/plugins/nemo-eval-author/tests/discover/test_validate.py b/plugins/nemo-eval-author/tests/discover/test_validate.py index 97e748fa8a4..1ac8347e373 100644 --- a/plugins/nemo-eval-author/tests/discover/test_validate.py +++ b/plugins/nemo-eval-author/tests/discover/test_validate.py @@ -15,7 +15,10 @@ Tests that care about the backend assert on that finding directly. """ +import subprocess import sys +from importlib.metadata import version +from pathlib import Path from typing import ClassVar from harbor_fixtures import ( @@ -389,6 +392,20 @@ async def test_a_config_the_cli_rejects_fails_the_round_trip(tmp_path): assert finding.path == config_path +async def test_the_round_trip_uses_the_harbor_that_produced_every_other_verdict(tmp_path): + """A ``uv tool`` or ``pipx`` install shadows the environment's own console script. + + The report stamps one Harbor version, so a round trip resolved off bare ``PATH`` can + contradict the rest of the ladder while claiming to agree with it. + """ + resolved = validate._harbor_executable() + + assert resolved is not None, "the environment running these tests installs harbor" + assert Path(resolved).parent == Path(sys.executable).parent + completed = subprocess.run([resolved, "--version"], capture_output=True, text=True, check=True) + assert completed.stdout.strip() == version("harbor"), "the CLI and the imported package must be one Harbor" + + async def test_the_full_pipeline_agrees_with_the_source_it_chose(tmp_path): """Sources and the ladder have to compose: what was assembled is what gets validated.""" write_dataset(tmp_path / "evals" / "validation") From c932fd552cd867d684c0bb5720a82854d76e5beb Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Fri, 31 Jul 2026 16:43:11 -0500 Subject: [PATCH 12/15] fix(eval-author): record the search path the agent import actually needs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The persisted harbor-job.yaml named a bare `harbor_wrapper:WrappedAgent`, and the command discover printed alongside it failed on the first trial with `No module named 'harbor_wrapper'`. Harbor imports agents through importlib.import_module and never adds the working directory to sys.path, so a bare module name resolves only if something already put its directory there. Worse for a nested wrapper: _find_wrapper locates src/myagent/harbor_wrapper.py and the import path dropped src/myagent entirely, while the finding's own hint pointed at the file. Nothing in the ladder could catch it. --print-config returns before any agent import, and _check_agent_import rglobbed the repo for a matching module and inserted its directory into sys.path itself — so the rung passed for a reason `harbor job start -c` would not have. That is the part worth naming: the config was not merely wrong, it was vouched for by a check that had quietly arranged its own success. _agent_entry now returns the wrapper's directory beside the import path, repo-relative like every other path in the artifact and `.` for a wrapper at the root. A Harbor JobConfig has nowhere to carry it, so it travels as run_config.pythonpath in discovery.md's front matter and as a PYTHONPATH prefix on the command both the report and the CLI print, built in one place so the two cannot drift. _check_agent_import imports with exactly that directory and nothing else: if the recorded path does not make the module importable, the rung fails and names a directory that would. The sys.modules eviction stays and now carries more weight, since with nothing added to the path a stale module is the only way an unimportable config could still pass. Three related fixes ride along, each touching the same functions closely enough that their hunks do not separate: _from_profile resolved every declared dataset as a path, so a profile pairing `validation: tau2-bench-live-validation@1.0` with a registry_url yielded a directory under the profile dir that does not exist and a Job.create FileNotFoundError — a false "cannot run" about a profile the optimizer runs daily. registry_url was not even visible before, being swallowed by extra="ignore". A ref now becomes a DatasetConfig naming name, version and registry_url, and warns that resolving it needs the registry to be reachable. Dropping base=BaseAgent matches harbor/agents/factory.py, which calls import_class(import_path, label="agent") with no base — Harbor is strict for verifiers and deliberately not for agents. A rung stricter than the gate it stands for fails repos Harbor runs. A class that is not a BaseAgent now warns instead, carrying no harbor_call because Harbor does not make that judgement. A harbor_wrapper.py whose class did not match _AGENT_BASE_CLASSES reported "No harbor_wrapper.py found" and fell back to the oracle, which replays solution/solve.sh and evaluates nothing. The file is named now, along with the bases that were looked for, so the reader is not sent hunting for something that is right there. Signed-off-by: Alec Khoury --- .../src/nemo_eval_author_plugin/cli.py | 9 +- .../discovery/models.py | 16 ++ .../discovery/report.py | 41 ++- .../discovery/sources.py | 242 ++++++++++++++---- .../discovery/validate.py | 111 +++++--- .../eval_author/README.md | 32 ++- .../tests/discover/test_command.py | 29 ++- .../tests/discover/test_report.py | 61 ++++- .../tests/discover/test_sources.py | 152 +++++++++++ .../tests/discover/test_validate.py | 138 +++++++++- .../nemo-eval-author/tests/harbor_fixtures.py | 11 +- 11 files changed, 727 insertions(+), 115 deletions(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index 596792f3615..d01232e14e7 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -19,8 +19,8 @@ import typer from nemo_eval_author_plugin.discovery import run as discovery -from nemo_eval_author_plugin.discovery.models import FILESET_NAME, JOB_CONFIG_FILENAME, Finding -from nemo_eval_author_plugin.discovery.report import run_target +from nemo_eval_author_plugin.discovery.models import FILESET_NAME, Finding +from nemo_eval_author_plugin.discovery.report import run_command, run_target from nemo_platform_plugin.cli import NemoCLI _STATUS_MARK = {"pass": " ok ", "warn": " warn ", "fail": " FAIL "} @@ -55,11 +55,12 @@ def _report_discovery(result: discovery.DiscoverResult) -> None: typer.echo(f"Harbor can run this repo's evals ({source.detail if source else 'unknown source'}).") if target.location == "repo": typer.echo(f"Run it from {record.repo_root}, using the config this repo already maintains:") - typer.echo(f" harbor job start -c {target.path}") else: typer.echo(f"Discovery wrote the config to fileset '{FILESET_NAME}' at {target.path}.") typer.echo(f"Fetch it into {record.repo_root}, then:") - typer.echo(f" harbor job start -c {JOB_CONFIG_FILENAME}") + typer.echo(f" {run_command(target)}") + if target.pythonpath is not None: + typer.echo(f" PYTHONPATH is required: Harbor imports the agent module from {target.pythonpath}.") if record.required_env_vars: typer.echo(f" Needs: {', '.join(item.name for item in record.required_env_vars)}") else: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py index 472178dc402..3c4134e2c3f 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py @@ -37,6 +37,13 @@ SOURCE_PRIORITY: tuple[SourceKind, ...] = ("config_file", "prior_job", "profile", "convention") +AGENT_SEARCH_PATH_DESCRIPTION = ( + "Repo-relative directory that must be on PYTHONPATH for the config's agent import " + "path to resolve, or None when it names no module. Harbor imports agents with plain " + "importlib and never adds the working directory, and a Harbor JobConfig has nowhere to " + "record this, so it travels beside the config instead of in it." +) + class Finding(BaseModel): """One thing discover learned, and who vouches for it.""" @@ -87,6 +94,10 @@ class CandidateConfig(BaseModel): data: dict[str, Any] source: ConfigSource + agent_search_path: str | None = Field( + default=None, + description=AGENT_SEARCH_PATH_DESCRIPTION, + ) class RunTarget(BaseModel): @@ -100,6 +111,10 @@ class RunTarget(BaseModel): location: Literal["repo", "fileset"] path: str + pythonpath: str | None = Field( + default=None, + description=AGENT_SEARCH_PATH_DESCRIPTION, + ) class RequiredEnvVar(BaseModel): @@ -122,6 +137,7 @@ class DiscoveryReport(BaseModel): "which is why Harbor stamps its own version into lock.json.", ) config_source: ConfigSource | None = None + agent_search_path: str | None = Field(default=None, description=AGENT_SEARCH_PATH_DESCRIPTION) findings: list[Finding] = Field(default_factory=list) required_env_vars: list[RequiredEnvVar] = Field(default_factory=list) discovered_at: datetime diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py index 97aafe8421d..f2ac61d4496 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py @@ -14,6 +14,12 @@ Paths in the persisted config are rewritten relative to the repo root. An absolute path would encode this machine into an artifact meant to outlive it, so the config is written to be run from ``repo_root``, and the front matter records where that is. + +``run_config.pythonpath`` is part of that contract rather than a convenience. A Harbor +``JobConfig`` has no field for a module search path, and Harbor imports an agent with plain +``importlib``, so a config naming a bare ``harbor_wrapper:WrappedAgent`` runs only with that +directory exported. Recording the config without it would hand out a command that fails on +the first trial. """ from datetime import UTC, datetime @@ -64,6 +70,7 @@ def build_report( repo_root=repo_root, harbor_version=harbor_version(), config_source=candidate.source if candidate is not None else None, + agent_search_path=candidate.agent_search_path if candidate is not None else None, findings=findings, required_env_vars=required_env_vars, discovered_at=discovered_at or datetime.now(UTC), @@ -82,8 +89,28 @@ def run_target(report: DiscoveryReport) -> RunTarget | None: return None source = report.config_source if source is not None and source.owns_file and source.path is not None: - return RunTarget(location="repo", path=display_path(source.path, report.repo_root)) - return RunTarget(location="fileset", path=f"{report.agent}/{JOB_CONFIG_FILENAME}") + return RunTarget( + location="repo", + path=display_path(source.path, report.repo_root), + pythonpath=report.agent_search_path, + ) + return RunTarget( + location="fileset", + path=f"{report.agent}/{JOB_CONFIG_FILENAME}", + pythonpath=report.agent_search_path, + ) + + +def run_command(target: RunTarget) -> str: + """The exact command a later run issues, search path included when the agent needs one. + + Built here rather than in each renderer so the command the CLI prints and the one the + artifact records cannot drift; a reader who copies whichever they saw has no way to tell + that the other said something else. + """ + config_arg = target.path if target.location == "repo" else JOB_CONFIG_FILENAME + prefix = f"PYTHONPATH={target.pythonpath} " if target.pythonpath is not None else "" + return f"{prefix}harbor job start -c {config_arg}" def render_job_config(config: JobConfig, repo_root: Path) -> str: @@ -165,10 +192,8 @@ def _verdict_section(report: DiscoveryReport) -> list[str]: source = report.config_source if target.location == "repo": - config_arg = target.path where = f"From `{report.repo_root}`, because the config's paths are relative to it:" else: - config_arg = JOB_CONFIG_FILENAME where = f"Fetch `{target.path}` from the `{report.workspace}` workspace into `{report.repo_root}`, then:" lines = [ @@ -178,10 +203,16 @@ def _verdict_section(report: DiscoveryReport) -> list[str]: where, "", "```bash", - f"harbor job start -c {config_arg}", + run_command(target), "```", "", ] + if target.pythonpath is not None: + lines += [ + f"`PYTHONPATH` is required: the agent is the module in `{target.pythonpath}`, and Harbor " + "imports it with plain `importlib`, which does not search the working directory.", + "", + ] if report.required_env_vars: names = " ".join(f"{item.name}=..." for item in report.required_env_vars) lines += [f"Set the host variables first: `{names}`", ""] diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py index df20a5cdafb..d1af96b1ebc 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py @@ -13,14 +13,17 @@ accepted it" into a property that can be checked rather than a promise: if this module returned a parsed ``JobConfig``, the schema rung would already have run off to the side. -Paths come back absolute so validation needs no working-directory tricks. Rewriting them -relative to the repo for the persisted artifact is ``report``'s job. +Paths inside the config come back absolute so validation needs no working-directory tricks. +Rewriting them relative to the repo for the persisted artifact is ``report``'s job. The one +exception is ``CandidateConfig.agent_search_path``, which is repo-relative from the start +because it is not a config field: it is the ``PYTHONPATH`` a run needs, and both the ladder +and the artifact read it as written. """ import ast import json from pathlib import Path -from typing import Any +from typing import Any, Literal, NamedTuple import yaml from nemo_eval_author_plugin.discovery.models import ( @@ -41,6 +44,8 @@ _GROUP = "config" +DatasetKind = Literal["path", "ref"] + # `harbor job init` writes into `configs/` unless told otherwise, so look there first. _CONFIG_SEARCH_DIRS = ("configs", ".", "harbor", ".harbor", "evals") _CONFIG_SUFFIXES = (".yaml", ".yml", ".json") @@ -57,6 +62,13 @@ class _ProfileDatasets(BaseModel): train: str | None = None validation: str | None = None + registry_url: str | None = None + """Present or absent, this decides how the split values are read, so it cannot be ignored. + + ``extra="ignore"`` swallowed it before, which left every value looking like a local path + and turned ``validation: tau2-bench-live-validation@1.0`` into a directory that is not + there. + """ class _DiscoveryProfile(BaseModel): @@ -241,11 +253,11 @@ def _from_profile(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding ) ] - # validation is the eval set; train exists to optimize against, so preferring it - # here would quietly evaluate on the wrong split. + # validation first: it is the eval set, and train exists to optimize against, so + # preferring train here would quietly evaluate on the wrong split. declared = {"validation": profile.datasets.validation, "train": profile.datasets.train} - chosen_split = next((split for split in ("validation", "train") if declared[split]), None) - if chosen_split is None: + evaluable = [(split, value) for split, value in declared.items() if value] + if not evaluable: findings.append( Finding( name="profile-datasets", @@ -257,47 +269,82 @@ def _from_profile(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding ) return None, findings - dataset_path = _resolve_profile_path(declared[chosen_split], profile.profile_dir) - if dataset_path is None: + chosen_split, declared_value = evaluable[0] + other_split = "train" if chosen_split == "validation" else "validation" + also_declares = ( + f"{PROFILE_FILENAME} also declares datasets.{other_split}, which is not evaluated here." + if declared[other_split] + else None + ) + registry_url = profile.datasets.registry_url + + if classify_dataset_value(declared_value, profile.profile_dir, registry_url=registry_url) == "ref": + dataset_entry = _registry_dataset(declared_value, registry_url) findings.append( Finding( name="profile-datasets", group=_GROUP, + # A ref is a legitimate way to declare a dataset, and one this machine may + # have no reach to. Recorded as a warning rather than passed over in silence, + # because a reader of the artifact cannot see the tasks the way they can for + # a local path. status="warn", - message=f"Could not resolve datasets.{chosen_split} from {PROFILE_FILENAME}", + message=( + f"datasets.{chosen_split} is the registry ref '{declared_value}', " + f"which a run downloads rather than reads from this repo" + ), path=profile_path, + hint=" ".join( + filter( + None, + [ + "Resolving it needs the registry to be reachable, and Harbor caches " + "it under ~/.cache/harbor on first use.", + also_declares, + ], + ) + ), ) ) - return None, findings + else: + dataset_path = _resolve_profile_path(declared_value, profile.profile_dir) + if dataset_path is None: + findings.append( + Finding( + name="profile-datasets", + group=_GROUP, + status="warn", + message=f"Could not resolve datasets.{chosen_split} from {PROFILE_FILENAME}", + path=profile_path, + ) + ) + return None, findings - other_split = "train" if chosen_split == "validation" else "validation" - findings.append( - Finding( - name="profile-datasets", - group=_GROUP, - status="pass", - message=f"Evaluating datasets.{chosen_split} at {display_path(dataset_path, repo_root)}", - path=dataset_path, - hint=( - f"{PROFILE_FILENAME} also declares datasets.{other_split}, which is not evaluated here." - if declared[other_split] - else None - ), + dataset_entry = {"path": str(dataset_path)} + findings.append( + Finding( + name="profile-datasets", + group=_GROUP, + status="pass", + message=f"Evaluating datasets.{chosen_split} at {display_path(dataset_path, repo_root)}", + path=dataset_path, + hint=also_declares, + ) ) - ) agent_root = _resolve_profile_path(profile.agent_source, profile.profile_dir) or repo_root - agent_entry, agent_findings = _agent_entry(agent_root, repo_root) - findings.extend(agent_findings) + agent = _agent_entry(agent_root, repo_root) + findings.extend(agent.findings) return ( CandidateConfig( - data={"agents": [agent_entry], "datasets": [{"path": str(dataset_path)}]}, + data={"agents": [agent.data], "datasets": [dataset_entry]}, source=ConfigSource( kind="profile", detail=f"assembled from {PROFILE_FILENAME} datasets.{chosen_split}", path=profile_path, ), + agent_search_path=agent.search_path, ), findings, ) @@ -346,17 +393,18 @@ def _from_convention(repo_root: Path) -> tuple[CandidateConfig | None, list[Find ) ] - agent_entry, agent_findings = _agent_entry(repo_root, repo_root) - findings.extend(agent_findings) + agent = _agent_entry(repo_root, repo_root) + findings.extend(agent.findings) return ( CandidateConfig( - data={"agents": [agent_entry], "datasets": [{"path": str(chosen)}]}, + data={"agents": [agent.data], "datasets": [{"path": str(chosen)}]}, source=ConfigSource( kind="convention", detail=f"inferred from task dirs under {shown}", path=chosen, ), + agent_search_path=agent.search_path, ), findings, ) @@ -371,39 +419,88 @@ def _preferred_dataset_dir(repo_root: Path, dataset_dirs: dict[Path, list[Path]] return max(dataset_dirs, key=lambda parent: (len(dataset_dirs[parent]), str(parent))) -def _agent_entry(agent_root: Path, repo_root: Path) -> tuple[dict[str, Any], list[Finding]]: +class _AgentEntry(NamedTuple): + """One ``agents`` entry, plus the search path the entry needs to be importable.""" + + data: dict[str, Any] + search_path: str | None + findings: list[Finding] + + +def _agent_entry(agent_root: Path, repo_root: Path) -> _AgentEntry: """Describe the agent to run, preferring a wrapper in the repo over Harbor's default. Falls back to ``oracle``, which is what Harbor itself defaults to and the only agent that needs no model or credentials. It runs ``solution/solve.sh``, so a config that lands here still proves the tasks work even though it evaluates nothing. + + A wrapper yields a bare ``module:Class`` import path, which is what Harbor's own + examples use, plus the directory holding that module. The directory is not decoration: + Harbor imports through ``importlib.import_module`` and adds nothing to ``sys.path``, so + a bare module name resolves only if something already put its directory there. Recording + it is what lets the artifact hand out a run command that works, and a nested wrapper is + why it cannot be assumed to be the repo root. """ wrapper = _find_wrapper(agent_root) or _find_wrapper(repo_root) if wrapper is None: - return {"name": "oracle"}, [ + return _AgentEntry({"name": "oracle"}, None, [_no_wrapper_finding(agent_root, repo_root)]) + + path, class_name = wrapper + search_path = display_path(path.parent, repo_root) + return _AgentEntry( + {"import_path": f"{path.stem}:{class_name}"}, + search_path, + [ Finding( name="agent-entrypoint", group=_GROUP, - status="warn", - message=f"No {_WRAPPER_FILENAME} found; falling back to Harbor's oracle agent", - hint=( - "The oracle replays solution/solve.sh, so it validates the tasks but " - "evaluates no agent. Add a harbor_wrapper.py to evaluate yours." - ), + status="pass", + message=f"Agent import path {path.stem}:{class_name}, importable from {search_path}", + path=path, + hint=f"Read from the class definition in {display_path(path, repo_root)}, not assumed.", ) - ] + ], + ) - path, class_name = wrapper - return {"import_path": f"{path.stem}:{class_name}"}, [ - Finding( + +def _no_wrapper_finding(agent_root: Path, repo_root: Path) -> Finding: + """Say why the oracle is standing in, distinguishing no wrapper from no agent in one. + + The two read identically from the config and mean opposite things. A repo with no + wrapper has nothing to evaluate yet; a repo whose wrapper this module could not + recognize has an agent that is simply not being run, and reporting that as "no + harbor_wrapper.py found" sends its author looking for a missing file. + """ + unmatched = _wrapper_paths(agent_root) or _wrapper_paths(repo_root) + oracle = ( + "The oracle replays solution/solve.sh, so it validates the tasks but evaluates no agent. " + "Add a harbor_wrapper.py to evaluate yours." + ) + if not unmatched: + return Finding( name="agent-entrypoint", group=_GROUP, - status="pass", - message=f"Agent import path {path.stem}:{class_name}", - path=path, - hint=f"Read from the class definition in {display_path(path, repo_root)}, not assumed.", + status="warn", + message=f"No {_WRAPPER_FILENAME} found; falling back to Harbor's oracle agent", + hint=oracle, ) - ] + + bases = " or ".join(sorted(_AGENT_BASE_CLASSES)) + return Finding( + name="agent-entrypoint", + group=_GROUP, + status="warn", + message=( + f"{display_path(unmatched[0], repo_root)} declares no class based on {bases}; " + "falling back to Harbor's oracle agent" + ), + path=unmatched[0], + hint=( + f"The base is matched by name in the source, so a wrapper reaching {bases} through an " + "alias or an intermediate class is not recognized. A Harbor config file declaring the " + "agent's import_path outranks this source, and would run it. " + oracle + ), + ) def _find_wrapper(root: Path) -> tuple[Path, str] | None: @@ -413,16 +510,18 @@ def _find_wrapper(root: Path) -> tuple[Path, str] | None: repo, but a wrapper is a file the user wrote and the ladder's agent rung is the thing that gets to import it. """ - for directory in walk_dirs(root): - path = directory / _WRAPPER_FILENAME - if not path.is_file(): - continue + for path in _wrapper_paths(root): class_name = _agent_class_name(path) if class_name is not None: return path, class_name return None +def _wrapper_paths(root: Path) -> list[Path]: + """Every ``harbor_wrapper.py`` under *root*, shallowest first.""" + return [directory / _WRAPPER_FILENAME for directory in walk_dirs(root) if (directory / _WRAPPER_FILENAME).is_file()] + + def _agent_class_name(path: Path) -> str | None: try: tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) @@ -438,6 +537,45 @@ def _agent_class_name(path: Path) -> str | None: return None +def classify_dataset_value(value: str, base_dir: Path, *, registry_url: str | None = None) -> DatasetKind: + """Classify an ``optimizer.yaml`` dataset value as a local path or a Harbor registry ref. + + Mirrors ``nemo_experimentalist_plugin.resolve.classify_dataset_value``, which is the rule + Experimentalist applies to the same file, so the two must agree — a value the optimizer + downloads and discover resolves as a path yields an artifact about a directory nobody has. + A copy rather than an import because Eval Author's dependency on Experimentalist is being + removed rather than added to; ``test_sources.py`` pins the agreement instead. + """ + if value.startswith(("./", "../", "/", "~")): + return "path" + if registry_url is not None: + return "ref" + if "/" in value: + return "path" + try: + if (base_dir / value).exists(): + return "path" + except OSError: # not representable as a local path (e.g. name too long) + pass + return "ref" + + +def _registry_dataset(value: str, registry_url: str | None) -> dict[str, Any]: + """A ``DatasetConfig`` naming a registry dataset, which is what Harbor resolves refs from. + + ``name`` and ``version`` rather than ``path``: Harbor's ``DatasetConfig`` rejects both at + once, and a ref pointed at ``path`` is how the profile's ``name@version`` became a + nonexistent directory under the profile dir. + """ + name, separator, version = value.partition("@") + entry: dict[str, Any] = {"name": name} + if separator: + entry["version"] = version + if registry_url is not None: + entry["registry_url"] = registry_url + return entry + + def _resolve_profile_path(value: str | None, profile_dir: Path) -> Path | None: if not value: return None diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py index 2a362e3d1b5..4857f098e77 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py @@ -18,14 +18,17 @@ 4. coverage every task dir on disk against the set ``Job.create`` actually resolved, because Harbor drops one it cannot parse without raising. 5. credentials ``get_required_host_vars`` over the task and job env templates. -6. agent ``import_class(..., base=BaseAgent)`` or ``AgentFactory.get_agent_class``. +6. agent ``import_class`` or ``AgentFactory.get_agent_class``, called the way Harbor's + own ``AgentFactory`` calls them. 7. backend ``EnvironmentFactory.run_preflight``. 8. round trip ``harbor job start --print-config -c `` against the persisted bytes. -The one exception is the reward advisory, which reads the test scripts itself because -Harbor has no API that answers the question before a trial runs. It carries no -``harbor_call`` and can only warn, since a text search cannot tell a script that writes a -reward through a variable from one that never writes a reward at all. +Two findings are ours rather than Harbor's, and neither carries a ``harbor_call``. The reward +advisory reads the test scripts itself, because Harbor has no API that answers the question +before a trial runs, and it can only warn since a text search cannot tell a script that writes +a reward through a variable from one that never writes a reward at all. The agent base-class +advisory is a judgement Harbor deliberately does not make: it enforces a base for verifiers +and not for agents, so an agent that is a plain class is worth saying and not worth failing. A failing rung is recorded, not raised. A report listing every problem is worth more than one that stops at the first, and the command's whole job is to say why a repo cannot run. @@ -58,6 +61,7 @@ from harbor.utils.env import get_required_host_vars from harbor.utils.import_path import import_class from nemo_eval_author_plugin.discovery.models import CandidateConfig, Finding, RequiredEnvVar, Status +from nemo_eval_author_plugin.discovery.scan import display_path from pydantic import ValidationError _GROUP = "validation" @@ -124,7 +128,7 @@ async def _ladder(candidate: CandidateConfig, repo_root: Path) -> ValidationOutc outcome.config = config job = await _rung_resolution(config, outcome) - _rung_agent(config, repo_root, outcome) + _rung_agent(config, repo_root, candidate.agent_search_path, outcome) _rung_backend(config, outcome) if job is None: return outcome @@ -506,25 +510,38 @@ def collect(env: dict[str, str], declared_in: Path) -> None: ) -def _rung_agent(config: JobConfig, repo_root: Path, outcome: ValidationOutcome) -> None: +def _rung_agent(config: JobConfig, repo_root: Path, search_path: str | None, outcome: ValidationOutcome) -> None: """Does the agent this config names actually exist? Importing the class proves what matters without constructing it. Harbor instantiates agents at trial time, but a discovery command has no business running a user's - ``__init__``, and ``import_class`` already enforces the ``BaseAgent`` contract. + ``__init__``. """ for agent in config.agents: if agent.import_path is not None: - _check_agent_import(agent.import_path, repo_root, outcome) + _check_agent_import(agent.import_path, repo_root, search_path, outcome) elif agent.name is not None: _check_agent_name(agent.name, outcome) -def _check_agent_import(import_path: str, repo_root: Path, outcome: ValidationOutcome) -> None: +def _check_agent_import(import_path: str, repo_root: Path, search_path: str | None, outcome: ValidationOutcome) -> None: + """Import the agent with the search path the persisted config will actually get. + + *search_path* is the single directory the artifact tells a run to put on ``PYTHONPATH``, + or ``None`` when the config came with an import path we did not author. Arranging the + import any other way — searching the repo for a file named after the module, say — passes + this rung for a reason ``harbor job start -c`` will not have, which is how a config that + cannot import its own agent came to be recorded as runnable. + + ``base`` is deliberately not passed. Harbor's ``AgentFactory`` calls + ``import_class(import_path, label="agent")``, strict for verifiers and not for agents, and + a rung stricter than the gate it stands for fails repos Harbor would run. + """ module_name = import_path.split(":", 1)[0] - with _module_search_path(repo_root, module_name): + search_dir = None if search_path is None else (repo_root / search_path).resolve() + with _module_search_path(search_dir, module_name): try: - agent_class = import_class(import_path, base=BaseAgent, label="agent") + agent_class = import_class(import_path, label="agent") except Exception as exc: outcome.findings.append( _harbor( @@ -532,7 +549,7 @@ def _check_agent_import(import_path: str, repo_root: Path, outcome: ValidationOu "fail", f"Could not load agent {import_path}: {type(exc).__name__}: {exc}", "import_class", - hint="Harbor needs the module importable and the class to subclass BaseAgent.", + hint=_import_hint(repo_root, module_name, search_path), ) ) return @@ -540,10 +557,47 @@ def _check_agent_import(import_path: str, repo_root: Path, outcome: ValidationOu _harbor( "agent", "pass", - f"Agent {import_path} imports and subclasses BaseAgent ({agent_class.__name__})", + f"Agent {import_path} imports as a class ({agent_class.__name__})" + + (f", searching {search_path}" if search_path is not None else ""), "import_class", ) ) + if not issubclass(agent_class, BaseAgent): + outcome.findings.append( + Finding( + name="agent-base", + group=_GROUP, + status="warn", + message=f"{import_path} does not subclass harbor.agents.base.BaseAgent", + hint=( + "Harbor imports agents without checking a base class, so a run starts and " + "then fails at trial time on whichever method it expected." + ), + ) + ) + + +def _import_hint(repo_root: Path, module_name: str, search_path: str | None) -> str: + """Say what would make the import work, naming a directory holding the module if one does. + + The search is for the hint only. Letting it widen the path the rung imports from is the + bug this whole function exists to explain. + """ + top = module_name.split(".", 1)[0] + found = [ + display_path(path.parent, repo_root) + for path in sorted(repo_root.rglob(f"{top}.py")) + if ".venv" not in path.parts and "site-packages" not in path.parts + ] + reason = ( + "Harbor imports the agent with plain importlib and never adds the working directory to sys.path." + if search_path is None + else f"PYTHONPATH={search_path} is what this config is recorded with, and {top} does not import from there." + ) + remainder = [directory for directory in found if directory != search_path] + if remainder: + return f"{reason} {top}.py is at {remainder[0]}, so a run needs PYTHONPATH={remainder[0]} from the repo root." + return reason def _check_agent_name(name: str, outcome: ValidationOutcome) -> None: @@ -674,32 +728,29 @@ def check_config_file(config_path: Path, repo_root: Path) -> Finding: @contextlib.contextmanager -def _module_search_path(repo_root: Path, module_name: str) -> Iterator[None]: - """Make *module_name* importable from this repo, then undo it. +def _module_search_path(directory: Path | None, module_name: str) -> Iterator[None]: + """Put exactly *directory* on ``sys.path`` for the duration, then undo it. - Two things have to be arranged. A wrapper is referenced as - ``harbor_wrapper:WrappedAgent``, a bare module name that only imports if its directory - is on ``sys.path``; Harbor's callers arrange that themselves at run time. + One directory, because that is what the artifact tells a run to export as ``PYTHONPATH`` + and the rung is only worth anything if it imports from the same place. ``None`` adds + nothing, which is what a separate ``harbor`` process gets. - And the name has to be evicted from ``sys.modules`` first. ``harbor_wrapper`` is a + The eviction is unconditional and matters more than the insertion. ``harbor_wrapper`` is a convention, so two different repos, or the same repo before and after an edit, claim the - same module name. Without eviction the second import silently returns the first repo's - module and the rung would validate a file that is not the one under inspection. Both + same module name. Without it the second import silently returns the first repo's module and + the rung would validate a file that is not the one under inspection — and with nothing + added to the path, a stale entry is the only way the import could succeed at all. Both changes are reversed on the way out, since this process did not ask to be reshaped. """ top = module_name.split(".", 1)[0] - directories = [ - path.parent - for path in sorted(repo_root.rglob(f"{top}.py")) - if ".venv" not in path.parts and "site-packages" not in path.parts - ] - added = [str(directory) for directory in directories if str(directory) not in sys.path] - sys.path[:0] = added + entry = str(directory) if directory is not None and str(directory) not in sys.path else None + if entry is not None: + sys.path.insert(0, entry) displaced = sys.modules.pop(top, None) try: yield finally: - for entry in added: + if entry is not None: with contextlib.suppress(ValueError): sys.path.remove(entry) sys.modules.pop(top, None) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md index c929090c465..b8df64c46aa 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md @@ -40,10 +40,13 @@ reimplemented rules: schema, job resolution, task validity and coverage, required host variables, the agent class, the environment backend, and a round trip of the persisted bytes through `harbor job start --print-config`. [`discovery/validate.py`](../discovery/validate.py) names the Harbor API behind -each rung. Findings that Harbor returned carry a `harbor_call`; the one check -that reads the repository directly — whether each test script names a reward -file — carries none and can only warn, because a script that builds the path in -a variable is indistinguishable from one that writes nothing. +each rung. Findings that Harbor returned carry a `harbor_call`; the two checks +that are discovery's own carry none and can only warn. Whether each test script +names a reward file is read from the repository, because a script that builds +the path in a variable is indistinguishable from one that writes nothing. +Whether the agent subclasses `BaseAgent` is a judgement Harbor deliberately +does not make — it is strict for verifiers and not for agents — so failing it +would block a repository Harbor's own gate accepts. The result is recorded to the `nemo-eval-author` fileset as `/discovery.md`. A `/harbor-job.yaml` is published alongside the @@ -51,6 +54,27 @@ report only when discovery authored the config; when the repository maintains its own valid config file, the report points at that file instead. Nothing is written into the repository under inspection. +When the config's agent is a `harbor_wrapper.py` in the repository, the run +command carries the wrapper's directory as `PYTHONPATH`: + +```bash +PYTHONPATH=src/myagent harbor job start -c harbor-job.yaml +``` + +This is not a convenience. Harbor imports an agent with plain +`importlib.import_module` and never adds the working directory to `sys.path`, so +a config naming `harbor_wrapper:WrappedAgent` fails at the first trial with +`No module named 'harbor_wrapper'` without it. A Harbor `JobConfig` has no field +for a module search path, so it is recorded beside the config as +`run_config.pythonpath` in the report's front matter, repo-relative like every +other path in the artifact — `.` for a wrapper at the repository root. The agent +rung imports with exactly that search path and nothing else, so a rung that +passes is a rung the recorded command will pass too. + +A dataset the profile declares as a registry ref alongside a `registry_url` is +recorded as a ref Harbor downloads rather than as a local directory, and +reported as a warning because resolving it needs the registry to be reachable. + Every run revalidates from scratch. The report is a record of what was true when it was written, not a cache that a later run consults. diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index c733e9242eb..82cf751cf9a 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -85,10 +85,31 @@ def test_a_healthy_repo_exits_zero_and_records_both_artifacts(app, client, tmp_p assert result.exit_code == 0, result.output assert "Harbor can run this repo's evals" in result.output - assert "harbor job start -c harbor-job.yaml" in result.output + assert "PYTHONPATH=. harbor job start -c harbor-job.yaml" in result.output assert sorted(client.files.stored) == [f"{AGENT}/discovery.md", f"{AGENT}/harbor-job.yaml"] +def test_the_command_printed_for_a_nested_wrapper_can_actually_import_it(app, client, tmp_path): + """The command is the deliverable, so it has to name the directory the module is in. + + ``harbor job start -c harbor-job.yaml`` against a config naming ``harbor_wrapper`` fails + with ``No module named 'harbor_wrapper'``; Harbor's importer never looks in the working + directory. The printed command and the recorded one both have to carry the fix, and + they have to agree. + """ + write_dataset(tmp_path / "evals" / "validation") + write_wrapper(tmp_path / "src" / "myagent") + + result = _invoke_named(app, tmp_path) + + assert result.exit_code == 0, result.output + assert "PYTHONPATH=src/myagent harbor job start -c harbor-job.yaml" in result.output + front = read_front_matter(client.files.stored[memory.remote_report_path(AGENT)]) + assert front["run_config"]["pythonpath"] == "src/myagent" + # The config itself is a Harbor JobConfig and has nowhere to say this. + assert "PYTHONPATH" not in client.files.stored[f"{AGENT}/{JOB_CONFIG_FILENAME}"].decode() + + def test_a_repo_that_maintains_its_own_config_keeps_it_and_records_only_the_report(app, client, tmp_path): """The repo's file is what Harbor validated, so a copy in the fileset could only drift from it.""" write_dataset(tmp_path / "evals" / "validation") @@ -276,4 +297,8 @@ def test_the_uploaded_report_carries_the_verdict_that_was_printed(app, client, t front = read_front_matter(client.files.stored[memory.remote_report_path(AGENT)]) assert front["runnable"] is True assert front["config_source"]["kind"] == "convention" - assert front["run_config"] == {"location": "fileset", "path": f"{AGENT}/{JOB_CONFIG_FILENAME}"} + assert front["run_config"] == { + "location": "fileset", + "path": f"{AGENT}/{JOB_CONFIG_FILENAME}", + "pythonpath": None, + } diff --git a/plugins/nemo-eval-author/tests/discover/test_report.py b/plugins/nemo-eval-author/tests/discover/test_report.py index 0a937116904..bfb0f660013 100644 --- a/plugins/nemo-eval-author/tests/discover/test_report.py +++ b/plugins/nemo-eval-author/tests/discover/test_report.py @@ -33,6 +33,14 @@ def _record(tmp_path, findings=(), env_vars=(), candidate=None): ) +def _authored(**kwargs): + return CandidateConfig( + data={}, + source=ConfigSource(kind="convention", detail="inferred from task dirs under evals/validation"), + **kwargs, + ) + + def test_front_matter_survives_a_round_trip(tmp_path): record = _record( tmp_path, @@ -68,28 +76,65 @@ def test_a_repo_that_maintains_its_own_config_is_told_to_run_that_file(tmp_path) markdown = report.render_markdown(record) front = read_front_matter(markdown) - assert front["run_config"] == {"location": "repo", "path": "configs/eval.yaml"} + assert front["run_config"] == {"location": "repo", "path": "configs/eval.yaml", "pythonpath": None} assert "harbor job start -c configs/eval.yaml" in markdown assert "harbor-job.yaml" not in markdown def test_a_config_discovery_authored_points_at_the_fileset_copy(tmp_path): """Nothing in the repo declares a config, so the fileset is the only place it exists.""" - record = _record( - tmp_path, - candidate=CandidateConfig( - data={}, source=ConfigSource(kind="convention", detail="inferred from task dirs under evals/validation") - ), - ) + record = _record(tmp_path, candidate=_authored()) markdown = report.render_markdown(record) front = read_front_matter(markdown) - assert front["run_config"] == {"location": "fileset", "path": "ticket-triage/harbor-job.yaml"} + assert front["run_config"] == { + "location": "fileset", + "path": "ticket-triage/harbor-job.yaml", + "pythonpath": None, + } assert "harbor job start -c harbor-job.yaml" in markdown assert "Fetch `ticket-triage/harbor-job.yaml`" in markdown, "the config is not on disk yet" +def test_a_config_whose_agent_is_a_repo_module_records_the_search_path_in_the_command(tmp_path): + """A Harbor JobConfig cannot carry this, and the run fails without it. + + ``harbor job start -c harbor-job.yaml`` on a config naming ``harbor_wrapper:WrappedAgent`` + raises ``No module named 'harbor_wrapper'``: Harbor imports through ``importlib`` and the + working directory is not on ``sys.path``. So the search path is part of the contract, in + the front matter for the agent that reads it and in the command for the human who runs it. + """ + record = _record(tmp_path, candidate=_authored(agent_search_path="src/myagent")) + + markdown = report.render_markdown(record) + front = read_front_matter(markdown) + + assert front["run_config"]["pythonpath"] == "src/myagent" + assert "PYTHONPATH=src/myagent harbor job start -c harbor-job.yaml" in markdown + + +def test_a_wrapper_at_the_repo_root_records_a_repo_relative_dot(tmp_path): + """Recorded relative like every other path, so the artifact outlives this machine.""" + record = _record(tmp_path, candidate=_authored(agent_search_path=".")) + + markdown = report.render_markdown(record) + target = report.run_target(record) + + assert read_front_matter(markdown)["run_config"]["pythonpath"] == "." + assert "PYTHONPATH=. harbor job start -c harbor-job.yaml" in markdown + assert target is not None and str(tmp_path) not in report.run_command(target) + + +def test_a_config_naming_a_builtin_agent_asks_for_no_search_path(tmp_path): + """The oracle is Harbor's own, so there is nothing to put on the path.""" + record = _record(tmp_path, candidate=_authored()) + + markdown = report.render_markdown(record) + + assert "PYTHONPATH" not in markdown + + def test_the_persisted_config_carries_no_absolute_paths(tmp_path): dataset = write_dataset(tmp_path / "evals" / "validation", count=1) config = JobConfig.model_validate({"datasets": [{"path": str(dataset)}]}) diff --git a/plugins/nemo-eval-author/tests/discover/test_sources.py b/plugins/nemo-eval-author/tests/discover/test_sources.py index b81eacdbe19..5599f9a10fa 100644 --- a/plugins/nemo-eval-author/tests/discover/test_sources.py +++ b/plugins/nemo-eval-author/tests/discover/test_sources.py @@ -9,9 +9,11 @@ """ import yaml +from harbor.models.job.config import JobConfig from harbor_fixtures import write_dataset, write_job_dir, write_task, write_wrapper from nemo_eval_author_plugin.discovery import sources from nemo_experimentalist_plugin.experimentalist.components.evaluator.harbor import _AGENT_IMPORT_ROOT +from nemo_experimentalist_plugin.resolve import classify_dataset_value def _job_config(dataset: str) -> dict: @@ -137,6 +139,91 @@ def test_profile_outranks_convention_and_reads_the_validation_split(tmp_path): assert split.hint is not None and "train" in split.hint +def test_a_registry_dataset_ref_is_passed_to_harbor_as_a_ref(tmp_path): + """A ref is a name Harbor downloads, not a directory under the profile. + + ``resolve_profile_path`` has no registry awareness, so it turned + ``tau2-bench-live-validation@1.0`` into ``/tau2-bench-live-validation@1.0`` and + ``Job.create`` raised ``FileNotFoundError`` — discover reporting "cannot run" about a + profile the optimizer runs every day. + """ + (tmp_path / "optimizer.yaml").write_text( + yaml.safe_dump( + { + "agent": "nemo-oo-airline", + "datasets": { + "train": "tau2-bench-live-train@1.0", + "validation": "tau2-bench-live-validation@1.0", + "registry_url": "https://registry.example/registry.json", + }, + } + ) + ) + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.source.kind == "profile" + assert candidate.data["datasets"] == [ + { + "name": "tau2-bench-live-validation", + "version": "1.0", + "registry_url": "https://registry.example/registry.json", + } + ] + # Harbor is the judge of whether that names a dataset it can fetch. + assert JobConfig.model_validate(candidate.data).datasets[0].is_registry() + split = next(item for item in findings if item.name == "profile-datasets") + assert split.status == "warn" + assert "registry ref" in split.message + assert split.hint is not None and "reachable" in split.hint + + +def test_a_local_dataset_path_is_unaffected_by_a_declared_registry(tmp_path): + """An explicit relative path stays a path, which is the rule Experimentalist applies.""" + write_dataset(tmp_path / "evals" / "validation") + (tmp_path / "optimizer.yaml").write_text( + yaml.safe_dump( + { + "datasets": { + "validation": "./evals/validation", + "registry_url": "https://registry.example/registry.json", + } + } + ) + ) + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.data["datasets"] == [{"path": str(tmp_path / "evals" / "validation")}] + assert next(item for item in findings if item.name == "profile-datasets").status == "pass" + + +def test_the_dataset_classifier_agrees_with_experimentalist(tmp_path): + """The copy exists to keep the plugin boundary shrinking, not to hold a second opinion. + + Both plugins read the same ``optimizer.yaml``. A value the optimizer downloads and discover + resolves as a path would produce an artifact describing a directory nobody has. + """ + (tmp_path / "local-dir").mkdir() + values = [ + "./evals/validation", + "../sibling/evals", + "/absolute/evals", + "~/evals", + "local-dir", + "not-on-disk", + "namespaced/dataset", + "tau2-bench-live-validation@1.0", + ] + + for registry_url in (None, "https://registry.example/registry.json"): + ours = [sources.classify_dataset_value(value, tmp_path, registry_url=registry_url) for value in values] + theirs = [classify_dataset_value(value, tmp_path, registry_url=registry_url) for value in values] + assert ours == theirs, f"classifiers disagree with registry_url={registry_url}" + + def test_convention_prefers_a_conventional_eval_dir_over_a_larger_one(tmp_path): write_dataset(tmp_path / "evals" / "validation", count=2) write_dataset(tmp_path / "experiments" / "scratch", count=5) @@ -169,6 +256,45 @@ def test_wrapper_class_name_is_read_from_the_file(tmp_path): assert entry.hint is not None and "not assumed" in entry.hint +def test_a_wrapper_at_the_repo_root_is_importable_from_the_root(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + write_wrapper(tmp_path) + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.agent_search_path == "." + + +def test_a_nested_wrapper_records_the_directory_the_import_path_omits(tmp_path): + """``harbor_wrapper:WrappedAgent`` is where the module is *not*, which is the whole problem. + + The wrapper is found by walking, so it can be anywhere; the import path Harbor takes is a + bare module name. Without the directory beside it, ``harbor job start -c`` fails with + ``No module named 'harbor_wrapper'`` on a config discovery called runnable. + """ + write_dataset(tmp_path / "evals" / "validation") + write_wrapper(tmp_path / "src" / "myagent") + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.data["agents"] == [{"import_path": "harbor_wrapper:WrappedAgent"}] + assert candidate.agent_search_path == "src/myagent" + entry = next(item for item in findings if item.name == "agent-entrypoint") + assert "src/myagent" in entry.message, "a reader has to be able to see where it is imported from" + + +def test_a_builtin_agent_needs_no_search_path(tmp_path): + write_dataset(tmp_path / "evals" / "validation") + + candidate, _ = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.data["agents"] == [{"name": "oracle"}] + assert candidate.agent_search_path is None + + def test_missing_wrapper_falls_back_to_the_oracle_and_says_what_that_means(tmp_path): write_dataset(tmp_path / "evals" / "validation") @@ -178,6 +304,32 @@ def test_missing_wrapper_falls_back_to_the_oracle_and_says_what_that_means(tmp_p assert candidate.data["agents"] == [{"name": "oracle"}] entry = next(item for item in findings if item.name == "agent-entrypoint") assert entry.status == "warn" + assert "No harbor_wrapper.py found" in entry.message + assert entry.hint is not None and "evaluates no agent" in entry.hint + + +def test_a_wrapper_whose_class_was_not_recognized_is_not_reported_as_a_missing_file(tmp_path): + """The oracle silently replaces the agent, so the reason has to be the true one. + + The class is matched by the base name in the source, so a duck-typed wrapper falls through + to the oracle — which replays ``solution/solve.sh`` and evaluates nothing. Reporting that + as "No harbor_wrapper.py found" sends the author looking for a file that is right there. + """ + write_dataset(tmp_path / "evals" / "validation") + (tmp_path / "agent" / "nested").mkdir(parents=True) + (tmp_path / "agent" / "nested" / "harbor_wrapper.py").write_text( + "class WrappedAgent:\n async def run(self, instruction, environment):\n return None\n" + ) + + candidate, findings = sources.find_candidate(tmp_path) + + assert candidate is not None + assert candidate.data["agents"] == [{"name": "oracle"}] + entry = next(item for item in findings if item.name == "agent-entrypoint") + assert entry.status == "warn" + assert "No harbor_wrapper.py found" not in entry.message + assert "agent/nested/harbor_wrapper.py" in entry.message + assert "BaseAgent" in entry.message and "BaseInstalledAgent" in entry.message assert entry.hint is not None and "evaluates no agent" in entry.hint diff --git a/plugins/nemo-eval-author/tests/discover/test_validate.py b/plugins/nemo-eval-author/tests/discover/test_validate.py index 1ac8347e373..aed6f36537e 100644 --- a/plugins/nemo-eval-author/tests/discover/test_validate.py +++ b/plugins/nemo-eval-author/tests/discover/test_validate.py @@ -32,8 +32,12 @@ from nemo_eval_author_plugin.discovery.models import CandidateConfig, ConfigSource -def _candidate(data: dict) -> CandidateConfig: - return CandidateConfig(data=data, source=ConfigSource(kind="config_file", detail="test fixture")) +def _candidate(data: dict, agent_search_path: str | None = None) -> CandidateConfig: + return CandidateConfig( + data=data, + source=ConfigSource(kind="config_file", detail="test fixture"), + agent_search_path=agent_search_path, + ) def _finding(outcome, name): @@ -314,7 +318,8 @@ async def test_a_repo_wrapper_is_imported_and_sys_path_is_left_alone(tmp_path): { "agents": [{"import_path": "harbor_wrapper:TicketTriageAgent"}], "datasets": [{"path": str(dataset)}], - } + }, + agent_search_path=".", ) before = list(sys.path) @@ -322,10 +327,54 @@ async def test_a_repo_wrapper_is_imported_and_sys_path_is_left_alone(tmp_path): agent = _finding(outcome, "agent") assert agent.status == "pass" - assert "subclasses BaseAgent" in agent.message + assert "TicketTriageAgent" in agent.message assert sys.path == before, "the wrapper's directory must not be left on sys.path" +async def test_the_agent_rung_imports_only_from_the_search_path_the_artifact_records(tmp_path): + """The rung has to fail wherever the recorded command would. + + Harbor imports through ``importlib`` and adds nothing to ``sys.path``, so a bare + ``harbor_wrapper:...`` resolves only from the directory the artifact tells a run to + export. A rung that goes looking for the file itself passes for a reason + ``harbor job start -c`` will not have, and that is precisely how an unimportable config + came to be published as runnable. + """ + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + write_wrapper(tmp_path / "src" / "myagent") + data = {"agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], "datasets": [{"path": str(dataset)}]} + + reachable = await validate.run_ladder(_candidate(data, agent_search_path="src/myagent"), tmp_path) + assert _finding(reachable, "agent").status == "pass" + + unreachable = await validate.run_ladder(_candidate(data, agent_search_path="."), tmp_path) + agent = _finding(unreachable, "agent") + assert agent.status == "fail" + assert "No module named 'harbor_wrapper'" in agent.message + # The directory that would work is named, since the whole point is to be actionable. + assert agent.hint is not None and "PYTHONPATH=src/myagent" in agent.hint + + +async def test_an_agent_import_with_no_recorded_search_path_gets_no_help_finding_it(tmp_path): + """A config the repo maintains is validated with the environment a bare ``harbor`` has. + + Nothing about that config says where its module lives, so an import that only works + because discovery went hunting for the file is a verdict about this process rather than + about the run. + """ + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + write_wrapper(tmp_path) + candidate = _candidate( + {"agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], "datasets": [{"path": str(dataset)}]} + ) + + outcome = await validate.run_ladder(candidate, tmp_path) + + agent = _finding(outcome, "agent") + assert agent.status == "fail" + assert agent.hint is not None and "PYTHONPATH=." in agent.hint + + async def test_a_second_repos_wrapper_is_not_shadowed_by_the_first(tmp_path): """``harbor_wrapper`` is a convention, so two repos claim the same module name.""" first, second = tmp_path / "first", tmp_path / "second" @@ -338,17 +387,72 @@ async def test_a_second_repos_wrapper_is_not_shadowed_by_the_first(tmp_path): { "agents": [{"import_path": f"harbor_wrapper:{class_name}"}], "datasets": [{"path": str(repo / "evals/validation")}], - } + }, + agent_search_path=".", ) outcome = await validate.run_ladder(candidate, repo) assert _finding(outcome, "agent").status == "pass", f"{class_name} was shadowed by a cached module" -async def test_a_wrapper_that_is_not_an_agent_fails_the_agent_rung(tmp_path): +async def test_a_module_left_in_sys_modules_cannot_stand_in_for_a_missing_one(tmp_path): + """Eviction is what keeps the rung honest once nothing is added to the path. + + With the search path narrowed to one directory, a stale ``harbor_wrapper`` from an earlier + repo is the only way an unimportable config could still pass — the exact false verdict + this rung exists to prevent. + """ + first, second = tmp_path / "first", tmp_path / "second" + for repo in (first, second): + write_dataset(repo / "evals" / "validation", count=1) + write_wrapper(first) + + def candidate(repo): + return _candidate( + { + "agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], + "datasets": [{"path": str(repo / "evals/validation")}], + }, + agent_search_path=".", + ) + + assert _finding(await validate.run_ladder(candidate(first), first), "agent").status == "pass" + + outcome = await validate.run_ladder(candidate(second), second) + + assert _finding(outcome, "agent").status == "fail", "the first repo's module answered for the second" + assert "harbor_wrapper" not in sys.modules + + +async def test_a_wrapper_that_is_not_an_agent_is_a_warning_rather_than_a_failure(tmp_path): + """Harbor's own agent gate passes this, so failing it would block a repo Harbor runs. + + ``harbor/agents/factory.py`` calls ``import_class(import_path, label="agent")`` with no + ``base`` — strict for verifiers, deliberately not for agents. Still worth saying: the run + starts and then dies at trial time on a method the class does not have. + """ dataset = write_dataset(tmp_path / "evals" / "validation", count=1) (tmp_path / "harbor_wrapper.py").write_text("class NotAnAgent:\n pass\n") candidate = _candidate( - {"agents": [{"import_path": "harbor_wrapper:NotAnAgent"}], "datasets": [{"path": str(dataset)}]} + {"agents": [{"import_path": "harbor_wrapper:NotAnAgent"}], "datasets": [{"path": str(dataset)}]}, + agent_search_path=".", + ) + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _finding(outcome, "agent").status == "pass" + base = _finding(outcome, "agent-base") + assert base.status == "warn" + assert base.harbor_call is None, "Harbor does not make this judgement, so it cannot be credited with it" + assert _repo_failures(outcome) == [] + + +async def test_an_import_path_naming_something_that_is_not_a_class_still_fails(tmp_path): + """The one thing ``import_class`` enforces without a ``base``, so it stays a failure.""" + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + (tmp_path / "harbor_wrapper.py").write_text("def not_a_class():\n return None\n") + candidate = _candidate( + {"agents": [{"import_path": "harbor_wrapper:not_a_class"}], "datasets": [{"path": str(dataset)}]}, + agent_search_path=".", ) outcome = await validate.run_ladder(candidate, tmp_path) @@ -418,3 +522,23 @@ async def test_the_full_pipeline_agrees_with_the_source_it_chose(tmp_path): assert _repo_failures(outcome) == [] assert outcome.config is not None assert outcome.config.agents[0].import_path == "harbor_wrapper:WrappedAgent" + + +async def test_the_full_pipeline_carries_a_nested_wrapper_s_search_path_through_the_ladder(tmp_path): + """The case the bare import path dropped on the floor. + + ``_find_wrapper`` walks the repo, so the wrapper it finds need not be at the root, and the + emitted ``harbor_wrapper:WrappedAgent`` says nothing about where it was. Assembly and the + ladder have to agree on the directory or the ladder is judging a different config. + """ + write_dataset(tmp_path / "evals" / "validation", count=1) + write_wrapper(tmp_path / "src" / "myagent") + + candidate, _ = sources.find_candidate(tmp_path) + assert candidate is not None + assert candidate.agent_search_path == "src/myagent" + + outcome = await validate.run_ladder(candidate, tmp_path) + + assert _repo_failures(outcome) == [] + assert _finding(outcome, "agent").status == "pass" diff --git a/plugins/nemo-eval-author/tests/harbor_fixtures.py b/plugins/nemo-eval-author/tests/harbor_fixtures.py index ae31df5e7ca..16eb4b6cc8c 100644 --- a/plugins/nemo-eval-author/tests/harbor_fixtures.py +++ b/plugins/nemo-eval-author/tests/harbor_fixtures.py @@ -112,9 +112,14 @@ def write_dataset(root: Path, *, count: int = 2, test_script: str = WRITES_REWAR return root -def write_wrapper(repo_root: Path, *, class_name: str = "WrappedAgent", base: str = "BaseAgent") -> Path: - """A ``harbor_wrapper.py`` holding a real ``BaseAgent`` subclass.""" - path = repo_root / "harbor_wrapper.py" +def write_wrapper(wrapper_dir: Path, *, class_name: str = "WrappedAgent", base: str = "BaseAgent") -> Path: + """A ``harbor_wrapper.py`` holding a real ``BaseAgent`` subclass. + + *wrapper_dir* is created if needed, because a wrapper nested under ``src/`` is the case + that separates the module's directory from the repo root. + """ + wrapper_dir.mkdir(parents=True, exist_ok=True) + path = wrapper_dir / "harbor_wrapper.py" path.write_text( f"from harbor.agents.base import {base}\n\n\n" f"class {class_name}({base}):\n" From 2f570117254531c632c4b720fac43f7584d6f3fe Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Mon, 10 Aug 2026 13:26:33 -0500 Subject: [PATCH 13/15] refactor(eval-author): reduce discover to repository preflight Use only repository-owned Harbor inputs and persist one concise discovery report. Remove inferred config synthesis and duplicate validation scaffolding. Signed-off-by: Alec Khoury --- plugins/nemo-eval-author/pyproject.toml | 5 +- .../src/nemo_eval_author_plugin/cli.py | 111 +-- .../discovery/memory.py | 90 -- .../discovery/models.py | 156 ---- .../discovery/report.py | 299 ++----- .../nemo_eval_author_plugin/discovery/run.py | 193 ++-- .../nemo_eval_author_plugin/discovery/scan.py | 303 ++++--- .../discovery/sources.py | 637 ------------- .../discovery/validate.py | 837 ++++-------------- .../eval_author/README.md | 100 +-- .../tests/discover/test_command.py | 362 +++----- .../tests/discover/test_report.py | 268 ++---- .../tests/discover/test_scan.py | 201 +++-- .../tests/discover/test_sources.py | 384 -------- .../tests/discover/test_validate.py | 685 ++++++-------- .../nemo-eval-author/tests/harbor_fixtures.py | 176 +--- plugins/nemo-eval-author/tests/test_cli.py | 77 +- 17 files changed, 1161 insertions(+), 3723 deletions(-) delete mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py delete mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py delete mode 100644 plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py delete mode 100644 plugins/nemo-eval-author/tests/discover/test_sources.py diff --git a/plugins/nemo-eval-author/pyproject.toml b/plugins/nemo-eval-author/pyproject.toml index 89ae08f92c8..1ba44422c93 100644 --- a/plugins/nemo-eval-author/pyproject.toml +++ b/plugins/nemo-eval-author/pyproject.toml @@ -5,10 +5,7 @@ description = "Eval Author agent for NeMo Platform (hard-depends on Experimental requires-python = ">=3.12,<3.14" dependencies = [ "pydantic>=2", - # Floor is 0.18 because discovery validates through Harbor's own APIs instead of - # reimplementing its rules: Task.is_valid_dir, get_required_host_vars, and the - # JobConfig schema are load-bearing, and an older Harbor fails at import rather - # than at the point of use. + # Harbor 0.18 provides the discovery APIs used by this plugin. "harbor>=0.18", "nooa", "nemo-experimentalist-plugin", diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py index 8da05344a5f..5f5db9b4297 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py @@ -1,19 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Eval Author plugin CLI — ``nemo agents eval-author ...`` subcommands. - -Registered under ``nemo.cli.agents`` and mounted by ``AgentsCLI`` as -``nemo agents eval-author ``. - -Every verb is registered under its final name so the command tree is discoverable -and the child tickets have a landing spot. The ones still unimplemented exit -non-zero. - -This module imports nothing from ``eval_author`` while the command bodies remain -placeholders. The completed runner resolves the active Platform model pair at run -time. ``discovery.run`` builds no model client at import, so it is safe to load here. -""" +"""Eval Author commands under ``nemo agents eval-author``.""" import asyncio from pathlib import Path @@ -21,70 +9,41 @@ import typer from nemo_eval_author_plugin.discovery import run as discovery -from nemo_eval_author_plugin.discovery.models import FILESET_NAME, Finding -from nemo_eval_author_plugin.discovery.report import run_command, run_target +from nemo_insights_plugin.contracts.checks import format_report from nemo_platform_plugin.cli import NemoCLI -_STATUS_MARK = {"pass": " ok ", "warn": " warn ", "fail": " FAIL "} - -# Order the ladder's own sequence, so the printed report reads the way validation ran -# rather than the way findings happened to accumulate. -_GROUP_ORDER = ("config", "validation", "repo", "memory") - def _not_implemented(ctx: typer.Context, ticket: str) -> NoReturn: - """Fail loudly, so a placeholder verb can never be mistaken for a successful run. - - The message quotes ``ctx.command_path`` rather than a hardcoded path. - """ typer.echo(f"`{ctx.command_path}` is not implemented yet ({ticket}).", err=True) raise typer.Exit(code=1) -def _echo_finding(finding: Finding) -> None: - typer.echo(f"[{_STATUS_MARK[finding.status]}] {finding.group}/{finding.name}: {finding.message}") - - def _report_discovery(result: discovery.DiscoverResult) -> None: - """Print the run, then the verdict, because the verdict is what the reader came for.""" - record = result.report - findings = [*record.findings, *result.memory_findings] - for group in _GROUP_ORDER: - for finding in (item for item in findings if item.group == group): - _echo_finding(finding) + status = format_report(result.report.checks) + if status: + typer.echo(status) + if result.report.run_command: + typer.echo("") + typer.echo(f"Run: {result.report.run_command}") typer.echo("") - target = run_target(record) - if target is not None: - source = record.config_source - typer.echo(f"Harbor can run this repo's evals ({source.detail if source else 'unknown source'}).") - if target.location == "repo": - typer.echo(f"Run it from {record.repo_root}, using the config this repo already maintains:") - else: - typer.echo(f"Discovery wrote the config to fileset '{FILESET_NAME}' at {target.path}.") - typer.echo(f"Fetch it into {record.repo_root}, then:") - typer.echo(f" {run_command(target)}") - if target.pythonpath is not None: - typer.echo(f" PYTHONPATH is required: Harbor imports the agent module from {target.pythonpath}.") - if record.required_env_vars: - typer.echo(f" Needs: {', '.join(item.name for item in record.required_env_vars)}") - else: - typer.echo("Harbor cannot run this repo's evals. Blocking:", err=True) - for finding in record.blocking: - call = f" ({finding.harbor_call})" if finding.harbor_call else "" - typer.echo(f" - {finding.name}: {finding.message}{call}", err=True) - if finding.hint: - typer.echo(f" {finding.hint}", err=True) - if result.dry_run: + typer.echo("Dry run: no files were uploaded.") typer.echo("") - typer.echo("Dry run: nothing was uploaded.") - elif result.persisted: - typer.echo("") - typer.echo(f"Recorded to fileset '{FILESET_NAME}' under {record.agent}/.") + typer.echo(result.markdown, nl=False) + elif result.uploaded: + remote_path = f"{result.report.agent}/{discovery.REPORT_FILENAME}" + typer.echo(f"Uploaded {remote_path} to fileset '{discovery.FILESET_NAME}'.") else: - typer.echo("") - typer.echo("Discovery could not be recorded, so a later run has nothing to read.", err=True) + typer.echo(f"Upload failed: {result.upload_error or 'unknown error'}", err=True) + + failures = sum(check.status == "fail" for check in result.report.checks) + failures += not result.dry_run and not result.uploaded + warnings = sum(check.status == "warn" for check in result.report.checks) + failure_label = "failure" if failures == 1 else "failures" + warning_label = "warning" if warnings == 1 else "warnings" + status = "passed" if result.ok else "failed" + typer.echo(f"Final overview: Discovery {status} with {failures} {failure_label} and {warnings} {warning_label}.") class EvalAuthorCLI(NemoCLI): @@ -98,27 +57,27 @@ def get_cli(self) -> typer.Typer: @app.callback() def _root() -> None: - """Force subcommand dispatch even when only one verb is registered.""" + """Select an Eval Author command.""" @app.command("discover") def discover( repo: Annotated[ Path, - typer.Option("--repo", help="Agent repository to inspect.", exists=True, file_okay=False), + typer.Option("--repo", help="Repository that contains the agent.", exists=True, file_okay=False), ] = Path(), agent: Annotated[ str | None, - typer.Option("--agent", help="Agent name. Defaults to optimizer.yaml, else the directory name."), + typer.Option("--agent", help="Agent name. The default comes from optimizer.yaml or the directory."), ] = None, dry_run: Annotated[ bool, - typer.Option("--dry-run", help="Print the findings and config without uploading anything."), + typer.Option("--dry-run", help="Print discovery.md without an upload."), ] = False, ) -> None: - """Find and validate how this repo runs Harbor evals, then record it. + """Inspect the repository and record its Harbor preflight. - Validating a config imports the repo's agent module into this process, which runs - that module's top level. Only point this at a repo you trust. + WARNING: Use this command only with a trusted repository. + Agent imports execute module top-level code. """ result = asyncio.run( discovery.discover( @@ -130,17 +89,11 @@ def discover( ) ) _report_discovery(result) - if result.dry_run: - typer.echo("") - typer.echo(result.markdown) - if result.job_config: - typer.echo(result.job_config) - # Non-zero on an unrunnable config is what makes this usable as a gate in CI. raise typer.Exit(code=0 if result.ok else 1) @app.command("audit") def audit(ctx: typer.Context) -> None: - """Audit an existing eval suite for coverage gaps.""" + """Report coverage gaps in an existing eval suite.""" # TODO(ASE-676): declare flags and wire the audit. _not_implemented(ctx, "ASE-676") @@ -152,13 +105,13 @@ def propose(ctx: typer.Context) -> None: @app.command("run") def run(ctx: typer.Context) -> None: - """Run the Eval Author pipeline end to end.""" + """Run the Eval Author pipeline.""" # TODO(ASE-673): declare flags and wire the pipeline to run_eval_author. _not_implemented(ctx, "ASE-673") @app.command("doctor") def doctor(ctx: typer.Context) -> None: - """Diagnose Eval Author setup: credentials, platform, runtime.""" + """Diagnose credentials, platform access, and the runtime.""" # TODO(ASE-678): report the prerequisites the other verbs gate on. _not_implemented(ctx, "ASE-678") diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py deleted file mode 100644 index bbbe9f96283..00000000000 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/memory.py +++ /dev/null @@ -1,90 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Persist discovery to a fileset. - -One fixed fileset with agent-scoped paths, following the telemetry exporter's precedent of -``nemo-agent-telemetry`` plus ``{agent}/...``. Nothing is written into the user's repo: the -repo is the thing under inspection, and a command that inspects a repo should not change it. - -``harbor-job.yaml`` is uploaded only when it exists, and it only exists when Harbor accepted -the schema. A config that is present in the fileset is therefore a config Harbor could load, -which is the invariant the whole artifact rests on. -""" - -from typing import Any - -from nemo_eval_author_plugin.discovery.models import ( - FILESET_NAME, - JOB_CONFIG_FILENAME, - REPORT_FILENAME, - Finding, -) - -_GROUP = "memory" - - -def remote_report_path(agent: str) -> str: - return f"{agent}/{REPORT_FILENAME}" - - -def remote_config_path(agent: str) -> str: - return f"{agent}/{JOB_CONFIG_FILENAME}" - - -async def persist( - sdk: Any, - *, - agent: str, - workspace: str, - markdown: str, - job_config: str | None, -) -> tuple[bool, list[Finding]]: - """Upload the report, and the config when the caller passed one. - - Reports only what it did. Why a config might be absent is the caller's to explain — - withheld because nothing validated, or not needed because the repo maintains its own — - and a message here could only guess between them. - - Returns whether everything landed. Upload failures are reported as warnings rather - than failures, because ``runnable`` answers one question only — can Harbor run this - config — and a fileset being down does not change that answer. The caller folds the - ``False`` into its exit code. - """ - findings: list[Finding] = [] - ok = True - - for remote_path, content, label in ( - (remote_report_path(agent), markdown, REPORT_FILENAME), - *(((remote_config_path(agent), job_config, JOB_CONFIG_FILENAME),) if job_config is not None else ()), - ): - try: - await sdk.files.upload_content( - content=content.encode("utf-8"), - remote_path=remote_path, - fileset=FILESET_NAME, - workspace=workspace, - fileset_auto_create=True, - ) - except Exception as exc: - ok = False - findings.append( - Finding( - name="upload", - group=_GROUP, - status="warn", - message=f"Could not upload {label}: {type(exc).__name__}: {exc}", - hint=f"Target was fileset '{FILESET_NAME}' at {remote_path} in workspace '{workspace}'.", - ) - ) - continue - findings.append( - Finding( - name="upload", - group=_GROUP, - status="pass", - message=f"Uploaded {label} to fileset '{FILESET_NAME}' at {remote_path}", - ) - ) - - return ok, findings diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py deleted file mode 100644 index 3c4134e2c3f..00000000000 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/models.py +++ /dev/null @@ -1,156 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Result types for ``nemo eval-author discover``. - -``Finding.harbor_call`` names the Harbor API or CLI that returned a verdict. A finding -without one was observed directly rather than judged by Harbor, which is the difference -between "Harbor rejected this config" and "we read this off the filesystem". Both the CLI -and the report render the call, so the distinction reaches the reader. -""" - -from datetime import datetime -from pathlib import Path -from typing import Any, Literal - -from pydantic import BaseModel, Field - -FILESET_NAME = "nemo-eval-author" -"""One fixed fileset with agent-scoped paths, following the telemetry precedent.""" - -JOB_CONFIG_FILENAME = "harbor-job.yaml" -REPORT_FILENAME = "discovery.md" - -Status = Literal["pass", "warn", "fail"] - -SourceKind = Literal["config_file", "prior_job", "profile", "convention"] -"""Where a candidate job config came from. - -Ordered by how much of it Harbor already agreed to, which is what -``SOURCE_PRIORITY`` encodes: - -``config_file`` a config file in the repo; the user declared this. -``prior_job`` ``config.json`` from a job Harbor resolved and ran. Evidence, not a guess. -``profile`` assembled from ``optimizer.yaml`` plus the agent wrapper. -``convention`` assembled from directory layout alone. Weakest, so say so out loud. -""" - -SOURCE_PRIORITY: tuple[SourceKind, ...] = ("config_file", "prior_job", "profile", "convention") - -AGENT_SEARCH_PATH_DESCRIPTION = ( - "Repo-relative directory that must be on PYTHONPATH for the config's agent import " - "path to resolve, or None when it names no module. Harbor imports agents with plain " - "importlib and never adds the working directory, and a Harbor JobConfig has nowhere to " - "record this, so it travels beside the config instead of in it." -) - - -class Finding(BaseModel): - """One thing discover learned, and who vouches for it.""" - - name: str - group: str - status: Status - message: str - path: Path | None = None - hint: str | None = None - harbor_call: str | None = Field( - default=None, - description="The Harbor API or CLI that returned this verdict, when one did.", - ) - - -class ConfigSource(BaseModel): - """The winning source, kept so a reader knows how much to trust the config.""" - - kind: SourceKind - detail: str - path: Path | None = None - - @property - def rank(self) -> int: - return SOURCE_PRIORITY.index(self.kind) - - @property - def owns_file(self) -> bool: - """Whether the repo maintains the config file we validated. - - The one case where discovery has nothing of its own to persist: the file already - exists, someone maintains it, and Harbor accepted exactly its contents. ``prior_job`` - is excluded even though it has a path, because that path is a record Harbor wrote - inside a job's output directory rather than an input anyone maintains. - """ - return self.kind == "config_file" and self.path is not None - - -class CandidateConfig(BaseModel): - """An unvalidated Harbor job config payload plus where it came from. - - Deliberately a raw ``dict`` rather than a ``JobConfig``. Assembling and judging are - separate jobs here: if this held a parsed ``JobConfig`` then the schema rung of the - ladder would have already run somewhere off to the side, and "no config reaches the - artifact unless a Harbor validator accepted it" would stop being checkable. - """ - - data: dict[str, Any] - source: ConfigSource - agent_search_path: str | None = Field( - default=None, - description=AGENT_SEARCH_PATH_DESCRIPTION, - ) - - -class RunTarget(BaseModel): - """The config a later run passes to ``harbor job start -c``, and where to get it. - - Harbor runs local task directories through ``-c`` and no other way: ``--dataset`` and - ``--task`` name registry packages, so a filesystem path handed to either is read as a - package reference. A repo full of task dirs and no config file therefore cannot be run - as-is, which is why discovery writes one when the repo does not. - """ - - location: Literal["repo", "fileset"] - path: str - pythonpath: str | None = Field( - default=None, - description=AGENT_SEARCH_PATH_DESCRIPTION, - ) - - -class RequiredEnvVar(BaseModel): - """A host variable a task config templates as ``${VAR}`` or ``${VAR:-default}``.""" - - name: str - default: str | None = None - declared_in: Path - - -class DiscoveryReport(BaseModel): - """Everything a later run needs to trust or redo this discovery.""" - - schema_version: int = 1 - agent: str - workspace: str - repo_root: Path - harbor_version: str = Field( - description="A validation result is only as good as the Harbor that produced it, " - "which is why Harbor stamps its own version into lock.json.", - ) - config_source: ConfigSource | None = None - agent_search_path: str | None = Field(default=None, description=AGENT_SEARCH_PATH_DESCRIPTION) - findings: list[Finding] = Field(default_factory=list) - required_env_vars: list[RequiredEnvVar] = Field(default_factory=list) - discovered_at: datetime - - @property - def blocking(self) -> list[Finding]: - return [finding for finding in self.findings if finding.status == "fail"] - - @property - def runnable(self) -> bool: - """True only when a config was found and nothing about it failed. - - The whole artifact turns on this flag, so it stays conservative: no source means - not runnable even with an empty failure list, because there is nothing to run. - """ - return self.config_source is not None and not self.blocking diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py index f2ac61d4496..fe5d722e4eb 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py @@ -1,57 +1,58 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Render the two artifacts discover persists. - -``harbor-job.yaml`` is the config a later agent hands to Harbor. ``discovery.md`` is the -record around it: which source won, what every rung of the ladder concluded, what a run -needs from the host, and what is blocking when something is. - -The markdown leads with front matter because the first reader is a program: ``runnable`` -and ``run_config`` are the whole machine-readable contract, and the body below them is a -short human summary of the same thing. - -Paths in the persisted config are rewritten relative to the repo root. An absolute path -would encode this machine into an artifact meant to outlive it, so the config is written to -be run from ``repo_root``, and the front matter records where that is. - -``run_config.pythonpath`` is part of that contract rather than a convenience. A Harbor -``JobConfig`` has no field for a module search path, and Harbor imports an agent with plain -``importlib``, so a config naming a bare ``harbor_wrapper:WrappedAgent`` runs only with that -directory exported. Recording the config without it would hand out a command that fails on -the first trial. -""" +"""Discovery report contract and Markdown renderer.""" +import shlex +from dataclasses import dataclass, field from datetime import UTC, datetime -from importlib.metadata import PackageNotFoundError, version +from importlib.metadata import version from pathlib import Path from typing import Any import yaml -from harbor.models.job.config import JobConfig -from nemo_eval_author_plugin.discovery.models import ( - JOB_CONFIG_FILENAME, - CandidateConfig, - DiscoveryReport, - Finding, - RequiredEnvVar, - RunTarget, -) -from nemo_eval_author_plugin.discovery.scan import display_path - -_STATUS_MARK = {"pass": "ok", "warn": "warn", "fail": "FAIL"} +from nemo_eval_author_plugin.discovery.scan import RepositoryScan +from nemo_eval_author_plugin.discovery.validate import RequiredEnvVar, ValidationOutcome +from nemo_insights_plugin.contracts.checks import CheckResult, format_report, required_failures + + +@dataclass +class DiscoveryReport: + """Repository facts and current Harbor preflight results.""" + + agent: str + workspace: str + repo_root: Path + config_path: Path | None + dataset_paths: list[Path] + ethos_path: Path | None + harbor_version: str + required_env_vars: list[RequiredEnvVar] + discovered_at: datetime + fingerprint: str + input_file_count: int + checks: list[CheckResult] + schema_version: int = field(init=False, default=1) + + @property + def runnable(self) -> bool: + """Return whether the repository-owned config passed all required checks.""" + return self.config_path is not None and not required_failures(self.checks) + + @property + def run_command(self) -> str | None: + """Return the Harbor command only for a runnable repository config.""" + if not self.runnable or self.config_path is None: + return None + config_path = self.config_path.resolve().relative_to(self.repo_root.resolve()).as_posix() + cd_command = shlex.join(["cd", str(self.repo_root.resolve())]) + harbor_command = shlex.join(["harbor", "job", "start", "-c", config_path]) + return f"{cd_command} && {harbor_command}" def harbor_version() -> str: - """The Harbor that produced these verdicts. - - A validation result is only as good as the version that returned it, which is why - Harbor stamps its own version into ``lock.json``. Same reasoning here. - """ - try: - return version("harbor") - except PackageNotFoundError: - return "unknown" + """Return the installed Harbor version.""" + return version("harbor") def build_report( @@ -59,214 +60,74 @@ def build_report( agent: str, workspace: str, repo_root: Path, - candidate: CandidateConfig | None, - findings: list[Finding], - required_env_vars: list[RequiredEnvVar], + scan_result: RepositoryScan, + validation: ValidationOutcome, + trace_check: CheckResult, discovered_at: datetime | None = None, ) -> DiscoveryReport: + """Build one report from the repository scan and current preflight.""" return DiscoveryReport( agent=agent, workspace=workspace, - repo_root=repo_root, + repo_root=repo_root.resolve(), + config_path=scan_result.config.path if scan_result.config else None, + dataset_paths=scan_result.dataset_paths, + ethos_path=scan_result.ethos_path, harbor_version=harbor_version(), - config_source=candidate.source if candidate is not None else None, - agent_search_path=candidate.agent_search_path if candidate is not None else None, - findings=findings, - required_env_vars=required_env_vars, + required_env_vars=validation.required_env_vars, discovered_at=discovered_at or datetime.now(UTC), + fingerprint=f"sha256:{scan_result.fingerprint}", + input_file_count=scan_result.input_file_count, + checks=[*scan_result.checks, *validation.checks, trace_check], ) -def run_target(report: DiscoveryReport) -> RunTarget | None: - """Which config a later run should pass to ``-c``, or ``None`` when there is none. - - A repo that maintains its own config keeps it: Harbor accepted exactly that file, so the - artifact points at it rather than shipping a copy that starts drifting the moment - someone edits the original. Every other source has no such file — the payload is - discovery's own synthesis — so the fileset is the only place it exists. - """ - if not report.runnable: - return None - source = report.config_source - if source is not None and source.owns_file and source.path is not None: - return RunTarget( - location="repo", - path=display_path(source.path, report.repo_root), - pythonpath=report.agent_search_path, - ) - return RunTarget( - location="fileset", - path=f"{report.agent}/{JOB_CONFIG_FILENAME}", - pythonpath=report.agent_search_path, - ) - - -def run_command(target: RunTarget) -> str: - """The exact command a later run issues, search path included when the agent needs one. - - Built here rather than in each renderer so the command the CLI prints and the one the - artifact records cannot drift; a reader who copies whichever they saw has no way to tell - that the other said something else. - """ - config_arg = target.path if target.location == "repo" else JOB_CONFIG_FILENAME - prefix = f"PYTHONPATH={target.pythonpath} " if target.pythonpath is not None else "" - return f"{prefix}harbor job start -c {config_arg}" - - -def render_job_config(config: JobConfig, repo_root: Path) -> str: - """Serialize the validated config, with in-repo paths made relative. - - ``exclude_defaults`` keeps the file to what was actually decided, so a reader can tell - a deliberate setting from a Harbor default. Secrets are safe to write: Harbor's own - ``AgentConfig.env`` serializer rewrites sensitive values as ``${VAR}`` templates on the - way out, so the dump carries the variable names a run needs and none of their values. - - ``job_name`` is dropped unless the source config named it. Harbor's default is a - timestamp generated at load, and freezing one into a reusable artifact would label - every future run with the moment discovery happened. - """ - generated = set() if "job_name" in config.model_fields_set else {"job_name"} - payload = _relativize(config.model_dump(mode="json", exclude_defaults=True, exclude=generated), repo_root) - return yaml.safe_dump(payload, sort_keys=True, default_flow_style=False) - - def render_markdown(report: DiscoveryReport) -> str: - """The narrative artifact, front matter first.""" + """Render YAML front matter and a concise status report.""" front = yaml.safe_dump(_front_matter(report), sort_keys=False, default_flow_style=False).rstrip() - body = "\n".join(_body(report)) + lines = [f"# Discovery report for `{report.agent}`"] + status = format_report(report.checks) + if status: + lines.extend(["", "```text", status, "```"]) + if report.run_command: + lines.extend(["", "## Run", "", "```bash", report.run_command, "```"]) + body = "\n".join(lines) return f"---\n{front}\n---\n\n{body}\n" def _front_matter(report: DiscoveryReport) -> dict[str, Any]: - source = report.config_source - target = run_target(report) return { "schema_version": report.schema_version, "agent": report.agent, "workspace": report.workspace, "repo_root": str(report.repo_root), "runnable": report.runnable, - "config_source": ( - { - "kind": source.kind, - "detail": source.detail, - "path": display_path(source.path, report.repo_root) if source.path else None, - } - if source is not None - else None - ), - "run_config": target.model_dump() if target is not None else None, - "validation": {finding.name: finding.status for finding in report.findings if finding.group == "validation"}, + "config_path": _display_path(report.config_path, report.repo_root), + "dataset_paths": [_display_path(path, report.repo_root) for path in report.dataset_paths], + "run_command": report.run_command, + "ethos_path": _display_path(report.ethos_path, report.repo_root), "harbor_version": report.harbor_version, "required_env_vars": [ { "name": item.name, "default": item.default, - "declared_in": display_path(item.declared_in, report.repo_root), + "declared_in": _display_path(item.declared_in, report.repo_root), } for item in report.required_env_vars ], "discovered_at": report.discovered_at.isoformat(), + "fingerprint": report.fingerprint, + "input_file_count": report.input_file_count, + "checks": [check.model_dump(mode="json") for check in report.checks], } -def _body(report: DiscoveryReport) -> list[str]: - lines = [f"# Harbor eval setup for `{report.agent}`", ""] - lines += _verdict_section(report) - lines += _findings_section(report) - lines += _env_section(report) - return lines - - -def _verdict_section(report: DiscoveryReport) -> list[str]: - target = run_target(report) - if target is None: - lines = ["**Harbor cannot run this repo's evals yet.** Blocking:", ""] - for finding in report.blocking: - lines.append(f"- **{finding.name}** — {finding.message}") - if finding.harbor_call: - lines.append(f" - reported by `{finding.harbor_call}`") - if finding.hint: - lines.append(f" - {finding.hint}") - return [*lines, ""] - - source = report.config_source - if target.location == "repo": - where = f"From `{report.repo_root}`, because the config's paths are relative to it:" - else: - where = f"Fetch `{target.path}` from the `{report.workspace}` workspace into `{report.repo_root}`, then:" - - lines = [ - f"Harbor {report.harbor_version} can run this repo's evals. The config was " - f"{source.detail if source is not None else 'unknown'}.", - "", - where, - "", - "```bash", - run_command(target), - "```", - "", - ] - if target.pythonpath is not None: - lines += [ - f"`PYTHONPATH` is required: the agent is the module in `{target.pythonpath}`, and Harbor " - "imports it with plain `importlib`, which does not search the working directory.", - "", - ] - if report.required_env_vars: - names = " ".join(f"{item.name}=..." for item in report.required_env_vars) - lines += [f"Set the host variables first: `{names}`", ""] - return lines - - -def _findings_section(report: DiscoveryReport) -> list[str]: - groups = [("validation", "What Harbor checked"), ("repo", "Repo shape")] - lines: list[str] = [] - for group, heading in groups: - items = [finding for finding in report.findings if finding.group == group] - if not items: - continue - lines += [f"## {heading}", ""] - for finding in items: - call = f" (`{finding.harbor_call}`)" if finding.harbor_call else "" - lines.append(f"- `{_STATUS_MARK[finding.status]}` **{finding.name}**: {finding.message}{call}") - if finding.hint: - lines.append(f" - {finding.hint}") - lines.append("") - return lines - - -def _env_section(report: DiscoveryReport) -> list[str]: - if not report.required_env_vars: - return [] - lines = [ - "## Host variables", - "", - "Harbor resolves these from the environment at trial start and raises on a missing one.", - "", - ] - for item in report.required_env_vars: - default = f", default `{item.default}`" if item.default is not None else ", no default" - lines.append(f"- `{item.name}`{default} — declared in `{display_path(item.declared_in, report.repo_root)}`") - return [*lines, ""] - - -def _relativize(payload: Any, repo_root: Path) -> Any: - """Rewrite absolute paths under *repo_root* as repo-relative posix strings. - - Applied to the whole dumped structure rather than named fields, because Harbor carries - paths in several places (datasets, tasks, skills, output dirs) and a config that only - half-relativizes is worse than one that does not try. Paths outside the repo are left - alone: they are genuinely elsewhere, and pretending otherwise would break the run. - """ - prefix = f"{repo_root}/" - if isinstance(payload, dict): - return {key: _relativize(value, repo_root) for key, value in payload.items()} - if isinstance(payload, list): - return [_relativize(item, repo_root) for item in payload] - if isinstance(payload, str): - if payload == str(repo_root): - return "." - if payload.startswith(prefix): - return Path(payload).relative_to(repo_root).as_posix() - return payload +def _display_path(path: Path | None, repo_root: Path) -> str | None: + if path is None: + return None + if not path.is_absolute(): + return path.as_posix() + try: + return path.resolve().relative_to(repo_root.resolve()).as_posix() + except ValueError: + return path.as_posix() diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py index 512551e2a86..c227f3d097c 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -1,44 +1,26 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Orchestration for ``nemo eval-author discover``. - -Assemble a candidate config, let Harbor judge it, then persist what it concluded. - -Kept apart from ``cli.py`` so it can be tested without a ``CliRunner`` and so the CLI holds -nothing but flags, printing, and the exit code. ``make_client`` is a module global for the -same reason it is in ``eval_author/run.py``: tests replace it. -""" +"""Orchestration for ``nemo agents eval-author discover``.""" import re -import tempfile -from dataclasses import dataclass, field +from dataclasses import dataclass from pathlib import Path -from nemo_eval_author_plugin.discovery import memory, report, scan, sources, validate -from nemo_eval_author_plugin.discovery.models import ( - JOB_CONFIG_FILENAME, - DiscoveryReport, - Finding, -) -from nemo_eval_author_plugin.discovery.validate import ValidationOutcome +import yaml +from nemo_eval_author_plugin.discovery import report, scan, validate from nemo_experimentalist_plugin.client import make_client -from nemo_insights_plugin.contracts.profile import discover_profile from nemo_platform import AsyncNeMoPlatform from nemo_platform.config.config import Config +FILESET_NAME = "nemo-eval-author" +REPORT_FILENAME = "discovery.md" _SLUG_PATTERN = re.compile(r"[^a-z0-9]+") @dataclass class DiscoverOptions: - """Everything the CLI passes through, resolved. - - Deliberately holds nothing about where the platform is. Which cluster, which - credentials and which workspace are settled by the active ``nemo`` context, and a repo's - Harbor environment backend is settled by its own config or Harbor's default. Accepting - flags for those would let one invocation contradict the config every other command obeys. - """ + """Resolved command options.""" repo_root: Path agent: str | None = None @@ -47,38 +29,25 @@ class DiscoverOptions: @dataclass class DiscoverResult: - """The artifacts, plus what the command needs to report and exit on.""" + """The report and upload result for one invocation.""" - report: DiscoveryReport + report: report.DiscoveryReport markdown: str - job_config: str | None = None - persisted: bool = False + uploaded: bool = False dry_run: bool = False - memory_findings: list[Finding] = field(default_factory=list) + upload_error: str | None = None @property def ok(self) -> bool: - """Exit-zero condition: Harbor can run it and the record was written. - - Two independent claims, deliberately kept apart. ``runnable`` is Harbor's verdict - on the config; persistence is whether a later agent will actually find it. A run - that validates but cannot upload has not delivered what the command promises. A dry - run is exempt because it was asked not to write anything. - """ - return self.report.runnable and (self.persisted or self.dry_run) + """Return the command exit condition.""" + return self.report.runnable and (self.dry_run or self.uploaded) async def discover(options: DiscoverOptions) -> DiscoverResult: - """Run discovery end to end. - - One call at a time per process. The validation ladder chdirs into the repo and puts it on - ``sys.path``, both process-wide, so a second concurrent call would judge the wrong tree. A - caller that needs several repos at once has to run them in separate processes. - """ + """Scan, revalidate, report, and optionally upload one repository.""" repo_root = options.repo_root.resolve() - agent = options.agent or _infer_agent_name(repo_root) + agent = _slug(options.agent) if options.agent is not None else _infer_agent_name(repo_root) workspace = _active_workspace() - # No base_url: the active context supplies the cluster and the credentials for it. client = make_client(None) try: return await _discover(client, options, repo_root=repo_root, agent=agent, workspace=workspace) @@ -86,117 +55,59 @@ async def discover(options: DiscoverOptions) -> DiscoverResult: await client.close() -def _active_workspace() -> str: - """The workspace the platform context resolves to. - - Read rather than accepted as a flag, so the artifact lands where every other ``nemo`` - command in this context looks. The report records the answer, since a later agent needs - to name a workspace to fetch from. ``NMP_WORKSPACE`` still overrides, because that is the - platform's own escape hatch rather than one of ours. - """ - return Config.load().resolve().workspace - - async def _discover( - client: AsyncNeMoPlatform, options: DiscoverOptions, *, repo_root: Path, agent: str, workspace: str + client: AsyncNeMoPlatform, + options: DiscoverOptions, + *, + repo_root: Path, + agent: str, + workspace: str, ) -> DiscoverResult: - candidate, findings = sources.find_candidate(repo_root) - outcome = ValidationOutcome() - if candidate is not None: - outcome = await validate.run_ladder(candidate, repo_root) - - findings.extend(outcome.findings) - findings.extend(await _probe_repo(client, repo_root, agent=agent, workspace=workspace)) - - # When the repo maintains the config Harbor accepted, that file is what a later run will - # pass to -c, so it is the thing worth round-tripping and there is nothing of ours to - # persist. Rendering a copy anyway would put a second config in the fileset that no one - # owns and that goes stale the moment the real one is edited. - repo_config = candidate.source.path if candidate is not None and candidate.source.owns_file else None - job_config = None - if repo_config is not None: - findings.append(validate.check_config_file(repo_config, repo_root)) - elif outcome.config is not None: - job_config = report.render_job_config(outcome.config, repo_root) - findings.append(_round_trip(job_config, repo_root)) - + scan_result = scan.scan_repository(repo_root) + validation = validate.ValidationOutcome() + if scan_result.config is not None: + validation = await validate.run_ladder(scan_result.config, repo_root) + trace_check = await scan.probe_traces(client, agent=agent, workspace=workspace) record = report.build_report( agent=agent, workspace=workspace, repo_root=repo_root, - candidate=candidate, - findings=findings, - required_env_vars=outcome.required_env_vars, + scan_result=scan_result, + validation=validation, + trace_check=trace_check, ) - # A config only travels with a report that vouches for it. The schema rung can pass - # while a later rung fails, and shipping the config anyway would put a file in the - # fileset that reads as ready to run. - publishable = job_config if record.runnable else None markdown = report.render_markdown(record) - + result = DiscoverResult(report=record, markdown=markdown, dry_run=options.dry_run) if options.dry_run: - return DiscoverResult(report=record, markdown=markdown, job_config=job_config, dry_run=True) + return result - persisted, memory_findings = await memory.persist( - client, - agent=agent, - workspace=workspace, - markdown=markdown, - job_config=publishable, - ) - if job_config is not None and publishable is None: - memory_findings.append( - Finding( - # Not "upload": withholding is a decision, and memory.persist uses that name - # for an upload that actually broke. - name="config-withheld", - group="memory", - status="warn", - message=f"Withheld {JOB_CONFIG_FILENAME}: the config did not clear every check", - hint="A config in this fileset is always one Harbor could run, so none was written.", - ) + try: + await client.files.upload_content( + content=markdown.encode("utf-8"), + remote_path=f"{agent}/{REPORT_FILENAME}", + fileset=FILESET_NAME, + workspace=workspace, + fileset_auto_create=True, ) - return DiscoverResult( - report=record, - markdown=markdown, - job_config=job_config, - persisted=persisted, - memory_findings=memory_findings, - ) - + except Exception as exc: + result.upload_error = f"{type(exc).__name__}: {exc}" + else: + result.uploaded = True + return result -async def _probe_repo(client: AsyncNeMoPlatform, repo_root: Path, *, agent: str, workspace: str) -> list[Finding]: - return [ - scan.find_doctrine(repo_root), - scan.find_skills(repo_root), - await scan.probe_traces(client, agent=agent, workspace=workspace), - ] - -def _round_trip(job_config: str, repo_root: Path) -> Finding: - """Validate the exact bytes we intend to persist, from a scratch directory. - - Written outside the repo on purpose: discover inspects a repo and must not leave - anything in it. Harbor loads the config relative to ``cwd``, which the round trip sets - to the repo root, so the file's own location does not matter. - """ - with tempfile.TemporaryDirectory(prefix="eval-author-discover-") as scratch: - config_path = Path(scratch) / JOB_CONFIG_FILENAME - config_path.write_text(job_config, encoding="utf-8") - return validate.check_config_file(config_path, repo_root) +def _active_workspace() -> str: + return Config.load().resolve().workspace def _infer_agent_name(repo_root: Path) -> str: - """Name from ``optimizer.yaml`` when it says, else a slug of the directory.""" - profile = discover_profile(repo_root) - if profile is not None: - try: - declared = sources.read_profile_agent(profile) - except Exception: - declared = None - if declared: - return _slug(declared) - return _slug(repo_root.name) + """Read a root profile name, or use the repository directory.""" + try: + data = yaml.safe_load((repo_root / "optimizer.yaml").read_text(encoding="utf-8")) + except (OSError, UnicodeError, yaml.YAMLError): + data = None + declared = data.get("agent") if isinstance(data, dict) else None + return _slug(declared) if isinstance(declared, str) and declared.strip() else _slug(repo_root.name) def _slug(value: str) -> str: diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py index 4af70e8670f..457458f1f0a 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py @@ -1,33 +1,21 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Repo-shape probes, plus the traversal helpers the rest of discovery shares. - -Three things matter to Eval Author but are not fields of a Harbor job config: the doctrine -document describing what the agent is for, any Harbor skill bundles the repo ships, and -whether the platform has traces for this agent to author evals from. - -None of these probes ever returns a ``fail``. ``DiscoveryReport.runnable`` is false when -any finding failed, and that flag means precisely one thing: Harbor cannot run this -config. A repo with no traces yet, or no ``ETHOS.md``, runs its evals perfectly well. Only -the ladder in ``validate`` gets to fail a report. -""" +"""Scan repository-owned Harbor inputs.""" +import hashlib +import json import os from collections.abc import Iterator +from dataclasses import dataclass from pathlib import Path from typing import Any -from nemo_eval_author_plugin.discovery.models import Finding +import yaml +from nemo_insights_plugin.contracts.checks import CheckResult, CheckSeverity, CheckStatus -_GROUP = "repo" - -# Vendored and generated trees dwarf a repo's own content and never hold its eval setup. -# -# `eval-and-optimize` and `.nemo-optimizer` are Experimentalist's output, and pruning them is -# what keeps discover from reading the optimizer's own results as the repo's declared setup: -# they hold Harbor job dirs from the optimizer's runs and working copies of the agent, which -# every probe here would otherwise treat as candidates the repo maintains. +_CONFIG_DIRS = ("configs", ".", "harbor", ".harbor", "evals") +_CONFIG_SUFFIXES = (".yaml", ".yml", ".json") _PRUNE_DIR_NAMES = frozenset( { ".git", @@ -42,116 +30,170 @@ ".eggs", ".cache", "site-packages", + "vendor", + "cache", "dist", "build", "eval-and-optimize", ".nemo-optimizer", } ) -_MAX_WALK_DEPTH = 6 -# ETHOS.md is the new name and AGENT-SPEC.md the old one, so both are honored while the -# rename is in flight. README.md is the fallback every repo has. -_DOCTRINE_FILENAMES = ("ETHOS.md", "AGENT-SPEC.md", "README.md") -_SKILL_FILENAME = "SKILL.md" -_MAX_LISTED_SKILLS = 10 +@dataclass(frozen=True) +class ConfigCandidate: + """A repository-owned Harbor config file.""" + + path: Path + data: dict[str, Any] + + +@dataclass +class RepositoryScan: + """The repository facts that the validation ladder needs.""" + + config: ConfigCandidate | None + dataset_paths: list[Path] + ethos_path: Path | None + fingerprint: str + input_file_count: int + checks: list[CheckResult] -def walk_dirs(root: Path, max_depth: int = _MAX_WALK_DEPTH) -> Iterator[Path]: - """Yield directories under *root*, pruning vendored trees and bottoming out by depth.""" - root = root.resolve() - root_depth = len(root.parts) + +def _check( + name: str, + status: CheckStatus, + message: str, + *, + severity: CheckSeverity = "required", + hint: str | None = None, +) -> CheckResult: + return CheckResult(name=name, group="repository", status=status, severity=severity, message=message, hint=hint) + + +def walk_dirs(root: Path) -> Iterator[Path]: + """Yield repository directories and skip generated trees.""" for current, dir_names, _ in os.walk(root): - current_path = Path(current) - if len(current_path.parts) - root_depth >= max_depth: - dir_names.clear() - else: - dir_names[:] = sorted(name for name in dir_names if name not in _PRUNE_DIR_NAMES) - yield current_path - - -def display_path(path: Path, repo_root: Path) -> str: - """Render *path* relative to the repo when it lives there, absolute when it does not. - - Not every discovered path is inside the repo: ``discover_profile`` walks upward, so an - ``optimizer.yaml`` in a parent directory is a legitimate find rather than an error to - crash on. A path that is already relative is left alone, which also covers the - ```` sentinel used for values declared inline rather than in a file. - """ - if not path.is_absolute(): - return str(path) - try: - return str(path.resolve().relative_to(repo_root.resolve())) - except ValueError: - return str(path) - - -def find_doctrine(repo_root: Path) -> Finding: - """Locate the document describing what the agent is supposed to do. - - Recording which name matched makes the report double as a signal for the - ``AGENT-SPEC.md`` to ``ETHOS.md`` rename: a repo still on the old name says so here. - """ - for name in _DOCTRINE_FILENAMES: - candidate = repo_root / name - if candidate.is_file(): - return Finding( - name="doctrine", - group=_GROUP, - status="pass", - message=f"Agent doctrine at {name}", - path=candidate, - hint=( - "ETHOS.md is the current name; this repo predates the rename." if name == "AGENT-SPEC.md" else None - ), + dir_names[:] = sorted(name for name in dir_names if name not in _PRUNE_DIR_NAMES) + yield Path(current) + + +def scan_repository(repo_root: Path) -> RepositoryScan: + """Find one repo-owned config and local Harbor datasets.""" + repo_root = repo_root.resolve() + candidates = _config_candidates(repo_root) + checks: list[CheckResult] = [] + config = candidates[0] if candidates else None + if config is None: + checks.append( + _check( + "config", + "fail", + "No repository-owned Harbor config file exists.", + hint="Add a YAML, YML, or JSON config with a nonempty datasets or tasks list.", + ) + ) + else: + checks.append(_check("config", "pass", f"Using Harbor config {config.path.relative_to(repo_root)}.")) + if len(candidates) > 1: + extras = ", ".join(str(item.path.relative_to(repo_root)) for item in candidates[1:]) + checks.append( + _check( + "config", + "warn", + f"More Harbor config files exist: {extras}.", + severity="advisory", + hint="Discovery uses the first file in its fixed search order.", ) - return Finding( - name="doctrine", - group=_GROUP, - status="warn", - message=f"No {' or '.join(_DOCTRINE_FILENAMES)} at the repo root", - hint="Eval Author writes better cases when the repo states what the agent is for.", - ) - - -def find_skills(repo_root: Path) -> Finding: - """Find Harbor skill bundles, the directories a ``SKILL.md`` marks. - - These are what ``harbor.skills`` resolves for ``AgentConfig.skills`` and mounts at - ``[environment].skills_dir``. Not the same thing as ``framework_skills`` in - ``optimizer.yaml``: a repo can ship both, and they are handed to different consumers. - """ - skills = [directory for directory in walk_dirs(repo_root) if (directory / _SKILL_FILENAME).is_file()] - if not skills: - return Finding( - name="skills", - group=_GROUP, - status="warn", - message=f"No {_SKILL_FILENAME} bundles found", - hint="Only relevant if the agent under test is meant to receive Harbor skills.", ) - listed = ", ".join(display_path(path, repo_root) for path in skills[:_MAX_LISTED_SKILLS]) - remainder = len(skills) - _MAX_LISTED_SKILLS - return Finding( - name="skills", - group=_GROUP, - status="pass", - message=f"{len(skills)} Harbor skill bundle(s): {listed}" - + (f", and {remainder} more" if remainder > 0 else ""), - path=skills[0], - hint="Pass these to a job via AgentConfig.skills; they mount at [environment].skills_dir.", - ) - - -async def probe_traces(client: Any, *, agent: str, workspace: str) -> Finding: - """Count the agent's distinct sessions in Intake, which is Eval Author's raw material. - - A "trace" is one distinct ``session_id`` among the agent's spans, because only spans - carry the agent identity. This is the rollup ``count_agent_sessions`` performs in the - insights analyst backend; the SDK call is made directly here rather than importing - that class, which would drag a backend and its persistence into a read-only probe. - """ + ethos_path = repo_root / "ETHOS.md" + if ethos_path.is_file(): + checks.append(_check("ethos", "pass", "ETHOS.md defines the agent doctrine.", severity="advisory")) + else: + ethos_path = None + checks.append( + _check( + "ethos", + "warn", + "ETHOS.md does not exist at the repository root.", + severity="advisory", + hint="Add ETHOS.md to define the agent doctrine.", + ) + ) + + datasets = _dataset_paths(repo_root) + fingerprint, count = _fingerprint(repo_root, config.path if config else None, ethos_path, datasets) + return RepositoryScan(config, datasets, ethos_path, fingerprint, count, checks) + + +def _config_candidates(repo_root: Path) -> list[ConfigCandidate]: + candidates: list[ConfigCandidate] = [] + for relative in _CONFIG_DIRS: + directory = repo_root if relative == "." else repo_root / relative + if not directory.is_dir(): + continue + for path in sorted(directory.iterdir()): + if not path.is_file() or path.suffix.lower() not in _CONFIG_SUFFIXES: + continue + try: + if not path.resolve().is_relative_to(repo_root): + continue + except (OSError, RuntimeError): + continue + data = _load_mapping(path) + if data is not None and _has_work(data): + candidates.append(ConfigCandidate(path=path, data=data)) + return candidates + + +def _load_mapping(path: Path) -> dict[str, Any] | None: + try: + text = path.read_text(encoding="utf-8") + data = json.loads(text) if path.suffix.lower() == ".json" else yaml.safe_load(text) + except (OSError, UnicodeError, json.JSONDecodeError, yaml.YAMLError): + return None + return data if isinstance(data, dict) else None + + +def _has_work(data: dict[str, Any]) -> bool: + return any(isinstance(data.get(name), list) and data[name] for name in ("datasets", "tasks")) + + +def _dataset_paths(repo_root: Path) -> list[Path]: + datasets: set[Path] = set() + for directory in walk_dirs(repo_root): + if directory != repo_root and directory.name != "task_template" and (directory / "task.toml").is_file(): + datasets.add(directory.parent) + return sorted(datasets) + + +def _fingerprint( + repo_root: Path, + config_path: Path | None, + ethos_path: Path | None, + datasets: list[Path], +) -> tuple[str, int]: + files: set[Path] = { + path for path in (config_path, ethos_path, repo_root / "optimizer.yaml") if path and path.is_file() + } + for dataset in datasets: + if not dataset.is_relative_to(repo_root): + continue + for directory in walk_dirs(dataset): + files.update(path for path in directory.iterdir() if path.is_file()) + + digest = hashlib.sha256() + for path in sorted(files): + digest.update(str(path.relative_to(repo_root)).encode()) + digest.update(b"\0") + digest.update(path.read_bytes()) + digest.update(b"\0") + return digest.hexdigest(), len(files) + + +async def probe_traces(client: Any, *, agent: str, workspace: str) -> CheckResult: + """Check whether Intake has traces for later authoring steps.""" try: page = await client.intake.spans.groups.list( workspace=workspace, @@ -162,26 +204,13 @@ async def probe_traces(client: Any, *, agent: str, workspace: str) -> Finding: sort="-span_count", ) except Exception as exc: - return Finding( - name="traces", - group=_GROUP, - status="warn", - message=f"Could not read traces for '{agent}': {type(exc).__name__}: {exc}", - hint="Traces feed later Eval Author stages; Harbor runs fine without them.", + return _check( + "traces", + "warn", + f"Cannot read traces for {agent}: {type(exc).__name__}: {exc}", + severity="advisory", ) - total = page.pagination.total_results if page.pagination is not None else len(page.data) if not total: - return Finding( - name="traces", - group=_GROUP, - status="warn", - message=f"No traces recorded for agent '{agent}' in workspace '{workspace}'", - hint="Run the agent with telemetry enabled to give Eval Author something to author from.", - ) - return Finding( - name="traces", - group=_GROUP, - status="pass", - message=f"{total} trace session(s) available for '{agent}' in workspace '{workspace}'", - ) + return _check("traces", "warn", f"No traces exist for {agent}.", severity="advisory") + return _check("traces", "pass", f"{total} trace sessions exist for {agent}.", severity="advisory") diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py deleted file mode 100644 index d1af96b1ebc..00000000000 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/sources.py +++ /dev/null @@ -1,637 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Assemble a candidate Harbor job config from whatever the repo already declares. - -Four sources, ranked in ``SOURCE_PRIORITY`` by how much of the config Harbor has already -agreed to. A config file the user wrote beats a config Harbor once ran, which beats one -we assembled from ``optimizer.yaml``, which beats one inferred from directory names. - -Nothing in this module validates anything. Every source hands back a raw mapping and a -note about where it came from, and the ladder in ``validate`` owns every verdict. Keeping -assembly apart from judgement is what turns "no config reaches the artifact unless Harbor -accepted it" into a property that can be checked rather than a promise: if this module -returned a parsed ``JobConfig``, the schema rung would already have run off to the side. - -Paths inside the config come back absolute so validation needs no working-directory tricks. -Rewriting them relative to the repo for the persisted artifact is ``report``'s job. The one -exception is ``CandidateConfig.agent_search_path``, which is repo-relative from the start -because it is not a config field: it is the ``PYTHONPATH`` a run needs, and both the ladder -and the artifact read it as written. -""" - -import ast -import json -from pathlib import Path -from typing import Any, Literal, NamedTuple - -import yaml -from nemo_eval_author_plugin.discovery.models import ( - CandidateConfig, - ConfigSource, - Finding, -) -from nemo_eval_author_plugin.discovery.scan import display_path, walk_dirs -from nemo_experimentalist_plugin.experimentalist.components.evaluator.harbor import _AGENT_IMPORT_ROOT -from nemo_insights_plugin.contracts.profile import ( - PROFILE_FILENAME, - ProfileError, - discover_profile, - load_profile_model, - resolve_profile_path, -) -from pydantic import BaseModel, ConfigDict, Field - -_GROUP = "config" - -DatasetKind = Literal["path", "ref"] - -# `harbor job init` writes into `configs/` unless told otherwise, so look there first. -_CONFIG_SEARCH_DIRS = ("configs", ".", "harbor", ".harbor", "evals") -_CONFIG_SUFFIXES = (".yaml", ".yml", ".json") - -_TASK_CONFIG_FILENAME = "task.toml" -_TEMPLATE_DIR_NAME = "task_template" -_WRAPPER_FILENAME = "harbor_wrapper.py" -_AGENT_BASE_CLASSES = frozenset({"BaseAgent", "BaseInstalledAgent"}) -_CONVENTIONAL_DATASET_DIRS = ("evals/validation", "evals/val", "evals/train") - - -class _ProfileDatasets(BaseModel): - model_config = ConfigDict(extra="ignore") - - train: str | None = None - validation: str | None = None - registry_url: str | None = None - """Present or absent, this decides how the split values are read, so it cannot be ignored. - - ``extra="ignore"`` swallowed it before, which left every value looking like a local path - and turned ``validation: tau2-bench-live-validation@1.0`` into a directory that is not - there. - """ - - -class _DiscoveryProfile(BaseModel): - """The ``optimizer.yaml`` fields discover needs, and nothing else. - - Lenient where Experimentalist's ``AgentProfile`` is strict. That model forbids extras - and lives behind the import boundary, so a repo written for a newer Experimentalist - would make discover fail on a key it does not even read. Ignoring extras is the point. - """ - - model_config = ConfigDict(extra="ignore") - - agent: str | None = None - task_template: str | None = None - agent_source: str = "." - datasets: _ProfileDatasets = Field(default_factory=_ProfileDatasets) - profile_dir: Path - - -def find_candidate(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: - """Return the highest-priority candidate config found in *repo_root*. - - Every source is attempted even once one has won, because "we also found a prior job - directory" is worth saying: it tells a reader which evidence was passed over. - """ - # Resolved once here so every path downstream is comparable. The walk resolves as it - # goes, and on macOS a caller's /tmp is the walk's /private/tmp, which would make - # rendering a path relative to the repo fail on a symlinked root. - repo_root = repo_root.resolve() - findings: list[Finding] = [] - candidates: list[CandidateConfig] = [] - - for source in (_from_config_file, _from_prior_job, _from_profile, _from_convention): - candidate, source_findings = source(repo_root) - findings.extend(source_findings) - if candidate is not None: - candidates.append(candidate) - - if not candidates: - findings.append( - Finding( - name="config-source", - group=_GROUP, - status="fail", - message="No Harbor job config could be assembled from this repo", - hint=( - f"Add a config with `harbor job init`, or a {PROFILE_FILENAME} naming a " - "task_template and datasets, or a directory of Harbor task dirs." - ), - ) - ) - return None, findings - - winner = min(candidates, key=lambda item: item.source.rank) - passed_over = [item.source.kind for item in candidates if item is not winner] - findings.append( - Finding( - name="config-source", - group=_GROUP, - status="pass", - message=f"Using the {winner.source.kind} source: {winner.source.detail}", - path=winner.source.path, - hint=(f"Also found, lower trust: {', '.join(passed_over)}" if passed_over else None), - ) - ) - return winner, findings - - -def _from_config_file(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: - """A config file the user wrote, which is the strongest thing a repo can offer.""" - matches: list[tuple[Path, dict[str, Any]]] = [] - for relative in _CONFIG_SEARCH_DIRS: - directory = repo_root / relative - if not directory.is_dir(): - continue - for path in sorted(directory.iterdir()): - if not path.is_file() or path.suffix.lower() not in _CONFIG_SUFFIXES: - continue - payload = _load_mapping(path) - if payload is not None and _looks_like_job_config(payload): - matches.append((path, payload)) - - if not matches: - return None, [] - - path, payload = matches[0] - shown = display_path(path, repo_root) - extra = [display_path(other, repo_root) for other, _ in matches[1:]] - findings = [ - Finding( - name="config-file", - group=_GROUP, - status="pass", - message=f"Found a Harbor job config at {shown}", - path=path, - hint=(f"Ignoring additional candidates: {', '.join(extra)}" if extra else None), - ) - ] - return ( - CandidateConfig( - data=payload, - source=ConfigSource( - kind="config_file", - detail=f"declared at {shown}", - path=path, - ), - ), - findings, - ) - - -def _from_prior_job(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: - """A ``config.json`` Harbor itself resolved and ran. - - Harbor writes ``config.json`` and ``lock.json`` into the job directory and again into - every trial directory, so matching on those filenames alone would also pick up trial - configs. ``_looks_like_job_config`` is the discriminator: a trial config names one - ``task``, never a list of ``datasets`` or ``tasks``. - """ - job_dirs: list[tuple[Path, dict[str, Any]]] = [] - for directory in walk_dirs(repo_root): - config_path = directory / "config.json" - if not config_path.is_file() or not (directory / "lock.json").is_file(): - continue - payload = _load_mapping(config_path) - if payload is not None and _looks_like_job_config(payload) and not _has_synthetic_agent(payload): - job_dirs.append((config_path, payload)) - - if not job_dirs: - return None, [] - - config_path, payload = max(job_dirs, key=lambda item: item[0].stat().st_mtime) - shown = display_path(config_path.parent, repo_root) - return ( - CandidateConfig( - data=payload, - source=ConfigSource( - kind="prior_job", - detail=f"resolved by a previous run at {shown}", - path=config_path, - ), - ), - [ - Finding( - name="prior-job", - group=_GROUP, - status="pass", - message=f"Found {len(job_dirs)} previous Harbor job config(s); using {shown}", - path=config_path, - hint="A config Harbor already ran is evidence, so it outranks anything inferred from layout.", - ) - ], - ) - - -def _from_profile(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: - """Assemble from ``optimizer.yaml`` plus the agent wrapper it implies.""" - profile_path = discover_profile(repo_root) - if profile_path is None: - return None, [] - - try: - profile = load_profile_model(profile_path, _DiscoveryProfile) - except ProfileError as exc: - return None, [ - Finding( - name="profile", - group=_GROUP, - status="warn", - message=f"Found {PROFILE_FILENAME} but could not read it: {exc}", - path=profile_path, - ) - ] - - findings = [ - Finding( - name="profile", - group=_GROUP, - status="pass", - message=f"Read {PROFILE_FILENAME}", - path=profile_path, - ) - ] - - # validation first: it is the eval set, and train exists to optimize against, so - # preferring train here would quietly evaluate on the wrong split. - declared = {"validation": profile.datasets.validation, "train": profile.datasets.train} - evaluable = [(split, value) for split, value in declared.items() if value] - if not evaluable: - findings.append( - Finding( - name="profile-datasets", - group=_GROUP, - status="warn", - message=f"{PROFILE_FILENAME} declares no datasets.train or datasets.validation", - path=profile_path, - ) - ) - return None, findings - - chosen_split, declared_value = evaluable[0] - other_split = "train" if chosen_split == "validation" else "validation" - also_declares = ( - f"{PROFILE_FILENAME} also declares datasets.{other_split}, which is not evaluated here." - if declared[other_split] - else None - ) - registry_url = profile.datasets.registry_url - - if classify_dataset_value(declared_value, profile.profile_dir, registry_url=registry_url) == "ref": - dataset_entry = _registry_dataset(declared_value, registry_url) - findings.append( - Finding( - name="profile-datasets", - group=_GROUP, - # A ref is a legitimate way to declare a dataset, and one this machine may - # have no reach to. Recorded as a warning rather than passed over in silence, - # because a reader of the artifact cannot see the tasks the way they can for - # a local path. - status="warn", - message=( - f"datasets.{chosen_split} is the registry ref '{declared_value}', " - f"which a run downloads rather than reads from this repo" - ), - path=profile_path, - hint=" ".join( - filter( - None, - [ - "Resolving it needs the registry to be reachable, and Harbor caches " - "it under ~/.cache/harbor on first use.", - also_declares, - ], - ) - ), - ) - ) - else: - dataset_path = _resolve_profile_path(declared_value, profile.profile_dir) - if dataset_path is None: - findings.append( - Finding( - name="profile-datasets", - group=_GROUP, - status="warn", - message=f"Could not resolve datasets.{chosen_split} from {PROFILE_FILENAME}", - path=profile_path, - ) - ) - return None, findings - - dataset_entry = {"path": str(dataset_path)} - findings.append( - Finding( - name="profile-datasets", - group=_GROUP, - status="pass", - message=f"Evaluating datasets.{chosen_split} at {display_path(dataset_path, repo_root)}", - path=dataset_path, - hint=also_declares, - ) - ) - - agent_root = _resolve_profile_path(profile.agent_source, profile.profile_dir) or repo_root - agent = _agent_entry(agent_root, repo_root) - findings.extend(agent.findings) - - return ( - CandidateConfig( - data={"agents": [agent.data], "datasets": [dataset_entry]}, - source=ConfigSource( - kind="profile", - detail=f"assembled from {PROFILE_FILENAME} datasets.{chosen_split}", - path=profile_path, - ), - agent_search_path=agent.search_path, - ), - findings, - ) - - -def _from_convention(repo_root: Path) -> tuple[CandidateConfig | None, list[Finding]]: - """Assemble from directory layout alone, which is the weakest source on offer.""" - task_dirs = [directory for directory in walk_dirs(repo_root) if (directory / _TASK_CONFIG_FILENAME).is_file()] - if not task_dirs: - return None, [] - - # Harbor takes the parent of task dirs as the dataset, and skips a child named - # task_template, so a parent whose only task child is the template is a template - # holder rather than a dataset. - by_parent: dict[Path, list[Path]] = {} - for task_dir in task_dirs: - by_parent.setdefault(task_dir.parent, []).append(task_dir) - - dataset_dirs = { - parent: children - for parent, children in by_parent.items() - if [child for child in children if child.name != _TEMPLATE_DIR_NAME] - } - if not dataset_dirs: - return None, [ - Finding( - name="convention-datasets", - group=_GROUP, - status="warn", - message=f"Found Harbor task dirs but only under a {_TEMPLATE_DIR_NAME} directory", - path=task_dirs[0], - hint="A template is a scaffold for one task, not a dataset Harbor can evaluate.", - ) - ] - - chosen = _preferred_dataset_dir(repo_root, dataset_dirs) - shown = display_path(chosen, repo_root) - findings = [ - Finding( - name="convention-datasets", - group=_GROUP, - status="pass", - message=f"Found {len(dataset_dirs[chosen])} Harbor task dir(s) under {shown}", - path=chosen, - hint="Inferred from directory layout, so confirm it is the set you meant to evaluate.", - ) - ] - - agent = _agent_entry(repo_root, repo_root) - findings.extend(agent.findings) - - return ( - CandidateConfig( - data={"agents": [agent.data], "datasets": [{"path": str(chosen)}]}, - source=ConfigSource( - kind="convention", - detail=f"inferred from task dirs under {shown}", - path=chosen, - ), - agent_search_path=agent.search_path, - ), - findings, - ) - - -def _preferred_dataset_dir(repo_root: Path, dataset_dirs: dict[Path, list[Path]]) -> Path: - """Prefer a conventional eval directory, then the largest set, then a stable name.""" - for relative in _CONVENTIONAL_DATASET_DIRS: - candidate = (repo_root / relative).resolve() - if candidate in dataset_dirs: - return candidate - return max(dataset_dirs, key=lambda parent: (len(dataset_dirs[parent]), str(parent))) - - -class _AgentEntry(NamedTuple): - """One ``agents`` entry, plus the search path the entry needs to be importable.""" - - data: dict[str, Any] - search_path: str | None - findings: list[Finding] - - -def _agent_entry(agent_root: Path, repo_root: Path) -> _AgentEntry: - """Describe the agent to run, preferring a wrapper in the repo over Harbor's default. - - Falls back to ``oracle``, which is what Harbor itself defaults to and the only agent - that needs no model or credentials. It runs ``solution/solve.sh``, so a config that - lands here still proves the tasks work even though it evaluates nothing. - - A wrapper yields a bare ``module:Class`` import path, which is what Harbor's own - examples use, plus the directory holding that module. The directory is not decoration: - Harbor imports through ``importlib.import_module`` and adds nothing to ``sys.path``, so - a bare module name resolves only if something already put its directory there. Recording - it is what lets the artifact hand out a run command that works, and a nested wrapper is - why it cannot be assumed to be the repo root. - """ - wrapper = _find_wrapper(agent_root) or _find_wrapper(repo_root) - if wrapper is None: - return _AgentEntry({"name": "oracle"}, None, [_no_wrapper_finding(agent_root, repo_root)]) - - path, class_name = wrapper - search_path = display_path(path.parent, repo_root) - return _AgentEntry( - {"import_path": f"{path.stem}:{class_name}"}, - search_path, - [ - Finding( - name="agent-entrypoint", - group=_GROUP, - status="pass", - message=f"Agent import path {path.stem}:{class_name}, importable from {search_path}", - path=path, - hint=f"Read from the class definition in {display_path(path, repo_root)}, not assumed.", - ) - ], - ) - - -def _no_wrapper_finding(agent_root: Path, repo_root: Path) -> Finding: - """Say why the oracle is standing in, distinguishing no wrapper from no agent in one. - - The two read identically from the config and mean opposite things. A repo with no - wrapper has nothing to evaluate yet; a repo whose wrapper this module could not - recognize has an agent that is simply not being run, and reporting that as "no - harbor_wrapper.py found" sends its author looking for a missing file. - """ - unmatched = _wrapper_paths(agent_root) or _wrapper_paths(repo_root) - oracle = ( - "The oracle replays solution/solve.sh, so it validates the tasks but evaluates no agent. " - "Add a harbor_wrapper.py to evaluate yours." - ) - if not unmatched: - return Finding( - name="agent-entrypoint", - group=_GROUP, - status="warn", - message=f"No {_WRAPPER_FILENAME} found; falling back to Harbor's oracle agent", - hint=oracle, - ) - - bases = " or ".join(sorted(_AGENT_BASE_CLASSES)) - return Finding( - name="agent-entrypoint", - group=_GROUP, - status="warn", - message=( - f"{display_path(unmatched[0], repo_root)} declares no class based on {bases}; " - "falling back to Harbor's oracle agent" - ), - path=unmatched[0], - hint=( - f"The base is matched by name in the source, so a wrapper reaching {bases} through an " - "alias or an intermediate class is not recognized. A Harbor config file declaring the " - "agent's import_path outranks this source, and would run it. " + oracle - ), - ) - - -def _find_wrapper(root: Path) -> tuple[Path, str] | None: - """Find ``harbor_wrapper.py`` and the agent class inside it, by parsing not importing. - - The class name is read rather than assumed: ``WrappedAgent`` is the convention in this - repo, but a wrapper is a file the user wrote and the ladder's agent rung is the thing - that gets to import it. - """ - for path in _wrapper_paths(root): - class_name = _agent_class_name(path) - if class_name is not None: - return path, class_name - return None - - -def _wrapper_paths(root: Path) -> list[Path]: - """Every ``harbor_wrapper.py`` under *root*, shallowest first.""" - return [directory / _WRAPPER_FILENAME for directory in walk_dirs(root) if (directory / _WRAPPER_FILENAME).is_file()] - - -def _agent_class_name(path: Path) -> str | None: - try: - tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) - except (OSError, UnicodeError, SyntaxError): - return None - for node in ast.walk(tree): - if not isinstance(node, ast.ClassDef): - continue - for base in node.bases: - name = base.attr if isinstance(base, ast.Attribute) else getattr(base, "id", None) - if name in _AGENT_BASE_CLASSES: - return node.name - return None - - -def classify_dataset_value(value: str, base_dir: Path, *, registry_url: str | None = None) -> DatasetKind: - """Classify an ``optimizer.yaml`` dataset value as a local path or a Harbor registry ref. - - Mirrors ``nemo_experimentalist_plugin.resolve.classify_dataset_value``, which is the rule - Experimentalist applies to the same file, so the two must agree — a value the optimizer - downloads and discover resolves as a path yields an artifact about a directory nobody has. - A copy rather than an import because Eval Author's dependency on Experimentalist is being - removed rather than added to; ``test_sources.py`` pins the agreement instead. - """ - if value.startswith(("./", "../", "/", "~")): - return "path" - if registry_url is not None: - return "ref" - if "/" in value: - return "path" - try: - if (base_dir / value).exists(): - return "path" - except OSError: # not representable as a local path (e.g. name too long) - pass - return "ref" - - -def _registry_dataset(value: str, registry_url: str | None) -> dict[str, Any]: - """A ``DatasetConfig`` naming a registry dataset, which is what Harbor resolves refs from. - - ``name`` and ``version`` rather than ``path``: Harbor's ``DatasetConfig`` rejects both at - once, and a ref pointed at ``path`` is how the profile's ``name@version`` became a - nonexistent directory under the profile dir. - """ - name, separator, version = value.partition("@") - entry: dict[str, Any] = {"name": name} - if separator: - entry["version"] = version - if registry_url is not None: - entry["registry_url"] = registry_url - return entry - - -def _resolve_profile_path(value: str | None, profile_dir: Path) -> Path | None: - if not value: - return None - try: - return resolve_profile_path(value, profile_dir) - except ProfileError: - return None - - -def _has_synthetic_agent(payload: dict[str, Any]) -> bool: - """Whether a config's agent only exists inside the process that wrote the config. - - Experimentalist's Harbor evaluator rewrites the agent's import path under a package it - synthesizes in ``sys.modules`` for the duration of its own run, so the config it leaves - behind names a module no separate ``harbor`` process can import. Harbor resolved and ran - it, which is exactly what makes it tempting: without this guard, running the optimizer - and then discover in the same repo reports "Harbor cannot run this repo's evals" about a - repo that was just evaluated successfully. - """ - agents = payload.get("agents") - if not isinstance(agents, list): - return False - return any( - isinstance(agent, dict) - and isinstance(agent.get("import_path"), str) - and agent["import_path"].startswith(f"{_AGENT_IMPORT_ROOT}.") - for agent in agents - ) - - -def _looks_like_job_config(payload: dict[str, Any]) -> bool: - """Whether a mapping declares a Harbor task source. - - Requiring ``datasets`` or ``tasks`` rather than ``agents`` does double duty: a job - config without a task source cannot run at all, and the stricter test keeps unrelated - YAML that happens to mention agents (a NAT workflow, a CI matrix) from matching. - """ - for key in ("datasets", "tasks"): - value = payload.get(key) - if isinstance(value, list) and value: - return True - return False - - -def _load_mapping(path: Path) -> dict[str, Any] | None: - try: - text = path.read_text(encoding="utf-8") - payload = json.loads(text) if path.suffix.lower() == ".json" else yaml.safe_load(text) - except (OSError, UnicodeError, json.JSONDecodeError, yaml.YAMLError): - return None - return payload if isinstance(payload, dict) else None - - -def read_profile_agent(profile_path: Path) -> str | None: - """The agent name ``optimizer.yaml`` declares, if it declares one.""" - try: - return load_profile_model(profile_path, _DiscoveryProfile).agent - except ProfileError: - return None diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py index 4857f098e77..3761c8e9073 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/validate.py @@ -1,42 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Prove a candidate job config runnable using Harbor's own validators. - -Every rung here is a Harbor call. That is the entire point: a later agent is meant to run -what discover recorded without re-deriving it, which is only safe if the verdicts came -from the same code the run will use. Reimplementing Harbor's rules would produce a report -that agrees with Harbor today and drifts silently tomorrow. - -The rungs, in order, and the Harbor API each one leans on: - -1. schema ``JobConfig.model_validate`` plus ``validate_agent_concurrency_limits``, - which is what ``harbor job start --print-config`` runs before it returns. -2. resolution ``Job.create``, which resolves skills, task configs, resource policies and - metrics, and starts no container. -3. tasks ``Task.is_valid_dir``, then ``Task()`` to get the reason a task failed. -4. coverage every task dir on disk against the set ``Job.create`` actually resolved, - because Harbor drops one it cannot parse without raising. -5. credentials ``get_required_host_vars`` over the task and job env templates. -6. agent ``import_class`` or ``AgentFactory.get_agent_class``, called the way Harbor's - own ``AgentFactory`` calls them. -7. backend ``EnvironmentFactory.run_preflight``. -8. round trip ``harbor job start --print-config -c `` against the persisted bytes. - -Two findings are ours rather than Harbor's, and neither carries a ``harbor_call``. The reward -advisory reads the test scripts itself, because Harbor has no API that answers the question -before a trial runs, and it can only warn since a text search cannot tell a script that writes -a reward through a variable from one that never writes a reward at all. The agent base-class -advisory is a judgement Harbor deliberately does not make: it enforces a base for verifiers -and not for agents, so an agent that is a plain class is worth saying and not worth failing. - -A failing rung is recorded, not raised. A report listing every problem is worth more than -one that stops at the first, and the command's whole job is to say why a repo cannot run. - -Two side effects worth knowing. ``Job.create`` populates ``~/.cache/harbor`` when a config -names remote datasets, and rung 6 imports a module from the repo under test, which runs -that module's top level. Neither starts a container or writes into the repo. -""" +"""Run Harbor preflight checks against a repository-owned config.""" import contextlib import shutil @@ -46,228 +11,115 @@ import tomllib from collections.abc import Iterator from dataclasses import dataclass, field +from fnmatch import fnmatchcase from pathlib import Path -from harbor.agents.base import BaseAgent from harbor.agents.factory import AgentFactory from harbor.environments.factory import EnvironmentFactory from harbor.job import Job from harbor.models.agent.name import AgentName from harbor.models.job.config import JobConfig -from harbor.models.task.config import TaskConfig as TaskDefinitionConfig +from harbor.models.task.config import TaskConfig from harbor.models.task.paths import TaskPaths from harbor.models.task.task import Task -from harbor.models.task.verifier_mode import resolve_effective_verifier_env_config from harbor.utils.env import get_required_host_vars from harbor.utils.import_path import import_class -from nemo_eval_author_plugin.discovery.models import CandidateConfig, Finding, RequiredEnvVar, Status -from nemo_eval_author_plugin.discovery.scan import display_path +from nemo_eval_author_plugin.discovery.scan import ConfigCandidate +from nemo_insights_plugin.contracts.checks import CheckResult, CheckSeverity, CheckStatus from pydantic import ValidationError -_GROUP = "validation" -# Harbor reads reward.json first and falls back to reward.txt; a test script naming -# neither fails the trial with RewardFileNotFoundError no matter how good the agent is. -_REWARD_FILENAMES = ("reward.json", "reward.txt") - -_TASK_CONFIG_FILENAME = "task.toml" -# Harbor skips a dataset child named task_template; it is a scaffold, not a task. -_TEMPLATE_DIR_NAME = "task_template" -_MAX_LISTED_DROPPED = 5 +@dataclass +class RequiredEnvVar: + """A host variable required by a Harbor config.""" -_PRINT_CONFIG_TIMEOUT_SEC = 120.0 + name: str + default: str | None + declared_in: Path @dataclass class ValidationOutcome: - """What the ladder concluded, and the evidence it gathered on the way.""" + """Results from one Harbor preflight.""" - config: JobConfig | None = None - findings: list[Finding] = field(default_factory=list) + checks: list[CheckResult] = field(default_factory=list) required_env_vars: list[RequiredEnvVar] = field(default_factory=list) - @property - def runnable(self) -> bool: - return self.config is not None and not any(item.status == "fail" for item in self.findings) - - -def _harbor(name: str, status: Status, message: str, call: str, **kwargs) -> Finding: - """A finding Harbor returned, which is what ``harbor_call`` claims on the way out.""" - return Finding( - name=name, - group=_GROUP, - status=status, - message=message, - harbor_call=call, - **kwargs, - ) +def _check( + name: str, + status: CheckStatus, + message: str, + *, + severity: CheckSeverity = "required", + hint: str | None = None, +) -> CheckResult: + return CheckResult(name=name, group="validation", status=status, severity=severity, message=message, hint=hint) -async def run_ladder(candidate: CandidateConfig, repo_root: Path) -> ValidationOutcome: - """Judge the config from the directory a real run would be started in. - Harbor resolves a config's relative paths against the process directory, and a config a - repo maintains says ``path: evals/validation`` meaning "from the repo root". Validating - it from anywhere else reports a dataset Harbor cannot find while ``harbor job start -c`` - from the repo root would run it — a false verdict on the case that matters most. The - subprocess round trip already passes ``cwd``; this gives the in-process rungs the same - footing. A process-wide chdir is only defensible because the CLI awaits one ladder and - nothing else. - """ - with contextlib.chdir(repo_root): - return await _ladder(candidate, repo_root) - - -async def _ladder(candidate: CandidateConfig, repo_root: Path) -> ValidationOutcome: - """Walk the ladder, stopping only where a later rung has nothing left to judge.""" +async def run_ladder(candidate: ConfigCandidate, repo_root: Path) -> ValidationOutcome: + """Run the complete preflight without caching or skipping any check.""" outcome = ValidationOutcome() - - config = _rung_schema(candidate, outcome) - if config is None: - return outcome - outcome.config = config - - job = await _rung_resolution(config, outcome) - _rung_agent(config, repo_root, candidate.agent_search_path, outcome) - _rung_backend(config, outcome) - if job is None: - return outcome - - resolved = _resolved_local_paths(job) - if resolved is None: - # Not a `_harbor` finding: Harbor did not return this verdict, we reached for one of - # its attributes and found it gone. Same shape as the round trip's "no harbor - # executable on PATH" — the honest report is that Harbor could not be asked. - outcome.findings.append( - Finding( - name="compatibility", - group=_GROUP, - status="fail", - message="This Harbor version no longer exposes the resolved task list through Job._task_configs", - hint=( - "Discovery reads the same private attribute Harbor's own CLI does, so this is an " - "incompatibility with the installed Harbor rather than a problem with this repo." - ), + with contextlib.chdir(repo_root): + try: + config = JobConfig.model_validate(candidate.data) + config.validate_agent_concurrency_limits() + except ValidationError as exc: + errors = exc.errors(include_url=False, include_input=False) + outcome.checks.append(_check("schema", "fail", f"Harbor rejected the job config: {errors}")) + return outcome + except ValueError as exc: + outcome.checks.append(_check("schema", "fail", f"Harbor rejected the job config: {exc}")) + return outcome + outcome.checks.append(_check("schema", "pass", "Harbor accepts the job config schema.")) + + job = await _resolve(config, outcome) + _check_agent(config, outcome) + _check_backend(config, outcome) + outcome.checks.append(check_config_file(candidate.path, repo_root)) + if job is None: + return outcome + + resolved = _resolved_task_paths(job) + if resolved is None: + outcome.checks.append( + _check( + "compatibility", + "fail", + "This Harbor version does not expose Job._task_configs.", + hint="Install a Harbor version that exposes the resolved task list.", + ) ) - ) - return outcome - - task_dirs = _rung_tasks(resolved, outcome) - _rung_coverage(config, resolved, outcome) - if not task_dirs: - return outcome - - _rung_reward(task_dirs, outcome) - _rung_credentials(config, task_dirs, outcome) + return outcome + task_dirs = _check_tasks(resolved, outcome) + _check_coverage(config, resolved, outcome) + _check_required_env_vars(config, task_dirs, outcome) return outcome -def _rung_schema(candidate: CandidateConfig, outcome: ValidationOutcome) -> JobConfig | None: - """Does the payload satisfy Harbor's job config schema?""" - try: - config = JobConfig.model_validate(candidate.data) - # Redundant with the model's own after-validator, and kept because it is the gate - # the CLI runs by hand at harbor/cli/jobs.py:1473 after it applies flags. If we - # ever mutate a config post-validation, this is the line that catches it. - config.validate_agent_concurrency_limits() - except ValidationError as exc: - details = "; ".join(error["msg"] for error in exc.errors(include_url=False, include_input=False)) - outcome.findings.append( - _harbor( - "schema", - "fail", - f"Job config does not satisfy Harbor's schema: {details}", - "JobConfig.model_validate", - path=candidate.source.path, - hint=f"Assembled from the {candidate.source.kind} source ({candidate.source.detail}).", - ) - ) - return None - except ValueError as exc: - outcome.findings.append( - _harbor( - "schema", - "fail", - f"Job config is internally inconsistent: {exc}", - "JobConfig.validate_agent_concurrency_limits", - path=candidate.source.path, - ) - ) - return None - - outcome.findings.append( - _harbor( - "schema", - "pass", - "Harbor accepts the job config schema", - "JobConfig.model_validate", - path=candidate.source.path, - ) - ) - return config - - -async def _rung_resolution(config: JobConfig, outcome: ValidationOutcome) -> Job | None: - """Can Harbor resolve every dataset, skill and metric the config names? - - ``Job.create`` is the deepest gate available without running anything: it expands - datasets into task configs, resolves skill sources, validates resource policies - against the chosen backend, and builds metrics. Anything it raises is an error the - real run would have hit at the same point. - - It does have one side effect: it opens its output directory and starts a ``job.log`` - there. ``jobs_dir`` defaults to a relative ``jobs/``, which the ladder's chdir would put - inside the repo, so resolution runs against a copy pointed at scratch space. A copy - because the original is what gets persisted, and a real run's output belongs wherever - that run decides, not in a temp dir that no longer exists. - """ +async def _resolve(config: JobConfig, outcome: ValidationOutcome) -> Job | None: try: with tempfile.TemporaryDirectory(prefix="eval-author-jobs-") as scratch: job = await Job.create(config.model_copy(update={"jobs_dir": Path(scratch)})) + job._close_logger_handlers() except Exception as exc: - outcome.findings.append( - _harbor( + outcome.checks.append( + _check( "resolution", "fail", f"Harbor could not resolve the job: {type(exc).__name__}: {exc}", - "Job.create", - hint="This is the error a real run would raise before starting any container.", + hint="This error occurs before Harbor starts a container.", ) ) return None - - outcome.findings.append( - _harbor( - "resolution", - "pass", - "Harbor resolved datasets, skills, metrics and resource policies", - "Job.create", - ) - ) + outcome.checks.append(_check("resolution", "pass", "Harbor resolved the job.")) return job -def _resolved_local_paths(job: Job) -> list[Path] | None: - """The on-disk task directories Harbor expanded this job into, or ``None`` if it cannot say. - - Harbor's own CLI reaches for this attribute at harbor/cli/jobs.py:93 for the same - reason; there is no public accessor for the resolved list. Tasks that live only in a - remote registry are skipped, since the resolution rung already spoke for whether they - could be fetched. - - A missing attribute is ``None`` rather than an empty list, because the two mean opposite - things. Empty is a repo Harbor found no tasks in; absent is a Harbor that no longer - answers the question, and collapsing them would report "the config resolves to zero - tasks" about a repo whose tasks are fine. - - Absolute on the way out. Harbor hands back whatever the config said, and a relative path - means the repo root only while the ladder's chdir is in effect, so the coverage rung - would compare it against the wrong directory. - """ +def _resolved_task_paths(job: Job) -> list[Path] | None: task_configs = getattr(job, "_task_configs", None) if task_configs is None: return None - paths: list[Path] = [] for task_config in task_configs: try: @@ -277,526 +129,181 @@ def _resolved_local_paths(job: Job) -> list[Path] | None: return paths -def _rung_tasks(resolved: list[Path], outcome: ValidationOutcome) -> list[Path]: - """Is each resolved task a valid Harbor task directory? - - Deferring to ``Task.is_valid_dir`` rather than checking for ``tests/`` and - ``environment/`` by hand is what keeps this from crying wolf on the four shapes a - naive check gets wrong: a multi-step task whose instruction lives under ``steps/``, a - Windows task carrying ``test.bat``, a task whose verifier bakes its tests into a - separate image, and a task with ``[environment].docker_image`` and no Dockerfile. - """ - valid: list[Path] = [] - invalid: list[tuple[Path, str]] = [] - for local_path in resolved: - if Task.is_valid_dir(local_path): - valid.append(local_path) - else: - invalid.append((local_path, _task_failure_reason(local_path))) - +def _check_tasks(resolved: list[Path], outcome: ValidationOutcome) -> list[Path]: + valid = [path for path in resolved if Task.is_valid_dir(path)] if not resolved: - outcome.findings.append( - _harbor( - "tasks", - "fail", - "The config resolves to zero tasks", - "Job.create", - hint="Harbor raises 'Either datasets or tasks must be provided' for an empty task set.", - ) - ) + outcome.checks.append(_check("tasks", "fail", "The config resolves to zero tasks.")) return [] - - status = "fail" if invalid else "pass" - outcome.findings.append( - _harbor( + outcome.checks.append( + _check( "tasks", - status, - f"{len(valid)} of {len(valid) + len(invalid)} task dirs are valid Harbor tasks", - "Task.is_valid_dir", + "fail" if len(valid) != len(resolved) else "pass", + f"{len(valid)} of {len(resolved)} task dirs are valid Harbor tasks.", ) ) - for path, reason in invalid: - outcome.findings.append(_harbor("tasks", "fail", f"{path.name}: {reason}", "Task.is_valid_dir", path=path)) return valid -def _rung_coverage(config: JobConfig, resolved: list[Path], outcome: ValidationOutcome) -> None: - """Did Harbor pick up every task the repo appears to contain? - - Harbor drops a directory it cannot parse as a task without saying so: given ten task - dirs where three are half-written, ``Job.create`` resolves seven and raises nothing. - The tasks rung then reports seven of seven valid, the run scores seven, and nothing - about the output looks incomplete. Without this rung the whole ladder returns a clean - verdict on a suite that is quietly missing a third of itself. - - A dataset that narrows itself with ``task_names``, ``exclude_task_names`` or ``n_tasks`` - is deliberately running a subset, so its unresolved directories are reported as - information rather than as a problem. - """ +def _check_coverage(config: JobConfig, resolved: list[Path], outcome: ValidationOutcome) -> None: resolved_set = {path.resolve() for path in resolved} + dropped_any = False for dataset in config.datasets: if dataset.path is None or not dataset.path.is_dir(): continue on_disk = [ child for child in sorted(dataset.path.iterdir()) - if child.is_dir() and (child / _TASK_CONFIG_FILENAME).is_file() and child.name != _TEMPLATE_DIR_NAME + if child.is_dir() and child.name != "task_template" and (child / "task.toml").is_file() ] dropped = [child for child in on_disk if child.resolve() not in resolved_set] if not dropped: continue - - selective = dataset.task_names or dataset.exclude_task_names or dataset.n_tasks - listed = ", ".join(f"{child.name} ({_task_failure_reason(child)})" for child in dropped[:_MAX_LISTED_DROPPED]) - remainder = len(dropped) - _MAX_LISTED_DROPPED - message = f"{len(dropped)} of {len(on_disk)} task dir(s) under {dataset.path.name} were not picked up: {listed}" - outcome.findings.append( - _harbor( + dropped_any = True + selected_dropped = [ + path + for path in dropped + if (not dataset.task_names or any(fnmatchcase(path.name, pattern) for pattern in dataset.task_names)) + and not any(fnmatchcase(path.name, pattern) for pattern in dataset.exclude_task_names or []) + ] + required = bool(selected_dropped) and dataset.n_tasks is None + filtered = bool(dataset.task_names or dataset.exclude_task_names) + reported = selected_dropped if required else dropped + names = ", ".join(path.name for path in reported) + outcome.checks.append( + _check( "coverage", - "warn" if selective else "fail", - message + (f", and {remainder} more" if remainder > 0 else ""), - "Job.create", - path=dataset.path, - hint=( - "The dataset selects a subset, so this is expected." - if selective - else "Harbor skips these silently, so a run would score fewer tasks than the repo contains." - ), - ) - ) - - -def _task_failure_reason(task_dir: Path) -> str: - """Ask Harbor why a task is invalid, since ``is_valid_dir`` only says that it is.""" - try: - Task(task_dir) - except FileNotFoundError as exc: - return str(exc) - except (OSError, tomllib.TOMLDecodeError, ValidationError) as exc: - return f"task.toml could not be read: {exc}" - except Exception as exc: - return f"{type(exc).__name__}: {exc}" - return "rejected by Task.is_valid_dir" - - -def _rung_reward(task_dirs: list[Path], outcome: ValidationOutcome) -> None: - """Advisory: does each task's test script look like it writes a reward file? - - A task can be structurally valid and still score nothing, and Harbor only says so by - raising ``RewardFileNotFoundError`` after a full trial. There is no Harbor API that - answers earlier, so this reads the scripts and searches for a reward filename. - - That makes it a heuristic and it is reported as one: no ``harbor_call``, and never - worse than a warning. A script that builds the path in a variable writes a reward this - search cannot see, and failing the run over that would block a repo whose evals are - fine. - """ - silent: list[Path] = [] - reward_forms: set[str] = set() - - for task_dir in task_dirs: - for script in _test_scripts(task_dir): - text = _executable_lines(_read_text(script)) - found = [name for name in _REWARD_FILENAMES if name in text] - if found: - reward_forms.update(found) - elif task_dir not in silent: - silent.append(task_dir) - - if silent: - outcome.findings.append( - Finding( - name="reward", - group=_GROUP, - status="warn", - message=f"{len(silent)} task(s) have a test script that never names a reward file", - path=silent[0], + "fail" if required else "warn", + f"Harbor did not resolve {len(reported)} task dirs: {names}.", + severity="required" if required else "advisory", hint=( - "Harbor reads /logs/verifier/reward.json then reward.txt, and raises " - "RewardFileNotFoundError when neither exists. Read as text, so a script that " - "builds the path dynamically looks the same as one that writes nothing." + "Harbor skipped a task selected by the dataset filters." + if required and filtered + else "Harbor skips these task dirs silently." + if required + else "The dataset filters or n_tasks select a task subset." ), ) ) - return - - detail = ", ".join(sorted(reward_forms)) if reward_forms else "none read" - outcome.findings.append( - Finding( - name="reward", - group=_GROUP, - status="pass", - message=f"Every test script names a reward file ({detail})", - ) - ) - - -def _test_scripts(task_dir: Path) -> list[Path]: - """Every host test script that has to produce a reward. - - Mirrors ``Task._validate_tests``: one script for a single-step task, and for a - multi-step task the effective script per step, which is the step's own or the shared - one it falls back to. Checking only the first would pass a task whose later step never - scores, and that failure surfaces only after a full run. - - A step that grades from its own verifier image contributes no host script, which - ``resolve_effective_verifier_env_config`` is what decides. Asking Harbor beats - inferring it from a missing file, which cannot tell a task that grades from an image - apart from one whose author forgot to write a test. - """ - paths = TaskPaths(task_dir) - config = _task_config(task_dir) - if config is None: - return [] + if not dropped_any: + outcome.checks.append(_check("coverage", "pass", "Harbor dropped no local task dirs.")) - task_os = config.environment.os - shared = paths.discovered_test_path_for(task_os) - if not config.steps: - if resolve_effective_verifier_env_config(config, step_cfg=None) is not None: - return [] - return [shared] if shared is not None else [] - - scripts: list[Path] = [] - for step in config.steps: - if resolve_effective_verifier_env_config(config, step_cfg=step) is not None: - continue - effective = paths.discovered_step_test_path_for(step.name, task_os) or shared - if effective is not None and effective not in scripts: - scripts.append(effective) - return scripts - - -def _rung_credentials(config: JobConfig, task_dirs: list[Path], outcome: ValidationOutcome) -> None: - """Which host variables must be set for this config to run? - - Harbor resolves ``${VAR}`` and ``${VAR:-default}`` templates from the host - environment at run time and raises on a missing one, and ``harbor run`` stops to ask - the user before handing any of them to a container. Discover records the names so the - persisted artifact is honest about what a run needs. Whether this machine has values - for them is ``doctor``'s question. - """ +def _check_required_env_vars(config: JobConfig, task_dirs: list[Path], outcome: ValidationOutcome) -> None: required: dict[str, RequiredEnvVar] = {} def collect(env: dict[str, str], declared_in: Path) -> None: for name, default in get_required_host_vars(env): - required.setdefault(name, RequiredEnvVar(name=name, default=default, declared_in=declared_in)) + required.setdefault(name, RequiredEnvVar(name, default, declared_in)) for task_dir in task_dirs: task_config = _task_config(task_dir) if task_config is None: continue - config_path = TaskPaths(task_dir).config_path - collect(task_config.environment.env, config_path) - collect(task_config.verifier.env, config_path) - collect(task_config.solution.env, config_path) - - job_level = Path("") - collect(config.environment.env, job_level) - collect(config.verifier.env, job_level) + path = TaskPaths(task_dir).config_path + collect(task_config.environment.env, path) + collect(task_config.verifier.env, path) + collect(task_config.solution.env, path) + collect(config.environment.env, Path("")) + collect(config.verifier.env, Path("")) for agent in config.agents: - collect(agent.env, job_level) - + collect(agent.env, Path("")) outcome.required_env_vars = sorted(required.values(), key=lambda item: item.name) names = ", ".join(item.name for item in outcome.required_env_vars) - outcome.findings.append( - _harbor( - "credentials", - "pass", - f"{len(outcome.required_env_vars)} host variable(s) required" + (f": {names}" if names else ""), - "get_required_host_vars", - hint="Set these before running; Harbor raises on a missing template at trial start." if names else None, - ) + outcome.checks.append( + _check("credentials", "pass", f"{len(required)} host variables required" + (f": {names}." if names else ".")) ) -def _rung_agent(config: JobConfig, repo_root: Path, search_path: str | None, outcome: ValidationOutcome) -> None: - """Does the agent this config names actually exist? +def _task_config(task_dir: Path) -> TaskConfig | None: + try: + return TaskConfig.model_validate_toml(TaskPaths(task_dir).config_path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, tomllib.TOMLDecodeError, ValidationError): + return None + - Importing the class proves what matters without constructing it. Harbor instantiates - agents at trial time, but a discovery command has no business running a user's - ``__init__``. - """ +def _check_agent(config: JobConfig, outcome: ValidationOutcome) -> None: for agent in config.agents: if agent.import_path is not None: - _check_agent_import(agent.import_path, repo_root, search_path, outcome) + with _evict_module_tree(agent.import_path): + try: + imported = import_class(agent.import_path, label="agent") + except (Exception, SystemExit) as exc: + outcome.checks.append( + _check("agent", "fail", f"Cannot import agent {agent.import_path}: {type(exc).__name__}: {exc}") + ) + else: + outcome.checks.append(_check("agent", "pass", f"Agent {imported.__name__} imports as a class.")) elif agent.name is not None: - _check_agent_name(agent.name, outcome) - - -def _check_agent_import(import_path: str, repo_root: Path, search_path: str | None, outcome: ValidationOutcome) -> None: - """Import the agent with the search path the persisted config will actually get. - - *search_path* is the single directory the artifact tells a run to put on ``PYTHONPATH``, - or ``None`` when the config came with an import path we did not author. Arranging the - import any other way — searching the repo for a file named after the module, say — passes - this rung for a reason ``harbor job start -c`` will not have, which is how a config that - cannot import its own agent came to be recorded as runnable. - - ``base`` is deliberately not passed. Harbor's ``AgentFactory`` calls - ``import_class(import_path, label="agent")``, strict for verifiers and not for agents, and - a rung stricter than the gate it stands for fails repos Harbor would run. - """ - module_name = import_path.split(":", 1)[0] - search_dir = None if search_path is None else (repo_root / search_path).resolve() - with _module_search_path(search_dir, module_name): - try: - agent_class = import_class(import_path, label="agent") - except Exception as exc: - outcome.findings.append( - _harbor( - "agent", - "fail", - f"Could not load agent {import_path}: {type(exc).__name__}: {exc}", - "import_class", - hint=_import_hint(repo_root, module_name, search_path), + try: + AgentFactory.get_agent_class(AgentName(agent.name)) + except Exception as exc: + outcome.checks.append( + _check("agent", "fail", f"Cannot load Harbor agent {agent.name}: {type(exc).__name__}: {exc}") ) - ) - return - outcome.findings.append( - _harbor( - "agent", - "pass", - f"Agent {import_path} imports as a class ({agent_class.__name__})" - + (f", searching {search_path}" if search_path is not None else ""), - "import_class", - ) - ) - if not issubclass(agent_class, BaseAgent): - outcome.findings.append( - Finding( - name="agent-base", - group=_GROUP, - status="warn", - message=f"{import_path} does not subclass harbor.agents.base.BaseAgent", - hint=( - "Harbor imports agents without checking a base class, so a run starts and " - "then fails at trial time on whichever method it expected." - ), - ) - ) - - -def _import_hint(repo_root: Path, module_name: str, search_path: str | None) -> str: - """Say what would make the import work, naming a directory holding the module if one does. - - The search is for the hint only. Letting it widen the path the rung imports from is the - bug this whole function exists to explain. - """ - top = module_name.split(".", 1)[0] - found = [ - display_path(path.parent, repo_root) - for path in sorted(repo_root.rglob(f"{top}.py")) - if ".venv" not in path.parts and "site-packages" not in path.parts - ] - reason = ( - "Harbor imports the agent with plain importlib and never adds the working directory to sys.path." - if search_path is None - else f"PYTHONPATH={search_path} is what this config is recorded with, and {top} does not import from there." - ) - remainder = [directory for directory in found if directory != search_path] - if remainder: - return f"{reason} {top}.py is at {remainder[0]}, so a run needs PYTHONPATH={remainder[0]} from the repo root." - return reason + else: + outcome.checks.append(_check("agent", "pass", f"Built-in agent {agent.name} is available.")) -def _check_agent_name(name: str, outcome: ValidationOutcome) -> None: - if name not in AgentName.values(): - outcome.findings.append( - _harbor( - "agent", - "fail", - f"'{name}' is not a Harbor agent name", - "AgentName.values", - hint=f"Valid names: {', '.join(sorted(AgentName.values()))}", - ) - ) - return - try: - AgentFactory.get_agent_class(AgentName(name)) - except Exception as exc: - outcome.findings.append( - _harbor( - "agent", - "fail", - f"Harbor knows agent '{name}' but cannot import it: {type(exc).__name__}: {exc}", - "AgentFactory.get_agent_class", - hint="Built-in agents can need an optional extra, as in `pip install 'harbor[...]'`.", - ) - ) - return - outcome.findings.append( - _harbor("agent", "pass", f"Built-in agent '{name}' is available", "AgentFactory.get_agent_class") - ) - - -def _rung_backend(config: JobConfig, outcome: ValidationOutcome) -> None: - """Is the environment backend usable here? - - Harbor's own preflight is the check. For docker that means the binary is on PATH and - the daemon answers, and it reports the problem by raising ``SystemExit``, which is - fine for a CLI and has to be caught here. - """ - label = config.environment.import_path or ( - config.environment.type.value if config.environment.type is not None else "docker" - ) +def _check_backend(config: JobConfig, outcome: ValidationOutcome) -> None: + label = config.environment.import_path or (config.environment.type.value if config.environment.type else "docker") try: EnvironmentFactory.run_preflight(config.environment.type, config.environment.import_path) - except SystemExit as exc: - outcome.findings.append( - _harbor( - "backend", - "fail", - f"Environment backend '{label}' is not ready: {exc}", - "EnvironmentFactory.run_preflight", - ) - ) - return - except Exception as exc: - outcome.findings.append( - _harbor( - "backend", - "fail", - f"Environment backend '{label}' preflight failed: {type(exc).__name__}: {exc}", - "EnvironmentFactory.run_preflight", - hint="Cloud backends need their optional extra installed and vendor credentials set.", - ) - ) - return - outcome.findings.append( - _harbor( - "backend", "pass", f"Environment backend '{label}' passed preflight", "EnvironmentFactory.run_preflight" + except (Exception, SystemExit) as exc: + outcome.checks.append( + _check("backend", "fail", f"Environment backend {label} is not ready: {type(exc).__name__}: {exc}") ) - ) + else: + outcome.checks.append(_check("backend", "pass", f"Environment backend {label} passed preflight.")) -def check_config_file(config_path: Path, repo_root: Path) -> Finding: - """Load the file a later run will pass to ``-c`` through the Harbor CLI itself. - - The only rung that judges bytes rather than an in-memory object, which matters - because bytes are what a later agent will hand to Harbor. ``--print-config`` returns - before ``Job.create``, so this re-validates the schema and resolves nothing. It runs - with ``cwd`` at the repo root because these configs use repo-relative paths. - - The file is either one discovery wrote or the repo's own, whichever the artifact ends - up pointing at; the check is the same either way. - """ - harbor_bin = _harbor_executable() - if harbor_bin is None: - return Finding( - name="round-trip", - group=_GROUP, - status="warn", - message="Skipped the CLI round trip: no `harbor` executable on PATH", - hint="The in-process schema rung already accepted this config.", +def check_config_file(config_path: Path, repo_root: Path) -> CheckResult: + """Check the bytes that Harbor receives from its CLI.""" + harbor = _harbor_executable() + if harbor is None: + return _check( + "round-trip", + "warn", + "The Harbor CLI round trip did not run.", + severity="advisory", + hint="No harbor executable exists on PATH.", ) - try: completed = subprocess.run( - [harbor_bin, "job", "start", "--print-config", "-c", str(config_path)], + [harbor, "job", "start", "--print-config", "-c", str(config_path)], cwd=repo_root, capture_output=True, text=True, - timeout=_PRINT_CONFIG_TIMEOUT_SEC, + timeout=120, check=False, ) except (OSError, subprocess.SubprocessError) as exc: - return Finding( - name="round-trip", - group=_GROUP, - status="warn", - message=f"Could not run the CLI round trip: {type(exc).__name__}: {exc}", - path=config_path, - ) - - if completed.returncode != 0: + return _check("round-trip", "warn", f"The Harbor CLI round trip failed: {exc}", severity="advisory") + if completed.returncode: detail = (completed.stderr or completed.stdout).strip().splitlines() - return _harbor( - "round-trip", - "fail", - f"`harbor job start --print-config` rejected the config file: {detail[-1] if detail else 'no output'}", - "harbor job start --print-config", - path=config_path, + return _check( + "round-trip", "fail", f"The Harbor CLI rejected the config: {detail[-1] if detail else 'no output'}." ) - return _harbor( - "round-trip", - "pass", - "The config file loads through the Harbor CLI", - "harbor job start --print-config", - path=config_path, - ) + return _check("round-trip", "pass", "The config file loads through the Harbor CLI.") + + +def _harbor_executable() -> str | None: + local = Path(sys.executable).parent / "harbor" + return str(local) if local.is_file() else shutil.which("harbor") @contextlib.contextmanager -def _module_search_path(directory: Path | None, module_name: str) -> Iterator[None]: - """Put exactly *directory* on ``sys.path`` for the duration, then undo it. - - One directory, because that is what the artifact tells a run to export as ``PYTHONPATH`` - and the rung is only worth anything if it imports from the same place. ``None`` adds - nothing, which is what a separate ``harbor`` process gets. - - The eviction is unconditional and matters more than the insertion. ``harbor_wrapper`` is a - convention, so two different repos, or the same repo before and after an edit, claim the - same module name. Without it the second import silently returns the first repo's module and - the rung would validate a file that is not the one under inspection — and with nothing - added to the path, a stale entry is the only way the import could succeed at all. Both - changes are reversed on the way out, since this process did not ask to be reshaped. - """ - top = module_name.split(".", 1)[0] - entry = str(directory) if directory is not None and str(directory) not in sys.path else None - if entry is not None: - sys.path.insert(0, entry) - displaced = sys.modules.pop(top, None) +def _evict_module_tree(import_path: str) -> Iterator[None]: + """Import without cached modules from another repository.""" + module = import_path.split(":", 1)[0].split(".", 1)[0] + previous = { + name: cached for name, cached in list(sys.modules.items()) if name == module or name.startswith(f"{module}.") + } + for name in previous: + sys.modules.pop(name) try: yield finally: - if entry is not None: - with contextlib.suppress(ValueError): - sys.path.remove(entry) - sys.modules.pop(top, None) - if displaced is not None: - sys.modules[top] = displaced - - -def _task_config(task_dir: Path) -> TaskDefinitionConfig | None: - try: - return TaskDefinitionConfig.model_validate_toml(TaskPaths(task_dir).config_path.read_text(encoding="utf-8")) - except (OSError, UnicodeError, tomllib.TOMLDecodeError, ValidationError): - return None - - -def _read_text(path: Path) -> str: - try: - return path.read_text(encoding="utf-8") - except (OSError, UnicodeError): - return "" - - -def _executable_lines(text: str) -> str: - """Drop comment lines before looking for a reward file. - - Harbor's own task template ships a ``test.sh`` that writes nothing and only mentions - ``reward.txt`` in a comment telling the author to write one. Grepping raw text would - pass exactly the task most likely to be broken: a scaffold nobody finished. - """ - kept = [ - line - for line in text.splitlines() - if not line.lstrip().startswith(("#", "::")) and not line.lstrip().upper().startswith("REM ") - ] - return "\n".join(kept) - - -def _harbor_executable() -> str | None: - """The ``harbor`` console script from the same environment as the in-process Harbor. - - ``PATH`` is not good enough here. A ``uv tool`` or ``pipx`` install shadows the - environment's own script, so a plain lookup can hand the round trip a different Harbor than - every other rung used, while the report stamps only the in-process version. The script - beside ``sys.executable`` is the one that imports the Harbor these verdicts came from. - ``PATH`` remains the fallback, for an interpreter whose scripts live elsewhere. - """ - beside = Path(sys.executable).parent / "harbor" - if beside.is_file(): - return str(beside) - return shutil.which("harbor") + for name in list(sys.modules): + if name == module or name.startswith(f"{module}."): + sys.modules.pop(name) + sys.modules.update(previous) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md index b352c6d8391..56acfce8233 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/eval_author/README.md @@ -5,14 +5,10 @@ SPDX-License-Identifier: Apache-2.0 # Eval Author -> **Active development. Not intended for external use.** +> **Eval Author is in active development and is not intended for external use.** > -> This plugin is incomplete and its interfaces will change without notice. It also -> runs code from the repository you point it at: validating a config imports that -> repository's agent module into the running process, which executes that module's -> top level. Treat pointing Eval Author at a repository as equivalent to running that -> repository's code yourself, and only do it for code you already trust. Sandboxing is -> not implemented yet. +> **WARNING:** Use Eval Author only with a trusted repository. +> An agent import executes module top-level code. The top-level `nemo_eval_author_plugin.eval_author` package is the canonical Eval Author implementation. It turns an Experimentalist Insight and its production trace refs into @@ -115,83 +111,33 @@ asyncio.run(main()) ## Discovery CLI -`nemo agents eval-author discover` is the only implemented CLI command. It -answers whether Harbor can run a repository's evals and records the answer. - -The command assembles a candidate Harbor `JobConfig` from the strongest source -the repository offers: a Harbor config file it already maintains, a `config.json` -from a prior job Harbor resolved and ran, an Experimentalist `optimizer.yaml` -profile plus the agent wrapper, or the Harbor task directory layout alone. - -It validates that candidate through a ladder of Harbor's own calls rather than -reimplemented rules: schema, job resolution, task validity and coverage, -required host variables, the agent class, the environment backend, and a round -trip of the persisted bytes through `harbor job start --print-config`. -[`discovery/validate.py`](../discovery/validate.py) names the Harbor API behind -each rung. Findings that Harbor returned carry a `harbor_call`; the two checks -that are discovery's own carry none and can only warn. Whether each test script -names a reward file is read from the repository, because a script that builds -the path in a variable is indistinguishable from one that writes nothing. -Whether the agent subclasses `BaseAgent` is a judgement Harbor deliberately -does not make — it is strict for verifiers and not for agents — so failing it -would block a repository Harbor's own gate accepts. - -The result is recorded to the `nemo-eval-author` fileset as -`/discovery.md`. A `/harbor-job.yaml` is published alongside the -report only when discovery authored the config; when the repository maintains -its own valid config file, the report points at that file instead. Nothing is -written into the repository under inspection. - -When the config's agent is a `harbor_wrapper.py` in the repository, the run -command carries the wrapper's directory as `PYTHONPATH`: - -```bash -PYTHONPATH=src/myagent harbor job start -c harbor-job.yaml -``` - -This is not a convenience. Harbor imports an agent with plain -`importlib.import_module` and never adds the working directory to `sys.path`, so -a config naming `harbor_wrapper:WrappedAgent` fails at the first trial with -`No module named 'harbor_wrapper'` without it. A Harbor `JobConfig` has no field -for a module search path, so it is recorded beside the config as -`run_config.pythonpath` in the report's front matter, repo-relative like every -other path in the artifact — `.` for a wrapper at the repository root. The agent -rung imports with exactly that search path and nothing else, so a rung that -passes is a rung the recorded command will pass too. +`nemo agents eval-author discover` validates one repository-owned Harbor config and writes no repository files. -A dataset the profile declares as a registry ref alongside a `registry_url` is -recorded as a ref Harbor downloads rather than as a local directory, and -reported as a warning because resolving it needs the registry to be reachable. +The command accepts these flags: -Every run revalidates from scratch. The report is a record of what was true when -it was written, not a cache that a later run consults. +- `--repo` selects the repository. The current directory is the default. +- `--agent` sets the name. Without it, a string `agent` in root `optimizer.yaml` takes precedence over the repository directory slug. +- `--dry-run` prints the report and uploads no files. -Exit code 0 means a config was validated and recorded. Every other outcome exits -non-zero, including a config Harbor accepted but that could not be uploaded, -which is what makes the command usable as a gate. +Discovery does not infer or generate a config. The preflight includes: -`discover` takes these flags: +- Harbor validates the schema, agent concurrency limits, task directories, and dataset coverage. Harbor also resolves the job. +- Discovery identifies required environment variables. Harbor imports the agent and validates the environment backend. +- `harbor job start --print-config` loads the config file. -- `--repo`: agent repository to inspect. Defaults to the current directory. -- `--agent`: name the artifacts are stored under. Defaults to the agent named in - `optimizer.yaml`, else a slug of the directory name. -- `--dry-run`: print the findings and the config without uploading anything. +The `ETHOS.md` and trace checks are advisory. +Each invocation repeats the preflight and records one `sha256:` fingerprint plus the input file count. The fingerprint never skips validation. -There are no flags for platform state. The workspace and cluster come from the -active `nemo` context, `NMP_WORKSPACE` still overrides the workspace, and the -Harbor environment backend comes from the repository's own config or Harbor's -default. +Without `--dry-run`, the command uploads only `/discovery.md` to the `nemo-eval-author` fileset. +Only a runnable report includes `cd && harbor job start -c `. -The other verbs are registered in [`cli.py`](../cli.py) so the command tree is -discoverable. Each one exits non-zero with a not-implemented message. +A standard run returns exit code 0 only for a runnable report and a successful upload. +A dry run returns exit code 0 only if the report is runnable. +All other outcomes return exit code 1. The command still uploads a report for an absent or rejected config. ## Planned Commands -- `nemo agents eval-author audit`: report coverage gaps in an existing Harbor suite - against `ETHOS.md`, without changing the suite. -- `nemo agents eval-author propose`: draft reviewable Harbor tasks and verifier - patches for the gaps the audit found. -- `nemo agents eval-author run`: run `discover`, `audit`, and `propose` as one - pipeline. -- `nemo agents eval-author doctor`: check the credentials, platform access, and - runtime the other commands need. +- `nemo agents eval-author audit` will report coverage gaps against `ETHOS.md` and will not change the current Harbor suite. +- `nemo agents eval-author propose` will draft Harbor tasks and verifier patches for review. +- `nemo agents eval-author run` will run `discover`, `audit`, and `propose` as one pipeline. +- `nemo agents eval-author doctor` will check credentials, platform access, and the runtime for the other commands. diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index 82cf751cf9a..8ee47f12618 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -1,39 +1,21 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""End to end through the CLI, with the platform stubbed out. +"""End-to-end tests for the discovery command.""" -Every test passes ``--repo`` explicitly and replaces ``make_client``. Without both, the -command defaults to the current directory and uploads to whatever platform the developer -happens to have running, which is how a unit test quietly becomes a network call. - -The exit code is the contract these pin down: this command is meant to be usable as a gate, -so exit 0 has to mean a config was validated *and* recorded, and nothing else. - -Named for the command rather than ``test_cli.py`` because ``tests/test_cli.py`` already -covers the plugin's command surface. Running the plugin's suite on its own picks up the -plugin's pytest config, which leaves the default prepend import mode in place, and two test -files sharing a basename abort collection there. -""" +from pathlib import Path +from unittest.mock import AsyncMock import pytest import typer -from harbor_fixtures import ( - StubClient, - StubFiles, - read_front_matter, - write_dataset, - write_job_config, - write_task, - write_wrapper, -) +from harbor_fixtures import StubClient, StubFiles, read_front_matter, write_dataset, write_job_config from nemo_eval_author_plugin import cli -from nemo_eval_author_plugin.discovery import memory from nemo_eval_author_plugin.discovery import run as discovery -from nemo_eval_author_plugin.discovery.models import JOB_CONFIG_FILENAME +from nemo_eval_author_plugin.discovery import validate from typer.testing import CliRunner runner = CliRunner() +AGENT = "ticket-triage" @pytest.fixture @@ -43,7 +25,6 @@ def app() -> typer.Typer: @pytest.fixture def client(monkeypatch) -> StubClient: - """A stub platform, installed where ``run`` looks it up.""" stub = StubClient() monkeypatch.setattr(discovery, "make_client", lambda base_url: stub) return stub @@ -51,254 +32,191 @@ def client(monkeypatch) -> StubClient: @pytest.fixture(autouse=True) def workspace(monkeypatch, tmp_path): - """Pin the workspace, which the command reads from the platform context rather than a flag. - - Both variables are needed. ``NMP_WORKSPACE`` fixes the value, but resolving a context still - reads the config file and raises on a dangling cluster or user reference, so this points the - platform at an empty one. Empty rather than absent, because an explicit ``NMP_CONFIG_FILE`` - that does not exist is an error rather than a fallback. - """ config = tmp_path / "nmp-config.yaml" config.touch() monkeypatch.setenv("NMP_WORKSPACE", "default") monkeypatch.setenv("NMP_CONFIG_FILE", str(config)) -# Pytest's tmp_path names would be slugged, so tests that assert on a remote path name the -# agent outright. Defaulting is covered on its own below. -AGENT = "ticket-triage" +@pytest.fixture(autouse=True) +def successful_external_preflight(monkeypatch): + monkeypatch.setattr(validate.EnvironmentFactory, "run_preflight", lambda *args: None) + monkeypatch.setattr( + validate, + "check_config_file", + lambda path, root: validate._check("round-trip", "pass", "The config file loads through the Harbor CLI."), + ) -def _invoke(app, repo, *extra): +def _invoke(app: typer.Typer, repo: Path, *extra: str): return runner.invoke(app, ["discover", "--repo", str(repo), *extra]) -def _invoke_named(app, repo, *extra): - return _invoke(app, repo, "--agent", AGENT, *extra) +def _healthy_repo(root: Path) -> Path: + write_dataset(root / "evals" / "validation") + write_job_config(root / "configs" / "eval.yaml", dataset="evals/validation") + return root -def test_a_healthy_repo_exits_zero_and_records_both_artifacts(app, client, tmp_path): - write_dataset(tmp_path / "evals" / "validation") - write_wrapper(tmp_path) +def _snapshot(root: Path) -> list[tuple[str, bytes | None]]: + return [ + (path.relative_to(root).as_posix(), path.read_bytes() if path.is_file() else None) + for path in sorted(root.rglob("*")) + ] - result = _invoke_named(app, tmp_path) - - assert result.exit_code == 0, result.output - assert "Harbor can run this repo's evals" in result.output - assert "PYTHONPATH=. harbor job start -c harbor-job.yaml" in result.output - assert sorted(client.files.stored) == [f"{AGENT}/discovery.md", f"{AGENT}/harbor-job.yaml"] +def test_healthy_config_uploads_only_discovery_report_and_does_not_write_to_repo(app, client, tmp_path): + repo = _healthy_repo(tmp_path / "agent-repo") + before = _snapshot(repo) -def test_the_command_printed_for_a_nested_wrapper_can_actually_import_it(app, client, tmp_path): - """The command is the deliverable, so it has to name the directory the module is in. - - ``harbor job start -c harbor-job.yaml`` against a config naming ``harbor_wrapper`` fails - with ``No module named 'harbor_wrapper'``; Harbor's importer never looks in the working - directory. The printed command and the recorded one both have to carry the fix, and - they have to agree. - """ - write_dataset(tmp_path / "evals" / "validation") - write_wrapper(tmp_path / "src" / "myagent") - - result = _invoke_named(app, tmp_path) - - assert result.exit_code == 0, result.output - assert "PYTHONPATH=src/myagent harbor job start -c harbor-job.yaml" in result.output - front = read_front_matter(client.files.stored[memory.remote_report_path(AGENT)]) - assert front["run_config"]["pythonpath"] == "src/myagent" - # The config itself is a Harbor JobConfig and has nowhere to say this. - assert "PYTHONPATH" not in client.files.stored[f"{AGENT}/{JOB_CONFIG_FILENAME}"].decode() - - -def test_a_repo_that_maintains_its_own_config_keeps_it_and_records_only_the_report(app, client, tmp_path): - """The repo's file is what Harbor validated, so a copy in the fileset could only drift from it.""" - write_dataset(tmp_path / "evals" / "validation") - write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/validation") - - result = _invoke_named(app, tmp_path) + result = _invoke(app, repo, "--agent", AGENT) assert result.exit_code == 0, result.output + assert "Repository\n ✓ Using Harbor config configs/eval.yaml." in result.output assert "harbor job start -c configs/eval.yaml" in result.output + assert "Uploaded ticket-triage/discovery.md to fileset 'nemo-eval-author'." in result.output assert client.files.stored.keys() == {f"{AGENT}/discovery.md"} - assert "Withheld" not in result.output, "nothing was withheld; there was nothing of ours to publish" + assert len(client.files.uploads) == 1 + assert client.files.uploads[0]["fileset"] == "nemo-eval-author" + assert client.files.uploads[0]["workspace"] == "default" + assert client.files.uploads[0]["fileset_auto_create"] is True + assert read_front_matter(client.files.stored[f"{AGENT}/discovery.md"])["runnable"] is True + assert _snapshot(repo) == before + assert client.closed is True + assert result.output.rstrip().endswith("Final overview: Discovery passed with 0 failures and 2 warnings.") -def test_a_repo_harbor_rejects_exits_one_and_withholds_the_config(app, client, tmp_path): - """The config names a dataset that is not there, so Harbor cannot resolve the job.""" - write_dataset(tmp_path / "evals" / "validation") - write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/missing") +def test_missing_config_exits_one_but_uploads_the_report(app, client, tmp_path): + repo = tmp_path / "empty-repo" + repo.mkdir() + (repo / "README.md").write_text("# Empty\n", encoding="utf-8") - result = _invoke_named(app, tmp_path) + result = _invoke(app, repo, "--agent", AGENT) assert result.exit_code == 1, result.output - assert "Harbor cannot run this repo's evals" in result.output - assert "resolution" in result.output - # The report still lands, so the failure is documented rather than lost. - assert sorted(client.files.stored) == [f"{AGENT}/discovery.md"] + assert client.files.stored.keys() == {f"{AGENT}/discovery.md"} + front = read_front_matter(client.files.stored[f"{AGENT}/discovery.md"]) + assert front["runnable"] is False + assert front["config_path"] is None + assert front["run_command"] is None + assert "harbor job start" not in result.output + assert result.output.rstrip().endswith("Final overview: Discovery failed with 1 failure and 2 warnings.") -def test_a_config_harbor_rejects_is_never_published(app, client, tmp_path): - """A config in this fileset is always one Harbor could run, so an absent one is explained.""" - write_task(tmp_path / "evals" / "validation" / "task-0", task_toml='\n[[steps]]\nname = "nowhere"\n') +def test_rejected_config_exits_one_and_uploads_its_report(app, client, tmp_path): + repo = tmp_path / "rejected-repo" + config = repo / "configs" / "eval.yaml" + config.parent.mkdir(parents=True) + config.write_text("datasets:\n - invalid\n", encoding="utf-8") - result = _invoke_named(app, tmp_path) + result = _invoke(app, repo, "--agent", AGENT) assert result.exit_code == 1, result.output - assert "Withheld harbor-job.yaml" in result.output, "an absent config has to be explained, not just missing" - assert sorted(client.files.stored) == [f"{AGENT}/discovery.md"] + front = read_front_matter(client.files.stored[f"{AGENT}/discovery.md"]) + assert front["runnable"] is False + assert any(check["name"] == "schema" and check["status"] == "fail" for check in front["checks"]) + assert front["run_command"] is None + assert result.output.rstrip().endswith("Final overview: Discovery failed with 1 failure and 2 warnings.") -def test_a_repo_with_no_harbor_setup_at_all_exits_one(app, client, tmp_path): - (tmp_path / "README.md").write_text("# Just a repo\n") +def test_schema_failure_does_not_upload_the_rejected_input_value(app, client, tmp_path): + secret = "nvapi-secret-value-123456789" + repo = tmp_path / "secret-rejected-repo" + config = repo / "configs" / "eval.yaml" + config.parent.mkdir(parents=True) + config.write_text(f"datasets:\n - {secret}\n", encoding="utf-8") - result = _invoke(app, tmp_path) + result = _invoke(app, repo, "--agent", AGENT) assert result.exit_code == 1, result.output - assert "No Harbor job config could be assembled" in result.output + uploaded = client.files.stored[f"{AGENT}/discovery.md"] + schema_check = next(check for check in read_front_matter(uploaded)["checks"] if check["name"] == "schema") + assert secret not in schema_check["message"] + assert secret.encode() not in uploaded + assert "errors.pydantic.dev" not in schema_check["message"] -def test_dry_run_prints_the_artifacts_and_uploads_nothing(app, client, tmp_path): - write_dataset(tmp_path / "evals" / "validation") +def test_dry_run_uploads_nothing_and_prints_the_report(app, client, tmp_path): + repo = _healthy_repo(tmp_path / "dry-repo") - result = _invoke(app, tmp_path, "--dry-run") + result = _invoke(app, repo, "--agent", AGENT, "--dry-run") assert result.exit_code == 0, result.output - assert "Dry run: nothing was uploaded." in result.output - assert "runnable: true" in result.output, "the report itself is printed" + assert "Dry run: no files were uploaded." in result.output + assert "---\nschema_version: 1" in result.output + assert "runnable: true" in result.output assert client.files.uploads == [] + assert result.output.rstrip().endswith("Final overview: Discovery passed with 0 failures and 2 warnings.") -def test_the_agent_name_defaults_to_the_repo_directory(app, client, tmp_path): - repo = tmp_path / "Ticket Triage Agent" - write_dataset(repo / "evals" / "validation") +def test_upload_error_exits_one(app, monkeypatch, tmp_path): + repo = _healthy_repo(tmp_path / "upload-error-repo") + client = StubClient(files=StubFiles(fail=True)) + monkeypatch.setattr(discovery, "make_client", lambda base_url: client) - result = _invoke(app, repo) + result = _invoke(app, repo, "--agent", AGENT) - assert result.exit_code == 0, result.output - assert "ticket-triage-agent/discovery.md" in client.files.stored + assert result.exit_code == 1, result.output + assert "Upload failed: RuntimeError: fileset unavailable" in result.output + assert "harbor job start -c configs/eval.yaml" in result.output + assert client.files.stored == {} + assert result.output.rstrip().endswith("Final overview: Discovery failed with 1 failure and 2 warnings.") + + +def test_agent_name_precedence_uses_explicit_profile_then_directory(app, client, tmp_path): + explicit = _healthy_repo(tmp_path / "explicit-checkout") + (explicit / "optimizer.yaml").write_text("agent: ignored\n", encoding="utf-8") + profiled = _healthy_repo(tmp_path / "profile-checkout") + (profiled / "optimizer.yaml").write_text("agent: Profile Agent\n", encoding="utf-8") + defaulted = _healthy_repo(tmp_path / "Directory Agent") + + results = [ + _invoke(app, explicit, "--agent", "explicit-agent"), + _invoke(app, profiled), + _invoke(app, defaulted), + ] + + assert all(result.exit_code == 0 for result in results), [result.output for result in results] + assert client.files.stored.keys() == { + "explicit-agent/discovery.md", + "profile-agent/discovery.md", + "directory-agent/discovery.md", + } -def test_the_name_declared_in_the_profile_beats_the_directory(app, client, tmp_path): - """The name is the fileset path, so guessing it wrong hides the artifacts from ASE-675.""" - repo = tmp_path / "some-checkout-dir" - write_dataset(repo / "evals" / "validation") - (repo / "optimizer.yaml").write_text( - "agent: Ticket Triage\ntask_template: evals/template\ndatasets:\n validation: evals/validation\n" +def test_explicit_agent_is_slugged_for_traces_and_remote_paths(app, client, tmp_path, monkeypatch): + repo = _healthy_repo(tmp_path / "explicit-agent-repo") + trace_probe = AsyncMock( + return_value=discovery.scan._check("traces", "warn", "No traces exist.", severity="advisory") ) + monkeypatch.setattr(discovery.scan, "probe_traces", trace_probe) - result = _invoke(app, repo) + result = _invoke(app, repo, "--agent", "../Ticket Agent#production") assert result.exit_code == 0, result.output - assert "ticket-triage/discovery.md" in client.files.stored - - -def test_a_profile_written_for_a_newer_experimentalist_still_names_the_directory(app, client, tmp_path): - """A profile we cannot parse costs the name, not the run.""" - repo = tmp_path / "invoice-parser" - write_dataset(repo / "evals" / "validation") - (repo / "optimizer.yaml").write_text("agent:\n name: Ticket Triage\n version: 2\n") - - result = _invoke(app, repo) - - assert result.exit_code == 0, result.output - assert "invoice-parser/discovery.md" in client.files.stored - - -def test_an_explicit_agent_name_wins(app, client, tmp_path): - write_dataset(tmp_path / "evals" / "validation") - (tmp_path / "optimizer.yaml").write_text("agent: ignored\ndatasets:\n validation: evals/validation\n") - - result = _invoke(app, tmp_path, "--agent", "invoice-parser") - - assert result.exit_code == 0, result.output - assert "invoice-parser/discovery.md" in client.files.stored - - -def test_a_run_that_needs_host_variables_names_them(app, client, tmp_path): - """Harbor raises on an unresolved template at trial start, so a run command that does - not name ``HF_TOKEN`` cannot work and says nothing about why.""" - write_task( - tmp_path / "evals" / "validation" / "task-0", - task_toml='\n[environment.env]\nHF_TOKEN = "${HF_TOKEN}"\n', + trace_probe.assert_awaited_once_with(client, agent="ticket-agent-production", workspace="default") + assert client.files.stored.keys() == {"ticket-agent-production/discovery.md"} + assert ( + read_front_matter(client.files.stored["ticket-agent-production/discovery.md"])["agent"] + == "ticket-agent-production" ) - result = _invoke_named(app, tmp_path) - assert result.exit_code == 0, result.output - assert "Needs: HF_TOKEN" in result.output - - -def test_every_run_revalidates_from_scratch(app, client, tmp_path): - """No verdict is taken on trust from a previous run: the repo may have moved under it.""" - dataset = write_dataset(tmp_path / "evals" / "validation") - assert _invoke(app, tmp_path).exit_code == 0 - - # A task Harbor cannot parse at all, added after the first run recorded a clean verdict. - (dataset / "task-1" / "task.toml").write_text("not = [valid\n") - result = _invoke(app, tmp_path) - - assert result.exit_code == 1, result.output - assert "validation/schema" in result.output, "the ladder ran again" - - -def test_an_unwritable_fileset_exits_one_even_though_harbor_is_happy(app, monkeypatch, tmp_path): - write_dataset(tmp_path / "evals" / "validation") - monkeypatch.setattr(discovery, "make_client", lambda base_url: StubClient(files=StubFiles(fail=True))) - - result = _invoke(app, tmp_path) - - assert result.exit_code == 1, result.output - assert "Harbor can run this repo's evals" in result.output - assert "could not be recorded" in result.output - - -def test_traces_are_reported_without_blocking_a_run(app, monkeypatch, tmp_path): - write_dataset(tmp_path / "evals" / "validation") - monkeypatch.setattr(discovery, "make_client", lambda base_url: StubClient(trace_total=None)) - - result = _invoke(app, tmp_path) - - assert result.exit_code == 0, result.output - assert "repo/traces" in result.output - - -def test_nothing_is_written_into_the_repo_being_inspected(app, client, tmp_path): - """The ladder runs with cwd inside the repo, so a Harbor side effect would land here.""" - write_dataset(tmp_path / "evals" / "validation") - write_job_config(tmp_path / "configs" / "eval.yaml", dataset="evals/validation") - before = {path.name for path in tmp_path.rglob("*")} - - assert _invoke_named(app, tmp_path).exit_code == 0 - - assert {path.name for path in tmp_path.rglob("*")} == before - - -def test_the_platform_client_is_closed(app, client, tmp_path): - write_dataset(tmp_path / "evals" / "validation") - - _invoke(app, tmp_path) - - assert client.closed is True - - -def test_a_nonexistent_repo_is_rejected_by_the_flag(app, client, tmp_path): - result = runner.invoke(app, ["discover", "--repo", str(tmp_path / "nope")]) - - assert result.exit_code != 0 - assert client.files.uploads == [] - - -def test_the_uploaded_report_carries_the_verdict_that_was_printed(app, client, tmp_path): - """A later agent reads the fileset copy, so it has to be the copy that was verified.""" - write_dataset(tmp_path / "evals" / "validation") - - assert _invoke_named(app, tmp_path).exit_code == 0 - - front = read_front_matter(client.files.stored[memory.remote_report_path(AGENT)]) - assert front["runnable"] is True - assert front["config_source"]["kind"] == "convention" - assert front["run_config"] == { - "location": "fileset", - "path": f"{AGENT}/{JOB_CONFIG_FILENAME}", - "pythonpath": None, - } +def test_every_invocation_revalidates_the_repository_config(app, client, tmp_path): + repo = _healthy_repo(tmp_path / "changing-repo") + config = repo / "configs" / "eval.yaml" + + first = _invoke(app, repo, "--agent", AGENT) + first_front = read_front_matter(client.files.stored[f"{AGENT}/discovery.md"]) + config.write_text("datasets:\n - invalid\n", encoding="utf-8") + second = _invoke(app, repo, "--agent", AGENT) + + assert first.exit_code == 0, first.output + assert second.exit_code == 1, second.output + second_front = read_front_matter(client.files.stored[f"{AGENT}/discovery.md"]) + assert second_front["runnable"] is False + assert any(check["name"] == "schema" and check["status"] == "fail" for check in second_front["checks"]) + assert { + "discovered_at": second_front["discovered_at"] != first_front["discovered_at"], + "fingerprint": second_front["fingerprint"] != first_front["fingerprint"], + } == {"discovered_at": True, "fingerprint": True} diff --git a/plugins/nemo-eval-author/tests/discover/test_report.py b/plugins/nemo-eval-author/tests/discover/test_report.py index bfb0f660013..5ed08c4aec8 100644 --- a/plugins/nemo-eval-author/tests/discover/test_report.py +++ b/plugins/nemo-eval-author/tests/discover/test_report.py @@ -1,216 +1,118 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""The persisted artifacts: portable, machine-readable, and honest about what failed. +"""Discovery report contract tests.""" -Two properties carry the weight. The front matter has to survive a round trip, because a -later agent reads it instead of redoing the work. And the config has to be free of this -machine: absolute paths, a frozen job name, or a real API key in the file would each make -the artifact wrong somewhere other than where it was produced. -""" +import shlex +from datetime import UTC, datetime -import yaml -from harbor.models.job.config import JobConfig -from harbor_fixtures import read_front_matter, write_dataset +from harbor_fixtures import read_front_matter from nemo_eval_author_plugin.discovery import report -from nemo_eval_author_plugin.discovery.models import ( - CandidateConfig, - ConfigSource, - Finding, - RequiredEnvVar, -) +from nemo_eval_author_plugin.discovery.validate import RequiredEnvVar +from nemo_insights_plugin.contracts.checks import CheckResult, CheckStatus, format_report -def _record(tmp_path, findings=(), env_vars=(), candidate=None): - return report.build_report( - agent="ticket-triage", - workspace="default", - repo_root=tmp_path, - candidate=candidate - or CandidateConfig(data={}, source=ConfigSource(kind="config_file", detail="declared at configs/eval.yaml")), - findings=list(findings), - required_env_vars=list(env_vars), - ) - - -def _authored(**kwargs): - return CandidateConfig( - data={}, - source=ConfigSource(kind="convention", detail="inferred from task dirs under evals/validation"), - **kwargs, +def _check(name: str = "config", status: CheckStatus = "pass", message: str = "Found the config.") -> CheckResult: + return CheckResult( + name=name, + group="repository" if name == "config" else "validation", + status=status, + severity="required", + message=message, ) -def test_front_matter_survives_a_round_trip(tmp_path): - record = _record( - tmp_path, - findings=[Finding(name="schema", group="validation", status="pass", message="ok", harbor_call="x")], - env_vars=[RequiredEnvVar(name="HF_TOKEN", declared_in=tmp_path / "evals/task-0/task.toml")], - ) - - front = read_front_matter(report.render_markdown(record)) - - assert front["runnable"] is True - assert front["agent"] == "ticket-triage" - assert front["validation"] == {"schema": "pass"} - assert front["harbor_version"] == report.harbor_version() - # Recorded relative, so the artifact means the same thing on another machine. - assert front["required_env_vars"][0]["declared_in"] == "evals/task-0/task.toml" - - -def _owned_config(tmp_path): - return CandidateConfig( - data={}, - source=ConfigSource( - kind="config_file", - detail="declared at configs/eval.yaml", - path=tmp_path / "configs" / "eval.yaml", - ), +def _record(tmp_path, *, config: bool = True, checks: list[CheckResult] | None = None): + root = tmp_path.resolve() + return report.DiscoveryReport( + agent="ticket-triage", + workspace="default", + repo_root=root, + config_path=root / "configs" / "eval.yaml" if config else None, + dataset_paths=[root / "evals" / "validation"], + ethos_path=root / "ETHOS.md", + harbor_version="0.18.0", + required_env_vars=[ + RequiredEnvVar(name="HF_TOKEN", default=None, declared_in=root / "evals" / "validation" / "task.toml") + ], + discovered_at=datetime(2026, 8, 10, 15, tzinfo=UTC), + fingerprint="sha256:abc123", + input_file_count=4, + checks=checks or [_check()], ) -def test_a_repo_that_maintains_its_own_config_is_told_to_run_that_file(tmp_path): - """Publishing a second copy would leave a config in the fileset that nobody edits.""" - record = _record(tmp_path, candidate=_owned_config(tmp_path)) +def test_front_matter_records_the_complete_repository_contract(tmp_path): + check = _check() + record = _record(tmp_path, checks=[check]) markdown = report.render_markdown(record) front = read_front_matter(markdown) - assert front["run_config"] == {"location": "repo", "path": "configs/eval.yaml", "pythonpath": None} - assert "harbor job start -c configs/eval.yaml" in markdown - assert "harbor-job.yaml" not in markdown - - -def test_a_config_discovery_authored_points_at_the_fileset_copy(tmp_path): - """Nothing in the repo declares a config, so the fileset is the only place it exists.""" - record = _record(tmp_path, candidate=_authored()) - - markdown = report.render_markdown(record) - front = read_front_matter(markdown) - - assert front["run_config"] == { - "location": "fileset", - "path": "ticket-triage/harbor-job.yaml", - "pythonpath": None, + assert front == { + "schema_version": 1, + "agent": "ticket-triage", + "workspace": "default", + "repo_root": str(tmp_path.resolve()), + "runnable": True, + "config_path": "configs/eval.yaml", + "dataset_paths": ["evals/validation"], + "run_command": f"cd {shlex.quote(str(tmp_path.resolve()))} && harbor job start -c configs/eval.yaml", + "ethos_path": "ETHOS.md", + "harbor_version": "0.18.0", + "required_env_vars": [ + { + "name": "HF_TOKEN", + "default": None, + "declared_in": "evals/validation/task.toml", + } + ], + "discovered_at": "2026-08-10T15:00:00+00:00", + "fingerprint": "sha256:abc123", + "input_file_count": 4, + "checks": [check.model_dump(mode="json")], } - assert "harbor job start -c harbor-job.yaml" in markdown - assert "Fetch `ticket-triage/harbor-job.yaml`" in markdown, "the config is not on disk yet" - + assert format_report([check]) in markdown -def test_a_config_whose_agent_is_a_repo_module_records_the_search_path_in_the_command(tmp_path): - """A Harbor JobConfig cannot carry this, and the run fails without it. - ``harbor job start -c harbor-job.yaml`` on a config naming ``harbor_wrapper:WrappedAgent`` - raises ``No module named 'harbor_wrapper'``: Harbor imports through ``importlib`` and the - working directory is not on ``sys.path``. So the search path is part of the contract, in - the front matter for the agent that reads it and in the command for the human who runs it. - """ - record = _record(tmp_path, candidate=_authored(agent_search_path="src/myagent")) +def test_a_rejected_config_is_blocked_and_has_no_command(tmp_path): + failure = _check("resolution", "fail", "Harbor could not resolve the job.") + record = _record(tmp_path, checks=[_check(), failure]) markdown = report.render_markdown(record) front = read_front_matter(markdown) - assert front["run_config"]["pythonpath"] == "src/myagent" - assert "PYTHONPATH=src/myagent harbor job start -c harbor-job.yaml" in markdown + assert front["runnable"] is False + assert front["run_command"] is None + assert "harbor job start" not in markdown + assert failure.message in markdown -def test_a_wrapper_at_the_repo_root_records_a_repo_relative_dot(tmp_path): - """Recorded relative like every other path, so the artifact outlives this machine.""" - record = _record(tmp_path, candidate=_authored(agent_search_path=".")) - - markdown = report.render_markdown(record) - target = report.run_target(record) - - assert read_front_matter(markdown)["run_config"]["pythonpath"] == "." - assert "PYTHONPATH=. harbor job start -c harbor-job.yaml" in markdown - assert target is not None and str(tmp_path) not in report.run_command(target) - - -def test_a_config_naming_a_builtin_agent_asks_for_no_search_path(tmp_path): - """The oracle is Harbor's own, so there is nothing to put on the path.""" - record = _record(tmp_path, candidate=_authored()) - - markdown = report.render_markdown(record) - - assert "PYTHONPATH" not in markdown - - -def test_the_persisted_config_carries_no_absolute_paths(tmp_path): - dataset = write_dataset(tmp_path / "evals" / "validation", count=1) - config = JobConfig.model_validate({"datasets": [{"path": str(dataset)}]}) - - rendered = report.render_job_config(config, tmp_path) - - assert yaml.safe_load(rendered)["datasets"] == [{"path": "evals/validation"}] - assert str(tmp_path) not in rendered - - -def test_a_path_outside_the_repo_is_left_absolute(tmp_path): - """Relativizing it would silently point the run at a directory that is not there.""" - outside = tmp_path.parent / "elsewhere" - config = JobConfig.model_validate({"datasets": [{"path": str(outside)}]}) - - rendered = report.render_job_config(config, tmp_path) - - assert yaml.safe_load(rendered)["datasets"] == [{"path": str(outside)}] - - -def test_a_generated_job_name_is_dropped_and_a_declared_one_is_kept(tmp_path): - generated = JobConfig.model_validate({"datasets": [{"path": "evals"}]}) - assert "job_name" not in yaml.safe_load(report.render_job_config(generated, tmp_path)) - - declared = JobConfig.model_validate({"datasets": [{"path": "evals"}], "job_name": "nightly-triage"}) - assert yaml.safe_load(report.render_job_config(declared, tmp_path))["job_name"] == "nightly-triage" - - -def test_a_secret_in_the_agent_env_is_templated_rather_than_written(tmp_path): - """Harbor's own serializer does this; the test pins the behavior we rely on.""" - config = JobConfig.model_validate( - { - "agents": [{"name": "oracle", "env": {"OPENAI_API_KEY": "sk-do-not-persist-me"}}], - "datasets": [{"path": "evals"}], - } - ) - - rendered = report.render_job_config(config, tmp_path) - - assert "sk-do-not-persist-me" not in rendered - - -def test_an_unrunnable_report_says_what_blocks_it_and_offers_no_command(tmp_path): +def test_a_report_without_a_repository_config_is_not_runnable(tmp_path): record = _record( tmp_path, - findings=[ - Finding( - name="resolution", - group="validation", - status="fail", - message="Harbor could not resolve the job", - harbor_call="Job.create", - ) - ], - ) - - markdown = report.render_markdown(record) - - assert record.runnable is False - assert "cannot run" in markdown - assert "could not resolve the job" in markdown - assert "harbor job start" not in markdown, "an unrunnable report must not hand out a run command" - - -def test_a_report_with_no_config_at_all_is_not_runnable(tmp_path): - record = report.build_report( - agent="ticket-triage", - workspace="default", - repo_root=tmp_path, - candidate=None, - findings=[], - required_env_vars=[], + config=False, + checks=[_check("config", "fail", "No repository-owned Harbor config file exists.")], ) front = read_front_matter(report.render_markdown(record)) - assert record.runnable is False - assert front["config_source"] is None - assert front["run_config"] is None + assert front["runnable"] is False + assert front["config_path"] is None + assert front["run_command"] is None + + +def test_the_run_command_changes_to_the_repo_and_quotes_shell_paths(tmp_path): + repo = tmp_path / "repo $(touch unsafe); name" + record = _record(repo) + record.config_path = repo.resolve() / "configs" / "eval $(touch unsafe); suite.yaml" + + cd_command, harbor_command = record.run_command.split(" && ") + assert shlex.split(cd_command) == ["cd", str(repo.resolve())] + assert shlex.split(harbor_command) == [ + "harbor", + "job", + "start", + "-c", + "configs/eval $(touch unsafe); suite.yaml", + ] diff --git a/plugins/nemo-eval-author/tests/discover/test_scan.py b/plugins/nemo-eval-author/tests/discover/test_scan.py index d0c516d49bc..d8f60e41e46 100644 --- a/plugins/nemo-eval-author/tests/discover/test_scan.py +++ b/plugins/nemo-eval-author/tests/discover/test_scan.py @@ -1,128 +1,153 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Repo-shape probes: context for authoring evals, never a reason a run cannot happen. - -The invariant these defend is the meaning of ``runnable``. It answers exactly one question, -"can Harbor run this config", so a repo with no traces yet or no doctrine document must not -be reported as unrunnable. Only the validation ladder is allowed to fail a report. -""" +"""Repository scan contract tests.""" from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock -from harbor_fixtures import StubClient from nemo_eval_author_plugin.discovery import scan -def test_ethos_is_preferred_over_the_name_it_replaced(tmp_path): - (tmp_path / "AGENT-SPEC.md").write_text("# Old\n") - (tmp_path / "ETHOS.md").write_text("# New\n") - (tmp_path / "README.md").write_text("# Readme\n") - - finding = scan.find_doctrine(tmp_path) - - assert finding.path == tmp_path / "ETHOS.md" - assert finding.status == "pass" - assert finding.hint is None - - -def test_the_old_name_still_works_and_says_so(tmp_path): - """Both names are honored while the rename is in flight, so the report is the signal.""" - (tmp_path / "AGENT-SPEC.md").write_text("# Old\n") - (tmp_path / "README.md").write_text("# Readme\n") - - finding = scan.find_doctrine(tmp_path) +def _config(path: Path, text: str = "datasets:\n- path: evals\n") -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path - assert finding.path == tmp_path / "AGENT-SPEC.md" - assert finding.hint is not None and "predates the rename" in finding.hint +def _task(path: Path) -> None: + path.mkdir(parents=True, exist_ok=True) + (path / "task.toml").write_text('version = "1.0"\n', encoding="utf-8") -def test_readme_is_the_last_resort(tmp_path): - (tmp_path / "README.md").write_text("# Readme\n") - finding = scan.find_doctrine(tmp_path) +def test_selects_the_first_config_and_warns_about_extras(tmp_path): + first = _config(tmp_path / "configs" / "a.yaml") + _config(tmp_path / "harbor" / "b.yaml") - assert finding.path == tmp_path / "README.md" - assert finding.status == "pass" + result = scan.scan_repository(tmp_path) + assert result.config is not None + assert result.config.path == first + assert {check.status for check in result.checks if check.name == "config"} == {"pass", "warn"} + assert any(check.name == "ethos" and check.status == "warn" for check in result.checks) -def test_no_doctrine_is_a_warning_not_a_failure(tmp_path): - finding = scan.find_doctrine(tmp_path) - - assert finding.path is None - assert finding.status == "warn" +def test_reads_yaml_yml_and_json_configs(tmp_path): + for suffix, text in ( + (".yaml", "datasets:\n- path: evals\n"), + (".yml", "datasets:\n- path: evals\n"), + (".json", '{"datasets": [{"path": "evals"}]}'), + ): + repo = tmp_path / suffix[1:] + expected = _config(repo / "configs" / f"job{suffix}", text) -def test_skill_bundles_are_found_by_their_marker_file(tmp_path): - for name in ("triage", "escalate"): - (tmp_path / "skills" / name).mkdir(parents=True) - (tmp_path / "skills" / name / "SKILL.md").write_text(f"# {name}\n") + result = scan.scan_repository(repo) - finding = scan.find_skills(tmp_path) + assert result.config is not None and result.config.path == expected - assert finding.status == "pass" - assert "2 Harbor skill bundle(s)" in finding.message - assert finding.hint is not None and "AgentConfig.skills" in finding.hint +def test_rejects_a_config_symlink_that_resolves_outside_the_repository(tmp_path): + repo = tmp_path / "repo" + outside = _config(tmp_path / "outside.yaml") + link = repo / "configs" / "eval.yaml" + link.parent.mkdir(parents=True) + link.symlink_to(outside) -def test_vendored_trees_are_not_searched(tmp_path): - """A dependency's skills are not the repo's, and .venv dwarfs everything else.""" - vendored = tmp_path / ".venv" / "lib" / "pkg" - vendored.mkdir(parents=True) - (vendored / "SKILL.md").write_text("# not ours\n") + result = scan.scan_repository(repo) - finding = scan.find_skills(tmp_path) + assert result.config is None + assert next(check for check in result.checks if check.name == "config").status == "fail" - assert finding.status == "warn" - assert finding.path is None +def test_profile_prior_job_and_task_layout_never_become_config_candidates(tmp_path): + (tmp_path / "optimizer.yaml").write_text( + "agent: ticket-triage\ndatasets:\n validation: evals/validation\n", + encoding="utf-8", + ) + prior_job = tmp_path / "jobs" / "run-1" + _config(prior_job / "config.json", '{"datasets": [{"path": "evals/validation"}]}') + (prior_job / "lock.json").write_text('{"harbor_version": "0.18.0"}\n', encoding="utf-8") + dataset = tmp_path / "evals" / "validation" + _task(dataset / "task-0") -def test_the_optimizer_s_own_output_is_not_part_of_the_repo(tmp_path): - """Experimentalist writes into ``.nemo-optimizer`` and ``eval-and-optimize``. + result = scan.scan_repository(tmp_path) - What it leaves there is candidate agent copies and its own Harbor job dirs: results of - evaluating this repo, not declarations of how to evaluate it. Every probe that walks the - tree would otherwise read them as the repo's own setup. - """ - for relative in ( - Path(".nemo-optimizer") / "experiments" / "run-1" / "candidate", - Path("eval-and-optimize") / "results" / "job-1", - ): - (tmp_path / relative).mkdir(parents=True) - (tmp_path / relative / "SKILL.md").write_text("# a candidate's copy\n") + assert (result.config, result.dataset_paths) == (None, [dataset]) - walked = list(scan.walk_dirs(tmp_path)) - assert walked == [tmp_path] - assert scan.find_skills(tmp_path).status == "warn" +def test_uses_only_ethos_for_the_doctrine_contract(tmp_path): + _config(tmp_path / "harbor-job.yaml") + (tmp_path / "README.md").write_text("# Readme\n", encoding="utf-8") + (tmp_path / "AGENT-SPEC.md").write_text("# Old\n", encoding="utf-8") + without_ethos = scan.scan_repository(tmp_path) + assert without_ethos.ethos_path is None + assert any(check.name == "ethos" and check.status == "warn" for check in without_ethos.checks) -async def test_available_traces_are_counted(): - finding = await scan.probe_traces(StubClient(trace_total=7), agent="ticket-triage", workspace="default") + ethos = tmp_path / "ETHOS.md" + ethos.write_text("# Agent doctrine\n", encoding="utf-8") + with_ethos = scan.scan_repository(tmp_path) - assert finding.status == "pass" - assert "7 trace session(s)" in finding.message + assert with_ethos.ethos_path == ethos + assert any(check.name == "ethos" and check.status == "pass" for check in with_ethos.checks) -async def test_no_traces_is_a_warning_with_a_next_step(): - finding = await scan.probe_traces(StubClient(trace_total=0), agent="ticket-triage", workspace="default") +def test_discovers_local_datasets_and_prunes_generated_trees(tmp_path): + _config(tmp_path / "harbor-job.yaml") + _task(tmp_path) + _task(tmp_path / "evals" / "suite" / "task-one") + _task(tmp_path / "evals" / "suite" / "task_template") + _task(tmp_path / ".nemo-optimizer" / "output" / "task-two") + _task(tmp_path / "node_modules" / "package" / "task-three") + _task(tmp_path / "vendor" / "package" / "task-four") + _task(tmp_path / "cache" / "package" / "task-five") - assert finding.status == "warn" - assert finding.hint is not None and "telemetry" in finding.hint + result = scan.scan_repository(tmp_path) + assert result.dataset_paths == [tmp_path / "evals" / "suite"] + assert result.input_file_count == 3 -async def test_an_unreachable_platform_never_blocks_a_run(): - finding = await scan.probe_traces(StubClient(trace_total=None), agent="ticket-triage", workspace="default") - assert finding.status == "warn" - assert finding.hint is not None and "Harbor runs fine without them" in finding.hint +def test_fingerprint_covers_config_ethos_optimizer_and_dataset_files(tmp_path): + config = _config(tmp_path / "harbor-job.yaml") + ethos = tmp_path / "ETHOS.md" + optimizer = tmp_path / "optimizer.yaml" + ethos.write_text("# One\n", encoding="utf-8") + optimizer.write_text("model: one\n", encoding="utf-8") + task = tmp_path / "evals" / "suite" / "task-one" + _task(task) + dataset_file = task / "notes.txt" + dataset_file.write_text("one\n", encoding="utf-8") + first = scan.scan_repository(tmp_path) -def test_a_path_above_the_repo_is_rendered_absolute_rather_than_crashing(tmp_path): - """``discover_profile`` walks upward, so this is a real case and not a defensive guess.""" - outside = tmp_path.parent / "optimizer.yaml" - - assert scan.display_path(outside, tmp_path) == str(outside) - assert scan.display_path(tmp_path / "evals" / "task", tmp_path) == "evals/task" - # The sentinel used for values declared inline rather than in a file. - assert scan.display_path(Path(""), tmp_path) == "" + assert first.input_file_count == 5 + assert first.config is not None and first.config.path == config + for path, replacement in ( + (config, "datasets:\n- path: another-evals\n"), + (ethos, "# Two\n"), + (optimizer, "model: two\n"), + (task / "task.toml", 'version = "2.0"\n'), + (dataset_file, "two\n"), + ): + original = path.read_text(encoding="utf-8") + path.write_text(replacement, encoding="utf-8") + assert scan.scan_repository(tmp_path).fingerprint != first.fingerprint + path.write_text(original, encoding="utf-8") + + +async def test_trace_probe_handles_exception_empty_and_positive_totals(): + for total, status in ((None, "warn"), (0, "warn"), (2, "pass")): + list_groups = ( + AsyncMock(side_effect=RuntimeError("intake unavailable")) + if total is None + else AsyncMock(return_value=SimpleNamespace(pagination=SimpleNamespace(total_results=total))) + ) + client = SimpleNamespace( + intake=SimpleNamespace(spans=SimpleNamespace(groups=SimpleNamespace(list=list_groups))) + ) + + finding = await scan.probe_traces(client, agent="ticket-triage", workspace="default") + + assert (finding.status, finding.severity) == (status, "advisory") diff --git a/plugins/nemo-eval-author/tests/discover/test_sources.py b/plugins/nemo-eval-author/tests/discover/test_sources.py deleted file mode 100644 index 5599f9a10fa..00000000000 --- a/plugins/nemo-eval-author/tests/discover/test_sources.py +++ /dev/null @@ -1,384 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -"""Which source wins, and what gets read rather than assumed. - -Priority is the load-bearing behavior here: the whole artifact is a trust claim, so a repo -offering both a config its author wrote and a layout we could guess at must resolve to the -former, and the report must say which it used. -""" - -import yaml -from harbor.models.job.config import JobConfig -from harbor_fixtures import write_dataset, write_job_dir, write_task, write_wrapper -from nemo_eval_author_plugin.discovery import sources -from nemo_experimentalist_plugin.experimentalist.components.evaluator.harbor import _AGENT_IMPORT_ROOT -from nemo_experimentalist_plugin.resolve import classify_dataset_value - - -def _job_config(dataset: str) -> dict: - return {"agents": [{"name": "oracle"}], "datasets": [{"path": dataset}]} - - -def test_config_file_outranks_every_inferred_source(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - write_job_dir(tmp_path / "jobs" / "run-1", config=_job_config("evals/validation")) - (tmp_path / "configs").mkdir() - (tmp_path / "configs" / "eval.yaml").write_text(yaml.safe_dump(_job_config("evals/validation"))) - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "config_file" - chosen = next(item for item in findings if item.name == "config-source") - assert "config_file" in chosen.message - # The passed-over sources are named, so a reader can tell what was available. - assert chosen.hint is not None and "prior_job" in chosen.hint - - -def test_prior_job_outranks_convention(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - write_job_dir(tmp_path / "jobs" / "run-1", config=_job_config("evals/validation")) - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "prior_job" - - -def test_trial_config_is_not_mistaken_for_a_job_config(tmp_path): - """Harbor writes config.json and lock.json into trial dirs too, not just job dirs.""" - write_dataset(tmp_path / "evals" / "validation") - write_job_dir( - tmp_path / "jobs" / "run-1" / "trial-0", - config={"task": {"path": "evals/validation/task-0"}, "trial_name": "trial-0"}, - ) - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "convention" - - -def test_an_optimizer_job_dir_is_not_read_as_the_repo_s_own_setup(tmp_path): - """Experimentalist writes config.json and lock.json into its own results directory. - - Harbor really did resolve and run that config, which is what makes it outrank the profile. - But its agent import path names a package Experimentalist synthesizes in ``sys.modules`` - for the duration of its run, so no separate ``harbor`` process can import it: running the - optimizer and then discover reported "Harbor cannot run this repo's evals" about a repo - that had just been evaluated successfully. - """ - write_dataset(tmp_path / "evals" / "validation") - write_job_dir( - tmp_path / ".nemo-optimizer" / "experiments" / "run-1" / "eval-and-optimize" / "results" / "job-1", - config={ - "agents": [{"import_path": "_nemo_experimentalist_eval_agents.agent_abc123:WrappedAgent"}], - "datasets": [{"path": "evals/validation"}], - }, - ) - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "convention" - assert not any(item.name == "prior-job" for item in findings) - - -def test_a_synthetic_agent_import_path_is_rejected_wherever_it_is_found(tmp_path): - """The pruned directories are Experimentalist's defaults, not a promise about the layout.""" - write_dataset(tmp_path / "evals" / "validation") - write_job_dir( - tmp_path / "elsewhere" / "job-1", - config={ - "agents": [{"import_path": f"{_AGENT_IMPORT_ROOT}.src_agent_deadbeef:WrappedAgent"}], - "datasets": [{"path": "evals/validation"}], - }, - ) - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "convention" - - -def test_a_real_prior_job_is_still_the_stronger_source(tmp_path): - """The guard is about synthetic import paths, not about distrusting prior jobs.""" - write_dataset(tmp_path / "evals" / "validation") - write_job_dir( - tmp_path / "jobs" / "run-1", - config={ - "agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], - "datasets": [{"path": "evals/validation"}], - }, - ) - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "prior_job" - - -def test_profile_outranks_convention_and_reads_the_validation_split(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - write_dataset(tmp_path / "evals" / "train", count=3) - (tmp_path / "optimizer.yaml").write_text( - yaml.safe_dump( - {"agent": "ticket-triage", "datasets": {"train": "evals/train", "validation": "evals/validation"}} - ) - ) - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "profile" - assert candidate.data["datasets"] == [{"path": str(tmp_path / "evals" / "validation")}] - split = next(item for item in findings if item.name == "profile-datasets") - assert "validation" in split.message - # Evaluating the train split would silently score the set used to optimize. - assert split.hint is not None and "train" in split.hint - - -def test_a_registry_dataset_ref_is_passed_to_harbor_as_a_ref(tmp_path): - """A ref is a name Harbor downloads, not a directory under the profile. - - ``resolve_profile_path`` has no registry awareness, so it turned - ``tau2-bench-live-validation@1.0`` into ``/tau2-bench-live-validation@1.0`` and - ``Job.create`` raised ``FileNotFoundError`` — discover reporting "cannot run" about a - profile the optimizer runs every day. - """ - (tmp_path / "optimizer.yaml").write_text( - yaml.safe_dump( - { - "agent": "nemo-oo-airline", - "datasets": { - "train": "tau2-bench-live-train@1.0", - "validation": "tau2-bench-live-validation@1.0", - "registry_url": "https://registry.example/registry.json", - }, - } - ) - ) - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "profile" - assert candidate.data["datasets"] == [ - { - "name": "tau2-bench-live-validation", - "version": "1.0", - "registry_url": "https://registry.example/registry.json", - } - ] - # Harbor is the judge of whether that names a dataset it can fetch. - assert JobConfig.model_validate(candidate.data).datasets[0].is_registry() - split = next(item for item in findings if item.name == "profile-datasets") - assert split.status == "warn" - assert "registry ref" in split.message - assert split.hint is not None and "reachable" in split.hint - - -def test_a_local_dataset_path_is_unaffected_by_a_declared_registry(tmp_path): - """An explicit relative path stays a path, which is the rule Experimentalist applies.""" - write_dataset(tmp_path / "evals" / "validation") - (tmp_path / "optimizer.yaml").write_text( - yaml.safe_dump( - { - "datasets": { - "validation": "./evals/validation", - "registry_url": "https://registry.example/registry.json", - } - } - ) - ) - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.data["datasets"] == [{"path": str(tmp_path / "evals" / "validation")}] - assert next(item for item in findings if item.name == "profile-datasets").status == "pass" - - -def test_the_dataset_classifier_agrees_with_experimentalist(tmp_path): - """The copy exists to keep the plugin boundary shrinking, not to hold a second opinion. - - Both plugins read the same ``optimizer.yaml``. A value the optimizer downloads and discover - resolves as a path would produce an artifact describing a directory nobody has. - """ - (tmp_path / "local-dir").mkdir() - values = [ - "./evals/validation", - "../sibling/evals", - "/absolute/evals", - "~/evals", - "local-dir", - "not-on-disk", - "namespaced/dataset", - "tau2-bench-live-validation@1.0", - ] - - for registry_url in (None, "https://registry.example/registry.json"): - ours = [sources.classify_dataset_value(value, tmp_path, registry_url=registry_url) for value in values] - theirs = [classify_dataset_value(value, tmp_path, registry_url=registry_url) for value in values] - assert ours == theirs, f"classifiers disagree with registry_url={registry_url}" - - -def test_convention_prefers_a_conventional_eval_dir_over_a_larger_one(tmp_path): - write_dataset(tmp_path / "evals" / "validation", count=2) - write_dataset(tmp_path / "experiments" / "scratch", count=5) - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.data["datasets"] == [{"path": str(tmp_path / "evals" / "validation")}] - - -def test_a_lone_task_template_is_not_a_dataset(tmp_path): - write_task(tmp_path / "evals" / "task_template") - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is None - assert any(item.name == "convention-datasets" and item.status == "warn" for item in findings) - assert any(item.name == "config-source" and item.status == "fail" for item in findings) - - -def test_wrapper_class_name_is_read_from_the_file(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - write_wrapper(tmp_path, class_name="TicketTriageAgent") - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.data["agents"] == [{"import_path": "harbor_wrapper:TicketTriageAgent"}] - entry = next(item for item in findings if item.name == "agent-entrypoint") - assert entry.hint is not None and "not assumed" in entry.hint - - -def test_a_wrapper_at_the_repo_root_is_importable_from_the_root(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - write_wrapper(tmp_path) - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.agent_search_path == "." - - -def test_a_nested_wrapper_records_the_directory_the_import_path_omits(tmp_path): - """``harbor_wrapper:WrappedAgent`` is where the module is *not*, which is the whole problem. - - The wrapper is found by walking, so it can be anywhere; the import path Harbor takes is a - bare module name. Without the directory beside it, ``harbor job start -c`` fails with - ``No module named 'harbor_wrapper'`` on a config discovery called runnable. - """ - write_dataset(tmp_path / "evals" / "validation") - write_wrapper(tmp_path / "src" / "myagent") - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.data["agents"] == [{"import_path": "harbor_wrapper:WrappedAgent"}] - assert candidate.agent_search_path == "src/myagent" - entry = next(item for item in findings if item.name == "agent-entrypoint") - assert "src/myagent" in entry.message, "a reader has to be able to see where it is imported from" - - -def test_a_builtin_agent_needs_no_search_path(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.data["agents"] == [{"name": "oracle"}] - assert candidate.agent_search_path is None - - -def test_missing_wrapper_falls_back_to_the_oracle_and_says_what_that_means(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.data["agents"] == [{"name": "oracle"}] - entry = next(item for item in findings if item.name == "agent-entrypoint") - assert entry.status == "warn" - assert "No harbor_wrapper.py found" in entry.message - assert entry.hint is not None and "evaluates no agent" in entry.hint - - -def test_a_wrapper_whose_class_was_not_recognized_is_not_reported_as_a_missing_file(tmp_path): - """The oracle silently replaces the agent, so the reason has to be the true one. - - The class is matched by the base name in the source, so a duck-typed wrapper falls through - to the oracle — which replays ``solution/solve.sh`` and evaluates nothing. Reporting that - as "No harbor_wrapper.py found" sends the author looking for a file that is right there. - """ - write_dataset(tmp_path / "evals" / "validation") - (tmp_path / "agent" / "nested").mkdir(parents=True) - (tmp_path / "agent" / "nested" / "harbor_wrapper.py").write_text( - "class WrappedAgent:\n async def run(self, instruction, environment):\n return None\n" - ) - - candidate, findings = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.data["agents"] == [{"name": "oracle"}] - entry = next(item for item in findings if item.name == "agent-entrypoint") - assert entry.status == "warn" - assert "No harbor_wrapper.py found" not in entry.message - assert "agent/nested/harbor_wrapper.py" in entry.message - assert "BaseAgent" in entry.message and "BaseInstalledAgent" in entry.message - assert entry.hint is not None and "evaluates no agent" in entry.hint - - -def test_a_config_file_is_read_as_written_and_stays_owned_by_the_repo(tmp_path): - """Nothing is injected into a config someone maintains, so the artifact can point at it. - - The environment backend is the case that tempts a default: assembly leaves it alone and - lets Harbor apply its own, rather than writing a value into a payload the repo's file - does not contain. - """ - write_dataset(tmp_path / "evals" / "validation") - (tmp_path / "configs").mkdir() - declared = {**_job_config("evals/validation"), "environment": {"type": "daytona"}} - (tmp_path / "configs" / "eval.yaml").write_text(yaml.safe_dump(declared)) - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.data["environment"] == {"type": "daytona"} - assert candidate.source.owns_file is True - - -def test_an_undeclared_backend_is_left_for_harbor_to_default(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert "environment" not in candidate.data - - -def test_an_inferred_source_never_claims_a_file_it_could_be_run_from(tmp_path): - """A prior job's config.json is Harbor's own output record, not an input anyone maintains.""" - write_dataset(tmp_path / "evals" / "validation") - write_job_dir(tmp_path / "jobs" / "run-1", config=_job_config("evals/validation")) - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.path is not None - assert candidate.source.owns_file is False - - -def test_unreadable_yaml_is_skipped_rather_than_raising(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - (tmp_path / "configs").mkdir() - (tmp_path / "configs" / "broken.yaml").write_text("datasets: [oops\n") - - candidate, _ = sources.find_candidate(tmp_path) - - assert candidate is not None - assert candidate.source.kind == "convention" diff --git a/plugins/nemo-eval-author/tests/discover/test_validate.py b/plugins/nemo-eval-author/tests/discover/test_validate.py index aed6f36537e..2c2acffe30f 100644 --- a/plugins/nemo-eval-author/tests/discover/test_validate.py +++ b/plugins/nemo-eval-author/tests/discover/test_validate.py @@ -1,544 +1,389 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""The validation ladder, against real Harbor task directories. - -Every fixture here is a layout Harbor itself accepts or rejects, so these tests assert -against Harbor's validators rather than against our reading of them. That matters most for -the shapes a hand-rolled "does tests/test.sh exist" check gets wrong: a multi-step task, a -Windows task, a task graded from a separate verifier image, and a task that names a -prebuilt image instead of shipping a Dockerfile. Each of those is legitimate, and each one -a naive check would fail. - -The backend rung is excluded from pass assertions because it runs Docker's preflight, and -whether a daemon is up is a fact about the machine rather than about the repo under test. -Tests that care about the backend assert on that finding directly. -""" +"""Focused Harbor preflight contract tests.""" import subprocess import sys -from importlib.metadata import version from pathlib import Path -from typing import ClassVar - -from harbor_fixtures import ( - MENTIONS_REWARD_IN_COMMENT, - WRITES_REWARD, - write_dataset, - write_task, - write_wrapper, -) -from nemo_eval_author_plugin.discovery import sources, validate -from nemo_eval_author_plugin.discovery.models import CandidateConfig, ConfigSource - - -def _candidate(data: dict, agent_search_path: str | None = None) -> CandidateConfig: - return CandidateConfig( - data=data, - source=ConfigSource(kind="config_file", detail="test fixture"), - agent_search_path=agent_search_path, - ) - - -def _finding(outcome, name): - matches = [item for item in outcome.findings if item.name == name] - assert matches, f"no {name!r} finding in {[item.name for item in outcome.findings]}" - return matches[0] - -def _repo_failures(outcome): - """Failures the repo is responsible for, so Docker's absence does not fail a test.""" - return [item for item in outcome.findings if item.status == "fail" and item.name != "backend"] +import pytest +from harbor.utils.logger import logger as harbor_logger +from harbor_fixtures import write_dataset, write_task, write_wrapper +from nemo_eval_author_plugin.discovery import scan, validate -async def test_a_well_formed_repo_passes_every_rung(tmp_path): - write_dataset(tmp_path / "evals" / "validation") - candidate = _candidate({"agents": [{"name": "oracle"}], "datasets": [{"path": str(tmp_path / "evals/validation")}]}) +def _candidate(path: Path, data: dict) -> scan.ConfigCandidate: + return scan.ConfigCandidate(path=path, data=data) - outcome = await validate.run_ladder(candidate, tmp_path) - assert _repo_failures(outcome) == [] - assert _finding(outcome, "tasks").message.startswith("2 of 2") - assert _finding(outcome, "schema").harbor_call == "JobConfig.model_validate" - assert _finding(outcome, "resolution").harbor_call == "Job.create" +def _check(outcome: validate.ValidationOutcome, name: str): + matches = [item for item in outcome.checks if item.name == name] + assert matches, f"no {name!r} check in {[item.name for item in outcome.checks]}" + return matches[0] -async def test_only_a_verdict_harbor_returned_claims_a_harbor_call(tmp_path): - """``harbor_call`` is what tells a reader a finding is as true as the run would be. +def _patch_external_preflight(monkeypatch) -> None: + monkeypatch.setattr(validate.EnvironmentFactory, "run_preflight", lambda *args: None) + monkeypatch.setattr( + validate, + "check_config_file", + lambda path, root: validate._check("round-trip", "pass", "The config file loads through the Harbor CLI"), + ) - The reward advisory reads the test scripts itself, so it must not carry one. Naming a - Harbor API there would dress a text search up as something Harbor vouched for. - """ - write_dataset(tmp_path / "evals" / "validation", count=1) - candidate = _candidate({"datasets": [{"path": str(tmp_path / "evals/validation")}]}) - outcome = await validate.run_ladder(candidate, tmp_path) +async def test_a_well_formed_repo_passes_the_ladder(tmp_path, monkeypatch): + dataset = write_dataset(tmp_path / "evals" / "validation") + _patch_external_preflight(monkeypatch) - assert _finding(outcome, "reward").harbor_call is None - judged_by_harbor = [item for item in outcome.findings if item.name != "reward"] - assert judged_by_harbor and all(item.harbor_call for item in judged_by_harbor) + outcome = await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", {"agents": [{"name": "oracle"}], "datasets": [{"path": str(dataset)}]} + ), + tmp_path, + ) + assert not [check for check in outcome.checks if check.status == "fail"] + assert {check.name for check in outcome.checks} == { + "schema", + "resolution", + "agent", + "backend", + "round-trip", + "tasks", + "coverage", + "credentials", + } + assert _check(outcome, "tasks").message.startswith("2 of 2") + assert _check(outcome, "coverage").status == "pass" + + +async def test_ladder_closes_added_harbor_logger_handlers(tmp_path, monkeypatch): + dataset = write_dataset(tmp_path / "evals" / "validation") + _patch_external_preflight(monkeypatch) + handlers_before = tuple(harbor_logger.handlers) + + await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", + {"agents": [{"name": "oracle"}], "datasets": [{"path": str(dataset)}]}, + ), + tmp_path, + ) -async def test_schema_failure_names_the_harbor_validator(tmp_path): - outcome = await validate.run_ladder(_candidate({"datasets": "not-a-list"}), tmp_path) + assert tuple(harbor_logger.handlers) == handlers_before - schema = _finding(outcome, "schema") - assert schema.status == "fail" - assert schema.harbor_call == "JobConfig.model_validate" - # Nothing downstream can be judged once the schema is wrong. - assert [item.name for item in outcome.findings] == ["schema"] - assert outcome.config is None +async def test_schema_failure_stops_the_ladder(tmp_path): + outcome = await validate.run_ladder(_candidate(tmp_path / "harbor-job.yaml", {"datasets": "not-a-list"}), tmp_path) -async def test_resolution_failure_reports_the_error_a_real_run_would_hit(tmp_path): - candidate = _candidate({"datasets": [{"path": str(tmp_path / "nope")}]}) + assert _check(outcome, "schema").status == "fail" + assert [item.name for item in outcome.checks] == ["schema"] - outcome = await validate.run_ladder(candidate, tmp_path) - resolution = _finding(outcome, "resolution") - assert resolution.status == "fail" - assert resolution.harbor_call == "Job.create" - assert resolution.hint is not None and "before starting any container" in resolution.hint +async def test_resolution_failure_reports_the_real_error(tmp_path, monkeypatch): + _patch_external_preflight(monkeypatch) + outcome = await validate.run_ladder( + _candidate(tmp_path / "harbor-job.yaml", {"datasets": [{"path": str(tmp_path / "nope")}]}), tmp_path + ) + finding = _check(outcome, "resolution") + assert finding.status == "fail" + assert "nope" in finding.message -async def test_a_harbor_that_stopped_exposing_its_resolved_tasks_does_not_blame_the_repo(tmp_path, monkeypatch): - """``Job._task_configs`` is private, so a Harbor upgrade is allowed to rename it. - Reading an absent attribute as zero tasks would report "the config resolves to zero tasks" - under a hint quoting a Harbor error Harbor never raised, about a repo whose tasks are fine. - An incompatibility of ours has to read as ours. - """ - write_dataset(tmp_path / "evals" / "validation", count=1) - candidate = _candidate({"datasets": [{"path": str(tmp_path / "evals/validation")}]}) +async def test_missing_resolved_task_attribute_is_a_compatibility_failure(tmp_path, monkeypatch): + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + _patch_external_preflight(monkeypatch) class _JobWithoutTaskConfigs: @classmethod - async def create(cls, config): + async def create(cls, _config): return cls() - monkeypatch.setattr(validate, "Job", _JobWithoutTaskConfigs) - - outcome = await validate.run_ladder(candidate, tmp_path) - - compatibility = _finding(outcome, "compatibility") - assert compatibility.status == "fail" - assert "Job._task_configs" in compatibility.message - assert not any(item.name == "tasks" for item in outcome.findings), "no verdict on tasks was available" - assert not any("zero tasks" in item.message for item in outcome.findings) - + def _close_logger_handlers(self): + pass -async def test_a_config_that_really_resolves_no_tasks_is_still_the_repo_s_failure(tmp_path, monkeypatch): - """The companion case: present but empty is a repo Harbor found nothing in, and it must still fail. + monkeypatch.setattr(validate, "Job", _JobWithoutTaskConfigs) + outcome = await validate.run_ladder( + _candidate(tmp_path / "harbor-job.yaml", {"datasets": [{"path": str(dataset)}]}), tmp_path + ) - Absent and empty mean opposite things, so this pins the distinction from the side that - would be lost if the attribute check were ever relaxed back to a falsy one. - """ - candidate = _candidate({"datasets": [{"path": str(write_dataset(tmp_path / "evals" / "validation", count=1))}]}) + assert _check(outcome, "compatibility").status == "fail" + assert "Job._task_configs" in _check(outcome, "compatibility").message - class _JobWithNoTasks: - _task_configs: ClassVar[list] = [] - @classmethod - async def create(cls, config): - return cls() +async def test_invalid_resolved_task_fails_tasks_check(tmp_path, monkeypatch): + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + _patch_external_preflight(monkeypatch) + create_job = validate.Job.create - monkeypatch.setattr(validate, "Job", _JobWithNoTasks) + async def resolve_then_invalidate(config): + job = await create_job(config) + monkeypatch.setattr(validate.Task, "is_valid_dir", lambda _path: False) + return job - outcome = await validate.run_ladder(candidate, tmp_path) + monkeypatch.setattr(validate.Job, "create", staticmethod(resolve_then_invalidate)) - tasks = _finding(outcome, "tasks") - assert tasks.status == "fail" - assert "zero tasks" in tasks.message - assert not any(item.name == "compatibility" for item in outcome.findings) + outcome = await validate.run_ladder( + _candidate(tmp_path / "harbor-job.yaml", {"datasets": [{"path": str(dataset)}]}), tmp_path + ) + assert _check(outcome, "tasks").status == "fail" -async def test_a_task_harbor_silently_skips_is_reported(tmp_path): - """Harbor drops a directory it cannot parse without raising. - Nothing else in the ladder catches this: the tasks rung only sees what Harbor - resolved, so it reports one of one valid while the repo holds two. The run would then - score half the suite and look complete doing it. - """ +async def test_silent_task_drop_fails_concrete_coverage(tmp_path, monkeypatch): dataset = tmp_path / "evals" / "validation" write_task(dataset / "task-0") write_task(dataset / "task-1", instruction=None) - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) - - outcome = await validate.run_ladder(candidate, tmp_path) - - assert _finding(outcome, "tasks").message.startswith("1 of 1"), "the tasks rung cannot see the dropped one" - coverage = _finding(outcome, "coverage") - assert coverage.status == "fail" - assert "task-1" in coverage.message - assert "instruction.md" in coverage.message - assert coverage.hint is not None and "silently" in coverage.hint + _patch_external_preflight(monkeypatch) - -async def test_a_dataset_that_selects_a_subset_is_not_accused_of_dropping_tasks(tmp_path): - dataset = write_dataset(tmp_path / "evals" / "validation", count=3) - candidate = _candidate({"datasets": [{"path": str(dataset), "task_names": ["task-0"]}]}) - - outcome = await validate.run_ladder(candidate, tmp_path) - - coverage = _finding(outcome, "coverage") - assert coverage.status == "warn" - assert coverage.hint is not None and "selects a subset" in coverage.hint - assert _repo_failures(outcome) == [] - - -async def test_a_scaffolded_task_that_never_names_a_reward_is_flagged_without_blocking(tmp_path): - """Harbor's own template mentions the reward file only in a comment. - - Worth saying, because the trial would run and then raise. Not worth failing over: the - check is a text search, and a script that builds the path in a variable looks identical - to one that writes nothing. - """ - dataset = write_dataset(tmp_path / "evals" / "validation", count=1, test_script=MENTIONS_REWARD_IN_COMMENT) - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) - - outcome = await validate.run_ladder(candidate, tmp_path) - - reward = _finding(outcome, "reward") - assert reward.status == "warn" - assert _repo_failures(outcome) == [], "a heuristic must not block a repo Harbor accepted" - assert _finding(outcome, "tasks").status == "pass", "the task is structurally fine; only its scoring is doubtful" - assert reward.hint is not None and "RewardFileNotFoundError" in reward.hint - - -async def test_a_reward_written_through_a_variable_is_not_called_a_failure(tmp_path): - """The false negative that makes this check unfit to gate on: the script does score.""" - dataset = write_dataset( - tmp_path / "evals" / "validation", - count=1, - test_script='#!/bin/bash\nOUT=/logs/verifier\nprintf 1 > "$OUT/reward.$(echo txt)"\n', + outcome = await validate.run_ladder( + _candidate(tmp_path / "harbor-job.yaml", {"datasets": [{"path": str(dataset)}]}), tmp_path ) - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) - outcome = await validate.run_ladder(candidate, tmp_path) + assert _check(outcome, "coverage").status == "fail" + assert "task-1" in _check(outcome, "coverage").message - assert _finding(outcome, "reward").status == "warn" - assert _repo_failures(outcome) == [] - -async def test_a_multi_step_task_is_valid_without_a_root_instruction(tmp_path): +async def test_empty_task_names_does_not_make_a_dropped_task_advisory(tmp_path, monkeypatch): dataset = tmp_path / "evals" / "validation" - write_task( - dataset / "task-0", - task_toml='\n[[steps]]\nname = "first"\n\n[[steps]]\nname = "second"\n', - instruction=None, - steps={"first": {"instruction": "Step one.\n"}, "second": {"instruction": "Step two.\n"}}, + write_task(dataset / "task-0") + write_task(dataset / "task-1", instruction=None) + _patch_external_preflight(monkeypatch) + + outcome = await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", + {"datasets": [{"path": str(dataset), "task_names": []}]}, + ), + tmp_path, ) - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) - outcome = await validate.run_ladder(candidate, tmp_path) - - assert _finding(outcome, "tasks").status == "pass" - assert _repo_failures(outcome) == [] + coverage = _check(outcome, "coverage") + assert (coverage.status, coverage.severity) == ("fail", "required") + assert "task-1" in coverage.message + assert coverage.hint == "Harbor skips these task dirs silently." -async def test_a_multi_step_task_is_checked_for_a_reward_in_every_step(tmp_path): - """A shared script covers a step with none of its own; a step's own script must score.""" +async def test_malformed_explicit_task_name_fails_coverage(tmp_path, monkeypatch): dataset = tmp_path / "evals" / "validation" - write_task( - dataset / "task-0", - task_toml='\n[[steps]]\nname = "first"\n\n[[steps]]\nname = "second"\n', - instruction=None, - test_script=WRITES_REWARD, - steps={ - "first": {"instruction": "Step one.\n"}, - "second": {"instruction": "Step two.\n", "test": MENTIONS_REWARD_IN_COMMENT}, - }, + write_task(dataset / "task-0") + write_task(dataset / "task-1", instruction=None) + _patch_external_preflight(monkeypatch) + + outcome = await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", + {"datasets": [{"path": str(dataset), "task_names": ["task-0", "task-1"]}]}, + ), + tmp_path, ) - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) - - outcome = await validate.run_ladder(candidate, tmp_path) - assert _finding(outcome, "tasks").status == "pass" - assert _finding(outcome, "reward").status == "warn" + assert (_check(outcome, "coverage").status, _check(outcome, "coverage").severity) == ("fail", "required") + assert "task-1" in _check(outcome, "coverage").message -async def test_a_windows_task_needing_test_bat_is_not_a_failure(tmp_path): +async def test_excluded_task_drop_is_advisory(tmp_path, monkeypatch): dataset = tmp_path / "evals" / "validation" - write_task( - dataset / "task-0", - task_toml='\n[environment]\nos = "windows"\n', - test_script="@echo off\r\necho 1 > /logs/verifier/reward.txt\r\n", - test_name="test.bat", + write_task(dataset / "task-0") + write_task(dataset / "task-1", instruction=None) + _patch_external_preflight(monkeypatch) + + outcome = await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", + {"datasets": [{"path": str(dataset), "exclude_task_names": ["task-1"]}]}, + ), + tmp_path, ) - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) - outcome = await validate.run_ladder(candidate, tmp_path) + assert (_check(outcome, "coverage").status, _check(outcome, "coverage").severity) == ("warn", "advisory") - assert _finding(outcome, "tasks").status == "pass" - assert _finding(outcome, "reward").status == "pass" - -async def test_a_task_graded_in_a_separate_verifier_image_needs_no_host_script(tmp_path): +async def test_non_excluded_invalid_task_fails_coverage_with_exclude_filter(tmp_path, monkeypatch): dataset = tmp_path / "evals" / "validation" - write_task(dataset / "task-0", task_toml='\n[verifier]\nenvironment_mode = "separate"\n', test_script=None) - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + write_task(dataset / "task-0") + write_task(dataset / "task-excluded") + write_task(dataset / "task-invalid", instruction=None) + _patch_external_preflight(monkeypatch) + + outcome = await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", + {"datasets": [{"path": str(dataset), "exclude_task_names": ["task-excluded"]}]}, + ), + tmp_path, + ) - outcome = await validate.run_ladder(candidate, tmp_path) + coverage = _check(outcome, "coverage") + assert (coverage.status, coverage.severity) == ("fail", "required") + assert "task-invalid" in coverage.message + assert "task-excluded" not in coverage.message + assert coverage.hint == "Harbor skipped a task selected by the dataset filters." - assert _finding(outcome, "tasks").status == "pass" - assert _finding(outcome, "reward").status == "pass", "an image-graded task ships no host script to read" +async def test_n_tasks_subset_drop_is_advisory(tmp_path, monkeypatch): + dataset = write_dataset(tmp_path / "evals" / "validation") + _patch_external_preflight(monkeypatch) -async def test_a_task_naming_a_prebuilt_image_needs_no_dockerfile(tmp_path): - dataset = tmp_path / "evals" / "validation" - task = write_task(dataset / "task-0", task_toml='\n[environment]\ndocker_image = "ubuntu:24.04"\n') - (task / "environment" / "Dockerfile").unlink() - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) - - outcome = await validate.run_ladder(candidate, tmp_path) + outcome = await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", + {"datasets": [{"path": str(dataset), "n_tasks": 1}]}, + ), + tmp_path, + ) - assert _finding(outcome, "tasks").status == "pass" + assert (_check(outcome, "coverage").status, _check(outcome, "coverage").severity) == ("warn", "advisory") -async def test_required_host_variables_are_recorded_with_their_defaults(tmp_path): +async def test_required_host_variables_are_recorded(tmp_path, monkeypatch): dataset = tmp_path / "evals" / "validation" write_task( dataset / "task-0", task_toml='\n[environment.env]\nHF_TOKEN = "${HF_TOKEN}"\nREGION = "${AWS_REGION:-us-west-2}"\n', ) - candidate = _candidate({"datasets": [{"path": str(dataset)}]}) + _patch_external_preflight(monkeypatch) - outcome = await validate.run_ladder(candidate, tmp_path) + outcome = await validate.run_ladder( + _candidate(tmp_path / "harbor-job.yaml", {"datasets": [{"path": str(dataset)}]}), tmp_path + ) - recorded = {item.name: item.default for item in outcome.required_env_vars} - assert recorded == {"HF_TOKEN": None, "AWS_REGION": "us-west-2"} - # Discover records what the repo demands; whether this host has it is doctor's job. - assert _finding(outcome, "credentials").status == "pass" + assert {item.name: item.default for item in outcome.required_env_vars} == { + "HF_TOKEN": None, + "AWS_REGION": "us-west-2", + } + assert _check(outcome, "credentials").status == "pass" -async def test_a_repo_wrapper_is_imported_and_sys_path_is_left_alone(tmp_path): +async def test_missing_custom_agent_import_is_recorded(tmp_path, monkeypatch): dataset = write_dataset(tmp_path / "evals" / "validation", count=1) - write_wrapper(tmp_path, class_name="TicketTriageAgent") - candidate = _candidate( - { - "agents": [{"import_path": "harbor_wrapper:TicketTriageAgent"}], - "datasets": [{"path": str(dataset)}], - }, - agent_search_path=".", + write_wrapper(tmp_path) + monkeypatch.setattr(sys, "path", [path for path in sys.path if path not in {"", str(tmp_path)}]) + monkeypatch.delitem(sys.modules, "harbor_wrapper", raising=False) + _patch_external_preflight(monkeypatch) + + outcome = await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", + {"agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], "datasets": [{"path": str(dataset)}]}, + ), + tmp_path, ) - before = list(sys.path) - outcome = await validate.run_ladder(candidate, tmp_path) + assert _check(outcome, "agent").status == "fail" - agent = _finding(outcome, "agent") - assert agent.status == "pass" - assert "TicketTriageAgent" in agent.message - assert sys.path == before, "the wrapper's directory must not be left on sys.path" +async def test_non_class_custom_agent_import_is_recorded(tmp_path, monkeypatch): + dataset = write_dataset(tmp_path / "evals" / "validation", count=1) + (tmp_path / "invalid_wrapper.py").write_text("def not_a_class():\n return None\n", encoding="utf-8") + monkeypatch.syspath_prepend(str(tmp_path)) + _patch_external_preflight(monkeypatch) + + outcome = await validate.run_ladder( + _candidate( + tmp_path / "harbor-job.yaml", + {"agents": [{"import_path": "invalid_wrapper:not_a_class"}], "datasets": [{"path": str(dataset)}]}, + ), + tmp_path, + ) -async def test_the_agent_rung_imports_only_from_the_search_path_the_artifact_records(tmp_path): - """The rung has to fail wherever the recorded command would. + assert _check(outcome, "agent").status == "fail" - Harbor imports through ``importlib`` and adds nothing to ``sys.path``, so a bare - ``harbor_wrapper:...`` resolves only from the directory the artifact tells a run to - export. A rung that goes looking for the file itself passes for a reason - ``harbor job start -c`` will not have, and that is precisely how an unimportable config - came to be published as runnable. - """ - dataset = write_dataset(tmp_path / "evals" / "validation", count=1) - write_wrapper(tmp_path / "src" / "myagent") - data = {"agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], "datasets": [{"path": str(dataset)}]} - reachable = await validate.run_ladder(_candidate(data, agent_search_path="src/myagent"), tmp_path) - assert _finding(reachable, "agent").status == "pass" +def test_custom_agent_import_system_exit_is_recorded(monkeypatch): + config = validate.JobConfig.model_validate({"agents": [{"import_path": "agent_module:Agent"}]}) + outcome = validate.ValidationOutcome() - unreachable = await validate.run_ladder(_candidate(data, agent_search_path="."), tmp_path) - agent = _finding(unreachable, "agent") - assert agent.status == "fail" - assert "No module named 'harbor_wrapper'" in agent.message - # The directory that would work is named, since the whole point is to be actionable. - assert agent.hint is not None and "PYTHONPATH=src/myagent" in agent.hint + def exit_import(*_args, **_kwargs): + raise SystemExit("agent stopped") + monkeypatch.setattr(validate, "import_class", exit_import) -async def test_an_agent_import_with_no_recorded_search_path_gets_no_help_finding_it(tmp_path): - """A config the repo maintains is validated with the environment a bare ``harbor`` has. + validate._check_agent(config, outcome) - Nothing about that config says where its module lives, so an import that only works - because discovery went hunting for the file is a verdict about this process rather than - about the run. - """ - dataset = write_dataset(tmp_path / "evals" / "validation", count=1) - write_wrapper(tmp_path) - candidate = _candidate( - {"agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], "datasets": [{"path": str(dataset)}]} + assert (_check(outcome, "agent").status, _check(outcome, "agent").message) == ( + "fail", + "Cannot import agent agent_module:Agent: SystemExit: agent stopped", ) - outcome = await validate.run_ladder(candidate, tmp_path) - agent = _finding(outcome, "agent") - assert agent.status == "fail" - assert agent.hint is not None and "PYTHONPATH=." in agent.hint +def test_custom_agent_import_keyboard_interrupt_propagates(monkeypatch): + config = validate.JobConfig.model_validate({"agents": [{"import_path": "agent_module:Agent"}]}) + outcome = validate.ValidationOutcome() + def interrupt_import(*_args, **_kwargs): + raise KeyboardInterrupt -async def test_a_second_repos_wrapper_is_not_shadowed_by_the_first(tmp_path): - """``harbor_wrapper`` is a convention, so two repos claim the same module name.""" - first, second = tmp_path / "first", tmp_path / "second" - for repo, class_name in ((first, "FirstAgent"), (second, "SecondAgent")): - write_dataset(repo / "evals" / "validation", count=1) - write_wrapper(repo, class_name=class_name) - - for repo, class_name in ((first, "FirstAgent"), (second, "SecondAgent")): - candidate = _candidate( - { - "agents": [{"import_path": f"harbor_wrapper:{class_name}"}], - "datasets": [{"path": str(repo / "evals/validation")}], - }, - agent_search_path=".", - ) - outcome = await validate.run_ladder(candidate, repo) - assert _finding(outcome, "agent").status == "pass", f"{class_name} was shadowed by a cached module" + monkeypatch.setattr(validate, "import_class", interrupt_import) + with pytest.raises(KeyboardInterrupt): + validate._check_agent(config, outcome) -async def test_a_module_left_in_sys_modules_cannot_stand_in_for_a_missing_one(tmp_path): - """Eviction is what keeps the rung honest once nothing is added to the path. - With the search path narrowed to one directory, a stale ``harbor_wrapper`` from an earlier - repo is the only way an unimportable config could still pass — the exact false verdict - this rung exists to prevent. - """ +async def test_custom_agent_import_does_not_reuse_another_repositorys_module(tmp_path, monkeypatch): first, second = tmp_path / "first", tmp_path / "second" - for repo in (first, second): - write_dataset(repo / "evals" / "validation", count=1) - write_wrapper(first) - - def candidate(repo): - return _candidate( - { - "agents": [{"import_path": "harbor_wrapper:WrappedAgent"}], - "datasets": [{"path": str(repo / "evals/validation")}], - }, - agent_search_path=".", + _patch_external_preflight(monkeypatch) + for repo, class_name in ((first, "FirstAgent"), (second, "SecondAgent")): + dataset = write_dataset(repo / "evals" / "validation", count=1) + write_wrapper(repo, class_name=class_name) + monkeypatch.syspath_prepend(str(repo)) + outcome = await validate.run_ladder( + _candidate( + repo / "harbor-job.yaml", + { + "agents": [{"import_path": f"harbor_wrapper:{class_name}"}], + "datasets": [{"path": str(dataset)}], + }, + ), + repo, ) + assert _check(outcome, "agent").status == "pass" - assert _finding(await validate.run_ladder(candidate(first), first), "agent").status == "pass" - - outcome = await validate.run_ladder(candidate(second), second) - - assert _finding(outcome, "agent").status == "fail", "the first repo's module answered for the second" - assert "harbor_wrapper" not in sys.modules - -async def test_a_wrapper_that_is_not_an_agent_is_a_warning_rather_than_a_failure(tmp_path): - """Harbor's own agent gate passes this, so failing it would block a repo Harbor runs. - - ``harbor/agents/factory.py`` calls ``import_class(import_path, label="agent")`` with no - ``base`` — strict for verifiers, deliberately not for agents. Still worth saying: the run - starts and then dies at trial time on a method the class does not have. - """ +async def test_backend_failure_is_recorded(tmp_path, monkeypatch): dataset = write_dataset(tmp_path / "evals" / "validation", count=1) - (tmp_path / "harbor_wrapper.py").write_text("class NotAnAgent:\n pass\n") - candidate = _candidate( - {"agents": [{"import_path": "harbor_wrapper:NotAnAgent"}], "datasets": [{"path": str(dataset)}]}, - agent_search_path=".", + _patch_external_preflight(monkeypatch) + monkeypatch.setattr( + validate.EnvironmentFactory, + "run_preflight", + lambda *args: (_ for _ in ()).throw(RuntimeError("no Docker")), ) - outcome = await validate.run_ladder(candidate, tmp_path) - - assert _finding(outcome, "agent").status == "pass" - base = _finding(outcome, "agent-base") - assert base.status == "warn" - assert base.harbor_call is None, "Harbor does not make this judgement, so it cannot be credited with it" - assert _repo_failures(outcome) == [] - - -async def test_an_import_path_naming_something_that_is_not_a_class_still_fails(tmp_path): - """The one thing ``import_class`` enforces without a ``base``, so it stays a failure.""" - dataset = write_dataset(tmp_path / "evals" / "validation", count=1) - (tmp_path / "harbor_wrapper.py").write_text("def not_a_class():\n return None\n") - candidate = _candidate( - {"agents": [{"import_path": "harbor_wrapper:not_a_class"}], "datasets": [{"path": str(dataset)}]}, - agent_search_path=".", + outcome = await validate.run_ladder( + _candidate(tmp_path / "harbor-job.yaml", {"datasets": [{"path": str(dataset)}]}), tmp_path ) - outcome = await validate.run_ladder(candidate, tmp_path) + assert _check(outcome, "backend").status == "fail" - agent = _finding(outcome, "agent") - assert agent.status == "fail" - assert agent.harbor_call == "import_class" +def test_config_file_round_trip_runs_harbor_cli(tmp_path, monkeypatch): + config_path = tmp_path / "harbor-job.yaml" + config_path.write_text("datasets: []\n", encoding="utf-8") + monkeypatch.setattr(validate, "_harbor_executable", lambda: "harbor") + calls = [] -async def test_an_unknown_builtin_agent_name_lists_the_valid_ones(tmp_path): - dataset = write_dataset(tmp_path / "evals" / "validation", count=1) - candidate = _candidate({"agents": [{"name": "not-an-agent"}], "datasets": [{"path": str(dataset)}]}) + def run(command, **kwargs): + calls.append((command, kwargs["cwd"])) + return subprocess.CompletedProcess(command, 0, "", "") - outcome = await validate.run_ladder(candidate, tmp_path) + monkeypatch.setattr(subprocess, "run", run) - agent = _finding(outcome, "agent") - assert agent.status == "fail" - assert agent.hint is not None and "oracle" in agent.hint + assert validate.check_config_file(config_path, tmp_path).status == "pass" + assert calls == [(["harbor", "job", "start", "--print-config", "-c", str(config_path)], tmp_path)] -async def test_the_persisted_config_is_checked_through_the_harbor_cli(tmp_path): - dataset = write_dataset(tmp_path / "evals" / "validation", count=1) +def test_config_file_round_trip_reports_harbor_rejection(tmp_path, monkeypatch): config_path = tmp_path / "harbor-job.yaml" - config_path.write_text(f"datasets:\n- path: {dataset}\n") + config_path.write_text("datasets: []\n", encoding="utf-8") + monkeypatch.setattr(validate, "_harbor_executable", lambda: "harbor") - finding = validate.check_config_file(config_path, tmp_path) + def reject(command, **_kwargs): + return subprocess.CompletedProcess(command, 1, "", "invalid config\n") - assert finding.status in {"pass", "warn"} - if finding.status == "pass": - assert finding.harbor_call == "harbor job start --print-config" - - -async def test_a_config_the_cli_rejects_fails_the_round_trip(tmp_path): - config_path = tmp_path / "harbor-job.yaml" - config_path.write_text("datasets: not-a-list\n") + monkeypatch.setattr(subprocess, "run", reject) finding = validate.check_config_file(config_path, tmp_path) - if finding.status != "warn": # warn means no harbor executable on PATH - assert finding.status == "fail" - assert finding.path == config_path - - -async def test_the_round_trip_uses_the_harbor_that_produced_every_other_verdict(tmp_path): - """A ``uv tool`` or ``pipx`` install shadows the environment's own console script. - - The report stamps one Harbor version, so a round trip resolved off bare ``PATH`` can - contradict the rest of the ladder while claiming to agree with it. - """ - resolved = validate._harbor_executable() - - assert resolved is not None, "the environment running these tests installs harbor" - assert Path(resolved).parent == Path(sys.executable).parent - completed = subprocess.run([resolved, "--version"], capture_output=True, text=True, check=True) - assert completed.stdout.strip() == version("harbor"), "the CLI and the imported package must be one Harbor" - - -async def test_the_full_pipeline_agrees_with_the_source_it_chose(tmp_path): - """Sources and the ladder have to compose: what was assembled is what gets validated.""" - write_dataset(tmp_path / "evals" / "validation") - write_wrapper(tmp_path) - - candidate, _ = sources.find_candidate(tmp_path) - assert candidate is not None - outcome = await validate.run_ladder(candidate, tmp_path) - - assert _repo_failures(outcome) == [] - assert outcome.config is not None - assert outcome.config.agents[0].import_path == "harbor_wrapper:WrappedAgent" - - -async def test_the_full_pipeline_carries_a_nested_wrapper_s_search_path_through_the_ladder(tmp_path): - """The case the bare import path dropped on the floor. - - ``_find_wrapper`` walks the repo, so the wrapper it finds need not be at the root, and the - emitted ``harbor_wrapper:WrappedAgent`` says nothing about where it was. Assembly and the - ladder have to agree on the directory or the ladder is judging a different config. - """ - write_dataset(tmp_path / "evals" / "validation", count=1) - write_wrapper(tmp_path / "src" / "myagent") - - candidate, _ = sources.find_candidate(tmp_path) - assert candidate is not None - assert candidate.agent_search_path == "src/myagent" - - outcome = await validate.run_ladder(candidate, tmp_path) - - assert _repo_failures(outcome) == [] - assert _finding(outcome, "agent").status == "pass" + assert (finding.status, finding.message) == ("fail", "The Harbor CLI rejected the config: invalid config.") diff --git a/plugins/nemo-eval-author/tests/harbor_fixtures.py b/plugins/nemo-eval-author/tests/harbor_fixtures.py index 16eb4b6cc8c..923af747106 100644 --- a/plugins/nemo-eval-author/tests/harbor_fixtures.py +++ b/plugins/nemo-eval-author/tests/harbor_fixtures.py @@ -1,31 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Builders for real Harbor task directories, plus a stub platform client. - -The discovery tests assert against Harbor's actual validators rather than against our -reading of them, which only works if the fixtures are things Harbor genuinely accepts. So -these write the same layout ``harbor task create`` produces — ``task.toml``, -``instruction.md``, ``environment/Dockerfile``, ``tests/test.sh``, ``solution/solve.sh`` — -and the interesting cases are departures from it. - -Imported as a module rather than declared as fixtures in ``conftest.py`` because the -builders take arguments; a test that needs a Windows task with no reward script should say -so at the call site instead of composing four fixtures to get there. - -Lives here rather than beside its tests in ``discover/`` because the repo-root -``conftest.py`` forces ``importmode = "importlib"``, under which pytest puts no test -directory on ``sys.path``. Only ``tests/`` ends up there, and only because pytest loads that -directory's ``conftest.py`` during startup while prepend mode is still in effect. A helper -one level down imports fine from within the plugin and fails the moment CI runs from the -repo root. - -Nor is it named ``fixtures.py``, tempting as that is: every plugin's ``tests/`` is on -``sys.path`` in that same root-config run, so a bare ``fixtures`` would bind to whichever -plugin's copy imported first, silently and with no collision error. -""" - -import json +"""Harbor task builders and platform stubs.""" + from pathlib import Path from typing import Any @@ -33,11 +10,6 @@ def read_front_matter(text: str | bytes) -> dict[str, Any]: - """Parse the YAML front matter of a rendered report. - - Lives here rather than in the plugin because only tests read a report back; the - artifact's consumer is a later agent outside this codebase. - """ if isinstance(text, bytes): text = text.decode("utf-8") assert text.startswith("---\n"), f"no front matter in {text[:40]!r}" @@ -46,117 +18,46 @@ def read_front_matter(text: str | bytes) -> dict[str, Any]: return payload -WRITES_REWARD = "#!/bin/bash\necho 1 > /logs/verifier/reward.txt\n" - -# What Harbor's own template ships: a comment telling the author to write a reward, and no -# code that does. A task scaffolded and abandoned looks exactly like this. -MENTIONS_REWARD_IN_COMMENT = "#!/bin/bash\n\n# Make sure to output a reward to /logs/verifier/reward.txt.\n" - -_DOCKERFILE = "FROM ubuntu:24.04\n\nWORKDIR /app\n" -_SOLVE = "#!/bin/bash\necho solved\n" - - def write_task( task_dir: Path, *, task_toml: str = "", instruction: str | None = "Do the thing.\n", - test_script: str | None = WRITES_REWARD, - test_name: str = "test.sh", - environment: bool = True, - steps: dict[str, dict[str, str | None]] | None = None, -) -> Path: - """Write a Harbor task directory, defaulting to one Harbor accepts. - - Args: - task_toml: TOML appended after the version line. The baseline deliberately declares - no sections, so a caller can add ``[environment]`` or ``[verifier]`` without - colliding with a duplicate table. - instruction: Root ``instruction.md`` contents; ``None`` to omit it. - test_script: Root ``tests/`` script contents; ``None`` to omit it. - test_name: Root test filename, so a Windows task can ask for ``test.bat``. - environment: Whether to write ``environment/Dockerfile``. - steps: Multi-step layout as ``{step_name: {"instruction": ..., "test": ...}}``, - where a ``None`` value omits that file. - """ +) -> None: task_dir.mkdir(parents=True, exist_ok=True) (task_dir / "task.toml").write_text(f'version = "1.0"\n{task_toml}', encoding="utf-8") if instruction is not None: (task_dir / "instruction.md").write_text(instruction, encoding="utf-8") - if environment: - (task_dir / "environment").mkdir(exist_ok=True) - (task_dir / "environment" / "Dockerfile").write_text(_DOCKERFILE, encoding="utf-8") - if test_script is not None: - (task_dir / "tests").mkdir(exist_ok=True) - (task_dir / "tests" / test_name).write_text(test_script, encoding="utf-8") - - (task_dir / "solution").mkdir(exist_ok=True) - (task_dir / "solution" / "solve.sh").write_text(_SOLVE, encoding="utf-8") - - for name, files in (steps or {}).items(): - step_dir = task_dir / "steps" / name - step_dir.mkdir(parents=True, exist_ok=True) - if files.get("instruction") is not None: - (step_dir / "instruction.md").write_text(str(files["instruction"]), encoding="utf-8") - if files.get("test") is not None: - (step_dir / "tests").mkdir(exist_ok=True) - (step_dir / "tests" / "test.sh").write_text(str(files["test"]), encoding="utf-8") - return task_dir - - -def write_dataset(root: Path, *, count: int = 2, test_script: str = WRITES_REWARD) -> Path: - """A directory of sibling task dirs, which is what Harbor treats as a dataset.""" + (task_dir / "environment").mkdir(exist_ok=True) + (task_dir / "environment" / "Dockerfile").write_text("FROM ubuntu:24.04\n\nWORKDIR /app\n", encoding="utf-8") + (task_dir / "tests").mkdir(exist_ok=True) + (task_dir / "tests" / "test.sh").write_text("#!/bin/bash\necho 1 > /logs/verifier/reward.txt\n", encoding="utf-8") + + +def write_dataset(root: Path, *, count: int = 2) -> Path: for index in range(count): - write_task(root / f"task-{index}", test_script=test_script) + write_task(root / f"task-{index}") return root -def write_wrapper(wrapper_dir: Path, *, class_name: str = "WrappedAgent", base: str = "BaseAgent") -> Path: - """A ``harbor_wrapper.py`` holding a real ``BaseAgent`` subclass. - - *wrapper_dir* is created if needed, because a wrapper nested under ``src/`` is the case - that separates the module's directory from the repo root. - """ +def write_wrapper(wrapper_dir: Path, *, class_name: str = "WrappedAgent") -> None: wrapper_dir.mkdir(parents=True, exist_ok=True) - path = wrapper_dir / "harbor_wrapper.py" - path.write_text( - f"from harbor.agents.base import {base}\n\n\n" - f"class {class_name}({base}):\n" - " @staticmethod\n" - " def name() -> str:\n" - f" return {class_name.lower()!r}\n\n" - " async def setup(self, environment):\n" - " return None\n\n" - " async def run(self, instruction, environment):\n" - " return None\n", + (wrapper_dir / "harbor_wrapper.py").write_text( + f"from harbor.agents.base import BaseAgent\n\n\nclass {class_name}(BaseAgent):\n pass\n", encoding="utf-8", ) - return path -def write_job_config(path: Path, *, dataset: str, agent: dict[str, Any] | None = None) -> Path: - """A job config of the kind a repo maintains itself, which is what ``-c`` takes.""" +def write_job_config(path: Path, *, dataset: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) - payload = {"agents": [agent or {"name": "oracle"}], "datasets": [{"path": dataset}]} + payload = {"agents": [{"name": "oracle"}], "datasets": [{"path": dataset}]} path.write_text(yaml.safe_dump(payload), encoding="utf-8") - return path - - -def write_job_dir(root: Path, *, config: dict[str, Any], with_lock: bool = True) -> Path: - """A completed Harbor job directory, which is a config Harbor already resolved.""" - root.mkdir(parents=True, exist_ok=True) - (root / "config.json").write_text(json.dumps(config), encoding="utf-8") - if with_lock: - (root / "lock.json").write_text(json.dumps({"harbor_version": "0.18.0"}), encoding="utf-8") - return root class StubFiles: - """Records uploads and serves whatever was uploaded before, like the real thing.""" - - def __init__(self, stored: dict[str, bytes] | None = None, fail: bool = False) -> None: - self.stored: dict[str, bytes] = dict(stored or {}) + def __init__(self, fail: bool = False) -> None: + self.stored: dict[str, bytes] = {} self.uploads: list[dict[str, Any]] = [] self.fail = fail @@ -166,50 +67,11 @@ async def upload_content(self, *, content: bytes, remote_path: str, **kwargs: An self.uploads.append({"remote_path": remote_path, "content": content, **kwargs}) self.stored[remote_path] = content - async def download_content(self, *, remote_path: str, **kwargs: Any) -> bytes: - if remote_path not in self.stored: - raise FileNotFoundError(remote_path) - return self.stored[remote_path] - class StubClient: - """The narrow slice of ``AsyncNeMoPlatform`` discovery touches.""" - - def __init__(self, files: StubFiles | None = None, trace_total: int | None = 3) -> None: + def __init__(self, files: StubFiles | None = None) -> None: self.files = files or StubFiles() - self.intake = _StubIntake(trace_total) self.closed = False async def close(self) -> None: self.closed = True - - -class _StubIntake: - def __init__(self, total: int | None) -> None: - self.spans = _StubSpans(total) - - -class _StubSpans: - def __init__(self, total: int | None) -> None: - self.groups = _StubGroups(total) - - -class _StubGroups: - def __init__(self, total: int | None) -> None: - self._total = total - - async def list(self, **kwargs: Any) -> Any: - if self._total is None: - raise RuntimeError("intake unreachable") - return _StubPage(self._total) - - -class _StubPage: - def __init__(self, total: int) -> None: - self.data = [object()] * min(total, 1) - self.pagination = _StubPagination(total) - - -class _StubPagination: - def __init__(self, total: int) -> None: - self.total_results = total diff --git a/plugins/nemo-eval-author/tests/test_cli.py b/plugins/nemo-eval-author/tests/test_cli.py index 4c2137ecd41..d42d8b0f796 100644 --- a/plugins/nemo-eval-author/tests/test_cli.py +++ b/plugins/nemo-eval-author/tests/test_cli.py @@ -1,18 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Scaffolding tests: the command tree exists, and unimplemented verbs still refuse to run. - -The entry-point cases cover the ``pyproject.toml`` wiring that nothing else exercises. A -typo in the key or the import path does not fail an import; it just makes ``nemo -agents eval-author`` quietly missing from the CLI, which no unit test of this module would -catch. - -``discover`` has shipped, so it is asserted on in ``discover/test_command.py`` instead. It -is listed in ``_IMPLEMENTED_VERBS`` here only so ``--help`` still has to show it. -""" - -from importlib.metadata import EntryPoint, entry_points +"""Command-tree and placeholder tests.""" import pytest import typer @@ -21,67 +10,27 @@ runner = CliRunner() -# Each verb is a placeholder owned by the child ticket named beside it. -_PLACEHOLDER_VERBS = [ - ("audit", "ASE-676"), - ("propose", "ASE-675"), - ("run", "ASE-673"), - ("doctor", "ASE-678"), -] - -_IMPLEMENTED_VERBS = ["discover"] - @pytest.fixture def app() -> typer.Typer: return cli.EvalAuthorCLI().get_cli() -def _eval_author_entry_point() -> EntryPoint: - matches = [entry for entry in entry_points(group="nemo.cli.agents") if entry.name == "eval-author"] - assert matches, "no nemo.cli.agents entry point named 'eval-author'; reinstall the plugin with uv sync" - return matches[0] - - -def test_help_lists_every_verb(app: typer.Typer) -> None: +def test_help_lists_discover(app: typer.Typer) -> None: result = runner.invoke(app, ["--help"]) assert result.exit_code == 0, result.output - for command in [*(name for name, _ in _PLACEHOLDER_VERBS), *_IMPLEMENTED_VERBS]: - assert command in result.output - - -@pytest.mark.parametrize(("command", "ticket"), _PLACEHOLDER_VERBS) -def test_verb_refuses_to_run_and_names_its_ticket(app: typer.Typer, command: str, ticket: str) -> None: - result = runner.invoke(app, [command]) - - assert result.exit_code == 1, result.output - assert ticket in result.output - - -def test_not_implemented_quotes_the_invoked_command_path() -> None: - """Placeholder messages use ``ctx.command_path``, not a hardcoded CLI string.""" - app = typer.Typer() - - @app.callback() - def _root() -> None: - """Force subcommand dispatch.""" - - @app.command("probe") - def probe(ctx: typer.Context) -> None: - cli._not_implemented(ctx, "ASE-000") - - result = runner.invoke(app, ["probe"], prog_name="nemo") - - assert result.exit_code == 1, result.output - assert "`nemo probe` is not implemented yet (ASE-000)." in result.output - + assert "discover" in result.output -def test_entry_point_key_matches_the_cli_name() -> None: - """Discovery rejects a plugin whose entry-point key differs from its ``name``.""" - assert _eval_author_entry_point().value == "nemo_eval_author_plugin.cli:EvalAuthorCLI" - assert cli.EvalAuthorCLI.name == "eval-author" +def test_placeholder_verbs_refuse_to_run_and_name_their_tickets(app: typer.Typer) -> None: + for command, ticket in ( + ("audit", "ASE-676"), + ("propose", "ASE-675"), + ("run", "ASE-673"), + ("doctor", "ASE-678"), + ): + result = runner.invoke(app, [command]) -def test_entry_point_loads_the_cli_class() -> None: - assert _eval_author_entry_point().load() is cli.EvalAuthorCLI + assert result.exit_code == 1, result.output + assert ticket in result.output From bc6a550a11f7fe2297c4c8447e62b9b9669ea4fe Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Mon, 10 Aug 2026 14:37:54 -0500 Subject: [PATCH 14/15] feat(eval-author): discover hosted agent doctrine Signed-off-by: Alec Khoury --- .../discovery/report.py | 4 +-- .../nemo_eval_author_plugin/discovery/run.py | 7 ++++- .../nemo_eval_author_plugin/discovery/scan.py | 28 ++++++++++--------- .../tests/discover/test_command.py | 18 ++++++++++++ .../tests/discover/test_report.py | 2 +- .../tests/discover/test_scan.py | 2 +- .../nemo-eval-author/tests/harbor_fixtures.py | 3 ++ 7 files changed, 46 insertions(+), 18 deletions(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py index fe5d722e4eb..b621ce41c50 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py @@ -25,7 +25,7 @@ class DiscoveryReport: repo_root: Path config_path: Path | None dataset_paths: list[Path] - ethos_path: Path | None + ethos_path: str | None harbor_version: str required_env_vars: list[RequiredEnvVar] discovered_at: datetime @@ -105,7 +105,7 @@ def _front_matter(report: DiscoveryReport) -> dict[str, Any]: "config_path": _display_path(report.config_path, report.repo_root), "dataset_paths": [_display_path(path, report.repo_root) for path in report.dataset_paths], "run_command": report.run_command, - "ethos_path": _display_path(report.ethos_path, report.repo_root), + "ethos_path": report.ethos_path, "harbor_version": report.harbor_version, "required_env_vars": [ { diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py index c227f3d097c..0320a204d88 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -63,7 +63,12 @@ async def _discover( agent: str, workspace: str, ) -> DiscoverResult: - scan_result = scan.scan_repository(repo_root) + ref = f"{workspace}/{agent}-spec#AGENT-SPEC.md" + try: + platform_ethos = (ref, await client.files.download_content(remote_path=ref)) + except Exception: + platform_ethos = None + scan_result = scan.scan_repository(repo_root, platform_ethos=platform_ethos) validation = validate.ValidationOutcome() if scan_result.config is not None: validation = await validate.run_ladder(scan_result.config, repo_root) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py index 457458f1f0a..16f7e573e0d 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py @@ -54,7 +54,7 @@ class RepositoryScan: config: ConfigCandidate | None dataset_paths: list[Path] - ethos_path: Path | None + ethos_path: str | None fingerprint: str input_file_count: int checks: list[CheckResult] @@ -78,7 +78,7 @@ def walk_dirs(root: Path) -> Iterator[Path]: yield Path(current) -def scan_repository(repo_root: Path) -> RepositoryScan: +def scan_repository(repo_root: Path, *, platform_ethos: tuple[str, bytes] | None = None) -> RepositoryScan: """Find one repo-owned config and local Harbor datasets.""" repo_root = repo_root.resolve() candidates = _config_candidates(repo_root) @@ -107,11 +107,12 @@ def scan_repository(repo_root: Path) -> RepositoryScan: ) ) - ethos_path = repo_root / "ETHOS.md" - if ethos_path.is_file(): - checks.append(_check("ethos", "pass", "ETHOS.md defines the agent doctrine.", severity="advisory")) + ethos = platform_ethos + if ethos is None and (repo_root / "ETHOS.md").is_file(): + ethos = ("ETHOS.md", (repo_root / "ETHOS.md").read_bytes()) + if ethos is not None: + checks.append(_check("ethos", "pass", f"{ethos[0]} defines the agent doctrine.", severity="advisory")) else: - ethos_path = None checks.append( _check( "ethos", @@ -123,8 +124,8 @@ def scan_repository(repo_root: Path) -> RepositoryScan: ) datasets = _dataset_paths(repo_root) - fingerprint, count = _fingerprint(repo_root, config.path if config else None, ethos_path, datasets) - return RepositoryScan(config, datasets, ethos_path, fingerprint, count, checks) + fingerprint, count = _fingerprint(repo_root, config.path if config else None, ethos, datasets) + return RepositoryScan(config, datasets, ethos[0] if ethos else None, fingerprint, count, checks) def _config_candidates(repo_root: Path) -> list[ConfigCandidate]: @@ -171,17 +172,16 @@ def _dataset_paths(repo_root: Path) -> list[Path]: def _fingerprint( repo_root: Path, config_path: Path | None, - ethos_path: Path | None, + ethos: tuple[str, bytes] | None, datasets: list[Path], ) -> tuple[str, int]: - files: set[Path] = { - path for path in (config_path, ethos_path, repo_root / "optimizer.yaml") if path and path.is_file() - } + files: set[Path] = {path for path in (config_path, repo_root / "optimizer.yaml") if path and path.is_file()} for dataset in datasets: if not dataset.is_relative_to(repo_root): continue for directory in walk_dirs(dataset): files.update(path for path in directory.iterdir() if path.is_file()) + files.discard(repo_root / "ETHOS.md") digest = hashlib.sha256() for path in sorted(files): @@ -189,7 +189,9 @@ def _fingerprint( digest.update(b"\0") digest.update(path.read_bytes()) digest.update(b"\0") - return digest.hexdigest(), len(files) + if ethos is not None: + digest.update(ethos[0].encode() + b"\0" + ethos[1] + b"\0") + return digest.hexdigest(), len(files) + (ethos is not None) async def probe_traces(client: Any, *, agent: str, workspace: str) -> CheckResult: diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index 8ee47f12618..36b06ec6aa0 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -65,6 +65,24 @@ def _snapshot(root: Path) -> list[tuple[str, bytes | None]]: ] +def test_command_reads_the_canonical_platform_agent_spec(app, client, monkeypatch, tmp_path): + repo = _healthy_repo(tmp_path / "agent-repo") + (repo / "ETHOS.md").write_text("# Local\n", encoding="utf-8") + ref = f"default/{AGENT}-spec#AGENT-SPEC.md" + download = AsyncMock(side_effect=[b"# Platform one\n", b"# Platform two\n"]) + monkeypatch.setattr(client.files, "download_content", download) + + first = _invoke(app, repo, "--agent", AGENT) + first_front = read_front_matter(client.files.stored[f"{AGENT}/discovery.md"]) + second = _invoke(app, repo, "--agent", AGENT) + second_front = read_front_matter(client.files.stored[f"{AGENT}/discovery.md"]) + + assert (first.exit_code, second.exit_code) == (0, 0) + assert first_front["ethos_path"] == ref + assert first_front["fingerprint"] != second_front["fingerprint"] + assert [awaited.kwargs for awaited in download.await_args_list] == [{"remote_path": ref}] * 2 + + def test_healthy_config_uploads_only_discovery_report_and_does_not_write_to_repo(app, client, tmp_path): repo = _healthy_repo(tmp_path / "agent-repo") before = _snapshot(repo) diff --git a/plugins/nemo-eval-author/tests/discover/test_report.py b/plugins/nemo-eval-author/tests/discover/test_report.py index 5ed08c4aec8..fcc17899f17 100644 --- a/plugins/nemo-eval-author/tests/discover/test_report.py +++ b/plugins/nemo-eval-author/tests/discover/test_report.py @@ -30,7 +30,7 @@ def _record(tmp_path, *, config: bool = True, checks: list[CheckResult] | None = repo_root=root, config_path=root / "configs" / "eval.yaml" if config else None, dataset_paths=[root / "evals" / "validation"], - ethos_path=root / "ETHOS.md", + ethos_path="ETHOS.md", harbor_version="0.18.0", required_env_vars=[ RequiredEnvVar(name="HF_TOKEN", default=None, declared_in=root / "evals" / "validation" / "task.toml") diff --git a/plugins/nemo-eval-author/tests/discover/test_scan.py b/plugins/nemo-eval-author/tests/discover/test_scan.py index d8f60e41e46..a2aed05312f 100644 --- a/plugins/nemo-eval-author/tests/discover/test_scan.py +++ b/plugins/nemo-eval-author/tests/discover/test_scan.py @@ -89,7 +89,7 @@ def test_uses_only_ethos_for_the_doctrine_contract(tmp_path): ethos.write_text("# Agent doctrine\n", encoding="utf-8") with_ethos = scan.scan_repository(tmp_path) - assert with_ethos.ethos_path == ethos + assert with_ethos.ethos_path == "ETHOS.md" assert any(check.name == "ethos" and check.status == "pass" for check in with_ethos.checks) diff --git a/plugins/nemo-eval-author/tests/harbor_fixtures.py b/plugins/nemo-eval-author/tests/harbor_fixtures.py index 923af747106..c3f21b92e2e 100644 --- a/plugins/nemo-eval-author/tests/harbor_fixtures.py +++ b/plugins/nemo-eval-author/tests/harbor_fixtures.py @@ -61,6 +61,9 @@ def __init__(self, fail: bool = False) -> None: self.uploads: list[dict[str, Any]] = [] self.fail = fail + async def download_content(self, *, remote_path: str) -> bytes: + raise FileNotFoundError(remote_path) + async def upload_content(self, *, content: bytes, remote_path: str, **kwargs: Any) -> None: if self.fail: raise RuntimeError("fileset unavailable") From 22e9d0665019008037f73f5a95baf60bed6f9bb3 Mon Sep 17 00:00:00 2001 From: Alec Khoury Date: Mon, 10 Aug 2026 21:43:37 -0500 Subject: [PATCH 15/15] feat(eval-author): discover every Harbor config Validate and report each repository-owned entrypoint so multi-suite repositories do not hide unsupported configurations. Signed-off-by: Alec Khoury --- .../discovery/report.py | 96 +++++++++++--- .../nemo_eval_author_plugin/discovery/run.py | 8 +- .../nemo_eval_author_plugin/discovery/scan.py | 72 ++++++----- .../tests/discover/test_command.py | 47 ++++++- .../tests/discover/test_report.py | 121 ++++++++++++++++-- .../tests/discover/test_scan.py | 40 ++++-- 6 files changed, 300 insertions(+), 84 deletions(-) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py index b621ce41c50..a241c891012 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/report.py @@ -16,6 +16,21 @@ from nemo_insights_plugin.contracts.checks import CheckResult, format_report, required_failures +@dataclass +class ConfigReport: + """Preflight results for one Harbor config.""" + + name: str + path: Path + required_env_vars: list[RequiredEnvVar] + checks: list[CheckResult] + + @property + def runnable(self) -> bool: + """Return whether the config passed all required checks.""" + return not required_failures(self.checks) + + @dataclass class DiscoveryReport: """Repository facts and current Harbor preflight results.""" @@ -23,28 +38,43 @@ class DiscoveryReport: agent: str workspace: str repo_root: Path - config_path: Path | None + configs: list[ConfigReport] dataset_paths: list[Path] ethos_path: str | None harbor_version: str - required_env_vars: list[RequiredEnvVar] discovered_at: datetime fingerprint: str input_file_count: int - checks: list[CheckResult] + repository_checks: list[CheckResult] + trace_check: CheckResult schema_version: int = field(init=False, default=1) @property def runnable(self) -> bool: - """Return whether the repository-owned config passed all required checks.""" - return self.config_path is not None and not required_failures(self.checks) + """Return whether all repository-owned configs passed required checks.""" + return bool(self.configs) and all(config.runnable for config in self.configs) + + @property + def checks(self) -> list[CheckResult]: + """Return repository, config, and trace checks in execution order.""" + checks = list(self.repository_checks) + for config in self.configs: + checks.extend(config.checks) + checks.append(self.trace_check) + return checks @property def run_command(self) -> str | None: - """Return the Harbor command only for a runnable repository config.""" - if not self.runnable or self.config_path is None: + """Return the Harbor command only for one runnable config.""" + if len(self.configs) != 1: + return None + return self.run_command_for(self.configs[0]) + + def run_command_for(self, config: ConfigReport) -> str | None: + """Return the Harbor command for one runnable config.""" + if not config.runnable: return None - config_path = self.config_path.resolve().relative_to(self.repo_root.resolve()).as_posix() + config_path = config.path.resolve().relative_to(self.repo_root.resolve()).as_posix() cd_command = shlex.join(["cd", str(self.repo_root.resolve())]) harbor_command = shlex.join(["harbor", "job", "start", "-c", config_path]) return f"{cd_command} && {harbor_command}" @@ -61,24 +91,33 @@ def build_report( workspace: str, repo_root: Path, scan_result: RepositoryScan, - validation: ValidationOutcome, + validations: list[ValidationOutcome], trace_check: CheckResult, discovered_at: datetime | None = None, ) -> DiscoveryReport: - """Build one report from the repository scan and current preflight.""" + """Build one report from the repository scan and config preflights.""" + configs = [ + ConfigReport( + name=candidate.name, + path=candidate.path, + required_env_vars=validation.required_env_vars, + checks=validation.checks, + ) + for candidate, validation in zip(scan_result.configs, validations, strict=True) + ] return DiscoveryReport( agent=agent, workspace=workspace, repo_root=repo_root.resolve(), - config_path=scan_result.config.path if scan_result.config else None, + configs=configs, dataset_paths=scan_result.dataset_paths, ethos_path=scan_result.ethos_path, harbor_version=harbor_version(), - required_env_vars=validation.required_env_vars, discovered_at=discovered_at or datetime.now(UTC), fingerprint=f"sha256:{scan_result.fingerprint}", input_file_count=scan_result.input_file_count, - checks=[*scan_result.checks, *validation.checks, trace_check], + repository_checks=scan_result.checks, + trace_check=trace_check, ) @@ -86,23 +125,43 @@ def render_markdown(report: DiscoveryReport) -> str: """Render YAML front matter and a concise status report.""" front = yaml.safe_dump(_front_matter(report), sort_keys=False, default_flow_style=False).rstrip() lines = [f"# Discovery report for `{report.agent}`"] - status = format_report(report.checks) + status = format_report([*report.repository_checks, report.trace_check]) if status: lines.extend(["", "```text", status, "```"]) - if report.run_command: - lines.extend(["", "## Run", "", "```bash", report.run_command, "```"]) + if report.configs: + lines.extend(["", "## Harbor entrypoints"]) + for config in report.configs: + path = _display_path(config.path, report.repo_root) + lines.extend( + [ + "", + f"### `{config.name}` (`{path}`)", + "", + f"Runnable: {'true' if config.runnable else 'false'}", + "", + "```text", + format_report(config.checks), + "```", + ] + ) + if command := report.run_command_for(config): + lines.extend(["", "```bash", command, "```"]) body = "\n".join(lines) return f"---\n{front}\n---\n\n{body}\n" def _front_matter(report: DiscoveryReport) -> dict[str, Any]: + config = report.configs[0] if len(report.configs) == 1 else None return { "schema_version": report.schema_version, "agent": report.agent, "workspace": report.workspace, "repo_root": str(report.repo_root), "runnable": report.runnable, - "config_path": _display_path(report.config_path, report.repo_root), + "configs": [ + {"name": config.name, "path": _display_path(config.path, report.repo_root)} for config in report.configs + ], + "config_path": _display_path(config.path if config is not None else None, report.repo_root), "dataset_paths": [_display_path(path, report.repo_root) for path in report.dataset_paths], "run_command": report.run_command, "ethos_path": report.ethos_path, @@ -113,7 +172,8 @@ def _front_matter(report: DiscoveryReport) -> dict[str, Any]: "default": item.default, "declared_in": _display_path(item.declared_in, report.repo_root), } - for item in report.required_env_vars + for config in report.configs + for item in config.required_env_vars ], "discovered_at": report.discovered_at.isoformat(), "fingerprint": report.fingerprint, diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py index 0320a204d88..016c1e04018 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/run.py @@ -44,7 +44,7 @@ def ok(self) -> bool: async def discover(options: DiscoverOptions) -> DiscoverResult: - """Scan, revalidate, report, and optionally upload one repository.""" + """Scan, validate, report, and optionally upload one repository.""" repo_root = options.repo_root.resolve() agent = _slug(options.agent) if options.agent is not None else _infer_agent_name(repo_root) workspace = _active_workspace() @@ -69,16 +69,14 @@ async def _discover( except Exception: platform_ethos = None scan_result = scan.scan_repository(repo_root, platform_ethos=platform_ethos) - validation = validate.ValidationOutcome() - if scan_result.config is not None: - validation = await validate.run_ladder(scan_result.config, repo_root) + validations = [await validate.run_ladder(config, repo_root) for config in scan_result.configs] trace_check = await scan.probe_traces(client, agent=agent, workspace=workspace) record = report.build_report( agent=agent, workspace=workspace, repo_root=repo_root, scan_result=scan_result, - validation=validation, + validations=validations, trace_check=trace_check, ) markdown = report.render_markdown(record) diff --git a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py index 16f7e573e0d..be90dcc3106 100644 --- a/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py +++ b/plugins/nemo-eval-author/src/nemo_eval_author_plugin/discovery/scan.py @@ -14,8 +14,8 @@ import yaml from nemo_insights_plugin.contracts.checks import CheckResult, CheckSeverity, CheckStatus -_CONFIG_DIRS = ("configs", ".", "harbor", ".harbor", "evals") _CONFIG_SUFFIXES = (".yaml", ".yml", ".json") +_MAX_CONFIG_DEPTH = 4 _PRUNE_DIR_NAMES = frozenset( { ".git", @@ -36,6 +36,7 @@ "build", "eval-and-optimize", ".nemo-optimizer", + "jobs", } ) @@ -47,12 +48,18 @@ class ConfigCandidate: path: Path data: dict[str, Any] + @property + def name(self) -> str: + """Return the declared job name or the file name.""" + job_name = self.data.get("job_name") + return job_name.strip() if isinstance(job_name, str) and job_name.strip() else self.path.name + @dataclass class RepositoryScan: """The repository facts that the validation ladder needs.""" - config: ConfigCandidate | None + configs: list[ConfigCandidate] dataset_paths: list[Path] ethos_path: str | None fingerprint: str @@ -71,20 +78,23 @@ def _check( return CheckResult(name=name, group="repository", status=status, severity=severity, message=message, hint=hint) -def walk_dirs(root: Path) -> Iterator[Path]: +def walk_dirs(root: Path, *, max_depth: int | None = None) -> Iterator[Path]: """Yield repository directories and skip generated trees.""" for current, dir_names, _ in os.walk(root): - dir_names[:] = sorted(name for name in dir_names if name not in _PRUNE_DIR_NAMES) - yield Path(current) + directory = Path(current) + depth = len(directory.relative_to(root).parts) + dir_names[:] = sorted( + name for name in dir_names if name not in _PRUNE_DIR_NAMES and (max_depth is None or depth < max_depth) + ) + yield directory def scan_repository(repo_root: Path, *, platform_ethos: tuple[str, bytes] | None = None) -> RepositoryScan: - """Find one repo-owned config and local Harbor datasets.""" + """Find repo-owned configs and local Harbor datasets.""" repo_root = repo_root.resolve() - candidates = _config_candidates(repo_root) + configs = _config_candidates(repo_root) checks: list[CheckResult] = [] - config = candidates[0] if candidates else None - if config is None: + if not configs: checks.append( _check( "config", @@ -94,17 +104,9 @@ def scan_repository(repo_root: Path, *, platform_ethos: tuple[str, bytes] | None ) ) else: - checks.append(_check("config", "pass", f"Using Harbor config {config.path.relative_to(repo_root)}.")) - if len(candidates) > 1: - extras = ", ".join(str(item.path.relative_to(repo_root)) for item in candidates[1:]) + count = len(configs) checks.append( - _check( - "config", - "warn", - f"More Harbor config files exist: {extras}.", - severity="advisory", - hint="Discovery uses the first file in its fixed search order.", - ) + _check("config", "pass", f"Found {count} repository-owned Harbor config file{'s' if count != 1 else ''}.") ) ethos = platform_ethos @@ -124,28 +126,26 @@ def scan_repository(repo_root: Path, *, platform_ethos: tuple[str, bytes] | None ) datasets = _dataset_paths(repo_root) - fingerprint, count = _fingerprint(repo_root, config.path if config else None, ethos, datasets) - return RepositoryScan(config, datasets, ethos[0] if ethos else None, fingerprint, count, checks) + fingerprint, count = _fingerprint(repo_root, [config.path for config in configs], ethos, datasets) + return RepositoryScan(configs, datasets, ethos[0] if ethos else None, fingerprint, count, checks) def _config_candidates(repo_root: Path) -> list[ConfigCandidate]: candidates: list[ConfigCandidate] = [] - for relative in _CONFIG_DIRS: - directory = repo_root if relative == "." else repo_root / relative - if not directory.is_dir(): - continue + for directory in walk_dirs(repo_root, max_depth=_MAX_CONFIG_DEPTH): for path in sorted(directory.iterdir()): - if not path.is_file() or path.suffix.lower() not in _CONFIG_SUFFIXES: - continue - try: - if not path.resolve().is_relative_to(repo_root): - continue - except (OSError, RuntimeError): + if path.is_symlink() or not path.is_file() or path.suffix.lower() not in _CONFIG_SUFFIXES: continue data = _load_mapping(path) if data is not None and _has_work(data): candidates.append(ConfigCandidate(path=path, data=data)) - return candidates + return sorted( + candidates, + key=lambda candidate: ( + len(candidate.path.relative_to(repo_root).parts) - 1, + candidate.path.relative_to(repo_root).as_posix(), + ), + ) def _load_mapping(path: Path) -> dict[str, Any] | None: @@ -171,16 +171,18 @@ def _dataset_paths(repo_root: Path) -> list[Path]: def _fingerprint( repo_root: Path, - config_path: Path | None, + config_paths: list[Path], ethos: tuple[str, bytes] | None, datasets: list[Path], ) -> tuple[str, int]: - files: set[Path] = {path for path in (config_path, repo_root / "optimizer.yaml") if path and path.is_file()} + files = {path for path in [*config_paths, repo_root / "optimizer.yaml"] if path.is_file()} for dataset in datasets: if not dataset.is_relative_to(repo_root): continue for directory in walk_dirs(dataset): - files.update(path for path in directory.iterdir() if path.is_file()) + files.update( + path for path in directory.iterdir() if path.is_file() and path.resolve().is_relative_to(repo_root) + ) files.discard(repo_root / "ETHOS.md") digest = hashlib.sha256() diff --git a/plugins/nemo-eval-author/tests/discover/test_command.py b/plugins/nemo-eval-author/tests/discover/test_command.py index 36b06ec6aa0..74f8abea1e2 100644 --- a/plugins/nemo-eval-author/tests/discover/test_command.py +++ b/plugins/nemo-eval-author/tests/discover/test_command.py @@ -3,6 +3,7 @@ """End-to-end tests for the discovery command.""" +import asyncio from pathlib import Path from unittest.mock import AsyncMock @@ -90,7 +91,7 @@ def test_healthy_config_uploads_only_discovery_report_and_does_not_write_to_repo result = _invoke(app, repo, "--agent", AGENT) assert result.exit_code == 0, result.output - assert "Repository\n ✓ Using Harbor config configs/eval.yaml." in result.output + assert "Repository\n ✓ Found 1 repository-owned Harbor config file." in result.output assert "harbor job start -c configs/eval.yaml" in result.output assert "Uploaded ticket-triage/discovery.md to fileset 'nemo-eval-author'." in result.output assert client.files.stored.keys() == {f"{AGENT}/discovery.md"} @@ -137,6 +138,50 @@ def test_rejected_config_exits_one_and_uploads_its_report(app, client, tmp_path) assert result.output.rstrip().endswith("Final overview: Discovery failed with 1 failure and 2 warnings.") +def test_preflights_every_config_sequentially_and_uploads_all_results_after_a_failure( + app, client, monkeypatch, tmp_path +): + repo = tmp_path / "multi-config-repo" + first = repo / "first.yaml" + second = repo / "nested" / "second.yml" + for path, text in ( + (first, "job_name: first-entry\ndatasets:\n- path: first\n"), + (second, "datasets:\n- path: second\n"), + ): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + calls: list[str] = [] + active = False + + async def preflight(candidate, root): + nonlocal active + assert root == repo + assert not active + active = True + await asyncio.sleep(0) + relative = candidate.path.relative_to(repo).as_posix() + calls.append(relative) + active = False + if candidate.path == first: + return validate.ValidationOutcome( + checks=[validate._check("schema", "fail", "Harbor rejected the first config.")] + ) + return validate.ValidationOutcome( + checks=[validate._check("schema", "pass", "Harbor accepted the second config.")] + ) + + monkeypatch.setattr(validate, "run_ladder", preflight) + + result = _invoke(app, repo, "--agent", AGENT) + + assert result.exit_code == 1, result.output + assert calls == ["first.yaml", "nested/second.yml"] + uploaded = client.files.stored[f"{AGENT}/discovery.md"].decode() + assert "Harbor rejected the first config." in uploaded + assert "Harbor accepted the second config." in uploaded + + def test_schema_failure_does_not_upload_the_rejected_input_value(app, client, tmp_path): secret = "nvapi-secret-value-123456789" repo = tmp_path / "secret-rejected-repo" diff --git a/plugins/nemo-eval-author/tests/discover/test_report.py b/plugins/nemo-eval-author/tests/discover/test_report.py index fcc17899f17..caf999e1ea1 100644 --- a/plugins/nemo-eval-author/tests/discover/test_report.py +++ b/plugins/nemo-eval-author/tests/discover/test_report.py @@ -7,7 +7,7 @@ from datetime import UTC, datetime from harbor_fixtures import read_front_matter -from nemo_eval_author_plugin.discovery import report +from nemo_eval_author_plugin.discovery import report, scan, validate from nemo_eval_author_plugin.discovery.validate import RequiredEnvVar from nemo_insights_plugin.contracts.checks import CheckResult, CheckStatus, format_report @@ -22,29 +22,48 @@ def _check(name: str = "config", status: CheckStatus = "pass", message: str = "F ) -def _record(tmp_path, *, config: bool = True, checks: list[CheckResult] | None = None): +_TRACE_CHECK = scan._check("traces", "pass", "Trace sessions exist.", severity="advisory") + + +def _config( + root, + *, + path: str = "configs/eval.yaml", + name: str = "evaluation", + checks: list[CheckResult] | None = None, +): + root = root.resolve() + return report.ConfigReport( + name=name, + path=root / path, + required_env_vars=[ + RequiredEnvVar(name="HF_TOKEN", default=None, declared_in=root / "evals" / "validation" / "task.toml") + ], + checks=checks if checks is not None else [_check()], + ) + + +def _record(tmp_path, *, configs=None, repository_checks: list[CheckResult] | None = None): root = tmp_path.resolve() return report.DiscoveryReport( agent="ticket-triage", workspace="default", repo_root=root, - config_path=root / "configs" / "eval.yaml" if config else None, + configs=[_config(root)] if configs is None else configs, dataset_paths=[root / "evals" / "validation"], ethos_path="ETHOS.md", harbor_version="0.18.0", - required_env_vars=[ - RequiredEnvVar(name="HF_TOKEN", default=None, declared_in=root / "evals" / "validation" / "task.toml") - ], discovered_at=datetime(2026, 8, 10, 15, tzinfo=UTC), fingerprint="sha256:abc123", input_file_count=4, - checks=checks or [_check()], + repository_checks=repository_checks or [], + trace_check=_TRACE_CHECK, ) def test_front_matter_records_the_complete_repository_contract(tmp_path): check = _check() - record = _record(tmp_path, checks=[check]) + record = _record(tmp_path, configs=[_config(tmp_path, checks=[check])]) markdown = report.render_markdown(record) front = read_front_matter(markdown) @@ -55,6 +74,7 @@ def test_front_matter_records_the_complete_repository_contract(tmp_path): "workspace": "default", "repo_root": str(tmp_path.resolve()), "runnable": True, + "configs": [{"name": "evaluation", "path": "configs/eval.yaml"}], "config_path": "configs/eval.yaml", "dataset_paths": ["evals/validation"], "run_command": f"cd {shlex.quote(str(tmp_path.resolve()))} && harbor job start -c configs/eval.yaml", @@ -70,14 +90,14 @@ def test_front_matter_records_the_complete_repository_contract(tmp_path): "discovered_at": "2026-08-10T15:00:00+00:00", "fingerprint": "sha256:abc123", "input_file_count": 4, - "checks": [check.model_dump(mode="json")], + "checks": [check.model_dump(mode="json"), _TRACE_CHECK.model_dump(mode="json")], } assert format_report([check]) in markdown def test_a_rejected_config_is_blocked_and_has_no_command(tmp_path): failure = _check("resolution", "fail", "Harbor could not resolve the job.") - record = _record(tmp_path, checks=[_check(), failure]) + record = _record(tmp_path, configs=[_config(tmp_path, checks=[_check(), failure])]) markdown = report.render_markdown(record) front = read_front_matter(markdown) @@ -91,8 +111,8 @@ def test_a_rejected_config_is_blocked_and_has_no_command(tmp_path): def test_a_report_without_a_repository_config_is_not_runnable(tmp_path): record = _record( tmp_path, - config=False, - checks=[_check("config", "fail", "No repository-owned Harbor config file exists.")], + configs=[], + repository_checks=[_check("config", "fail", "No repository-owned Harbor config file exists.")], ) front = read_front_matter(report.render_markdown(record)) @@ -104,8 +124,10 @@ def test_a_report_without_a_repository_config_is_not_runnable(tmp_path): def test_the_run_command_changes_to_the_repo_and_quotes_shell_paths(tmp_path): repo = tmp_path / "repo $(touch unsafe); name" - record = _record(repo) - record.config_path = repo.resolve() / "configs" / "eval $(touch unsafe); suite.yaml" + record = _record( + repo, + configs=[_config(repo, path="configs/eval $(touch unsafe); suite.yaml")], + ) cd_command, harbor_command = record.run_command.split(" && ") assert shlex.split(cd_command) == ["cd", str(repo.resolve())] @@ -116,3 +138,74 @@ def test_the_run_command_changes_to_the_repo_and_quotes_shell_paths(tmp_path): "-c", "configs/eval $(touch unsafe); suite.yaml", ] + + +def test_multi_config_report_uses_names_paths_stable_sections_and_one_command_each(tmp_path, monkeypatch): + root = tmp_path.resolve() + candidates = [ + scan.ConfigCandidate(root / "a.yaml", {"job_name": "shared", "tasks": ["a"]}), + scan.ConfigCandidate(root / "nested" / "b.yml", {"job_name": "shared", "tasks": ["b"]}), + scan.ConfigCandidate(root / "nested" / "fallback.json", {"job_name": " ", "tasks": ["c"]}), + ] + scan_result = scan.RepositoryScan( + configs=candidates, + dataset_paths=[], + ethos_path=None, + fingerprint="abc123", + input_file_count=3, + checks=[_check("config", "pass", "Found 3 repository-owned Harbor config files.")], + ) + validations = [ + validate.ValidationOutcome(checks=[_check("schema", "pass", f"Schema {index} passed.")]) for index in range(3) + ] + trace_check = scan._check("traces", "warn", "No traces exist.", severity="advisory") + monkeypatch.setattr(report, "harbor_version", lambda: "0.18.0") + + record = report.build_report( + agent="ticket-triage", + workspace="default", + repo_root=root, + scan_result=scan_result, + validations=validations, + trace_check=trace_check, + ) + markdown = report.render_markdown(record) + front = read_front_matter(markdown) + + assert front["configs"] == [ + {"name": "shared", "path": "a.yaml"}, + {"name": "shared", "path": "nested/b.yml"}, + {"name": "fallback.json", "path": "nested/fallback.json"}, + ] + assert (front["runnable"], front["config_path"], front["run_command"]) == (True, None, None) + headings = [ + "### `shared` (`a.yaml`)", + "### `shared` (`nested/b.yml`)", + "### `fallback.json` (`nested/fallback.json`)", + ] + positions = [markdown.index(heading) for heading in headings] + assert positions == sorted(positions) + for index, (position, candidate) in enumerate(zip(positions, candidates, strict=True)): + end = positions[index + 1] if index + 1 < len(positions) else len(markdown) + section = markdown[position:end] + assert f"Schema {index} passed." in section + assert f"harbor job start -c {candidate.path.relative_to(root).as_posix()}" in section + assert markdown.count("harbor job start -c") == 3 + + +def test_multi_config_report_is_not_runnable_when_one_config_fails(tmp_path): + failure = _check("schema", "fail", "Harbor rejected one config.") + record = _record( + tmp_path, + configs=[ + _config(tmp_path, path="first.yaml", name="first", checks=[failure]), + _config(tmp_path, path="second.yaml", name="second"), + ], + ) + + markdown = report.render_markdown(record) + front = read_front_matter(markdown) + + assert (front["runnable"], front["config_path"], front["run_command"]) == (False, None, None) + assert "harbor job start -c first.yaml" not in markdown + assert "harbor job start -c second.yaml" in markdown diff --git a/plugins/nemo-eval-author/tests/discover/test_scan.py b/plugins/nemo-eval-author/tests/discover/test_scan.py index a2aed05312f..7337367b734 100644 --- a/plugins/nemo-eval-author/tests/discover/test_scan.py +++ b/plugins/nemo-eval-author/tests/discover/test_scan.py @@ -21,15 +21,20 @@ def _task(path: Path) -> None: (path / "task.toml").write_text('version = "1.0"\n', encoding="utf-8") -def test_selects_the_first_config_and_warns_about_extras(tmp_path): - first = _config(tmp_path / "configs" / "a.yaml") - _config(tmp_path / "harbor" / "b.yaml") +def test_finds_configs_through_depth_four_in_stable_order_and_prunes_jobs(tmp_path): + expected = [ + _config(tmp_path / "root.yaml"), + _config(tmp_path / "z" / "depth-one.yml"), + _config(tmp_path / "a" / "a" / "depth-two.json", '{"tasks": ["task"]}'), + _config(tmp_path / "b" / "b" / "b" / "depth-three.yaml"), + _config(tmp_path / "c" / "c" / "c" / "c" / "depth-four.yaml"), + ] + _config(tmp_path / "d" / "d" / "d" / "d" / "d" / "depth-five.yaml") result = scan.scan_repository(tmp_path) - assert result.config is not None - assert result.config.path == first - assert {check.status for check in result.checks if check.name == "config"} == {"pass", "warn"} + assert [candidate.path for candidate in result.configs] == expected + assert {check.status for check in result.checks if check.name == "config"} == {"pass"} assert any(check.name == "ethos" and check.status == "warn" for check in result.checks) @@ -44,7 +49,7 @@ def test_reads_yaml_yml_and_json_configs(tmp_path): result = scan.scan_repository(repo) - assert result.config is not None and result.config.path == expected + assert [candidate.path for candidate in result.configs] == [expected] def test_rejects_a_config_symlink_that_resolves_outside_the_repository(tmp_path): @@ -56,10 +61,20 @@ def test_rejects_a_config_symlink_that_resolves_outside_the_repository(tmp_path) result = scan.scan_repository(repo) - assert result.config is None + assert result.configs == [] assert next(check for check in result.checks if check.name == "config").status == "fail" +def test_rejects_a_config_file_symlink_inside_the_repository(tmp_path): + config = _config(tmp_path / "configs" / "eval.yaml") + link = config.with_name("alias.yaml") + link.symlink_to(config.name) + + result = scan.scan_repository(tmp_path) + + assert [candidate.path for candidate in result.configs] == [config] + + def test_profile_prior_job_and_task_layout_never_become_config_candidates(tmp_path): (tmp_path / "optimizer.yaml").write_text( "agent: ticket-triage\ndatasets:\n validation: evals/validation\n", @@ -73,7 +88,7 @@ def test_profile_prior_job_and_task_layout_never_become_config_candidates(tmp_pa result = scan.scan_repository(tmp_path) - assert (result.config, result.dataset_paths) == (None, [dataset]) + assert (result.configs, result.dataset_paths) == ([], [dataset]) def test_uses_only_ethos_for_the_doctrine_contract(tmp_path): @@ -102,6 +117,7 @@ def test_discovers_local_datasets_and_prunes_generated_trees(tmp_path): _task(tmp_path / "node_modules" / "package" / "task-three") _task(tmp_path / "vendor" / "package" / "task-four") _task(tmp_path / "cache" / "package" / "task-five") + _task(tmp_path / "jobs" / "prior-run" / "task-six") result = scan.scan_repository(tmp_path) @@ -111,6 +127,7 @@ def test_discovers_local_datasets_and_prunes_generated_trees(tmp_path): def test_fingerprint_covers_config_ethos_optimizer_and_dataset_files(tmp_path): config = _config(tmp_path / "harbor-job.yaml") + other_config = _config(tmp_path / "nested" / "other.json", '{"tasks": ["task"]}') ethos = tmp_path / "ETHOS.md" optimizer = tmp_path / "optimizer.yaml" ethos.write_text("# One\n", encoding="utf-8") @@ -122,10 +139,11 @@ def test_fingerprint_covers_config_ethos_optimizer_and_dataset_files(tmp_path): first = scan.scan_repository(tmp_path) - assert first.input_file_count == 5 - assert first.config is not None and first.config.path == config + assert first.input_file_count == 6 + assert [candidate.path for candidate in first.configs] == [config, other_config] for path, replacement in ( (config, "datasets:\n- path: another-evals\n"), + (other_config, '{"tasks": ["another-task"]}'), (ethos, "# Two\n"), (optimizer, "model: two\n"), (task / "task.toml", 'version = "2.0"\n'),