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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions docs/apps-evaluate-cli.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Saved-request evaluation CLI

`inferrsi evaluate prepare`, `execute` and `assess` use the same Apps API and
persisted result as Python. They consume already saved requests. A trusted
Python caller or host allocates the Harness attempt before saving an execution
request; the CLI does not allocate one or automatically retry a failed call.

```bash
inferrsi evaluate prepare --request @<prepare-request.json> \
--output-id <prepare-output-id> --workspace <absolute-authorized-workspace> \
--storage-config <storage.json> --runtime-config <runtime.json>
inferrsi evaluate execute --request @<execute-request.json> \
--output-id <execute-output-id> --workspace <absolute-authorized-workspace> \
--storage-config <storage.json> --runtime-config <runtime.json>
inferrsi evaluate assess --request @<assess-request.json> \
--output-id <assess-output-id> --workspace <absolute-authorized-workspace> \
--storage-config <storage.json>
```

Missing `--output-id` is a parser error before any port is called. Optional
`--prepared-ref @<file>` / `--record-ref @<file>` must equal the corresponding
complete reference in the request. Optional `--scope` and `--primary-claim`
must agree with its operation/scope and selected claim. They never override
saved fields. The `@file` convention belongs to these new commands; existing
fixed-view `status`, `report`, `dashboard` and `trace` plain-path options retain
their original convention.
Checking `execute --scope` reads its fixed prepared archive before execution;
an unavailable or invalid archive fails that read-only agreement check.

Input files may be formatted JSON. Duplicate keys, non-object input, non-UTF-8,
unsafe integers, non-finite values and floating-point tokens are refused.
Decimal fields follow the existing string contract. Stored outputs and stdout
use the existing canonical result encoder.
Stdout appends a line ending after that JSON value; manifest hashes and byte
comparisons apply to the canonical `result.json` bytes without that line ending.

## Trusted local runtime configuration

The adapter is located only by explicit `--runtime-config`; it is not discovered
from the working directory, storage configuration or saved request. It grants
existing B/H capabilities and is therefore trusted host input. It accepts no
import names, factories, credentials or request-selected authorities.
`StorageConfig` retains its existing schema and independently authorizes Apps
archive/record access.

```json
{
"schema_version": 1,
"benchmark": {
"protocol": "<absolute-local-frozen-ProtocolV1-file>",
"worker_role": "worker-code",
"resources": {
"worker-code": "<absolute-local-worker-resource-file>",
"input-data": "<absolute-local-input-resource-file>"
}
},
"target": {
"target_id": "<configured-target-id>",
"config_revision": "<configured-revision>",
"work_root": "<absolute-authorized-local-work-directory>",
"controller_root": "<absolute-authorized-controller-directory>",
"target_root": null,
"module_root": "<absolute-authorized-worker-source-directory>"
}
}
```

Only `schema_version`, `benchmark` and `target` are recognized at the top level.
The selected operation requires only its section; other sections may be absent.
All configured resource/work/source paths are absolute local paths, with no
network-path or ambient-directory fallback. Output workspace is an existing
absolute local directory without symlink traversal.

- **prepare:** `benchmark` has exactly `protocol`, `worker_role`, `resources`.
The [existing B PreparationService](contracts/production-prepare.md) validates
the frozen task/rules and exact byte pins. Resource paths grant read-only
role-keyed file openers. Apps independently verifies the returned closure
before archiving it. No target or writable Store is constructed.
- **execute:** `target` requires `target_id`, `config_revision`, `work_root`.
`controller_root`, `target_root`, `module_root` are optional; absent/null means
unauthorized. These configure the existing H `LocalCpuTarget`. The existing
`harness_sqlite` mount selected by `StorageConfig.harness_namespace` configures
the Store. The adapter opens it for writing only when the verified Apps
binding calls H. The request cannot replace this configuration.
- **assess:** no runtime file is required or read. The existing offline B
assessor reads only fixed retained evidence through Apps; it does not prepare
a task, construct an execution target, launch a worker or access a network.

This first adapter exposes the production task family already supported by B
on main. It does not define a worker/profile or reinterpret frozen rules.
The separate real CPU profile delivery and full three-host integration remain
tracked by the parent Apps issue.

## Outputs, errors and replay

