diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index f0c35d4613..3abaeae7a8 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -9,6 +9,7 @@ on: - "scripts/chat_bundle.py" - "tests/test_core_distribution.py" - "tests/test_core_workspace_distribution.py" + - "tests/test_core_benchmark_distribution.py" - "tests/test_core_recall_distribution.py" - "tests/test_core_pr_review_distribution.py" - "tests/test_core_issue_fix_distribution.py" @@ -30,6 +31,7 @@ on: - "loopx/**" - "tests/test_core_distribution.py" - "tests/test_core_workspace_distribution.py" + - "tests/test_core_benchmark_distribution.py" - "tests/test_core_recall_distribution.py" - "tests/test_core_pr_review_distribution.py" - "tests/test_core_issue_fix_distribution.py" @@ -81,6 +83,17 @@ jobs: uv run --extra test python -m pytest -q tests/test_core_distribution.py tests/control_plane/test_installed_core_context.py + - name: Qualify matching Benchmark Toolkit installation and recovery + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-benchmark-toolkit --output "$RUNNER_TEMP/benchmark-source" + uv build --wheel "$RUNNER_TEMP/benchmark-source" --out-dir "$RUNNER_TEMP/benchmark-dist" + export LOOPX_CORE_TEST_WHEEL=$(printf '%s' "$RUNNER_TEMP"/core-dist/loopx_core-*.whl) + export LOOPX_BENCHMARK_TEST_WHEEL=$(printf '%s' "$RUNNER_TEMP"/benchmark-dist/loopx_capability_benchmark_toolkit-*.whl) + uv run --extra test python -m pytest -q tests/test_core_benchmark_distribution.py + - name: Qualify matched recall installation, execution, and removal env: LOOPX_USAGE_PING: "0" @@ -144,7 +157,6 @@ jobs: uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-research uv run --extra test python -m pytest -q tests/test_core_research_distribution.py LOOPX_CORE_TEST_PYTHON="$LOOPX_CORE_TEST_PYTHON" uv run --extra test python -m pytest -q tests/test_core_distribution.py -k 'identity_help_and_unavailable_workspace or defers_explore_evaluation' - - name: Build the matching Workspace wheel run: | uv run --extra test python scripts/chat_bundle.py build --install diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index 226749bafb..06ed7d1940 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -399,6 +399,17 @@ objective. Moving a file while retaining its shim does not reduce that count; combining unrelated responsibilities to meet it is not a successful refactor. Measure representative change locality and installation cost separately. +Standalone Core holds the benchmark catalog and its referenced four-arm +contract. The matching [Benchmark Toolkit wheel](../../../packages/loopx-capability-benchmark-toolkit/README.md) +owns the existing execution modules and CLI adapters. The capability catalog +reports availability from matching installed files, and ordinary discovery +leaves execution unloaded. An explicit benchmark command or scoped Workspace +analysis request uses the original toolkit. Installing or removing the wheel +preserves the existing task and analysis records. The ordinary distribution +continues to bundle the same implementation. This qualifies a D2 package +boundary for the tested toolkit journey. Benchmark-family execution, public +release and model-visible overhead have separate acceptance. + ### State model and schema No canonical record changes. The only new durable artefact is the architecture diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md index 867dfa588a..759e73a111 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -278,6 +278,14 @@ import 方向、剩余兼容接缝和从失败定位 owner 的路径。每个发 把无关职责塞进一个文件来满足预算不构成成功重构。代表性修改局部性与安装成本 分别测量。 +独立 Core 保留 benchmark 目录及其引用的四臂实验契约。同版本的 +[Benchmark Toolkit wheel](../../../packages/loopx-capability-benchmark-toolkit/README.md) +包含既有执行模块和 CLI 适配器。能力目录根据同版本安装文件报告可用性,常规发现 +不会加载执行模块。显式 benchmark 命令或经范围校验的 Workspace 分析请求使用原有 +工具包。安装和卸载保留既有任务及分析记录。普通发行物继续包含同一实现。已测试的 +工具包流程验证了 D2 的这项打包边界。具体 benchmark 家族的执行、公开发布和模型可见 +开销仍分别验收。 + ### 状态模型与 schema 不改任何规范记录。唯一新增的持久产物是架构 fixture: diff --git a/loopx/capabilities/benchmark_toolkit/catalog_entry.py b/loopx/capabilities/benchmark_toolkit/catalog_entry.py index 05418399ee..38f588ee13 100644 --- a/loopx/capabilities/benchmark_toolkit/catalog_entry.py +++ b/loopx/capabilities/benchmark_toolkit/catalog_entry.py @@ -2,11 +2,40 @@ from typing import Any +from ...python_install_owner import BENCHMARK_TOOLKIT_DISTRIBUTION, builtin_capability_installed from .four_arm_contract import ( BENCHMARK_FOUR_ARM_ATTESTATIONS, BENCHMARK_FOUR_ARM_RUNNER_OBLIGATIONS, ) +BENCHMARK_TOOLKIT_INSTALL_HINT = ( + "Install the matching loopx-capability-benchmark-toolkit wheel " + "or use the ordinary LoopX installation." +) + + +BENCHMARK_TOOLKIT_STARTUP_MODULES = ( + "loopx.cli_commands.benchmark_dispatch", + "loopx.cli_commands.benchmark_boundary", + "loopx.cli_commands.benchmark_concurrency", + "loopx.cli_commands.benchmark_continuation", + "loopx.cli_commands.benchmark_experiment_board", + "loopx.cli_commands.benchmark_rebalance", + "loopx.cli_commands.benchmark_study", + "loopx.cli_commands.benchmark_token_capacity", + "loopx.cli_commands.benchmark_trajectory", + "loopx.capabilities.benchmark_toolkit.trajectory_assessment_store", +) + + +def benchmark_toolkit_installed(*, builtin_cli_present: bool | None = None) -> bool: + return builtin_capability_installed( + BENCHMARK_TOOLKIT_DISTRIBUTION, + BENCHMARK_TOOLKIT_STARTUP_MODULES, + builtin_cli_present=builtin_cli_present, + ) + + BENCHMARK_TOOLKIT_CATALOG_ENTRY: dict[str, Any] = { "id": "benchmark-toolkit", "origin": "builtin", diff --git a/loopx/capabilities/catalog.py b/loopx/capabilities/catalog.py index 2824da9e2e..468b379f82 100644 --- a/loopx/capabilities/catalog.py +++ b/loopx/capabilities/catalog.py @@ -6,8 +6,12 @@ from typing import Any from ..extensions.runtime import extension_catalog_entries -from ..python_install_owner import RESEARCH_DISTRIBUTION -from .benchmark_toolkit.catalog_entry import BENCHMARK_TOOLKIT_CATALOG_ENTRY +from ..python_install_owner import BENCHMARK_TOOLKIT_DISTRIBUTION, RESEARCH_DISTRIBUTION +from .benchmark_toolkit.catalog_entry import ( + BENCHMARK_TOOLKIT_CATALOG_ENTRY, + BENCHMARK_TOOLKIT_INSTALL_HINT, + benchmark_toolkit_installed, +) from .integration_branch.catalog_entry import INTEGRATION_BRANCH_CATALOG_ENTRY from .repository_change_window.catalog_entry import ( REPOSITORY_CHANGE_WINDOW_CATALOG_ENTRY, @@ -158,6 +162,16 @@ def _record_for_installed_capability( *, builtin_cli_present: bool, ) -> Mapping[str, object]: + if record is BENCHMARK_TOOLKIT_CATALOG_ENTRY and not builtin_cli_present: + installed = benchmark_toolkit_installed(builtin_cli_present=False) + if not any(provider["id"] == BENCHMARK_TOOLKIT_DISTRIBUTION for provider in registry.providers()): + registry.register_provider( + {"id": BENCHMARK_TOOLKIT_DISTRIBUTION, "origin": "builtin", "installed": installed} + ) + updated = dict(record) | {"provider_id": BENCHMARK_TOOLKIT_DISTRIBUTION} + if not installed: + updated["next_real_step"] = BENCHMARK_TOOLKIT_INSTALL_HINT + return updated if record is AGENT_TURN_RECALL_CATALOG_ENTRY: installed = agent_turn_recall_installed(builtin_cli_present=builtin_cli_present) hint = RECALL_INSTALL_HINT diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index 9f2af735ff..89df88b673 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -995,6 +995,12 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: args, registry_path=registry_path, runtime_root_arg=args.runtime_root, print_payload=print_payload, ) + elif args.command == "benchmark": + from .cli_commands.benchmark_dispatch import handle_benchmark_command + + result = handle_benchmark_command( + args, registry_path=registry_path, print_payload=print_payload, output_format=output_format, + ) elif args.command == "agent-turn-recall": from .capabilities.agent_turn_recall.cli import handle_agent_turn_recall_command @@ -1053,11 +1059,14 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: def _available_selected_commands() -> frozenset[str]: from .capabilities.agent_turn_recall.catalog_entry import agent_turn_recall_installed + from .capabilities.benchmark_toolkit.catalog_entry import benchmark_toolkit_installed from .capabilities.deep_research.catalog_entry import research_workflows_installed from .capabilities.issue_fix.catalog_entry import issue_fix_workflow_installed from .capabilities.pr_review_queue.catalog_entry import pull_request_review_installed commands = set(_SELECTED_COMMANDS) + if benchmark_toolkit_installed(builtin_cli_present=False): + commands.add("benchmark") if agent_turn_recall_installed(builtin_cli_present=False): commands.add("agent-turn-recall") if pull_request_review_installed(builtin_cli_present=False): @@ -1176,6 +1185,25 @@ def main(argv: list[str] | None = None) -> int: def _run_command(command: str | None, raw_argv: list[str]) -> int: + if command == "benchmark" and _standalone_core(): + from .capabilities.benchmark_toolkit.catalog_entry import ( + BENCHMARK_TOOLKIT_INSTALL_HINT, benchmark_toolkit_installed, + ) + + parser, subparsers = build_cli_parser() + if not benchmark_toolkit_installed(builtin_cli_present=False): + parser.error(f"benchmark is unavailable in the standalone core. {BENCHMARK_TOOLKIT_INSTALL_HINT}") + try: + from .cli_commands.benchmark_dispatch import register_benchmark_command_group + + register_benchmark_command_group(subparsers, add_subcommand_format) + except ModuleNotFoundError as exc: + if not (exc.name or "").startswith( + ("loopx.capabilities.benchmark_toolkit", "loopx.cli_commands.benchmark_") + ): + raise + parser.error(f"benchmark is unavailable in the standalone core. {BENCHMARK_TOOLKIT_INSTALL_HINT}") + return _dispatch_selected(parse_cli_args(parser, raw_argv), raw_argv) if command in {"agent-turn-recall", "pr-review", "issue-fix"} and _standalone_core(): parser, subparsers = build_cli_parser() if command == "agent-turn-recall": diff --git a/loopx/presentation/research_analysis_api.py b/loopx/presentation/research_analysis_api.py index 1294c25704..e5e1b596b5 100644 --- a/loopx/presentation/research_analysis_api.py +++ b/loopx/presentation/research_analysis_api.py @@ -7,6 +7,10 @@ from importlib import import_module from urllib.parse import parse_qs, urlparse +from ..capabilities.benchmark_toolkit.catalog_entry import ( + BENCHMARK_TOOLKIT_INSTALL_HINT, + benchmark_toolkit_installed, +) from ..feedback import validate_goal_id from ..control_plane.effect_runtime import EffectRuntimeRejected from .goal_source_routing import goal_source_catalog, linked_goal_source @@ -18,13 +22,20 @@ class ResearchAnalysisRequestMixin: def _research_analysis_store(self): + if not benchmark_toolkit_installed(): + self._send_error( + BENCHMARK_TOOLKIT_INSTALL_HINT, + status=503, + error_code="research_analysis_unavailable", + ) + return None try: return import_module(_ASSESSMENT_STORE) except ModuleNotFoundError as exc: if exc.name not in {_ASSESSMENT_PACKAGE, _ASSESSMENT_STORE}: raise self._send_error( - "Research analysis needs the Benchmark Toolkit. Use an installation that includes it.", + BENCHMARK_TOOLKIT_INSTALL_HINT, status=503, error_code="research_analysis_unavailable", ) diff --git a/loopx/python_install_owner.py b/loopx/python_install_owner.py index f4c522691a..225b5363b1 100644 --- a/loopx/python_install_owner.py +++ b/loopx/python_install_owner.py @@ -218,6 +218,7 @@ def builtin_capability_installed( WORKSPACE_DISTRIBUTION = "loopx-workspace" RESEARCH_DISTRIBUTION = "loopx-capability-research" +BENCHMARK_TOOLKIT_DISTRIBUTION = "loopx-capability-benchmark-toolkit" @dataclass(frozen=True) class PythonInstallOwner: manager: str diff --git a/loopx/release_manifest.py b/loopx/release_manifest.py index a0ff888287..ff011e7977 100644 --- a/loopx/release_manifest.py +++ b/loopx/release_manifest.py @@ -11,6 +11,7 @@ from . import __version__ from .doctor_git import GitSourceState, git_source_metadata from .python_install_owner import ( + BENCHMARK_TOOLKIT_DISTRIBUTION, RESEARCH_DISTRIBUTION, WORKSPACE_DISTRIBUTION, distribution_recorded_files, @@ -314,6 +315,7 @@ def release_runtime_identity(release_root: Path | None = None) -> dict[str, str _CORE_COMPANION_DISTRIBUTIONS = ( WORKSPACE_DISTRIBUTION, + BENCHMARK_TOOLKIT_DISTRIBUTION, "loopx-capability-agent-turn-recall", "loopx-capability-pull-request-review", "loopx-capability-issue-fix", diff --git a/packages/README.md b/packages/README.md index d0865324f9..1e9e9880fb 100644 --- a/packages/README.md +++ b/packages/README.md @@ -26,6 +26,8 @@ Current co-located distributions, in directory order: - [`loopx-ark-turn`](loopx-ark-turn/README.md): an optional host for one LoopX-governed work unit on Ark Managed Agents (Python distribution, no `extension.toml`; selected with `turn run-once --host generic-cli`); +- [`loopx-capability-benchmark-toolkit`](loopx-capability-benchmark-toolkit/README.md) + adds benchmark commands and registered analysis packs to the matching Core. - [`loopx-codex-provider-routing`](loopx-codex-provider-routing/README.md): native Codex account slots, allowance observation and automatic handoff at safe boundaries, with legacy CPA qualification and rollback compatibility; diff --git a/packages/loopx-capability-benchmark-toolkit/README.md b/packages/loopx-capability-benchmark-toolkit/README.md new file mode 100644 index 0000000000..506a654953 --- /dev/null +++ b/packages/loopx-capability-benchmark-toolkit/README.md @@ -0,0 +1,36 @@ +# Benchmark Toolkit for LoopX Core + +Install this source-built wheel when you need benchmark commands or registered +analysis packs. It uses the same version of [LoopX Core](../loopx-core/README.md) +and the same Goal registry and runtime state. Capability discovery reads its +catalog without loading the toolkit's execution modules. + +Build both wheels from the same checkout and add the toolkit to your Core environment. + +```sh +uv run --extra test python packages/loopx-core/prepare.py --distribution loopx-capability-benchmark-toolkit --output /tmp/loopx-bench-source +uv build --wheel /tmp/loopx-bench-source --out-dir /tmp/loopx-bench-dist +uv pip install --python /tmp/loopx-core-env/bin/python /tmp/loopx-bench-dist/loopx_capability_benchmark_toolkit-*.whl +``` + +Check readiness and discover a registered Goal's analysis packs using the same +registry and runtime you used to run it. + +```sh +/tmp/loopx-core-env/bin/loopx capability show benchmark-toolkit +/tmp/loopx-core-env/bin/loopx --registry .loopx/registry.json benchmark trajectory-packs --goal-id "" +``` + +Pass the original `--runtime-root` if you supplied one. The toolkit exposes the +existing authority and evidence checks. See the +[capability guide](../../loopx/capabilities/benchmark_toolkit/README.md) for +benchmark families and execution prerequisites. + +When using a matching Workspace wheel, restart Workspace after adding or +removing the toolkit. Research Analysis reads the same registered packs. +Remove the toolkit when you no longer need those commands. The existing Goal +registry, task history and analysis records remain in your runtime directory. + +```sh +uv pip uninstall --python /tmp/loopx-core-env/bin/python loopx-capability-benchmark-toolkit +``` diff --git a/packages/loopx-capability-benchmark-toolkit/pyproject.toml b/packages/loopx-capability-benchmark-toolkit/pyproject.toml new file mode 100644 index 0000000000..9a74fb9d8e --- /dev/null +++ b/packages/loopx-capability-benchmark-toolkit/pyproject.toml @@ -0,0 +1,22 @@ +[build-system] +requires = ["setuptools==83.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "loopx-capability-benchmark-toolkit" +dynamic = ["version", "dependencies"] +description = "Optional Benchmark Toolkit for the matching LoopX Core release." +readme = "README.md" +requires-python = ">=3.11" +license = "Apache-2.0" +license-files = ["LICENSE", "NOTICE", "LICENSE-MIT"] + +[tool.setuptools.dynamic] +version = {file = "VERSION"} +dependencies = {file = "requires-core.txt"} + +[tool.setuptools.packages.find] +include = ["loopx.capabilities.benchmark_toolkit", "loopx.capabilities.benchmark_toolkit.*", "loopx.cli_commands"] + +[tool.setuptools.package-data] +"*" = ["*.ts", "*.json", "*.mjs", "*.js", "*.md", "*.toml"] diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index c096cbc369..eaa3555447 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -61,6 +61,12 @@ To view the same work in your browser, install the matching [`loopx-workspace` wheel](../loopx-workspace/README.md) in this environment and start `loopx dashboard` with the original registry. +Core keeps the benchmark catalog and the four-arm contract it references. +Install the matching [Benchmark Toolkit wheel](../loopx-capability-benchmark-toolkit/README.md) +to run `loopx benchmark` or use registered analysis packs in Workspace. +`loopx capability show benchmark-toolkit` reports availability and installation +guidance. Normal discovery leaves benchmark execution unloaded. + Ordinary Core goal previews omit Issue Fix command templates. Install the [matching workflow wheel](../loopx-capability-issue-fix/README.md) to select `--capability-route issue-fix` or run `loopx issue-fix`. Core retains existing @@ -131,7 +137,7 @@ new default, migration, automatic upgrade, PyPI publication or platform release. This is the first independently installable core-artifact slice of R1/M3 in the [small-kernel RFC](../../docs/architecture/rfcs/monorepo-distribution-split-v0.md). -It still retains built-in capability implementations, policy helpers and several +It still retains other built-in capability implementations, policy helpers and several host/CLI dependencies because the current imports are coupled. This makes it a workspace-free installation prerequisite, not a qualified minimal mechanism closure. Those dependencies are migration debt, not evidence that every diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index a14e802e94..1b51573201 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -14,7 +14,7 @@ from runpy import run_path REPOSITORY = Path(__file__).resolve().parents[2] -# These are distribution exclusions. +# These are distribution exclusions, not an authority or activation policy. EXCLUDED_TREES = ("loopx/web/", "loopx/canary/") WORKSPACE_DISTRIBUTION = "loopx-workspace" WORKSPACE_MODULES = { @@ -34,6 +34,17 @@ "loopx/presentation/runtime_workspace.py", } WORKSPACE_ASSETS = Path("loopx/web/chat") +BENCHMARK_DISTRIBUTION = "loopx-capability-benchmark-toolkit" +BENCHMARK_EXECUTION_PREFIXES = ( + "loopx/capabilities/benchmark_toolkit/", + "loopx/cli_commands/benchmark_", +) +# Keep the catalog in a namespace package so discovery skips the execution facade. +BENCHMARK_CATALOG_FILES = { + "loopx/capabilities/benchmark_toolkit/README.md", + "loopx/capabilities/benchmark_toolkit/catalog_entry.py", + "loopx/capabilities/benchmark_toolkit/four_arm_contract.py", +} SOURCE_SUFFIXES = {".py", ".ts", ".json", ".mjs", ".js", ".md", ".toml"} RECALL_DISTRIBUTION = "loopx-capability-agent-turn-recall" PR_REVIEW_DISTRIBUTION = "loopx-capability-pull-request-review" @@ -88,6 +99,10 @@ EXPLORE_DIRECTORY / "worker_branch_plan.py", } CAPABILITY_ENTRY_MODULES = { + BENCHMARK_DISTRIBUTION: { + Path("loopx/cli_commands/benchmark_dispatch.py"), + Path("loopx/capabilities/benchmark_toolkit/trajectory_assessment_store.py"), + }, RECALL_DISTRIBUTION: { Path("loopx/capabilities/agent_turn_recall/cli.py"), Path("loopx/capabilities/agent_turn_recall/core.py"), @@ -117,6 +132,10 @@ def _implementation_paths(sources: list[Path], directory: Path, core_files: set[ def _optional_capability_sources(sources: list[Path]) -> dict[str, set[Path]]: tracked = set(sources) return { + BENCHMARK_DISTRIBUTION: { + path for path in sources + if path.suffix in SOURCE_SUFFIXES and _benchmark_execution_source(path) + }, RECALL_DISTRIBUTION: tracked & CAPABILITY_ENTRY_MODULES[RECALL_DISTRIBUTION], PR_REVIEW_DISTRIBUTION: ( _implementation_paths(sources, PR_REVIEW_DIRECTORY, PR_REVIEW_CORE_FILES) @@ -141,6 +160,11 @@ def _workspace_source(path: Path) -> bool: ) +def _benchmark_execution_source(path: Path) -> bool: + name = path.as_posix() + return name.startswith(BENCHMARK_EXECUTION_PREFIXES) and name not in BENCHMARK_CATALOG_FILES + + def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: repository = repository.resolve() sources = _tracked_loopx_sources(repository) diff --git a/tests/test_ci_resource_policy.py b/tests/test_ci_resource_policy.py index 0e17d2d62e..8e20107db0 100644 --- a/tests/test_ci_resource_policy.py +++ b/tests/test_ci_resource_policy.py @@ -315,6 +315,9 @@ def test_required_merge_gate_workflow_is_not_suppressed_by_path_filters() -> Non ("package-smoke", ["loopx/cli.py"], False), ("package-smoke", ["README.md"], False), ("package-smoke", ["packages/loopx-core/prepare.py"], True), + ("package-smoke", ["apps/presentation/dashboard/src/App.tsx"], True), + ("package-smoke", ["scripts/chat_bundle.py"], True), + ("package-smoke", ["tests/test_core_benchmark_distribution.py"], True), ("package-smoke", ["loopx/extensions/runtime.py"], True), ("package-smoke", ["pyproject.toml"], True), ("desktop-release-artifacts", ["loopx/cli.py"], False), @@ -396,3 +399,28 @@ def test_nightly_schedules_exist_and_release_publication_never_fires_on_schedule package_smoke = workflow("package-smoke") assert package_smoke["concurrency"]["cancel-in-progress"] == "${{ github.event_name == 'pull_request' }}" + + +def test_package_smoke_prepares_each_distribution_output_once_before_workspace() -> None: + steps = workflow("package-smoke")["jobs"]["core"]["steps"] + prepare_outputs: list[str] = [] + for step in steps: + normalized = re.sub(r"\\\n\s*", " ", str(step.get("run", ""))) + for line in normalized.splitlines(): + if "packages/loopx-core/prepare.py" in line: + match = re.search(r'--output\s+"([^"]+)"|--output\s+(\S+)', line) + assert match is not None, line + prepare_outputs.append(match.group(1) or match.group(2)) + assert len(prepare_outputs) == len(set(prepare_outputs)), prepare_outputs + assert prepare_outputs.count("$RUNNER_TEMP/benchmark-source") == 1 + toolkit_indices = [ + idx for idx, step in enumerate(steps) + if "loopx-capability-benchmark-toolkit" in str(step.get("run", "")) + ] + workspace_indices = [ + idx for idx, step in enumerate(steps) + if "loopx-workspace" in str(step.get("run", "")) + ] + assert len(toolkit_indices) == 1 + assert len(workspace_indices) == 1 + assert toolkit_indices[0] < workspace_indices[0] diff --git a/tests/test_core_benchmark_distribution.py b/tests/test_core_benchmark_distribution.py new file mode 100644 index 0000000000..efa1dcda45 --- /dev/null +++ b/tests/test_core_benchmark_distribution.py @@ -0,0 +1,222 @@ +"""Installed Benchmark Toolkit over a checked Core task and an offline case pack.""" + +from hashlib import sha256 +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from zipfile import ZipFile + +import pytest + +from tests.test_core_distribution import GOAL, _assert_committed, _environment, _run +from tests.test_core_distribution import task as task + + +@pytest.fixture +def wheels(): + core = os.environ.get("LOOPX_CORE_TEST_WHEEL") + toolkit = os.environ.get("LOOPX_BENCHMARK_TEST_WHEEL") + if not core or not toolkit: + pytest.skip("set LOOPX_CORE_TEST_WHEEL and LOOPX_BENCHMARK_TEST_WHEEL to the built artifacts") + return Path(core).resolve(strict=True), Path(toolkit).resolve(strict=True) + + +@pytest.fixture +def core_python(tmp_path, wheels): + uv = shutil.which("uv") + assert uv, "uv is required to qualify a clean split installation" + environment = tmp_path / "environment" + subprocess.run([uv, "venv", "--python", sys.executable, str(environment)], check=True, timeout=45) + python = str(environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")) + subprocess.run([uv, "pip", "install", "--offline", "--python", python, str(wheels[0])], + check=True, timeout=45) + return python + + +def test_benchmark_wheel_owns_execution_and_keeps_the_catalog_in_core(wheels): + with ZipFile(wheels[0]) as core, ZipFile(wheels[1]) as toolkit: + assert not set(core.namelist()) & set(toolkit.namelist()) + assert "loopx/capabilities/benchmark_toolkit/catalog_entry.py" in core.namelist() + assert "loopx/capabilities/benchmark_toolkit/four_arm_contract.py" in core.namelist() + assert "loopx/capabilities/benchmark_toolkit/trajectory_assessment_store.py" in toolkit.namelist() + assert "loopx/cli_commands/benchmark_dispatch.py" in toolkit.namelist() + assert "loopx/cli.py" not in toolkit.namelist() + + +def _python_json(python, cwd, source): + result = subprocess.run([python, "-I", "-c", source], cwd=cwd, env=_environment(python), + capture_output=True, text=True, check=True, timeout=30) + return json.loads(result.stdout) + + +_IDENTITY = """import json +from loopx.release_manifest import release_runtime_identity +print(json.dumps(release_runtime_identity())) +""" + + +def test_installed_benchmark_reopens_the_same_analysis_after_removal(core_python, task, wheels, tmp_path): + workspace, runtime, registry, arguments = task + root = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + bench = [*root, "benchmark"] + discover = [*bench, "trajectory-packs", "--goal-id", GOAL] + before = _python_json(core_python, workspace, _IDENTITY) + assert before["package_fingerprint"] + assert "install the matching" in _run(core_python, discover, workspace, expected=2).stderr.lower() + turn = json.loads(_run(core_python, arguments, workspace).stdout) + turn_key = _assert_committed(core_python, workspace, runtime, turn) + registry_bytes = registry.read_bytes() + + install = ["uv", "pip", "install", "--offline", "--python", core_python, str(wheels[1])] + subprocess.run(install, check=True, timeout=45) + probe = _python_json(core_python, workspace, """import contextlib, io, json, sys +from importlib import metadata +from pathlib import Path +from loopx.entrypoint import main +owner = metadata.distribution("loopx-capability-benchmark-toolkit") +assert owner.requires == [f"loopx-core=={metadata.version('loopx-core')}"] +with contextlib.redirect_stdout(io.StringIO()): + assert main(["capability", "list", "--format", "json"]) == 0 + assert main(["commands", "--format", "json"]) == 0 +assert "loopx.cli_commands.benchmark_dispatch" not in sys.modules +assert "loopx.capabilities.benchmark_toolkit.trajectory_assessment_store" not in sys.modules +assert "loopx.capabilities.benchmark_toolkit.native_codex_goal" not in sys.modules +record = next(record for record in owner.files if record.as_posix().endswith(".dist-info/METADATA")) +print(json.dumps({"metadata": str(Path(owner.locate_file(record))), "version": owner.version})) +""") + detail = [*root, "capability", "show", "benchmark-toolkit"] + record = json.loads(_run(core_python, detail, workspace).stdout)["capability"] + assert record["provider_id"] == "loopx-capability-benchmark-toolkit" + assert record["provider_state"] == {"declared": True, "installed": True, "enabled": True, "ready": True} + current = _python_json(core_python, workspace, _IDENTITY) + assert current["package_fingerprint"] != before["package_fingerprint"] + assert json.loads(_run(core_python, discover, workspace).stdout)["packs"] == [] + + path = Path(probe["metadata"]) + contents = path.read_bytes() + try: + path.write_bytes(contents.replace(f"Version: {probe['version']}".encode(), b"Version: 0.0.0", 1)) + rejected = json.loads(_run(core_python, detail, workspace).stdout)["capability"]["provider_state"] + assert rejected["installed"] is rejected["ready"] is False + _run(core_python, discover, workspace, expected=2) + finally: + path.write_bytes(contents) + + evidence = b"Independent validation found eight expected values.\n" + source = tmp_path / "source" + source.mkdir() + (source / "check.txt").write_bytes(evidence) + input_file = tmp_path / "input.json" + payload = { + "schema_version": "trajectory_assessment_input_v1", + "scope": dict(goal_id=GOAL, case_id="checked-task", run_id="local-check", revision="fixed", + window="first accepted result"), + "objective": "Read the original independently accepted task evidence.", + "selection": dict(rule="One synthetic checked task", population_episodes=1, exhaustive=True), + "sources": [dict(id="check", artifact="check.txt", artifact_sha256=sha256(evidence).hexdigest(), + first_line=1, text=evidence.decode().strip())], + "episodes": [dict(id="episode", question="Did the independent check run?", source_ids=["check"], + eligible_metrics=["benefit_test"])], + } + register = [*bench, "trajectory-pack-register", "--goal-id", GOAL, + "--input-json", str(input_file), "--source-root", str(source), "--title", "Original checked result"] + payload["sources"][0]["artifact_sha256"] = "0" * 64 + input_file.write_text(json.dumps(payload), encoding="utf-8") + _run(core_python, register, workspace, expected=1) + assert json.loads(_run(core_python, discover, workspace).stdout)["packs"] == [] + payload["sources"][0]["artifact_sha256"] = sha256(evidence).hexdigest() + input_file.write_text(json.dumps(payload), encoding="utf-8") + pack = json.loads(_run(core_python, register, workspace).stdout) + observed = json.loads(_run(core_python, discover, workspace).stdout) + assert observed["default_pack_id"] == pack["pack_id"] + assert [item["title"] for item in observed["packs"]] == ["Original checked result"] + + subprocess.run(["uv", "pip", "uninstall", "--python", core_python, "loopx-capability-benchmark-toolkit"], + check=True, timeout=45) + assert _python_json(core_python, workspace, _IDENTITY) == before + _run(core_python, discover, workspace, expected=2) + replay = json.loads(_run(core_python, [*arguments, "--resume-turn-key", turn_key], workspace).stdout) + assert not any(replay["effects"][name] for name in ("host_invoked", "state_written", "quota_spent")) + assert _assert_committed(core_python, workspace, runtime, replay) == turn_key + assert registry.read_bytes() == registry_bytes + subprocess.run(install, check=True, timeout=45) + assert json.loads(_run(core_python, discover, workspace).stdout) == observed + + +@pytest.mark.parametrize( + "missing_member", + [ + "loopx/cli_commands/benchmark_study.py", + "loopx/capabilities/benchmark_toolkit/trajectory_assessment.py", + ], +) +def test_partial_toolkit_install_reports_unavailable_until_repaired( + core_python, task, wheels, tmp_path, missing_member, +): + workspace, runtime, registry, arguments = task + root = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + discover = [*root, "benchmark", "trajectory-packs", "--goal-id", GOAL] + subprocess.run( + ["uv", "pip", "install", "--offline", "--python", core_python, str(wheels[1])], + check=True, + timeout=45, + ) + probe = _python_json(core_python, workspace, f"""import json +from importlib import metadata +from pathlib import Path +owner = metadata.distribution("loopx-capability-benchmark-toolkit") +member = next(item for item in owner.files if item.as_posix() == {missing_member!r}) +print(json.dumps({{"member_path": str(Path(owner.locate_file(member)))}})) +""") + member_path = Path(probe["member_path"]) + backup_path = tmp_path / "removed_member.py" + detail = [*root, "capability", "show", "benchmark-toolkit"] + healthy_identity = _python_json(core_python, workspace, _IDENTITY) + assert healthy_identity["package_fingerprint"].startswith("sha256:") + assert json.loads(_run(core_python, detail, workspace).stdout)["capability"]["provider_state"]["ready"] is True + assert _run(core_python, [*root, "benchmark", "--help"], workspace).returncode == 0 + assert json.loads(_run(core_python, discover, workspace).stdout)["packs"] == [] + + try: + member_path.rename(backup_path) + partial = json.loads(_run(core_python, detail, workspace).stdout)["capability"] + assert partial["provider_id"] == "loopx-capability-benchmark-toolkit" + assert partial["provider_state"] == { + "declared": True, "installed": False, "enabled": False, "ready": False, + } + assert "install the matching loopx-capability-benchmark-toolkit" in partial["next_real_step"].lower() + partial_cmds = [ + entry["command"] + for group in json.loads(_run(core_python, [*root, "commands"], workspace).stdout)["groups"] + for entry in group["commands"] + ] + assert not any("loopx benchmark" in cmd for cmd in partial_cmds) + rejected = _run(core_python, [*root, "benchmark", "--help"], workspace, expected=2) + assert "install the matching loopx-capability-benchmark-toolkit" in rejected.stderr.lower() + rejected_discover = _run(core_python, discover, workspace, expected=2) + assert "install the matching loopx-capability-benchmark-toolkit" in rejected_discover.stderr.lower() + broken_identity = _python_json(core_python, workspace, _IDENTITY) + assert "package_fingerprint" not in broken_identity + core_turn = json.loads(_run(core_python, arguments, workspace).stdout) + _assert_committed(core_python, workspace, runtime, core_turn) + finally: + if backup_path.exists() and not member_path.exists(): + backup_path.rename(member_path) + + repaired = json.loads(_run(core_python, detail, workspace).stdout)["capability"] + assert repaired["provider_id"] == "loopx-capability-benchmark-toolkit" + assert repaired["provider_state"] == { + "declared": True, "installed": True, "enabled": True, "ready": True, + } + repaired_cmds = [ + entry["command"] + for group in json.loads(_run(core_python, [*root, "commands"], workspace).stdout)["groups"] + for entry in group["commands"] + ] + assert any("loopx benchmark" in cmd for cmd in repaired_cmds) + assert _run(core_python, [*root, "benchmark", "--help"], workspace).returncode == 0 + assert json.loads(_run(core_python, discover, workspace).stdout)["packs"] == [] + assert _python_json(core_python, workspace, _IDENTITY) == healthy_identity diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index c471fde2da..c2c4144012 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -60,6 +60,13 @@ def test_core_staging_excludes_workspace_and_reuses_kernel_bytes(tmp_path): assert not (staged / "loopx" / name).exists() # Chat UI/store modules are excluded; the typed action authority is Core-owned. assert {path.name for path in (staged / "loopx").glob("chat_*.py")} == {"chat_action_store.py"} + package = staged / "loopx" + assert {file.name for file in (package / "capabilities/benchmark_toolkit").iterdir()} == { + "README.md", "catalog_entry.py", "four_arm_contract.py", + } + assert not list((package / "cli_commands").glob("benchmark_*.py")) + assert not (package / "presentation/research_analysis_api.py").exists() + assert not (package / "presentation/runtime_workspace.py").exists() for name in ("entrypoint.py", "chat_action_store.py", "control_plane/turn_driver/executor.py", "control_plane/coordination/sqlite_authority_store.ts", "extensions/lark/extension.toml"): @@ -239,6 +246,12 @@ def test_installed_core_identity_help_and_unavailable_workspace(core_python, tmp script = '''import importlib.util as u,json,loopx from pathlib import Path for name in ('loopx.cli','loopx.chat','loopx.web','loopx.canary'):assert u.find_spec(name) is None,name +for name in ('loopx.capabilities.benchmark_toolkit.native_codex_goal', + 'loopx.capabilities.benchmark_toolkit.experiment_board', + 'loopx.capabilities.benchmark_toolkit.trajectory_assessment_store', + 'loopx.cli_commands.benchmark_dispatch','loopx.presentation.research_analysis_api', + 'loopx.presentation.runtime_workspace'): + assert u.find_spec(name) is None,name from loopx.release_manifest import _distribution_runtime_fingerprint assert _distribution_runtime_fingerprint() is not None from loopx import doctor @@ -269,6 +282,26 @@ def test_installed_core_identity_help_and_unavailable_workspace(core_python, tmp assert not list(tmp_path.iterdir()) +def test_installed_core_lists_benchmark_as_unavailable(core_python, tmp_path): + catalog = json.loads(_run(core_python, ["capability", "list", "--format", "json"], tmp_path, + environment={"PATH": str(tmp_path)}).stdout) + records = {record["id"]: record for record in catalog["capabilities"]} + detail = json.loads(_run(core_python, ["capability", "show", "benchmark-toolkit", "--format", "json"], + tmp_path).stdout)["capability"] + unavailable = {"declared": True, "installed": False, "enabled": False, "ready": False} + assert records["decision-context"]["provider_state"]["ready"] is True + for record in (records["benchmark-toolkit"], detail): + assert record["provider_id"] == "loopx-capability-benchmark-toolkit" + assert record["provider_state"] == unavailable + assert "ordinary LoopX installation" in record["next_real_step"] + provider = next(provider for provider in catalog["providers"] + if provider["id"] == "loopx-capability-benchmark-toolkit") + assert {key: provider[key] for key in unavailable} == unavailable + refusal = _run(core_python, ["benchmark", "--help"], tmp_path, expected=2) + assert "unavailable in the standalone core" in refusal.stderr + assert not list(tmp_path.iterdir()) + + @pytest.mark.parametrize("host_surface", ("shell", "traex-cli")) def test_installed_core_guided_start_identity_and_readback(core_python, tmp_path, monkeypatch, host_surface): from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime diff --git a/tests/test_distribution_runtime_identity.py b/tests/test_distribution_runtime_identity.py index a591b565e1..6e0324b91b 100644 --- a/tests/test_distribution_runtime_identity.py +++ b/tests/test_distribution_runtime_identity.py @@ -136,6 +136,59 @@ def test_record_root_alias_keeps_exact_physical_ownership(owned_package): assert manifest.release_runtime_identity() == before +def test_missing_record_declared_file_refuses_runtime_identity_in_real_wheel(tmp_path: Path): + version = manifest.__version__ + metadata = f"loopx-{version}.dist-info" + contents = { + "loopx/__init__.py": Path(manifest.__file__).with_name("__init__.py").read_text(), + "loopx/release_manifest.py": Path(manifest.__file__).read_text(), + "loopx/doctor_git.py": Path(manifest.__file__).with_name("doctor_git.py").read_text(), + "loopx/python_install_owner.py": Path(manifest.__file__).with_name("python_install_owner.py").read_text(), + "loopx/extensions/__init__.py": "", + "loopx/extensions/process_runtime.py": Path(manifest.__file__).with_name( + "extensions" + ).joinpath("process_runtime.py").read_text(), + f"{metadata}/METADATA": f"Metadata-Version: 2.1\nName: loopx\nVersion: {version}\n", + f"{metadata}/WHEEL": "Wheel-Version: 1.0\nGenerator: test\nRoot-Is-Purelib: true\nTag: py3-none-any\n", + } + contents[f"{metadata}/RECORD"] = "".join(f"{name},,\n" for name in [*contents, f"{metadata}/RECORD"]) + wheel = tmp_path / f"loopx-{version}-py3-none-any.whl" + with zipfile.ZipFile(wheel, "w") as archive: + for name, content in contents.items(): + archive.writestr(name, content) + environment = tmp_path / "env" + venv.EnvBuilder(with_pip=True, symlinks=os.name != "nt").create(environment) + python = environment / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python") + subprocess.run([str(python), "-I", "-m", "pip", "install", "--no-index", "--no-deps", + "--disable-pip-version-check", "--no-compile", str(wheel)], + check=True, capture_output=True, text=True, timeout=60) + probe = subprocess.check_output([str(python), "-I", "-c", + "import json; from importlib.metadata import distribution; " + "from loopx.release_manifest import release_runtime_identity; " + "target = next(p.locate() for p in distribution('loopx').files if p.as_posix() == 'loopx/extensions/process_runtime.py'); " + "print(json.dumps({'identity': release_runtime_identity(), 'target': str(target)}))" + ], text=True, timeout=60) + before = json.loads(probe) + assert before["identity"]["package_fingerprint"].startswith("sha256:") + target = Path(before["target"]) + backup = tmp_path / "process_runtime.py.removed" + try: + target.rename(backup) + broken = json.loads(subprocess.check_output([str(python), "-I", "-c", + "import json; from loopx.release_manifest import release_runtime_identity; " + "print(json.dumps(release_runtime_identity()))" + ], text=True, timeout=60)) + assert "package_fingerprint" not in broken + finally: + if backup.exists() and not target.exists(): + backup.rename(target) + restored = json.loads(subprocess.check_output([str(python), "-I", "-c", + "import json; from loopx.release_manifest import release_runtime_identity; " + "print(json.dumps(release_runtime_identity()))" + ], text=True, timeout=60)) + assert restored == before["identity"] + + def test_core_companion_distributions_extend_and_fence_runtime_identity( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ):