Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
28fe43c
feat(eval-author): implement the discover command
aleckhoury Jul 30, 2026
4a49ab2
test(eval-author): group the discover tests under tests/discover
aleckhoury Jul 30, 2026
d7978da
fix(eval-author): point discovery at the repo's own Harbor config
aleckhoury Jul 31, 2026
72549f7
refactor(eval-author): drop two unused entry points from the validati…
aleckhoury Jul 31, 2026
53c9ed6
feat(eval-author): make the discovery scout opt-in as --fix
aleckhoury Jul 31, 2026
383ae39
refactor(eval-author): drop the platform and backend flags from discover
aleckhoury Jul 31, 2026
2726e7d
fix(eval-author): harden discover's reuse gate and sharpen its findings
aleckhoury Jul 31, 2026
66f5efe
refactor(eval-author): rename --fix to --dangerously-fix and warn in …
aleckhoury Jul 31, 2026
d1b1e2f
refactor(eval-author): cut discover back to what it can prove
aleckhoury Jul 31, 2026
bbd37af
fix(eval-author): stop discover from reading the optimizer's own job …
aleckhoury Jul 31, 2026
695de10
fix(eval-author): run the round trip through the Harbor the ladder used
aleckhoury Jul 31, 2026
c932fd5
fix(eval-author): record the search path the agent import actually needs
aleckhoury Jul 31, 2026
14bc1ce
Merge remote-tracking branch 'origin/main' into ase-677-eval-author-d…
aleckhoury Aug 7, 2026
2f57011
refactor(eval-author): reduce discover to repository preflight
aleckhoury Aug 10, 2026
bc6a550
feat(eval-author): discover hosted agent doctrine
aleckhoury Aug 10, 2026
22e9d06
feat(eval-author): discover every Harbor config
aleckhoury Aug 11, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion plugins/nemo-eval-author/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]

Expand Down
141 changes: 126 additions & 15 deletions plugins/nemo-eval-author/src/nemo_eval_author_plugin/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,91 @@

"""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.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 "}

# 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."""
typer.echo(f"`nemo eval-author {command}` 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
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)

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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:")
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:
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."""

Expand All @@ -41,10 +102,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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# 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.")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


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,
# 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",
)
],
)
Loading
Loading