Each invocation prints its complete `AppsResultV1` and returns its `exit_code`.
The existing publication writes `output/<output-id>/manifest.json` and
`result.json` in the authorized workspace, refusing overwrite. Consumers verify
the manifest and read fixed references; raw facts and claim verdicts remain
separate.

| Existing result / error | Exit |
| --- | --- |
| Successful prepare/execute or archived primary `PASS` | 0 |
| Argument/config/ref conflict; other non-persistence public errors | 2 |
| Committed refusal with `process_outcome=not_started` | 3 |
| `AttemptInProgress` | 4 |
| `RecoveryRequired` | 5 |
| `ExecutionPersistenceError` / `ArchivePersistenceError`, including output publication | 6 |
| Committed failed, timed out, cancelled or nonzero worker execution | 7 |
| Archived primary `FAIL` | 8 |
| Archived primary `INCONCLUSIVE` | 9 |

The [existing Apps result mapping](../src/inferrsi/apps/storage/result.py)
remains authoritative. Publication failures preserve already committed refs
in the printed result. Explicitly resubmitting the original saved execute
request uses the original attempt and digest; H returns its original fixed
record or its existing in-progress/recovery/conflict response. Repeating a
completed call with an already published output ID refuses output overwrite
even though H has replayed the same record. Use another explicit output ID
when publishing a separate receipt. The CLI never substitutes a new attempt,
extends the original deadline or retries a worker.

These checks establish software behavior, not a service/performance verdict.
3 changes: 3 additions & 0 deletions docs/apps-module-migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"docs/operations.md",
"src/inferrsi/apps/api.py",
"src/inferrsi/apps/archive.py",
"src/inferrsi/apps/cli/evaluate.py",
"src/inferrsi/apps/delivery/__init__.py",
"src/inferrsi/apps/handoff/bridge.py",
"src/inferrsi/apps/handoff/candidate_provider.py",
Expand All @@ -30,6 +31,7 @@
"src/inferrsi/apps/workflows/benchmark_compare.py",
"tests/check_installed.py",
"tests/test_apps_assess.py",
"tests/test_apps_evaluate_cli.py",
"tests/test_apps_module_migrations.py",
"tests/test_apps_output.py",
"tests/test_apps_port_validation.py",
Expand All @@ -56,6 +58,7 @@
"docs/operations.md",
"src/inferrsi/apps/api.py",
"src/inferrsi/apps/artifact_reader.py",
"src/inferrsi/apps/cli/evaluate.py",
"src/inferrsi/apps/handoff/candidate_provider.py",
"src/inferrsi/apps/views/attempt.py",
"tests/check_installed.py",
Expand Down
1 change: 1 addition & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ Effect classes used below:
| Verify and execute one frozen source evaluation entry | Python `inferrsi.harness.api.Harness.execute` with trusted `LocalCpuTarget(module_root=...)` | Experiment-executing / record-writing | Fixed preparation and expected code digest; actual source captured after registration; T37 refusals start no worker; [source-entry contract](contracts/harness-entry-verification.md) |
| Replay the same saved execution request | Python `inferrsi.harness.api.Harness.execute` | Existing-state query / fixed record-reading | Same attempt and canonical digest; existing state short-circuits fresh binding/execution; [replay and original limits](contracts/harness-evaluation-replay.md) |
| Freeze a configured P1 preparation | Python `benchmark.preparation.PreparationService.prepare`; [production prepare](contracts/production-prepare.md) | Read-only resource access / pure encoding | Verifies supplied frozen worker/resource bytes and returns a preparation, protocol and role-keyed closure; Apps separately archives them before publishing a Ref |
| Evaluate saved requests | CLI `evaluate prepare/execute/assess`; [saved-request CLI](apps-evaluate-cli.md) | Local archive/output writing; execute additionally runs the configured H target | Explicit saved request, output ID, storage and trusted runtime configuration; reuses Apps ports and results without allocating attempts, selecting feedback or retrying |
| Assess one fixed P1 record offline | Python `benchmark.assessment.assess`; [production assess](contracts/production-assess.md) | Read-only retained evidence / pure encoding | Verifies the frozen protocol, actual capture and proof bytes; returns independent claims without launching a worker or writing an archive; Apps selects the primary key and archives the result |
| Seal a generation with frozen feedback authorization | Python `harness.generation.prepare_generation`; [opt-in feedback profile](contracts/generation-feedback-policy.md) | Local context / policy / generation-plan retention | Optional fixed policy and source record Refs authorize original scope/check proofs before provider calls. Absent-policy calls remain a trusted-host path; no automatic execution or policy-approval authentication |
| Seal host-approved generation context without a policy Ref | Python `harness.generation.prepare_generation`; [feedback boundary](contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. Without the opt-in policy Ref, H seals supplied material and does not prove feedback-policy enforcement or execute a worker |
Expand Down
4 changes: 4 additions & 0 deletions src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,10 @@ def main(argv: list[str] | None = None) -> int:
supplied = vars(args).pop(SUPPLIED, ())
task = _plan_run_task(command_parser(argument_parser, args.command), args, supplied)
try:
if args.command == "evaluate":
from .evaluate import dispatch

return dispatch(args)
if args.command == "task":
return _task_command(args)
if args.command == "export":
Expand Down
3 changes: 3 additions & 0 deletions src/inferrsi/apps/cli/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,9 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser:
)
root.add_argument("--version", action="version", version=__version__)
commands = root.add_subparsers(dest="command", required=True)
from .evaluate import add_parser as add_evaluate_parser

add_evaluate_parser(commands)
mindie = commands.add_parser("mindie", help="Use project-approved, local MindIE knowledge")
mindie_actions = mindie.add_subparsers(dest="mindie_action", required=True)
enable = mindie_actions.add_parser("enable", help="Approve a MindIE domain for this checkout")
Expand Down
187 changes: 187 additions & 0 deletions src/inferrsi/apps/cli/evaluate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
"""Saved-request CLI over the existing Apps ports and explicit host configuration."""

import json
from pathlib import Path

from ...contracts.json_v1 import encode


def add_parser(commands) -> None:
evaluate = commands.add_parser("evaluate", help="Prepare, execute or assess a saved request")
actions = evaluate.add_subparsers(dest="evaluate_action", required=True)
descriptions = {
"prepare": "Freeze and archive the configured evaluation task",
"execute": "Execute or replay the original saved attempt",
"assess": "Assess a fixed record using retained evidence only",
}
for action, description in descriptions.items():
command = actions.add_parser(action, help=description, description=description)
command.add_argument("--request", required=True, help="@<saved request JSON file>")
command.add_argument("--output-id", required=True)
command.add_argument("--workspace", type=Path, required=True,
help="Existing absolute directory authorized for Apps output")
command.add_argument("--storage-config", type=Path, required=True)
command.add_argument("--runtime-config", type=Path, required=action != "assess",
help="Trusted local B/H configuration; separate from the request")
command.add_argument("--prepared-ref", help="@<full PreparedRef JSON file>")
command.add_argument("--record-ref", help="@<full RecordRef JSON file>")
command.add_argument("--scope")
command.add_argument("--primary-claim")


def _object_file(path: Path) -> dict:
def unique(pairs):
value = {}
for key, item in pairs:
if key in value:
raise ValueError("Duplicate JSON object key")
value[key] = item
return value

try:
value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique)
if not isinstance(value, dict):
raise ValueError("Expected a JSON object")
encode(value)
except RecursionError as error:
raise ValueError("JSON input nesting is too deep") from error
return value


def _request_file(value: str) -> dict:
if not value.startswith("@") or len(value) == 1:
raise ValueError("Requests and references require @<JSON file>")
return _object_file(Path(value[1:]))


def _absolute(value) -> Path:
if not isinstance(value, str) or not value or "\0" in value:
raise ValueError("Runtime paths must be explicit absolute local paths")
path = Path(value)
if not path.is_absolute() or path.anchor.startswith(("\\\\", "//")):
raise ValueError("Runtime paths must be explicit absolute local paths")
return path


def _runtime(path: Path) -> dict:
value = _object_file(path)
if (type(value.get("schema_version")) is not int or value["schema_version"] != 1
or not value.keys() <= {"schema_version", "benchmark", "target"}):
raise ValueError("Unsupported evaluate runtime configuration")
return value


def _prepare_ports(config: dict) -> dict:
from ...benchmark import preparation

task = config.get("benchmark")
if not isinstance(task, dict) or task.keys() != {"protocol", "worker_role", "resources"}:
raise ValueError("prepare requires a configured frozen Benchmark task")
sources = task["resources"]
if not isinstance(sources, dict) or not sources:
raise ValueError("Expected role-keyed read-only Benchmark resources")
sources = {role: _absolute(path) for role, path in sources.items()}
protocol = _object_file(_absolute(task["protocol"]))
service = preparation.PreparationService(
protocol, resources=lambda role: sources[role].open("rb"), worker_role=task["worker_role"],
)
return {"prepare_benchmark": service.prepare, "encode_prepared": preparation.encode,
"validate_prepared": preparation.validate_prepared}


def _execute_ports(config: dict, storage: dict) -> dict:
from ...harness.api import Harness, LocalCpuTarget
from ...harness.run_store import RunStore
from ..storage.artifact_reader import ArtifactReader

target = config.get("target")
required = {"target_id", "config_revision", "work_root"}
optional = {"controller_root", "target_root", "module_root"}
if not isinstance(target, dict) or not required <= target.keys() <= required | optional:
raise ValueError("execute requires a configured local CPU target")
values = dict(target)
values["work_root"] = _absolute(values["work_root"])
for key in optional:
if key in values and values[key] is not None:
values[key] = _absolute(values[key])
target = LocalCpuTarget(**values)
reader = ArtifactReader(storage)
mount = next((item for item in storage["mounts"]
if item["namespace"] == storage["harness_namespace"]), None)
if mount is None or mount["kind"] != "harness_sqlite":
raise ValueError("execute requires the configured Harness SQLite mount")

def execute(spec):
# Opening a writable Store is an execution effect. Defer it until Apps
# has verified the saved request/preparation, and preserve PublicError.
harness = Harness(RunStore.from_mount(mount), target, artifact_reader=reader)
return harness.execute(spec)

return {"execute_harness": execute}


def _assess_ports() -> dict:
from ...benchmark import assessment

return {"assess_benchmark": assessment.assess,
"encode_assessment": assessment.encode,
"validate_assessment": assessment.validate_assessment}


def _check_options(args, request: dict, storage: dict) -> None:
for name in ("prepared_ref", "record_ref"):
option = getattr(args, name)
if option is not None and (
name not in request or encode(_request_file(option)) != encode(request[name])
):
raise ValueError(f"--{name.replace('_', '-')} disagrees with the saved request")
if args.primary_claim is not None and (
args.evaluate_action != "assess" or args.primary_claim != request.get("primary_claim_id")
):
raise ValueError("--primary-claim disagrees with the saved request")
if args.scope is not None:
if args.evaluate_action == "prepare":
nested = request.get("request")
scope = nested.get("validation_scope") if isinstance(nested, dict) else None
elif args.evaluate_action == "assess":
scope = request.get("primary_scope")
else:
from ..storage.archive import read_prepared

ref = request.get("prepared_ref")
if not isinstance(ref, dict):
raise ValueError("execute requires a saved PreparedRef")
scope = read_prepared(storage, ref).get("validation_scope")
if args.scope != scope:
raise ValueError("--scope disagrees with the saved request")


def dispatch(args) -> int:
"""Print the same result as Python, including committed refs on publication failure."""
from ...harness.errors import PublicError
from .. import api
from ..storage.archive import validate_output_id

try:
validate_output_id(args.output_id)
workspace = _absolute(str(args.workspace))
if not workspace.is_dir() or workspace.resolve() != workspace:
raise ValueError("--workspace requires an existing absolute authorized directory")
request = _request_file(args.request)
storage = _object_file(args.storage_config)
_check_options(args, request, storage)
if args.evaluate_action == "prepare":
ports = _prepare_ports(_runtime(args.runtime_config))
elif args.evaluate_action == "execute":
ports = _execute_ports(_runtime(args.runtime_config), storage)
else:
# Offline assessment ignores target/worker configuration entirely.
ports = _assess_ports()
output = getattr(api, args.evaluate_action)(
request, workspace=args.workspace, storage_config=storage,
output_id=args.output_id, **ports,
)
except PublicError as error:
raise ValueError(str(error)) from error
print(encode(output.result).decode("utf-8"))
return output.result["exit_code"]
Loading
Loading