From 8b2092d8bb5e89ddb2335dfa13cd9d9c49c7f363 Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 02:15:51 +0800 Subject: [PATCH 1/6] Keep optional Turn recall execution outside standalone Core Signed-off-by: cicolord --- .../rfcs/monorepo-distribution-split-v0.md | 9 +++ .../monorepo-distribution-split-v0.zh-CN.md | 5 ++ .../agent_turn_recall/__init__.py | 68 ++++++++++++------- .../agent_turn_recall/catalog_entry.py | 6 +- loopx/capabilities/agent_turn_recall/core.py | 6 +- .../capabilities/agent_turn_recall/runtime.py | 27 ++++++-- loopx/capabilities/catalog.py | 18 ++++- packages/loopx-core/README.md | 6 ++ packages/loopx-core/prepare.py | 6 ++ .../test_context_provider_loading.py | 13 ++++ tests/test_core_distribution.py | 43 ++++++++++++ 11 files changed, 173 insertions(+), 34 deletions(-) diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index 6e5521ac0a..e9de40a78a 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -413,6 +413,15 @@ packet cannot be treated as proof the executor has the prior context. Recover through the owning contract when continuity is unknown. Capability instructions are supplied when applicable; authority is never inferred from prompt text. +The standalone Core artifact keeps the `agent-turn-recall` catalog and +admission readback. The ordinary distribution supplies its command and +execution code. Discovery reads the declaration without loading recall, and +automatic recall loads its implementation after explicit opt-in. A Core Turn +with that opt-in records the missing implementation and continues ordinary work. +Independently enabled outcome ingest keeps its existing recovery path. This is +one artifact boundary for a Standard capability. The complete Standard preset +still needs package composition and installed qualification. + Optional observers consume committed events or bounded projections. Their latency must not enter admission/settlement transactions unless the existing contract explicitly requires their receipt. Batch best-effort telemetry only; 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 2303929af4..04a52c6b40 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -285,6 +285,11 @@ capability 包直接采用现有 `extension.toml` 契约,不做扩展。唯一 不能因为 packet 更小,就认为 executor 已掌握前文。连续性未知时走所属契约的恢复路径。 Capability 指令仅在适用时提供;authority 不能从 prompt 文字推导。 +独立 Core 安装包保留 `agent-turn-recall` 的目录声明和准入回读,普通发行版提供命令和执行代码。 +发现能力时只读取声明,显式启用自动回忆后才加载执行实现。启用了自动回忆的 Core Turn 会回读 +实现缺失并继续普通任务。独立启用的结果入库沿用既有恢复路径。这为 Standard 的一项能力划出了 +安装包边界,完整的 Standard 预设仍需完成装配和安装态验收。 + 可选 observer 消费已提交事件或有界投影。除非现有契约明确要求它的 receipt, 其延迟不能进入准入/结算事务。只批处理尽力而为的 telemetry;不能为满足时间目标而延迟 authority receipt 持久化、弱化 fsync/事务保证,或缓存过期权限/租约决策。 diff --git a/loopx/capabilities/agent_turn_recall/__init__.py b/loopx/capabilities/agent_turn_recall/__init__.py index a386cc7e33..2765ab5c65 100644 --- a/loopx/capabilities/agent_turn_recall/__init__.py +++ b/loopx/capabilities/agent_turn_recall/__init__.py @@ -1,25 +1,45 @@ -from .core import ( - AGENT_TURN_RECALL_CONTEXT_SCHEMA_VERSION, - AGENT_TURN_RECALL_SCHEMA_VERSION, - AGENT_TURN_SITUATION_SCHEMA_VERSION, - build_agent_turn_recall_preview, - build_agent_turn_situation, - run_agent_turn_recall, -) -from .runtime import ( - agent_turn_recall_receipt_path, - run_configured_agent_turn_recall, - run_configured_agent_turn_recall_fail_open, -) +"""Public recall exports, loaded when selected by a caller.""" -__all__ = [ - "AGENT_TURN_RECALL_CONTEXT_SCHEMA_VERSION", - "AGENT_TURN_RECALL_SCHEMA_VERSION", - "AGENT_TURN_SITUATION_SCHEMA_VERSION", - "build_agent_turn_recall_preview", - "build_agent_turn_situation", - "agent_turn_recall_receipt_path", - "run_configured_agent_turn_recall", - "run_configured_agent_turn_recall_fail_open", - "run_agent_turn_recall", -] +from importlib import import_module +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from .catalog_entry import AGENT_TURN_RECALL_SCHEMA_VERSION as AGENT_TURN_RECALL_SCHEMA_VERSION + from .core import ( + AGENT_TURN_RECALL_CONTEXT_SCHEMA_VERSION as AGENT_TURN_RECALL_CONTEXT_SCHEMA_VERSION, + AGENT_TURN_SITUATION_SCHEMA_VERSION as AGENT_TURN_SITUATION_SCHEMA_VERSION, + build_agent_turn_recall_preview as build_agent_turn_recall_preview, + build_agent_turn_situation as build_agent_turn_situation, + run_agent_turn_recall as run_agent_turn_recall, + ) + from .runtime import ( + agent_turn_recall_receipt_path as agent_turn_recall_receipt_path, + run_configured_agent_turn_recall as run_configured_agent_turn_recall, + run_configured_agent_turn_recall_fail_open as run_configured_agent_turn_recall_fail_open, + ) + +_EXPORTS = { + "AGENT_TURN_RECALL_CONTEXT_SCHEMA_VERSION": ".core", + "AGENT_TURN_RECALL_SCHEMA_VERSION": ".catalog_entry", + "AGENT_TURN_SITUATION_SCHEMA_VERSION": ".core", + "build_agent_turn_recall_preview": ".core", + "build_agent_turn_situation": ".core", + "agent_turn_recall_receipt_path": ".runtime", + "run_configured_agent_turn_recall": ".runtime", + "run_configured_agent_turn_recall_fail_open": ".runtime", + "run_agent_turn_recall": ".core", +} +__all__ = list(_EXPORTS) + + +def __getattr__(name: str) -> Any: + module = _EXPORTS.get(name) + if module is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + value = getattr(import_module(module, __name__), name) + globals()[name] = value + return value + + +def __dir__() -> list[str]: + return sorted(set(globals()) | set(__all__)) diff --git a/loopx/capabilities/agent_turn_recall/catalog_entry.py b/loopx/capabilities/agent_turn_recall/catalog_entry.py index 2879517e76..d778f6cbc8 100644 --- a/loopx/capabilities/agent_turn_recall/catalog_entry.py +++ b/loopx/capabilities/agent_turn_recall/catalog_entry.py @@ -3,6 +3,10 @@ from typing import Any +AGENT_TURN_RECALL_SCHEMA_VERSION = "agent_turn_recall_v0" +AGENT_TURN_RECALL_SURFACE_ID = "agent_workflow.turn_admission" + + AGENT_TURN_RECALL_CATALOG_ENTRY: dict[str, Any] = { "id": "agent-turn-recall", "origin": "builtin", @@ -60,7 +64,7 @@ "doc": "loopx/capabilities/agent_turn_recall/README.md", }, { - "schema_version": "agent_turn_recall_v0", + "schema_version": AGENT_TURN_RECALL_SCHEMA_VERSION, "module": "loopx.capabilities.agent_turn_recall.core", "doc": "loopx/capabilities/agent_turn_recall/README.md", }, diff --git a/loopx/capabilities/agent_turn_recall/core.py b/loopx/capabilities/agent_turn_recall/core.py index 631c99a262..6004be1ba8 100644 --- a/loopx/capabilities/agent_turn_recall/core.py +++ b/loopx/capabilities/agent_turn_recall/core.py @@ -7,12 +7,14 @@ from ...control_plane.digest_envelope import sha256_envelope from ...control_plane.runtime.public_safety import public_safe_compact_text from ..context_providers.base import ContextProvider +from .catalog_entry import ( + AGENT_TURN_RECALL_SCHEMA_VERSION as AGENT_TURN_RECALL_SCHEMA_VERSION, + AGENT_TURN_RECALL_SURFACE_ID as AGENT_TURN_RECALL_SURFACE_ID, +) AGENT_TURN_SITUATION_SCHEMA_VERSION = "agent_turn_situation_v0" AGENT_TURN_RECALL_CONTEXT_SCHEMA_VERSION = "agent_turn_recall_context_v0" -AGENT_TURN_RECALL_SCHEMA_VERSION = "agent_turn_recall_v0" -AGENT_TURN_RECALL_SURFACE_ID = "agent_workflow.turn_admission" MAX_RECENT_OUTCOMES = 3 diff --git a/loopx/capabilities/agent_turn_recall/runtime.py b/loopx/capabilities/agent_turn_recall/runtime.py index 5eaca95d6f..98b01f6fa5 100644 --- a/loopx/capabilities/agent_turn_recall/runtime.py +++ b/loopx/capabilities/agent_turn_recall/runtime.py @@ -8,23 +8,22 @@ from collections.abc import Mapping from datetime import datetime, timezone from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from ...history import load_registry from ...materials import find_registry_goal, goal_repo -from ..context_providers.base import ContextProvider from ..reward_memory.experiment import ( resolve_reward_memory_experiment, resolve_reward_memory_surface_config, ) -from .core import ( +from .catalog_entry import ( AGENT_TURN_RECALL_SCHEMA_VERSION, AGENT_TURN_RECALL_SURFACE_ID, - build_agent_turn_recall_preview, - build_agent_turn_situation, - run_agent_turn_recall, ) +if TYPE_CHECKING: + from ..context_providers.base import ContextProvider + AGENT_TURN_RECALL_RECEIPT_SCHEMA_VERSION = "agent_turn_recall_receipt_v1" _SAFE_PATH_TOKEN = re.compile(r"[^A-Za-z0-9._-]+") @@ -275,6 +274,22 @@ def with_reconciliation(payload: dict[str, Any]) -> dict[str, Any]: ) ) + try: + from .core import ( + build_agent_turn_recall_preview, + build_agent_turn_situation, + run_agent_turn_recall, + ) + except ModuleNotFoundError as error: + if error.name != f"{__package__}.core": + raise + # Recall is optional in an installed Core. Its absence must not mask + # the original configuration or suppress independent ingest recovery. + return with_reconciliation( + _unavailable_payload(goal_id=goal_id, agent_id=agent_id, status=experiment_status) + | {"status": "runtime_unavailable", "reason_code": "automatic_recall_not_installed"} + ) + identity = reward_memory_turn_identity_scope(config) situation = build_agent_turn_situation( quota_decision, diff --git a/loopx/capabilities/catalog.py b/loopx/capabilities/catalog.py index 13b7571ac1..6ed146459c 100644 --- a/loopx/capabilities/catalog.py +++ b/loopx/capabilities/catalog.py @@ -1,6 +1,7 @@ from __future__ import annotations from collections.abc import Iterable, Mapping +from importlib.util import find_spec from pathlib import Path from typing import Any @@ -139,6 +140,21 @@ def _register_declared_implementation_providers( ) +def _record_for_installed_recall( + registry: CapabilityRegistry, record: Mapping[str, Any], +) -> Mapping[str, Any]: + if record is not AGENT_TURN_RECALL_CATALOG_ENTRY or find_spec( + "loopx.capabilities.agent_turn_recall.core" + ) is not None: + return record + if not any(provider["id"] == "loopx" for provider in registry.providers()): + registry.register_provider({"id": "loopx", "origin": "builtin", "installed": False}) + return dict(record) | { + "provider_id": "loopx", + "next_real_step": "Use the ordinary LoopX installation for agent-turn recall.", + } + + def build_capability_registry( extension_manifest_paths: Iterable[str | Path] = (), *, @@ -156,7 +172,7 @@ def build_capability_registry( } ) for record in BUILTIN_CAPABILITIES: - registry.register_capability(record) + registry.register_capability(_record_for_installed_recall(registry, record)) for record in BUILTIN_CAPABILITIES: _register_declared_implementation_providers(registry, record) for manifest in extension_catalog_entries( diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index ae5ef9df5d..93f65081ee 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -58,6 +58,12 @@ complete constraints, compaction requires recovery, and changed capture bytes are refused. Its native events are protocol fixtures; they do not establish model retention or installed-host adoption. +`capability show agent-turn-recall` reports the optional recall implementation +as unavailable in Core. Use the ordinary LoopX installation to run recall. +If an existing Goal explicitly enables automatic recall, Core records the +missing implementation and continues the task. Outcome ingest retains its +independent configuration and recovery path. + The candidate owns the same `loopx` import namespace and console command as the ordinary distribution. Do not co-install or overlay them. Return to the ordinary installation by switching back to its environment; preserve task state and diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index d53291b160..b7b8fc05ad 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -15,6 +15,11 @@ EXCLUDED_TREES = ("loopx/chat/", "loopx/web/", "loopx/canary/") EXCLUDED_MODULES = {"loopx/cli.py", "loopx/chat.py"} SOURCE_SUFFIXES = {".py", ".ts", ".json", ".mjs", ".js", ".md", ".toml"} +# Keep recall's declaration and admission readback in Core. +RECALL_IMPLEMENTATION_MODULES = { + "loopx/capabilities/agent_turn_recall/cli.py", + "loopx/capabilities/agent_turn_recall/core.py", +} def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: @@ -29,6 +34,7 @@ def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: ).split(b"\0") sources = [Path(name.decode("utf-8")) for name in names if name] sources = [path for path in sources if path.suffix in SOURCE_SUFFIXES + and path.as_posix() not in RECALL_IMPLEMENTATION_MODULES and path.as_posix() not in EXCLUDED_MODULES and not (path.parent == Path("loopx") and path.name.startswith("chat_")) and not path.as_posix().startswith(EXCLUDED_TREES)] diff --git a/tests/capabilities/test_context_provider_loading.py b/tests/capabilities/test_context_provider_loading.py index 58232f774f..80c21102b1 100644 --- a/tests/capabilities/test_context_provider_loading.py +++ b/tests/capabilities/test_context_provider_loading.py @@ -179,11 +179,24 @@ def resolve(**kwargs): assert result['quota_spend_performed'] is False assert result['external_writes_performed'] is False assert result['grants_new_action_authority'] is False + assert 'loopx.capabilities.agent_turn_recall.core' not in sys.modules assert 'loopx.capabilities.reward_memory.runtime_hooks' not in sys.modules assert 'loopx.capabilities.reward_memory.read_authority' not in sys.modules """) +def test_turn_recall_catalog_discovery_does_not_load_execution() -> None: + _run(""" + import sys + from loopx.capabilities.catalog import build_capability_registry + recall = build_capability_registry().get('agent-turn-recall') + assert recall['default_enabled'] is False + assert recall['provider_state']['ready'] is True + for module in ('core', 'runtime', 'cli'): + assert 'loopx.capabilities.agent_turn_recall.' + module not in sys.modules, module + """) + + @pytest.mark.parametrize("package", ["context_providers", "anti_entropy", "agent_turn_recall"]) @pytest.mark.parametrize("mode", ["attribute", "from", "star"]) def test_explicit_exports_remain_original_owner_objects( diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index f39fae8197..842491c9d6 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -65,6 +65,11 @@ def test_core_staging_excludes_workspace_and_reuses_kernel_bytes(tmp_path): assert (staged / "loopx" / name).read_bytes() == (REPOSITORY / "loopx" / name).read_bytes() assert not (staged / ".loopx").exists() assert not (staged / "tests").exists() + recall = staged / "loopx/capabilities/agent_turn_recall" + for name in ("core.py", "cli.py"): + assert not (recall / name).exists() + for name in ("catalog_entry.py", "runtime.py"): + assert (recall / name).is_file() @pytest.fixture @@ -312,6 +317,18 @@ def test_installed_core_catalog_entries_have_executable_parsers(core_python, tmp _run(core_python, [*prefix, "--help"], tmp_path) +def test_installed_core_reports_optional_turn_recall(core_python, tmp_path): + detail = _run(core_python, ["capability", "show", "agent-turn-recall", "--format", "json"], tmp_path) + record = json.loads(detail.stdout)["capability"] + assert record["provider_id"] == "loopx" + assert record["default_enabled"] is False + assert record["provider_state"] == {"declared": True, "installed": False, "enabled": False, "ready": False} + assert "ordinary LoopX installation" in record["next_real_step"] + refusal = _run(core_python, ["agent-turn-recall", "--help"], tmp_path, expected=2) + assert "unavailable in the standalone core" in refusal.stderr + assert not list(tmp_path.iterdir()) + + def test_installed_core_deep_doctor_verifies_distribution_ownership(core_python, tmp_path, monkeypatch): from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime @@ -548,6 +565,32 @@ def test_installed_core_goal_lifecycle_respects_outer_controller(core_python, ta assert _spends(runtime) == 0 and not (workspace / "host-invocations").exists() +@pytest.mark.parametrize("ingest", [False, True]) +def test_installed_core_completes_turn_with_configured_optional_recall(core_python, task, ingest): + from tests.control_plane.reward_memory_host_fixture import enable_live_memory + + workspace, runtime, registry, arguments = task + enable_live_memory(registry, ingest=ingest) + host_index = arguments.index("--host-adapter-command-json") + 1 + host = workspace / "recall-host.py" + host.write_text(HOST_SOURCE.replace( + "request=json.load(sys.stdin)\n", """request=json.load(sys.stdin) +pathlib.Path('recall-readback.json').write_text(json.dumps(request.get('reward_memory_recall'))) +""", + )) + arguments[host_index] = json.dumps([core_python, "-I", str(host)]) + execution = subprocess.run([core_python, "-I", "-m", "loopx.entrypoint", *arguments], + cwd=workspace, env=_environment(core_python), capture_output=True, text=True, timeout=90) + assert execution.returncode == 0, (execution.stdout, execution.stderr) + _assert_committed(core_python, workspace, runtime, json.loads(execution.stdout)) + recall = json.loads((workspace / "recall-readback.json").read_text()) + assert recall["status"] == "runtime_unavailable" + assert recall["reason_code"] == "automatic_recall_not_installed" + assert recall["provider_call_count"] == 0 and recall["context"] is None + assert recall["experiment"]["automatic_ingest"] is ingest + assert ("outcome_ingest_reconciliation" in recall) is ingest + + def _assert_committed(core_python, workspace, runtime, result): assert result["status"] == "committed", result assert result["validation"]["status"] == "passed" From 4f525f42fcf4ae3c41a26111f8954c04925e45c3 Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 02:22:27 +0800 Subject: [PATCH 2/6] Preserve the capability catalog type budget Signed-off-by: cicolord --- loopx/capabilities/catalog.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/loopx/capabilities/catalog.py b/loopx/capabilities/catalog.py index 6ed146459c..c83eb11fdd 100644 --- a/loopx/capabilities/catalog.py +++ b/loopx/capabilities/catalog.py @@ -141,8 +141,8 @@ def _register_declared_implementation_providers( def _record_for_installed_recall( - registry: CapabilityRegistry, record: Mapping[str, Any], -) -> Mapping[str, Any]: + registry: CapabilityRegistry, record: Mapping[str, object], +) -> Mapping[str, object]: if record is not AGENT_TURN_RECALL_CATALOG_ENTRY or find_spec( "loopx.capabilities.agent_turn_recall.core" ) is not None: From 63f1e01d81b54748e8400561b2b87476a80becc6 Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 04:20:51 +0800 Subject: [PATCH 3/6] Install built-in Turn recall alongside the matching Core wheel Signed-off-by: cicolord --- .github/workflows/package-smoke.yml | 17 ++ .../rfcs/monorepo-distribution-split-v0.md | 20 ++- .../monorepo-distribution-split-v0.zh-CN.md | 10 +- .../agent_turn_recall/catalog_entry.py | 26 +++ .../capabilities/agent_turn_recall/runtime.py | 13 +- loopx/capabilities/catalog.py | 12 +- loopx/cli_runtime.py | 16 ++ .../README.md | 33 ++++ .../pyproject.toml | 19 +++ packages/loopx-core/README.md | 11 +- packages/loopx-core/prepare.py | 49 ++++-- tests/test_core_distribution.py | 3 +- tests/test_core_recall_distribution.py | 161 ++++++++++++++++++ 13 files changed, 346 insertions(+), 44 deletions(-) create mode 100644 packages/loopx-capability-agent-turn-recall/README.md create mode 100644 packages/loopx-capability-agent-turn-recall/pyproject.toml create mode 100644 tests/test_core_recall_distribution.py diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index d130915e13..6dadb66659 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -5,8 +5,10 @@ on: paths: - ".github/workflows/package-smoke.yml" - "packages/loopx-core/**" + - "packages/loopx-capability-agent-turn-recall/**" - "loopx/**" - "tests/test_core_distribution.py" + - "tests/test_core_recall_distribution.py" - "tests/control_plane/test_installed_core_context.py" - "packages/loopx-repo-health/**" - "packages/loopx-obelisk/**" @@ -19,8 +21,10 @@ on: paths: - ".github/workflows/package-smoke.yml" - "packages/loopx-core/**" + - "packages/loopx-capability-agent-turn-recall/**" - "loopx/**" - "tests/test_core_distribution.py" + - "tests/test_core_recall_distribution.py" - "tests/control_plane/test_installed_core_context.py" - "packages/loopx-repo-health/**" - "packages/loopx-obelisk/**" @@ -65,6 +69,19 @@ jobs: uv run --extra test python -m pytest -q tests/test_core_distribution.py tests/control_plane/test_installed_core_context.py + - name: Qualify matched recall installation, execution, and removal + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-agent-turn-recall --output "$RUNNER_TEMP/recall-source" + uv build --wheel "$RUNNER_TEMP/recall-source" --out-dir "$RUNNER_TEMP/recall-dist" + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ + "$RUNNER_TEMP"/recall-dist/loopx_capability_agent_turn_recall-*.whl + LOOPX_RECALL_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_recall_distribution.py + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-agent-turn-recall + uv run --extra test python -m pytest -q tests/test_core_distribution.py \ + -k 'reports_optional_turn_recall or completes_turn_with_configured_optional_recall' codex-provider-routing: name: loopx-codex-provider-routing diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index e9de40a78a..6a342835b1 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -413,14 +413,18 @@ packet cannot be treated as proof the executor has the prior context. Recover through the owning contract when continuity is unknown. Capability instructions are supplied when applicable; authority is never inferred from prompt text. -The standalone Core artifact keeps the `agent-turn-recall` catalog and -admission readback. The ordinary distribution supplies its command and -execution code. Discovery reads the declaration without loading recall, and -automatic recall loads its implementation after explicit opt-in. A Core Turn -with that opt-in records the missing implementation and continues ordinary work. -Independently enabled outcome ingest keeps its existing recovery path. This is -one artifact boundary for a Standard capability. The complete Standard preset -still needs package composition and installed qualification. +The first Standard capability artifact is the release-coupled +`loopx-capability-agent-turn-recall` wheel. It supplies the two existing built-in +command and execution modules in the same environment as matching Core. Core's +catalog and admission readback, the capability ID, and the original source-tree +owner govern both installations. The wheels own disjoint files and use the exact +Core release version for this built-in split. Independent provider packages use +the public capability boundary described above. Discovery reads metadata without +loading recall. Automatic recall loads its implementation only after the existing +Goal/Agent opt-in. Core alone reports the missing implementation and continues +ordinary work. Independently enabled outcome ingest retains its recovery path. +The remaining Standard capabilities and the full preset need installed +qualification. Optional observers consume committed events or bounded projections. Their latency must not enter admission/settlement transactions unless the existing 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 04a52c6b40..3b2aed727f 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -285,10 +285,12 @@ capability 包直接采用现有 `extension.toml` 契约,不做扩展。唯一 不能因为 packet 更小,就认为 executor 已掌握前文。连续性未知时走所属契约的恢复路径。 Capability 指令仅在适用时提供;authority 不能从 prompt 文字推导。 -独立 Core 安装包保留 `agent-turn-recall` 的目录声明和准入回读,普通发行版提供命令和执行代码。 -发现能力时只读取声明,显式启用自动回忆后才加载执行实现。启用了自动回忆的 Core Turn 会回读 -实现缺失并继续普通任务。独立启用的结果入库沿用既有恢复路径。这为 Standard 的一项能力划出了 -安装包边界,完整的 Standard 预设仍需完成装配和安装态验收。 +Standard 的首个能力安装包是随 Core 同版本构建的 `loopx-capability-agent-turn-recall`。 +它把现有的命令与执行两个内置模块安装到同一个 Core 环境。两种安装组合复用 Core 的 +能力目录和准入回读、原能力 ID 与源码 owner。两个 wheel 拥有互不重叠的文件,此内置 +拆分精确绑定 Core 版本。独立 provider 包仍按上文公共能力边界接入。能力发现只读取元数据, +按既有 Goal/Agent 配置显式启用后才加载自动回忆。只安装 Core 时会回读实现缺失并继续 +普通任务。独立启用的结果入库沿用既有恢复路径。其余 Standard 能力和完整预设仍需安装态验收。 可选 observer 消费已提交事件或有界投影。除非现有契约明确要求它的 receipt, 其延迟不能进入准入/结算事务。只批处理尽力而为的 telemetry;不能为满足时间目标而延迟 diff --git a/loopx/capabilities/agent_turn_recall/catalog_entry.py b/loopx/capabilities/agent_turn_recall/catalog_entry.py index d778f6cbc8..947169fe57 100644 --- a/loopx/capabilities/agent_turn_recall/catalog_entry.py +++ b/loopx/capabilities/agent_turn_recall/catalog_entry.py @@ -1,10 +1,36 @@ from __future__ import annotations +from importlib.util import find_spec from typing import Any AGENT_TURN_RECALL_SCHEMA_VERSION = "agent_turn_recall_v0" AGENT_TURN_RECALL_SURFACE_ID = "agent_workflow.turn_admission" +RECALL_DISTRIBUTION = "loopx-capability-agent-turn-recall" +RECALL_INSTALL_HINT = f"Install the matching {RECALL_DISTRIBUTION} wheel in this Core environment." + + +def agent_turn_recall_installed(*, builtin_cli_present: bool | None = None) -> bool: + """Observe the built-in deployment without loading its command or provider.""" + specs = [find_spec(f"{__package__}.{name}") for name in ("cli", "core")] + if any(spec is None or spec.origin is None for spec in specs): + return False + if builtin_cli_present is None: + builtin_cli_present = find_spec("loopx.cli") is not None + if builtin_cli_present: + return True + + from importlib.metadata import PackageNotFoundError, distribution + from pathlib import Path + + try: + recall = distribution(RECALL_DISTRIBUTION) + if recall.version != distribution("loopx-core").version: + return False + except PackageNotFoundError: + return False + recorded = {Path(recall.locate_file(path)).resolve() for path in recall.files or ()} + return all(spec and spec.origin and Path(spec.origin).resolve() in recorded for spec in specs) AGENT_TURN_RECALL_CATALOG_ENTRY: dict[str, Any] = { diff --git a/loopx/capabilities/agent_turn_recall/runtime.py b/loopx/capabilities/agent_turn_recall/runtime.py index 98b01f6fa5..2fba8abbb5 100644 --- a/loopx/capabilities/agent_turn_recall/runtime.py +++ b/loopx/capabilities/agent_turn_recall/runtime.py @@ -19,6 +19,7 @@ from .catalog_entry import ( AGENT_TURN_RECALL_SCHEMA_VERSION, AGENT_TURN_RECALL_SURFACE_ID, + agent_turn_recall_installed, ) if TYPE_CHECKING: @@ -274,15 +275,7 @@ def with_reconciliation(payload: dict[str, Any]) -> dict[str, Any]: ) ) - try: - from .core import ( - build_agent_turn_recall_preview, - build_agent_turn_situation, - run_agent_turn_recall, - ) - except ModuleNotFoundError as error: - if error.name != f"{__package__}.core": - raise + if not agent_turn_recall_installed(): # Recall is optional in an installed Core. Its absence must not mask # the original configuration or suppress independent ingest recovery. return with_reconciliation( @@ -290,6 +283,8 @@ def with_reconciliation(payload: dict[str, Any]) -> dict[str, Any]: | {"status": "runtime_unavailable", "reason_code": "automatic_recall_not_installed"} ) + from .core import build_agent_turn_recall_preview, build_agent_turn_situation, run_agent_turn_recall + identity = reward_memory_turn_identity_scope(config) situation = build_agent_turn_situation( quota_decision, diff --git a/loopx/capabilities/catalog.py b/loopx/capabilities/catalog.py index c83eb11fdd..8f5db43613 100644 --- a/loopx/capabilities/catalog.py +++ b/loopx/capabilities/catalog.py @@ -17,7 +17,9 @@ from .decision_context.catalog_entry import DECISION_CONTEXT_CATALOG_ENTRY from .project_skill_delivery.catalog_entry import PROJECT_SKILL_DELIVERY_CATALOG_ENTRY from .material_lifecycle.catalog_entry import MATERIAL_LIFECYCLE_CATALOG_ENTRY -from .agent_turn_recall.catalog_entry import AGENT_TURN_RECALL_CATALOG_ENTRY +from .agent_turn_recall.catalog_entry import ( + AGENT_TURN_RECALL_CATALOG_ENTRY, RECALL_INSTALL_HINT, agent_turn_recall_installed, +) from .semantic_preference.catalog_entry import SEMANTIC_PREFERENCE_CATALOG_ENTRY from .reward_memory.catalog_entry import REWARD_MEMORY_CATALOG_ENTRY from .periodic_report.catalog_entry import PERIODIC_REPORT_CATALOG_ENTRY @@ -143,15 +145,15 @@ def _register_declared_implementation_providers( def _record_for_installed_recall( registry: CapabilityRegistry, record: Mapping[str, object], ) -> Mapping[str, object]: - if record is not AGENT_TURN_RECALL_CATALOG_ENTRY or find_spec( - "loopx.capabilities.agent_turn_recall.core" - ) is not None: + if record is not AGENT_TURN_RECALL_CATALOG_ENTRY or agent_turn_recall_installed( + builtin_cli_present=find_spec("loopx.cli") is not None, + ): return record if not any(provider["id"] == "loopx" for provider in registry.providers()): registry.register_provider({"id": "loopx", "origin": "builtin", "installed": False}) return dict(record) | { "provider_id": "loopx", - "next_real_step": "Use the ordinary LoopX installation for agent-turn recall.", + "next_real_step": RECALL_INSTALL_HINT, } diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index bc674449aa..dd22837e96 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -932,6 +932,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 == "agent-turn-recall": + from .capabilities.agent_turn_recall.cli import handle_agent_turn_recall_command + + result = handle_agent_turn_recall_command( + args, registry_path=registry_path, output_format=output_format, print_payload=print_payload, + ) else: result = dispatch_common_command( args, @@ -1011,6 +1017,16 @@ def main(argv: list[str] | None = None) -> int: def _run_command(command: str | None, raw_argv: list[str]) -> int: + if command == "agent-turn-recall" and _standalone_core(): + from .capabilities.agent_turn_recall.catalog_entry import RECALL_INSTALL_HINT, agent_turn_recall_installed + + parser, subparsers = build_cli_parser() + if not agent_turn_recall_installed(): + parser.error(f"agent-turn-recall is unavailable in the standalone core. {RECALL_INSTALL_HINT}") + from .capabilities.agent_turn_recall.cli import register_agent_turn_recall_commands + + register_agent_turn_recall_commands(subparsers, add_subcommand_format) + return _dispatch_selected(parse_cli_args(parser, raw_argv), raw_argv) if command == "version": version_exports = sys.modules.get("loopx.cli_commands") # Inspect bound exports without triggering the lazy facade. Explicit diff --git a/packages/loopx-capability-agent-turn-recall/README.md b/packages/loopx-capability-agent-turn-recall/README.md new file mode 100644 index 0000000000..3e9dd9449c --- /dev/null +++ b/packages/loopx-capability-agent-turn-recall/README.md @@ -0,0 +1,33 @@ +# Agent Turn Recall for LoopX Core + +This optional wheel supplies the existing built-in Agent Turn Recall command and +implementation. It is built from the same checkout as `loopx-core` and requires +that exact Core version. Install the two wheels in one isolated environment. +The ordinary `loopx` wheel supplies its own bundled recall implementation and +uses a separate environment. + +From the repository root, stage and build the matched artifacts outside the +checkout: + +```sh +build_dir="$(mktemp -d)" +python packages/loopx-core/prepare.py --output "$build_dir/core" +python packages/loopx-core/prepare.py --distribution loopx-capability-agent-turn-recall \ + --output "$build_dir/recall" +uv build --wheel "$build_dir/core" --out-dir "$build_dir/wheels" +uv build --wheel "$build_dir/recall" --out-dir "$build_dir/wheels" +uv venv "$build_dir/env" +uv pip install --python "$build_dir/env/bin/python" \ + "$build_dir"/wheels/loopx_core-*.whl "$build_dir"/wheels/loopx_capability_agent_turn_recall-*.whl +"$build_dir/env/bin/loopx" capability show agent-turn-recall +"$build_dir/env/bin/loopx" agent-turn-recall --help +``` + +Installing the wheel makes the command available. Recall uses the existing +per-Goal/Agent configuration, provider authorization, and receipt scope. +Follow the [capability guide](../../loopx/capabilities/agent_turn_recall/README.md) +for preview, explicit enablement, and validation. Uninstall +`loopx-capability-agent-turn-recall` from the same environment and start a new +LoopX process to return to Core-only execution. The Core catalog reports recall +as unavailable and retains the existing task, configuration, and receipt +owners. diff --git a/packages/loopx-capability-agent-turn-recall/pyproject.toml b/packages/loopx-capability-agent-turn-recall/pyproject.toml new file mode 100644 index 0000000000..9bdc37b3e7 --- /dev/null +++ b/packages/loopx-capability-agent-turn-recall/pyproject.toml @@ -0,0 +1,19 @@ +[build-system] +requires = ["setuptools==83.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "loopx-capability-agent-turn-recall" +dynamic = ["version", "dependencies"] +description = "Built-in agent turn recall implementation for a matching LoopX Core installation." +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.agent_turn_recall"] diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index 93f65081ee..875c817c49 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -59,10 +59,11 @@ are refused. Its native events are protocol fixtures; they do not establish model retention or installed-host adoption. `capability show agent-turn-recall` reports the optional recall implementation -as unavailable in Core. Use the ordinary LoopX installation to run recall. -If an existing Goal explicitly enables automatic recall, Core records the -missing implementation and continues the task. Outcome ingest retains its -independent configuration and recovery path. +as unavailable in Core alone. Install the [matching recall wheel](../loopx-capability-agent-turn-recall/README.md) +in the Core environment to make its existing command available. Recall starts +only with the existing explicit Goal/Agent configuration. When the implementation +is unavailable, an enabled Goal records that fact and continues the task. +Outcome ingest uses its own configuration and recovery path. The candidate owns the same `loopx` import namespace and console command as the ordinary distribution. Do not co-install or overlay them. Return to the ordinary @@ -77,6 +78,6 @@ 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 capability belongs in the kernel. Full workspace/meta-package splitting, -independent capability packaging, other host/platform qualification and the +the remaining capability packages, other host/platform qualification and the complexity/coverage hypothesis remain separate work. Smaller installation or a passing process fixture alone does not establish model effectiveness. diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index b7b8fc05ad..c8c1ab025f 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -1,4 +1,4 @@ -"""Prepare a standalone core source distribution from the single source tree. +"""Prepare the standalone Core or its matching built-in recall distribution. Build the returned directory with a PEP 517 frontend. No runtime code is copied back into the repository and the ordinary distribution remains unchanged. @@ -9,6 +9,7 @@ import shutil import subprocess from pathlib import Path +from runpy import run_path REPOSITORY = Path(__file__).resolve().parents[2] # These are distribution exclusions, not an authority or activation policy. @@ -20,19 +21,12 @@ "loopx/capabilities/agent_turn_recall/cli.py", "loopx/capabilities/agent_turn_recall/core.py", } +RECALL_DISTRIBUTION = "loopx-capability-agent-turn-recall" def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: repository = repository.resolve() - output = output.resolve() - if output == repository or output.is_relative_to(repository): - raise ValueError("prepare the core distribution outside the source checkout") - if output.exists() and any(output.iterdir()): - raise ValueError("the output directory must be empty") - names = subprocess.check_output( - ["git", "ls-files", "--cached", "-z", "--", "loopx"], cwd=repository, - ).split(b"\0") - sources = [Path(name.decode("utf-8")) for name in names if name] + sources = _tracked_loopx_sources(repository) sources = [path for path in sources if path.suffix in SOURCE_SUFFIXES and path.as_posix() not in RECALL_IMPLEMENTATION_MODULES and path.as_posix() not in EXCLUDED_MODULES @@ -40,6 +34,15 @@ def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: and not path.as_posix().startswith(EXCLUDED_TREES)] if not sources or not (repository / "loopx/entrypoint.py").is_file(): raise ValueError("a complete LoopX source checkout is required") + return _stage_source(output, repository, "loopx-core", sources) + + +def _stage_source(output: Path, repository: Path, distribution: str, sources: list[Path]) -> Path: + output = output.resolve() + if output == repository or output.is_relative_to(repository): + raise ValueError("prepare the distribution outside the source checkout") + if output.exists() and any(output.iterdir()): + raise ValueError("the output directory must be empty") output.mkdir(parents=True, exist_ok=True) for relative in sources: source = repository / relative @@ -48,7 +51,7 @@ def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: target = output / relative target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source, target) - package = repository / "packages/loopx-core" + package = repository / "packages" / distribution for name in ("pyproject.toml", "README.md"): shutil.copyfile(package / name, output / name) for name in ("LICENSE", "LICENSE-MIT", "NOTICE"): @@ -59,11 +62,33 @@ def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: return output +def _tracked_loopx_sources(repository: Path) -> list[Path]: + names = subprocess.check_output( + ["git", "ls-files", "--cached", "-z", "--", "loopx"], cwd=repository, + ).split(b"\0") + return [Path(name.decode("utf-8")) for name in names if name] + + +def prepare_turn_recall_source(output: Path, *, repository: Path = REPOSITORY) -> Path: + repository = repository.resolve() + sources = [path for path in _tracked_loopx_sources(repository) + if path.as_posix() in RECALL_IMPLEMENTATION_MODULES] + if {path.as_posix() for path in sources} != RECALL_IMPLEMENTATION_MODULES: + raise ValueError("the complete built-in Turn recall source is required") + version = run_path(str(repository / "loopx/__init__.py"))["__version__"] + output = _stage_source(output, repository, RECALL_DISTRIBUTION, sources) + (output / "VERSION").write_text(f"{version}\n", encoding="utf-8") + (output / "requires-core.txt").write_text(f"loopx-core=={version}\n", encoding="utf-8") + return output + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--distribution", choices=["loopx-core", RECALL_DISTRIBUTION], default="loopx-core") args = parser.parse_args() - print(prepare_core_source(args.output)) + prepare = prepare_turn_recall_source if args.distribution == RECALL_DISTRIBUTION else prepare_core_source + print(prepare(args.output)) return 0 diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index 842491c9d6..ee16ab39c5 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -323,9 +323,10 @@ def test_installed_core_reports_optional_turn_recall(core_python, tmp_path): assert record["provider_id"] == "loopx" assert record["default_enabled"] is False assert record["provider_state"] == {"declared": True, "installed": False, "enabled": False, "ready": False} - assert "ordinary LoopX installation" in record["next_real_step"] + assert "loopx-capability-agent-turn-recall" in record["next_real_step"] refusal = _run(core_python, ["agent-turn-recall", "--help"], tmp_path, expected=2) assert "unavailable in the standalone core" in refusal.stderr + assert "loopx-capability-agent-turn-recall" in refusal.stderr assert not list(tmp_path.iterdir()) diff --git a/tests/test_core_recall_distribution.py b/tests/test_core_recall_distribution.py new file mode 100644 index 0000000000..ae9ab53caf --- /dev/null +++ b/tests/test_core_recall_distribution.py @@ -0,0 +1,161 @@ +"""Qualification for the independently installed built-in recall wheel.""" + +import json +import os +import subprocess +from datetime import datetime, timedelta, timezone + +import pytest + +from loopx import __version__ +from tests.control_plane.host_process_fixture import write_python_host_fixture +from tests.control_plane.reward_memory_host_fixture import enable_live_memory +from tests.test_core_distribution import ( + AGENT, + GOAL, + HOST_SOURCE, + REPOSITORY, + _assert_committed, + _environment, + _prepare_module, + _run, + _spends, + core_python as core_python, + task as task, +) + +RECALL_MODULES = { + "loopx/capabilities/agent_turn_recall/cli.py", + "loopx/capabilities/agent_turn_recall/core.py", +} + + +def test_recall_source_stages_only_the_optional_implementation(tmp_path): + staged = _prepare_module().prepare_turn_recall_source(tmp_path / "recall") + assert {path.relative_to(staged).as_posix() for path in (staged / "loopx").rglob("*.py")} == RECALL_MODULES + for path in RECALL_MODULES: + assert (staged / path).read_bytes() == (REPOSITORY / path).read_bytes() + assert (staged / "requires-core.txt").read_text().strip() == f"loopx-core=={__version__}" + + +def _install_fixture_provider(tmp_path, core_python, configuration): + config = json.loads(configuration.read_text()) + binding = config["project_provider_binding"] + corpus = config["corpora"][0]["corpus"] + scope = binding["corpus_scopes"][0]["scope_ref"] + uri = f"{scope}/validation.json" + guidance = "Read the checked artifact before reporting." + record = { + "schema_version": "reward_memory_active_record_v0", "corpus_id": corpus["corpus_id"], + "candidate_ref": "candidate:checked-artifact", "target_class": corpus["class_id"], + "content_summary": guidance, "scope": corpus["scope"], + "lifecycle": {"state": "active", "expires_at": (datetime.now(timezone.utc) + timedelta(days=1)).isoformat()}, + } + trace = tmp_path / "provider-operations" + source = f'''#!{core_python} +import json +from pathlib import Path +import sys + +args = sys.argv[1:] +if args[0] == "--actor-peer-id": + assert args[1] == {binding["actor_peer_id"]!r} + args = args[2:] +command = args[0] +if command == "--version": + print("0.4.19") +elif command == "version": + print("Server: 0.4.19") +elif command == "status": + print("{{}}") +elif command in {{"search", "read"}}: + with Path({str(trace)!r}).open("a") as stream: + stream.write(command + "\\n") + if command == "search": + assert args[args.index("-u") + 1] == {scope!r} + print(json.dumps([{{"uri": {uri!r}, "level": 2, "score": 0.97}}])) + else: + assert args[1] == {uri!r} + print(json.dumps({{"content": json.dumps({record!r})}})) +else: + raise AssertionError(command) +''' + write_python_host_fixture(tmp_path / binding["provider_binary"], source) + return trace, guidance + + +@pytest.mark.skipif(os.environ.get("LOOPX_RECALL_TEST_ENABLED") != "1", + reason="requires a disposable Core environment with the matching recall wheel") +def test_installed_core_with_recall_wheel(core_python, task, tmp_path): + workspace, runtime, registry, arguments = task + prefix = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + probe = '''import importlib.metadata as m,sys +from loopx.entrypoint import main +recall=m.distribution("loopx-capability-agent-turn-recall") +core=m.distribution("loopx-core") +assert recall.version==core.version +assert f"loopx-core=={core.version}" in recall.requires +members={str(path) for path in recall.files if str(path).startswith("loopx/")} +assert members=={"loopx/capabilities/agent_turn_recall/cli.py","loopx/capabilities/agent_turn_recall/core.py"} +assert members.isdisjoint(str(path) for path in core.files) +assert main(["capability","show","agent-turn-recall","--format","json"])==0 +assert "loopx.capabilities.agent_turn_recall.cli" not in sys.modules +assert "loopx.capabilities.agent_turn_recall.core" not in sys.modules +''' + discovered = subprocess.run([core_python, "-I", "-c", probe], cwd=workspace, env=_environment(core_python), + capture_output=True, text=True, timeout=45) + assert discovered.returncode == 0, discovered.stderr + capability = json.loads(discovered.stdout)["capability"] + assert capability["provider_state"]["installed"] is True and capability["default_enabled"] is False + assert "--quota-decision-json" in _run(core_python, ["agent-turn-recall", "--help"], workspace).stdout + quota_path = tmp_path / "original-quota.json" + turn_instance_id = "installed-recall" + arguments.extend(["--turn-instance-id", turn_instance_id]) + recall_command = [*prefix, "agent-turn-recall", "--goal-id", GOAL, "--agent-id", AGENT, + "--turn-instance-id", turn_instance_id, "--quota-decision-json", str(quota_path)] + before = registry.read_bytes() + disabled = json.loads(_run(core_python, recall_command, workspace).stdout) + assert disabled["status"] == "disabled" and disabled["provider_call_count"] == 0 + assert registry.read_bytes() == before and _spends(runtime) == 0 + + config = enable_live_memory(registry, ingest=False) + operations, guidance = _install_fixture_provider(tmp_path, core_python, config) + environment = {"PATH": os.pathsep.join([str(tmp_path), _environment(core_python)["PATH"]])} + host = workspace / "recall-host.py" + host.write_text(HOST_SOURCE.replace("request=json.load(sys.stdin)\n", + "request=json.load(sys.stdin)\n" + "pathlib.Path('recall-readback.json').write_text(json.dumps(request['reward_memory_recall']))\n")) + arguments[arguments.index("--host-adapter-command-json") + 1] = json.dumps([core_python, "-I", str(host)]) + execution = subprocess.run([core_python, "-I", "-m", "loopx.entrypoint", *arguments], cwd=workspace, + env=_environment(core_python, environment), capture_output=True, text=True, timeout=90) + assert execution.returncode == 0, (execution.stdout, execution.stderr) + _assert_committed(core_python, workspace, runtime, json.loads(execution.stdout)) + recall = json.loads((workspace / "recall-readback.json").read_text()) + assert recall["status"] == "applied" and recall["provider_call_count"] == 1 + assert recall["context"]["guidance"][0]["content_summary"] == guidance + assert operations.read_text().splitlines() == ["search", "read"] + + # The manual command consumes a quota admission, distinct from the + # generic Turn's lease-bound execution journal. + _run(core_python, [*prefix, "configure-goal", "--goal-id", GOAL, "--quota-compute", "2", "--execute"], workspace) + added = json.loads(_run(core_python, [*prefix, "todo", "add", "--goal-id", GOAL, "--role", "agent", + "--claimed-by", AGENT, "--text", "Independently check the next artifact.", "--priority", "P1", + "--task-class", "advancement_task", "--action-kind", "validate", + "--operation-id", "manual-recall-task"], workspace).stdout) + _run(core_python, [*prefix, "todo", "claim", "--goal-id", GOAL, "--todo-id", added["todo_id"], + "--agent-id", AGENT, "--claimed-by", AGENT, "--claim-operation-id", "manual-recall-claim"], workspace) + enable_live_memory(registry, recall=False, ingest=False) + manual_turn = "installed-manual-recall" + decision = _run(core_python, [*prefix, "quota", "should-run", "--goal-id", GOAL, "--agent-id", AGENT, + "--todo-id", added["todo_id"], "--turn-instance-id", manual_turn, "--context-delivery", "off"], workspace) + quota_path.write_text(decision.stdout) + enable_live_memory(registry, ingest=False) + recall_command[recall_command.index("--turn-instance-id") + 1] = manual_turn + preview = json.loads(_run(core_python, recall_command, workspace, environment=environment).stdout) + assert preview["status"] == "preview" and preview["provider_call_count"] == 0 + execute = [*recall_command, "--execute"] + selected = json.loads(_run(core_python, execute, workspace, environment=environment).stdout) + assert selected["status"] == "applied" and selected["context"]["guidance"][0]["content_summary"] == guidance + repeat = json.loads(_run(core_python, execute, workspace, environment=environment).stdout) + assert repeat["status"] == "deduplicated" and repeat["context"] == selected["context"] + assert operations.read_text().splitlines() == ["search", "read", "search", "read"] and _spends(runtime) == 1 From c18542f04bd2d194ee77bc058f9c8c0a1a5c8722 Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 04:53:32 +0800 Subject: [PATCH 4/6] Split PR review into a version-matched Core capability wheel Signed-off-by: cicolord --- .github/workflows/package-smoke.yml | 17 +++ .../rfcs/monorepo-distribution-split-v0.md | 26 +++-- .../monorepo-distribution-split-v0.zh-CN.md | 15 ++- .../agent_turn_recall/catalog_entry.py | 27 +---- loopx/capabilities/catalog.py | 33 ++++-- .../capabilities/pr_review_queue/__init__.py | 100 ++++++++-------- .../pr_review_queue/catalog_entry.py | 14 +++ loopx/cli_runtime.py | 29 +++-- loopx/python_install_owner.py | 34 +++++- .../README.md | 31 +++++ .../pyproject.toml | 22 ++++ packages/loopx-core/README.md | 5 + packages/loopx-core/prepare.py | 64 ++++++++--- tests/test_core_distribution.py | 8 ++ tests/test_core_pr_review_distribution.py | 108 ++++++++++++++++++ tests/test_core_recall_distribution.py | 4 +- 16 files changed, 407 insertions(+), 130 deletions(-) create mode 100644 packages/loopx-capability-pull-request-review/README.md create mode 100644 packages/loopx-capability-pull-request-review/pyproject.toml create mode 100644 tests/test_core_pr_review_distribution.py diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index 6dadb66659..e2e08ba475 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -15,6 +15,8 @@ on: - "packages/loopx-codex-provider-routing/**" - "loopx/capabilities/decision_context/extension_provider.py" - "loopx/extensions/runtime.py" + - "packages/loopx-capability-pull-request-review/**" + - "tests/test_core_pr_review_distribution.py" push: branches: - main @@ -31,6 +33,8 @@ on: - "packages/loopx-codex-provider-routing/**" - "loopx/capabilities/decision_context/extension_provider.py" - "loopx/extensions/runtime.py" + - "packages/loopx-capability-pull-request-review/**" + - "tests/test_core_pr_review_distribution.py" permissions: contents: read @@ -83,6 +87,19 @@ jobs: uv run --extra test python -m pytest -q tests/test_core_distribution.py \ -k 'reports_optional_turn_recall or completes_turn_with_configured_optional_recall' + - name: Qualify matched pull-request review installation, checkpoint and removal + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-pull-request-review --output "$RUNNER_TEMP/review-source" + uv build --wheel "$RUNNER_TEMP/review-source" --out-dir "$RUNNER_TEMP/review-dist" + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ + "$RUNNER_TEMP"/review-dist/loopx_capability_pull_request_review-*.whl + LOOPX_REVIEW_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_pr_review_distribution.py + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-pull-request-review + uv run --extra test python -m pytest -q tests/test_core_pr_review_distribution.py -k discovers + codex-provider-routing: name: loopx-codex-provider-routing runs-on: ubuntu-latest diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index 6a342835b1..15b831ba78 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -413,18 +413,20 @@ packet cannot be treated as proof the executor has the prior context. Recover through the owning contract when continuity is unknown. Capability instructions are supplied when applicable; authority is never inferred from prompt text. -The first Standard capability artifact is the release-coupled -`loopx-capability-agent-turn-recall` wheel. It supplies the two existing built-in -command and execution modules in the same environment as matching Core. Core's -catalog and admission readback, the capability ID, and the original source-tree -owner govern both installations. The wheels own disjoint files and use the exact -Core release version for this built-in split. Independent provider packages use -the public capability boundary described above. Discovery reads metadata without -loading recall. Automatic recall loads its implementation only after the existing -Goal/Agent opt-in. Core alone reports the missing implementation and continues -ordinary work. Independently enabled outcome ingest retains its recovery path. -The remaining Standard capabilities and the full preset need installed -qualification. +Standard has two source-built capability wheel candidates, +`loopx-capability-agent-turn-recall` and `loopx-capability-pull-request-review`. +Install each alongside the matching Core release. Core and each add-on own +disjoint files and keep the existing capability IDs, configuration and runtime +owners. Independent provider packages use the public capability boundary above. + +Discovery reads metadata without loading either implementation. Core can report +unavailable recall and continue ordinary work. The existing Goal/Agent opt-in +loads recall when installed, and outcome ingest retains its own recovery path. +Core keeps PR review catalog and settings. An explicit `pr-review` invocation +loads the matching wheel and uses the existing exact-head queue, action boundary +and checkpoint. Removing the wheel leaves saved settings and checkpoints +available to a later installation. Issue-fix and the full Standard preset still +need installation qualification. Optional observers consume committed events or bounded projections. Their latency must not enter admission/settlement transactions unless the existing 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 3b2aed727f..89136e8f90 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -285,12 +285,15 @@ capability 包直接采用现有 `extension.toml` 契约,不做扩展。唯一 不能因为 packet 更小,就认为 executor 已掌握前文。连续性未知时走所属契约的恢复路径。 Capability 指令仅在适用时提供;authority 不能从 prompt 文字推导。 -Standard 的首个能力安装包是随 Core 同版本构建的 `loopx-capability-agent-turn-recall`。 -它把现有的命令与执行两个内置模块安装到同一个 Core 环境。两种安装组合复用 Core 的 -能力目录和准入回读、原能力 ID 与源码 owner。两个 wheel 拥有互不重叠的文件,此内置 -拆分精确绑定 Core 版本。独立 provider 包仍按上文公共能力边界接入。能力发现只读取元数据, -按既有 Goal/Agent 配置显式启用后才加载自动回忆。只安装 Core 时会回读实现缺失并继续 -普通任务。独立启用的结果入库沿用既有恢复路径。其余 Standard 能力和完整预设仍需安装态验收。 +Standard 有两个可从源码构建的能力 wheel 候选,即 +`loopx-capability-agent-turn-recall` 和 `loopx-capability-pull-request-review`。 +两个能力可分别装入同版本的 Core 环境。Core 与各可选包各自拥有互不重叠的文件,沿用 +既有能力 ID、配置和运行时 owner。独立 provider 包仍按上文公共能力边界接入。 + +能力发现只读取元数据。Core 可报告召回实现缺失并继续普通任务。安装召回包后按既有 +Goal/Agent 设置显式启用,结果入库继续沿用自身的恢复路径。Core 保留 PR 评审目录与配置。 +显式调用 `pr-review` 时加载匹配的可选包,复用精确 head 队列、操作边界和 checkpoint。 +卸载后,既有设置与 checkpoint 留待日后安装续用。Issue 修复和完整 Standard 预设仍需安装态验收。 可选 observer 消费已提交事件或有界投影。除非现有契约明确要求它的 receipt, 其延迟不能进入准入/结算事务。只批处理尽力而为的 telemetry;不能为满足时间目标而延迟 diff --git a/loopx/capabilities/agent_turn_recall/catalog_entry.py b/loopx/capabilities/agent_turn_recall/catalog_entry.py index 947169fe57..c2ef4f5da2 100644 --- a/loopx/capabilities/agent_turn_recall/catalog_entry.py +++ b/loopx/capabilities/agent_turn_recall/catalog_entry.py @@ -1,8 +1,9 @@ from __future__ import annotations -from importlib.util import find_spec from typing import Any +from ...python_install_owner import builtin_capability_installed + AGENT_TURN_RECALL_SCHEMA_VERSION = "agent_turn_recall_v0" AGENT_TURN_RECALL_SURFACE_ID = "agent_workflow.turn_admission" @@ -11,26 +12,10 @@ def agent_turn_recall_installed(*, builtin_cli_present: bool | None = None) -> bool: - """Observe the built-in deployment without loading its command or provider.""" - specs = [find_spec(f"{__package__}.{name}") for name in ("cli", "core")] - if any(spec is None or spec.origin is None for spec in specs): - return False - if builtin_cli_present is None: - builtin_cli_present = find_spec("loopx.cli") is not None - if builtin_cli_present: - return True - - from importlib.metadata import PackageNotFoundError, distribution - from pathlib import Path - - try: - recall = distribution(RECALL_DISTRIBUTION) - if recall.version != distribution("loopx-core").version: - return False - except PackageNotFoundError: - return False - recorded = {Path(recall.locate_file(path)).resolve() for path in recall.files or ()} - return all(spec and spec.origin and Path(spec.origin).resolve() in recorded for spec in specs) + return builtin_capability_installed( + RECALL_DISTRIBUTION, (f"{__package__}.cli", f"{__package__}.core"), + builtin_cli_present=builtin_cli_present, + ) AGENT_TURN_RECALL_CATALOG_ENTRY: dict[str, Any] = { diff --git a/loopx/capabilities/catalog.py b/loopx/capabilities/catalog.py index 8f5db43613..e82d93d831 100644 --- a/loopx/capabilities/catalog.py +++ b/loopx/capabilities/catalog.py @@ -12,7 +12,9 @@ REPOSITORY_CHANGE_WINDOW_CATALOG_ENTRY, ) from .change_quality.catalog_entry import CHANGE_QUALITY_CATALOG_ENTRY -from .pr_review_queue.catalog_entry import PR_REVIEW_CATALOG_ENTRY +from .pr_review_queue.catalog_entry import ( + PR_REVIEW_CATALOG_ENTRY, PR_REVIEW_INSTALL_HINT, pull_request_review_installed, +) from .issue_fix.catalog_entry import ISSUE_FIX_CATALOG_ENTRY from .decision_context.catalog_entry import DECISION_CONTEXT_CATALOG_ENTRY from .project_skill_delivery.catalog_entry import PROJECT_SKILL_DELIVERY_CATALOG_ENTRY @@ -142,19 +144,25 @@ def _register_declared_implementation_providers( ) -def _record_for_installed_recall( - registry: CapabilityRegistry, record: Mapping[str, object], +def _record_for_installed_capability( + registry: CapabilityRegistry, + record: Mapping[str, object], + *, + builtin_cli_present: bool, ) -> Mapping[str, object]: - if record is not AGENT_TURN_RECALL_CATALOG_ENTRY or agent_turn_recall_installed( - builtin_cli_present=find_spec("loopx.cli") is not None, - ): + if record is AGENT_TURN_RECALL_CATALOG_ENTRY: + installed = agent_turn_recall_installed(builtin_cli_present=builtin_cli_present) + hint = RECALL_INSTALL_HINT + elif record is PR_REVIEW_CATALOG_ENTRY: + installed = pull_request_review_installed(builtin_cli_present=builtin_cli_present) + hint = PR_REVIEW_INSTALL_HINT + else: + return record + if installed: return record if not any(provider["id"] == "loopx" for provider in registry.providers()): registry.register_provider({"id": "loopx", "origin": "builtin", "installed": False}) - return dict(record) | { - "provider_id": "loopx", - "next_real_step": RECALL_INSTALL_HINT, - } + return dict(record) | {"provider_id": "loopx", "next_real_step": hint} def build_capability_registry( @@ -173,8 +181,11 @@ def build_capability_registry( "ready": True, } ) + builtin_cli_present = find_spec("loopx.cli") is not None for record in BUILTIN_CAPABILITIES: - registry.register_capability(_record_for_installed_recall(registry, record)) + registry.register_capability(_record_for_installed_capability( + registry, record, builtin_cli_present=builtin_cli_present, + )) for record in BUILTIN_CAPABILITIES: _register_declared_implementation_providers(registry, record) for manifest in extension_catalog_entries( diff --git a/loopx/capabilities/pr_review_queue/__init__.py b/loopx/capabilities/pr_review_queue/__init__.py index 387298cc13..73b54dce2a 100644 --- a/loopx/capabilities/pr_review_queue/__init__.py +++ b/loopx/capabilities/pr_review_queue/__init__.py @@ -1,57 +1,47 @@ """Deterministic observation and review contracts for pull-request queues.""" -from .core import build_pull_request_review_queue_observation -from .merge_readiness import build_merge_readiness -from .machine_defaults import ( - PULL_REQUEST_REVIEW_MACHINE_DEFAULTS_SCHEMA, - normalize_pull_request_review_machine_defaults, - pull_request_review_machine_configuration_namespace, - review_priority_machine_default, -) -from .review_contract import ( - build_agent_response_contract, - build_review_execution_contract, - build_review_plan, - build_review_template, -) -from .selection_execution import ( - exact_head_key, - materialize_review_execution, - normalize_fresh_audit_exact_heads, -) -from .scheduling import ( - DEFAULT_REVIEW_PRIORITY, - PullRequestReviewPriority, - PullRequestSchedulingLane, - build_scheduling_policy, - classify_scheduling_lane, - community_feedback_ready, - normalize_review_priority, - scheduling_sort_key, - scheduling_tier, -) - -__all__ = [ - "build_agent_response_contract", - "build_merge_readiness", - "PULL_REQUEST_REVIEW_MACHINE_DEFAULTS_SCHEMA", - "normalize_pull_request_review_machine_defaults", - "pull_request_review_machine_configuration_namespace", - "review_priority_machine_default", - "build_pull_request_review_queue_observation", - "build_review_execution_contract", - "build_review_plan", - "build_review_template", - "build_scheduling_policy", - "DEFAULT_REVIEW_PRIORITY", - "classify_scheduling_lane", - "community_feedback_ready", - "normalize_review_priority", - "exact_head_key", - "materialize_review_execution", - "normalize_fresh_audit_exact_heads", - "PullRequestSchedulingLane", - "PullRequestReviewPriority", - "scheduling_sort_key", - "scheduling_tier", -] +from importlib import import_module +from typing import Any + +# Configuration and catalog readers share this namespace with the optional +# review implementation. Resolve existing public exports only when requested. +_EXPORTS = { + "build_agent_response_contract": "review_contract", + "build_merge_readiness": "merge_readiness", + "PULL_REQUEST_REVIEW_MACHINE_DEFAULTS_SCHEMA": "machine_defaults", + "normalize_pull_request_review_machine_defaults": "machine_defaults", + "pull_request_review_machine_configuration_namespace": "machine_defaults", + "review_priority_machine_default": "machine_defaults", + "build_pull_request_review_queue_observation": "core", + "build_review_execution_contract": "review_contract", + "build_review_plan": "review_contract", + "build_review_template": "review_contract", + "build_scheduling_policy": "scheduling", + "DEFAULT_REVIEW_PRIORITY": "scheduling", + "classify_scheduling_lane": "scheduling", + "community_feedback_ready": "scheduling", + "normalize_review_priority": "scheduling", + "exact_head_key": "selection_execution", + "materialize_review_execution": "selection_execution", + "normalize_fresh_audit_exact_heads": "selection_execution", + "PullRequestSchedulingLane": "scheduling", + "PullRequestReviewPriority": "scheduling", + "scheduling_sort_key": "scheduling", + "scheduling_tier": "scheduling", +} + + +def __getattr__(name: str) -> Any: + module = _EXPORTS.get(name) + if module is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + value = getattr(import_module(f".{module}", __name__), name) + globals()[name] = value + return value + + +def __dir__() -> list[str]: + return sorted(set(globals()) | set(__all__)) + + +__all__ = list(_EXPORTS) diff --git a/loopx/capabilities/pr_review_queue/catalog_entry.py b/loopx/capabilities/pr_review_queue/catalog_entry.py index b8316312da..d76fcdb370 100644 --- a/loopx/capabilities/pr_review_queue/catalog_entry.py +++ b/loopx/capabilities/pr_review_queue/catalog_entry.py @@ -2,6 +2,20 @@ from typing import Any +from ...python_install_owner import builtin_capability_installed + +PR_REVIEW_DISTRIBUTION = "loopx-capability-pull-request-review" +PR_REVIEW_INSTALL_HINT = f"Install the matching {PR_REVIEW_DISTRIBUTION} wheel in this Core environment." + + +def pull_request_review_installed(*, builtin_cli_present: bool | None = None) -> bool: + return builtin_capability_installed( + PR_REVIEW_DISTRIBUTION, + ("loopx.cli_commands.pr_review", "loopx.pr_review", "loopx.pr_review_merge_readiness", f"{__package__}.core"), + builtin_cli_present=builtin_cli_present, + ) + + PR_REVIEW_CATALOG_ENTRY: dict[str, Any] = { "id": "pull-request-review", "origin": "builtin", diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index dd22837e96..2b74f7f1d8 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -938,6 +938,14 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: result = handle_agent_turn_recall_command( args, registry_path=registry_path, output_format=output_format, print_payload=print_payload, ) + elif args.command == "pr-review": + from .cli_commands.pr_review import handle_pr_review_command + from .paths import effective_runtime_root + + result = handle_pr_review_command( + args, registry_path=registry_path, output_format=output_format, print_payload=print_payload, + runtime_root=effective_runtime_root(registry_path, args.runtime_root) if registry_path.exists() else None, + ) else: result = dispatch_common_command( args, @@ -1017,15 +1025,22 @@ def main(argv: list[str] | None = None) -> int: def _run_command(command: str | None, raw_argv: list[str]) -> int: - if command == "agent-turn-recall" and _standalone_core(): - from .capabilities.agent_turn_recall.catalog_entry import RECALL_INSTALL_HINT, agent_turn_recall_installed - + if command in {"agent-turn-recall", "pr-review"} and _standalone_core(): parser, subparsers = build_cli_parser() - if not agent_turn_recall_installed(): - parser.error(f"agent-turn-recall is unavailable in the standalone core. {RECALL_INSTALL_HINT}") - from .capabilities.agent_turn_recall.cli import register_agent_turn_recall_commands + if command == "agent-turn-recall": + from .capabilities.agent_turn_recall.catalog_entry import RECALL_INSTALL_HINT, agent_turn_recall_installed + + if not agent_turn_recall_installed(builtin_cli_present=False): + parser.error(f"agent-turn-recall is unavailable in the standalone core. {RECALL_INSTALL_HINT}") + from .capabilities.agent_turn_recall.cli import register_agent_turn_recall_commands as register + else: + from .capabilities.pr_review_queue.catalog_entry import PR_REVIEW_INSTALL_HINT, pull_request_review_installed + + if not pull_request_review_installed(builtin_cli_present=False): + parser.error(f"pr-review is unavailable in the standalone core. {PR_REVIEW_INSTALL_HINT}") + from .cli_commands.pr_review import register_pr_review_command as register - register_agent_turn_recall_commands(subparsers, add_subcommand_format) + register(subparsers, add_subcommand_format) return _dispatch_selected(parse_cli_args(parser, raw_argv), raw_argv) if command == "version": version_exports = sys.modules.get("loopx.cli_commands") diff --git a/loopx/python_install_owner.py b/loopx/python_install_owner.py index 8270d105ce..de7041c016 100644 --- a/loopx/python_install_owner.py +++ b/loopx/python_install_owner.py @@ -9,7 +9,8 @@ from dataclasses import dataclass from collections.abc import Callable -from importlib.metadata import Distribution, PackageNotFoundError +from importlib.metadata import Distribution, PackageNotFoundError, distribution +from importlib.util import find_spec import json import os from pathlib import Path @@ -29,6 +30,37 @@ def installed_loopx_distribution(lookup: Callable[[str], Distribution]) -> Distr return lookup("loopx-core") +def builtin_capability_installed( + distribution_name: str, + modules: tuple[str, ...], + *, + builtin_cli_present: bool | None = None, +) -> bool: + """Check import locations and matching installed wheel ownership without loading code.""" + origins = [ + Path(spec.origin).resolve() + for module in modules + if (spec := find_spec(module)) is not None and spec.origin is not None + ] + if len(origins) != len(modules): + return False + if builtin_cli_present is None: + builtin_cli_present = find_spec("loopx.cli") is not None + if builtin_cli_present: + return True + try: + implementation = distribution(distribution_name) + if implementation.version != distribution("loopx-core").version: + return False + except PackageNotFoundError: + return False + recorded = { + Path(str(implementation.locate_file(path))).resolve() + for path in implementation.files or () + } + return all(origin in recorded for origin in origins) + + @dataclass(frozen=True) class PythonInstallOwner: manager: str diff --git a/packages/loopx-capability-pull-request-review/README.md b/packages/loopx-capability-pull-request-review/README.md new file mode 100644 index 0000000000..e547393421 --- /dev/null +++ b/packages/loopx-capability-pull-request-review/README.md @@ -0,0 +1,31 @@ +# LoopX pull-request review for Core + +Add the existing `loopx pr-review` command to a standalone Core installation. +Use a wheel built from the same LoopX release as Core. Core reads the catalog +and retains Goal and machine review settings on its own. The wheel supplies +queue observation, exact-head review packets and readiness checks. + +Build from the repository root. Set `LOOPX_CORE_PYTHON` to the interpreter in +the installed Core environment and use that environment for the commands below. + +```sh +python packages/loopx-core/prepare.py \ + --distribution loopx-capability-pull-request-review --output /tmp/loopx-review-source +uv build --wheel /tmp/loopx-review-source --out-dir /tmp/loopx-review-dist +uv pip install --python "$LOOPX_CORE_PYTHON" /tmp/loopx-review-dist/loopx_capability_pull_request_review-*.whl +loopx capability show pull-request-review --format json +loopx pr-review --help +``` + +The catalog reports availability once the matching wheel owns the command. +Review uses the existing explicit CLI and existing Goal configuration. +Installation grants no GitHub authority. Use `--fixture` for an offline queue +observation. Live observations require the existing GitHub access, and external +review publication and merge remain separate operations. + +Remove the wheel from the Core environment to disable the command. Saved +checkpoints and Goal or machine settings remain available to a later matching +install. Core task execution and recovery use their existing owners. + +See the [pull-request review capability](../../loopx/capabilities/pr_review_queue/README.md) +for the command, input contract and exact-head review semantics. diff --git a/packages/loopx-capability-pull-request-review/pyproject.toml b/packages/loopx-capability-pull-request-review/pyproject.toml new file mode 100644 index 0000000000..2b12a814fb --- /dev/null +++ b/packages/loopx-capability-pull-request-review/pyproject.toml @@ -0,0 +1,22 @@ +[build-system] +requires = ["setuptools==83.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "loopx-capability-pull-request-review" +dynamic = ["version", "dependencies"] +description = "Built-in pull-request review implementation for a matching LoopX Core installation." +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", "loopx.cli_commands", "loopx.capabilities.pr_review_queue"] + +[tool.setuptools.package-data] +"loopx.capabilities.pr_review_queue" = ["experiences/*/*/*.json", "experiences/*.md"] diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index 875c817c49..28c0da6049 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -65,6 +65,11 @@ only with the existing explicit Goal/Agent configuration. When the implementatio is unavailable, an enabled Goal records that fact and continues the task. Outcome ingest uses its own configuration and recovery path. +`capability show pull-request-review` reports whether the [matching PR review +wheel](../loopx-capability-pull-request-review/README.md) is installed. Core +retains its catalog and settings. The add-on provides the existing `pr-review` +command on explicit use. Removing it preserves review settings and checkpoints. + The candidate owns the same `loopx` import namespace and console command as the ordinary distribution. Do not co-install or overlay them. Return to the ordinary installation by switching back to its environment; preserve task state and diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index c8c1ab025f..d21b04aeb5 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -1,4 +1,4 @@ -"""Prepare the standalone Core or its matching built-in recall distribution. +"""Prepare standalone Core and its matching built-in capability distributions. Build the returned directory with a PEP 517 frontend. No runtime code is copied back into the repository and the ordinary distribution remains unchanged. @@ -16,19 +16,47 @@ EXCLUDED_TREES = ("loopx/chat/", "loopx/web/", "loopx/canary/") EXCLUDED_MODULES = {"loopx/cli.py", "loopx/chat.py"} SOURCE_SUFFIXES = {".py", ".ts", ".json", ".mjs", ".js", ".md", ".toml"} -# Keep recall's declaration and admission readback in Core. -RECALL_IMPLEMENTATION_MODULES = { - "loopx/capabilities/agent_turn_recall/cli.py", - "loopx/capabilities/agent_turn_recall/core.py", -} RECALL_DISTRIBUTION = "loopx-capability-agent-turn-recall" +PR_REVIEW_DISTRIBUTION = "loopx-capability-pull-request-review" +PR_REVIEW_DIRECTORY = Path("loopx/capabilities/pr_review_queue") +PR_REVIEW_CORE_FILES = { + "__init__.py", "catalog_entry.py", "goal_configuration.py", "machine_defaults.py", + "order.py", "scheduling.py", "README.md", +} +CAPABILITY_ENTRY_MODULES = { + RECALL_DISTRIBUTION: { + Path("loopx/capabilities/agent_turn_recall/cli.py"), + Path("loopx/capabilities/agent_turn_recall/core.py"), + }, + PR_REVIEW_DISTRIBUTION: { + Path("loopx/cli_commands/pr_review.py"), + Path("loopx/pr_review.py"), + Path("loopx/pr_review_merge_readiness.py"), + PR_REVIEW_DIRECTORY / "core.py", + }, +} + + +def _optional_capability_sources(sources: list[Path]) -> dict[str, set[Path]]: + tracked = set(sources) + review_sources = { + path for path in sources + if path.is_relative_to(PR_REVIEW_DIRECTORY) + and path.relative_to(PR_REVIEW_DIRECTORY).as_posix() not in PR_REVIEW_CORE_FILES + and path.suffix in SOURCE_SUFFIXES + } + return { + RECALL_DISTRIBUTION: tracked & CAPABILITY_ENTRY_MODULES[RECALL_DISTRIBUTION], + PR_REVIEW_DISTRIBUTION: review_sources | (tracked & CAPABILITY_ENTRY_MODULES[PR_REVIEW_DISTRIBUTION]), + } def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: repository = repository.resolve() sources = _tracked_loopx_sources(repository) + optional = set().union(*_optional_capability_sources(sources).values()) sources = [path for path in sources if path.suffix in SOURCE_SUFFIXES - and path.as_posix() not in RECALL_IMPLEMENTATION_MODULES + and path not in optional and path.as_posix() not in EXCLUDED_MODULES and not (path.parent == Path("loopx") and path.name.startswith("chat_")) and not path.as_posix().startswith(EXCLUDED_TREES)] @@ -69,14 +97,15 @@ def _tracked_loopx_sources(repository: Path) -> list[Path]: return [Path(name.decode("utf-8")) for name in names if name] -def prepare_turn_recall_source(output: Path, *, repository: Path = REPOSITORY) -> Path: +def prepare_capability_source( + output: Path, distribution: str, *, repository: Path = REPOSITORY, +) -> Path: repository = repository.resolve() - sources = [path for path in _tracked_loopx_sources(repository) - if path.as_posix() in RECALL_IMPLEMENTATION_MODULES] - if {path.as_posix() for path in sources} != RECALL_IMPLEMENTATION_MODULES: - raise ValueError("the complete built-in Turn recall source is required") + sources = _optional_capability_sources(_tracked_loopx_sources(repository))[distribution] + if not CAPABILITY_ENTRY_MODULES[distribution].issubset(sources): + raise ValueError(f"the complete {distribution} source is required") version = run_path(str(repository / "loopx/__init__.py"))["__version__"] - output = _stage_source(output, repository, RECALL_DISTRIBUTION, sources) + output = _stage_source(output, repository, distribution, sorted(sources)) (output / "VERSION").write_text(f"{version}\n", encoding="utf-8") (output / "requires-core.txt").write_text(f"loopx-core=={version}\n", encoding="utf-8") return output @@ -85,10 +114,13 @@ def prepare_turn_recall_source(output: Path, *, repository: Path = REPOSITORY) - def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--distribution", choices=["loopx-core", RECALL_DISTRIBUTION], default="loopx-core") + parser.add_argument("--distribution", choices=["loopx-core", *CAPABILITY_ENTRY_MODULES], default="loopx-core") args = parser.parse_args() - prepare = prepare_turn_recall_source if args.distribution == RECALL_DISTRIBUTION else prepare_core_source - print(prepare(args.output)) + output = ( + prepare_core_source(args.output) if args.distribution == "loopx-core" + else prepare_capability_source(args.output, args.distribution) + ) + print(output) return 0 diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index ee16ab39c5..372c149b42 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -70,6 +70,14 @@ def test_core_staging_excludes_workspace_and_reuses_kernel_bytes(tmp_path): assert not (recall / name).exists() for name in ("catalog_entry.py", "runtime.py"): assert (recall / name).is_file() + review = staged / "loopx/capabilities/pr_review_queue" + assert {path.name for path in review.iterdir()} == { + "__init__.py", "catalog_entry.py", "goal_configuration.py", "machine_defaults.py", + "order.py", "scheduling.py", "README.md", + } + assert not (staged / "loopx/cli_commands/pr_review.py").exists() + assert not (staged / "loopx/pr_review.py").exists() + assert not (staged / "loopx/pr_review_merge_readiness.py").exists() @pytest.fixture diff --git a/tests/test_core_pr_review_distribution.py b/tests/test_core_pr_review_distribution.py new file mode 100644 index 0000000000..40cd1b2085 --- /dev/null +++ b/tests/test_core_pr_review_distribution.py @@ -0,0 +1,108 @@ +"""Exercise the installed PR review capability and its independent package boundary.""" + +import json +import os +import subprocess + +import pytest + +from loopx import __version__ +from tests.test_core_distribution import REPOSITORY, _environment, _prepare_module, _run, core_python as core_python + +DISTRIBUTION = "loopx-capability-pull-request-review" +REVIEW_ENABLED = os.environ.get("LOOPX_REVIEW_TEST_ENABLED") == "1" + + +def test_review_source_stages_the_existing_execution_owners(tmp_path): + source = _prepare_module().prepare_capability_source(tmp_path / "review", DISTRIBUTION) + review = source / "loopx/capabilities/pr_review_queue" + assert {path.name for path in review.glob("*.py")}.isdisjoint({ + "__init__.py", "catalog_entry.py", "goal_configuration.py", "machine_defaults.py", + "order.py", "scheduling.py", + }) + assert (review / "core.py").is_file() + assert (review / "experiences/pr-5944-review-frame.md").is_file() + assert (source / "loopx/cli_commands/pr_review.py").is_file() + assert (source / "loopx/pr_review.py").is_file() + assert (source / "loopx/pr_review_merge_readiness.py").is_file() + for path in (source / "loopx").rglob("*.py"): + assert path.read_bytes() == (REPOSITORY / path.relative_to(source)).read_bytes() + assert (source / "requires-core.txt").read_text().strip() == f"loopx-core=={__version__}" + + +def test_installed_core_discovers_review_without_execution_imports(core_python, tmp_path): + script = ''' +from importlib.metadata import PackageNotFoundError, distribution +from importlib.util import find_spec +from loopx.entrypoint import main +import sys + +installed = sys.argv[1] == "True" +if installed: + review = distribution("loopx-capability-pull-request-review") + core = distribution("loopx-core") + recall_module = "loopx/capabilities/agent_turn_recall/core.py" + assert review.version == core.version + assert f"loopx-core=={core.version}" in review.requires + members = {path.as_posix() for path in review.files if path.parts[0] == "loopx"} + assert "loopx/cli_commands/pr_review.py" in members and "loopx/pr_review.py" in members + assert recall_module not in members + assert members.isdisjoint(path.as_posix() for path in core.files) +else: + try: + distribution("loopx-capability-pull-request-review") + except PackageNotFoundError: + pass + else: + raise AssertionError("unexpected review wheel") +assert (find_spec("loopx.cli_commands.pr_review") is not None) is installed +assert main(["capability", "show", "pull-request-review", "--format", "json"]) == 0 +from loopx.capabilities.pr_review_queue.goal_configuration import configuration_summary +assert configuration_summary({}) is None +for module in ("loopx.cli_commands.pr_review", "loopx.pr_review", "loopx.capabilities.pr_review_queue.core", + "loopx.capabilities.pr_review_queue.github_source"): + assert module not in sys.modules +''' + discovered = subprocess.run( + [core_python, "-I", "-c", script, str(REVIEW_ENABLED)], + cwd=tmp_path, env=_environment(core_python), capture_output=True, text=True, timeout=45, + ) + assert discovered.returncode == 0, discovered.stderr + capability = json.loads(discovered.stdout)["capability"] + assert capability["provider_state"]["ready"] is REVIEW_ENABLED + assert capability["provider_state"]["installed"] is REVIEW_ENABLED + if not REVIEW_ENABLED: + result = _run(core_python, ["pr-review", "--help"], tmp_path, expected=2) + assert DISTRIBUTION in result.stderr + + +@pytest.mark.skipif(not REVIEW_ENABLED, reason="requires the matching PR review wheel") +def test_installed_review_resumes_the_exact_head_queue(core_python, tmp_path): + registry = tmp_path / "registry.json" + registry.write_text('{"goals": []}', encoding="utf-8") + checkpoint = tmp_path / "checkpoint.json" + fixture = REPOSITORY / "examples/fixtures/pr-review.public.json" + command = [ + "--registry", str(registry), "--runtime-root", str(tmp_path / "runtime"), + "--format", "json", "pr-review", "--fixture", str(fixture), "--state", "open", + "--autonomous-observation", "--observation-state-file", str(checkpoint), + ] + first = json.loads(_run(core_python, command, tmp_path).stdout) + observation = first["autonomous_review"] + assert observation["candidate_count"] == 1 + assert observation["candidate"]["number"] == 771 + assert observation["candidate"]["head_oid"] == "7710000000000000000000000000000000000000" + assert observation["write_authority_granted"] is False + + replay = json.loads(_run(core_python, command, tmp_path).stdout) + assert replay["request"]["previous_observation_supplied"] is True + assert replay["autonomous_review"]["candidate"] == observation["candidate"] + + second = json.loads(_run( + core_python, + [*command, "--projected-exact-head", "771@7710000000000000000000000000000000000000"], + tmp_path, + ).stdout) + assert second["autonomous_review"]["projected_candidate_count"] == 1 + assert second["autonomous_review"]["candidate"]["number"] == 773 + assert second["autonomous_review"]["write_authority_granted"] is False diff --git a/tests/test_core_recall_distribution.py b/tests/test_core_recall_distribution.py index ae9ab53caf..770bed1bb3 100644 --- a/tests/test_core_recall_distribution.py +++ b/tests/test_core_recall_distribution.py @@ -31,7 +31,9 @@ def test_recall_source_stages_only_the_optional_implementation(tmp_path): - staged = _prepare_module().prepare_turn_recall_source(tmp_path / "recall") + staged = _prepare_module().prepare_capability_source( + tmp_path / "recall", "loopx-capability-agent-turn-recall", + ) assert {path.relative_to(staged).as_posix() for path in (staged / "loopx").rglob("*.py")} == RECALL_MODULES for path in RECALL_MODULES: assert (staged / path).read_bytes() == (REPOSITORY / path).read_bytes() From d29b011218999ee8a90d769cbf8c8c56b7f31b1c Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 05:17:17 +0800 Subject: [PATCH 5/6] Split issue-fix workflow from Core PR dependency recovery Signed-off-by: cicolord --- .github/workflows/package-smoke.yml | 25 +++ .../rfcs/monorepo-distribution-split-v0.md | 25 +-- .../monorepo-distribution-split-v0.zh-CN.md | 21 ++- .../issue-fix-pr-review-reconcile-smoke.py | 8 +- loopx/bootstrap_command_pack.py | 63 ++++--- loopx/capabilities/catalog.py | 10 +- loopx/capabilities/issue_fix/catalog_entry.py | 63 ++++--- .../issue_fix/pr_gate_reconcile.py | 8 +- .../issue_fix/pr_wait_reconcile.py | 3 +- loopx/cli_commands/start_goal.py | 51 +++--- loopx/cli_commands/starter_bootstrap.py | 42 +++-- loopx/cli_runtime.py | 21 ++- loopx/control_plane/goals/start_contract.py | 2 +- packages/loopx-capability-issue-fix/README.md | 29 +++ .../loopx-capability-issue-fix/pyproject.toml | 22 +++ packages/loopx-core/README.md | 24 ++- packages/loopx-core/prepare.py | 31 +++- tests/test_core_issue_fix_distribution.py | 167 ++++++++++++++++++ 18 files changed, 493 insertions(+), 122 deletions(-) create mode 100644 packages/loopx-capability-issue-fix/README.md create mode 100644 packages/loopx-capability-issue-fix/pyproject.toml create mode 100644 tests/test_core_issue_fix_distribution.py diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index e2e08ba475..279e566234 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -16,7 +16,9 @@ on: - "loopx/capabilities/decision_context/extension_provider.py" - "loopx/extensions/runtime.py" - "packages/loopx-capability-pull-request-review/**" + - "packages/loopx-capability-issue-fix/**" - "tests/test_core_pr_review_distribution.py" + - "tests/test_core_issue_fix_distribution.py" push: branches: - main @@ -34,7 +36,9 @@ on: - "loopx/capabilities/decision_context/extension_provider.py" - "loopx/extensions/runtime.py" - "packages/loopx-capability-pull-request-review/**" + - "packages/loopx-capability-issue-fix/**" - "tests/test_core_pr_review_distribution.py" + - "tests/test_core_issue_fix_distribution.py" permissions: contents: read @@ -100,6 +104,27 @@ jobs: uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-pull-request-review uv run --extra test python -m pytest -q tests/test_core_pr_review_distribution.py -k discovers + - name: Qualify Issue Fix and the Standard CLI composition + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-issue-fix --output "$RUNNER_TEMP/issue-fix-source" + uv build --wheel "$RUNNER_TEMP/issue-fix-source" --out-dir "$RUNNER_TEMP/issue-fix-dist" + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ + "$RUNNER_TEMP"/issue-fix-dist/loopx_capability_issue_fix-*.whl + LOOPX_ISSUE_FIX_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_issue_fix_distribution.py + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ + "$RUNNER_TEMP"/recall-dist/loopx_capability_agent_turn_recall-*.whl \ + "$RUNNER_TEMP"/review-dist/loopx_capability_pull_request_review-*.whl + LOOPX_ISSUE_FIX_TEST_ENABLED=1 LOOPX_REVIEW_TEST_ENABLED=1 LOOPX_RECALL_TEST_ENABLED=1 \ + uv run --extra test python -m pytest -q \ + tests/test_core_issue_fix_distribution.py tests/test_core_pr_review_distribution.py \ + tests/test_core_recall_distribution.py -k 'installed' + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" \ + loopx-capability-issue-fix loopx-capability-pull-request-review loopx-capability-agent-turn-recall + uv run --extra test python -m pytest -q tests/test_core_issue_fix_distribution.py -k 'quiet or retains_bound' + codex-provider-routing: name: loopx-codex-provider-routing runs-on: ubuntu-latest diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index 15b831ba78..d55736218e 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -413,20 +413,23 @@ packet cannot be treated as proof the executor has the prior context. Recover through the owning contract when continuity is unknown. Capability instructions are supplied when applicable; authority is never inferred from prompt text. -Standard has two source-built capability wheel candidates, -`loopx-capability-agent-turn-recall` and `loopx-capability-pull-request-review`. +The Standard CLI composition has three source-built capability wheel +candidates, `loopx-capability-agent-turn-recall`, +`loopx-capability-pull-request-review`, and `loopx-capability-issue-fix`. Install each alongside the matching Core release. Core and each add-on own -disjoint files and keep the existing capability IDs, configuration and runtime +disjoint files and keep existing capability IDs, configuration and runtime owners. Independent provider packages use the public capability boundary above. -Discovery reads metadata without loading either implementation. Core can report -unavailable recall and continue ordinary work. The existing Goal/Agent opt-in -loads recall when installed, and outcome ingest retains its own recovery path. -Core keeps PR review catalog and settings. An explicit `pr-review` invocation -loads the matching wheel and uses the existing exact-head queue, action boundary -and checkpoint. Removing the wheel leaves saved settings and checkpoints -available to a later installation. Issue-fix and the full Standard preset still -need installation qualification. +Discovery reads metadata on its own. The existing Goal/Agent opt-in loads +recall when installed, and outcome ingest retains its own recovery path. +The `pr-review` command uses its existing exact-head queue and checkpoint. +An explicit Issue Fix selection in a Core environment loads the matching +workflow and presents its existing candidate admission. Ordinary Core goal +previews stay free of its command templates. Generic PR-wait observation and +previously acknowledged review reconciliation remain in Core, with public PR +lifecycle code loaded for the selected observation or reconciliation. Existing +work and checkpoints survive add-on removal. The full Standard workspace and +published split release still need qualification. Optional observers consume committed events or bounded projections. Their latency must not enter admission/settlement transactions unless the existing 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 89136e8f90..fb4dc06856 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -285,15 +285,18 @@ capability 包直接采用现有 `extension.toml` 契约,不做扩展。唯一 不能因为 packet 更小,就认为 executor 已掌握前文。连续性未知时走所属契约的恢复路径。 Capability 指令仅在适用时提供;authority 不能从 prompt 文字推导。 -Standard 有两个可从源码构建的能力 wheel 候选,即 -`loopx-capability-agent-turn-recall` 和 `loopx-capability-pull-request-review`。 -两个能力可分别装入同版本的 Core 环境。Core 与各可选包各自拥有互不重叠的文件,沿用 -既有能力 ID、配置和运行时 owner。独立 provider 包仍按上文公共能力边界接入。 - -能力发现只读取元数据。Core 可报告召回实现缺失并继续普通任务。安装召回包后按既有 -Goal/Agent 设置显式启用,结果入库继续沿用自身的恢复路径。Core 保留 PR 评审目录与配置。 -显式调用 `pr-review` 时加载匹配的可选包,复用精确 head 队列、操作边界和 checkpoint。 -卸载后,既有设置与 checkpoint 留待日后安装续用。Issue 修复和完整 Standard 预设仍需安装态验收。 +Standard CLI 装配有三个可从源码构建的能力 wheel 候选,即 +`loopx-capability-agent-turn-recall`、`loopx-capability-pull-request-review` +和 `loopx-capability-issue-fix`。三个能力可分别装入同版本的 Core 环境。Core 与各可选包 +各自拥有互不重叠的文件,沿用既有能力 ID、配置和运行时 owner。独立 provider 包仍按 +上文公共能力边界接入。 + +能力发现只读取元数据。安装召回包后按既有 Goal/Agent 设置显式启用,结果入库沿用 +自身的恢复路径。显式调用 `pr-review` 时复用精确 head 队列与 checkpoint。在 Core 装配 +中显式选择 Issue 修复后,才加载相应 workflow 并提供原有候选准入。普通 Core 目标预览 +省去这组专用命令。通用 PR 等待观察和已确认评审的核对留在 Core,只有实际观察或核对时 +才加载公开 PR 生命周期代码。卸载可选包保留既有工作和 checkpoint。完整 Standard +工作区和拆包发布仍需验收。 可选 observer 消费已提交事件或有界投影。除非现有契约明确要求它的 receipt, 其延迟不能进入准入/结算事务。只批处理尽力而为的 telemetry;不能为满足时间目标而延迟 diff --git a/examples/issue-fix-pr-review-reconcile-smoke.py b/examples/issue-fix-pr-review-reconcile-smoke.py index d797710380..cf9b0831d9 100644 --- a/examples/issue-fix-pr-review-reconcile-smoke.py +++ b/examples/issue-fix-pr-review-reconcile-smoke.py @@ -72,7 +72,7 @@ def reconcile_without_provider( url: str = PR_URL, ) -> dict[str, Any]: with patch( - "loopx.capabilities.issue_fix.pr_gate_reconcile." + "loopx.capabilities.issue_fix.pr_lifecycle." "build_issue_fix_pr_lifecycle_monitor_packet", side_effect=AssertionError("invalid acknowledgement must not read provider"), ): @@ -215,7 +215,7 @@ def check_reconciliation(provider: str) -> None: first_ack["binding"]["todo_revision"] ) with patch( - "loopx.capabilities.issue_fix.pr_gate_reconcile." + "loopx.capabilities.issue_fix.pr_lifecycle." "build_issue_fix_pr_lifecycle_monitor_packet", side_effect=ValueError("private provider detail"), ): @@ -236,7 +236,7 @@ def check_reconciliation(provider: str) -> None: assert "error" not in degraded["results"][0], degraded with patch( - "loopx.capabilities.issue_fix.pr_gate_reconcile." + "loopx.capabilities.issue_fix.pr_lifecycle." "build_issue_fix_pr_lifecycle_monitor_packet", return_value={ "observation": { @@ -267,7 +267,7 @@ def check_reconciliation(provider: str) -> None: assert todo(state_file, "todo_github_review")["status"] == "done" with patch( - "loopx.capabilities.issue_fix.pr_gate_reconcile." + "loopx.capabilities.issue_fix.pr_lifecycle." "build_issue_fix_pr_lifecycle_monitor_packet", side_effect=AssertionError( "completed acknowledgement must not read provider" diff --git a/loopx/bootstrap_command_pack.py b/loopx/bootstrap_command_pack.py index 8451873ba5..b6b4972c69 100644 --- a/loopx/bootstrap_command_pack.py +++ b/loopx/bootstrap_command_pack.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +from importlib.util import find_spec from pathlib import Path from typing import Any @@ -356,6 +357,7 @@ def build_start_goal_host_surface_selection_packet( ) -> dict[str, Any]: """Fail closed when the caller has not identified the current Codex host.""" + _require_goal_capability_route(capability_route) resolved_project = str(_resolve_project(project)) registry_path = Path(resolved_project) / ".loopx" / "registry.json" registry_payload, _registry_error = _read_registry(registry_path) @@ -747,16 +749,30 @@ def _project_command(project: str, command: str) -> str: return "\n".join([f"cd {shell_arg_for_host(project)}", command]) -def _selected_goal_capability_route( - capability_route: str | None, -) -> dict[str, Any] | None: +class GoalCapabilityUnavailable(ValueError): + """The caller selected a workflow missing from this installation.""" + + +def _require_goal_capability_route(capability_route: str | None) -> None: if capability_route is None: - return None + return if capability_route not in START_GOAL_CAPABILITY_ROUTES: raise ValueError( "unsupported --capability-route; expected one of: " + ", ".join(START_GOAL_CAPABILITY_ROUTES) ) + from .capabilities.issue_fix.catalog_entry import ISSUE_FIX_INSTALL_HINT, issue_fix_workflow_installed + + if not issue_fix_workflow_installed(): + raise GoalCapabilityUnavailable(ISSUE_FIX_INSTALL_HINT) + + +def _selected_goal_capability_route( + capability_route: str | None, +) -> dict[str, Any] | None: + if capability_route is None: + return None + _require_goal_capability_route(capability_route) from .capabilities.issue_fix.candidate_preflight import candidate_preflight_input_contract return { @@ -798,6 +814,14 @@ def _selected_goal_capability_route( +def _goal_issue_fix_commands( + *, capability_route: str | None, cli_bin: str, goal_id: str, agent_id: str = "", +) -> dict[str, str]: + if capability_route is None and find_spec("loopx.cli") is None: + return {} + return build_issue_fix_goal_command_templates(cli_bin=cli_bin, goal_id=goal_id, agent_id=agent_id) + + def build_loopx_bootstrap_command_pack( *, project: Path, @@ -826,9 +850,9 @@ def build_loopx_bootstrap_command_pack( normalized_goal_text = " ".join(goal_text.split()) if goal_text else None normalized_thread_id = normalize_thread_id(thread_id) explicit_goal_start = bool(normalized_goal_text) - issue_fix_hint_commands = build_issue_fix_goal_command_templates( - cli_bin=cli_bin, - goal_id="", + selected_capability_route = _selected_goal_capability_route(capability_route) + issue_fix_hint_commands = _goal_issue_fix_commands( + capability_route=capability_route, cli_bin=cli_bin, goal_id="", ) agent_type = agent_type_for_host_surface(host_surface) registry_path = Path(str(inspection["registry"])) @@ -903,7 +927,8 @@ def build_loopx_bootstrap_command_pack( thread_binding_projection = {"status": thread_binding.get("status")} if thread_binding.get("agent_id"): thread_binding_projection["agent_id"] = thread_binding["agent_id"] - issue_fix_commands = build_issue_fix_goal_command_templates( + issue_fix_commands = _goal_issue_fix_commands( + capability_route=capability_route, cli_bin=cli_bin, goal_id=resolved_goal_id, agent_id=str(selected_agent_id) if selected_agent_id else "", @@ -1048,9 +1073,7 @@ def build_loopx_bootstrap_command_pack( "recommended_next_step": recommended_next_step, "goal_start_contract": build_goal_start_contract( goal_text=normalized_goal_text, - selected_capability_route=_selected_goal_capability_route( - capability_route - ), + selected_capability_route=selected_capability_route, connected=connected, agent_type=agent_type, issue_fix_commands=issue_fix_hint_commands, @@ -1192,9 +1215,9 @@ def _build_multi_goal_start_selection_packet( registry_path=registry_path, runtime_root_arg=runtime_root_arg, ) - issue_fix_commands = build_issue_fix_goal_command_templates( - cli_bin=cli_bin, - goal_id="", + selected_capability_route = _selected_goal_capability_route(capability_route) + issue_fix_commands = _goal_issue_fix_commands( + capability_route=capability_route, cli_bin=cli_bin, goal_id="", ) choices: list[dict[str, Any]] = [] for goal in goals: @@ -1293,9 +1316,7 @@ def _build_multi_goal_start_selection_packet( "recommended_next_step": recommended_next_step, "goal_start_contract": build_goal_start_contract( goal_text=normalized_goal_text, - selected_capability_route=_selected_goal_capability_route( - capability_route - ), + selected_capability_route=selected_capability_route, connected=True, agent_type=agent_type_for_host_surface(host_surface), issue_fix_commands=issue_fix_commands, @@ -2053,6 +2074,8 @@ def render_loopx_bootstrap_command_pack_markdown(payload: dict[str, Any]) -> str activation = activation if isinstance(activation, dict) else {} ordering = goal_start.get("priority_ordering") ordering = ordering if isinstance(ordering, dict) else {} + issue_fix_command = commands.get("issue_fix_workflow_plan_template") + issue_fix_block = f"\n```bash\n{issue_fix_command}\n```\n" if issue_fix_command else "" return f"""# /loopx Bootstrap Command Pack Canonical slash command: `{payload.get("slash_command")}` @@ -2120,11 +2143,7 @@ def render_loopx_bootstrap_command_pack_markdown(payload: dict[str, Any]) -> str ```bash {commands.get("goal_start_connect_if_needed", "")} ``` - -```bash -{commands.get("issue_fix_workflow_plan_template", "")} -``` - +{issue_fix_block} ## Safety Contract - read_only: `{payload.get("read_only")}` diff --git a/loopx/capabilities/catalog.py b/loopx/capabilities/catalog.py index e82d93d831..998246926e 100644 --- a/loopx/capabilities/catalog.py +++ b/loopx/capabilities/catalog.py @@ -15,7 +15,10 @@ from .pr_review_queue.catalog_entry import ( PR_REVIEW_CATALOG_ENTRY, PR_REVIEW_INSTALL_HINT, pull_request_review_installed, ) -from .issue_fix.catalog_entry import ISSUE_FIX_CATALOG_ENTRY +from .issue_fix.catalog_entry import ( + ISSUE_FIX_CATALOG_ENTRY, ISSUE_FIX_CORE_CATALOG_ENTRY, ISSUE_FIX_INSTALL_HINT, + issue_fix_workflow_installed, +) from .decision_context.catalog_entry import DECISION_CONTEXT_CATALOG_ENTRY from .project_skill_delivery.catalog_entry import PROJECT_SKILL_DELIVERY_CATALOG_ENTRY from .material_lifecycle.catalog_entry import MATERIAL_LIFECYCLE_CATALOG_ENTRY @@ -156,6 +159,11 @@ def _record_for_installed_capability( elif record is PR_REVIEW_CATALOG_ENTRY: installed = pull_request_review_installed(builtin_cli_present=builtin_cli_present) hint = PR_REVIEW_INSTALL_HINT + elif record is ISSUE_FIX_CATALOG_ENTRY: + installed = issue_fix_workflow_installed(builtin_cli_present=builtin_cli_present) + hint = ISSUE_FIX_INSTALL_HINT + if not builtin_cli_present: + record = ISSUE_FIX_CORE_CATALOG_ENTRY else: return record if installed: diff --git a/loopx/capabilities/issue_fix/catalog_entry.py b/loopx/capabilities/issue_fix/catalog_entry.py index 1b8b9ca0f2..40bf9fd49a 100644 --- a/loopx/capabilities/issue_fix/catalog_entry.py +++ b/loopx/capabilities/issue_fix/catalog_entry.py @@ -2,9 +2,46 @@ from typing import Any +from ...python_install_owner import builtin_capability_installed from .command_templates import build_issue_fix_pr_lifecycle_command +ISSUE_FIX_DISTRIBUTION = "loopx-capability-issue-fix" +ISSUE_FIX_INSTALL_HINT = f"Install the matching {ISSUE_FIX_DISTRIBUTION} wheel in this Core environment." + + +def issue_fix_workflow_installed(*, builtin_cli_present: bool | None = None) -> bool: + return builtin_capability_installed( + ISSUE_FIX_DISTRIBUTION, + tuple(f"{__package__}.{name}" for name in ("cli", "candidate_preflight", "workflow_plan", "acceptance_loop")), + builtin_cli_present=builtin_cli_present, + ) + + +# The ordinary CLI continues to expose these compatibility command groups. +_COMPATIBILITY_COMMANDS = [ + { + "command": "loopx content-ops issue-fix-metadata-preview --url --fetch-metadata --format json", + "purpose": "Fetch body-free public GitHub issue/PR metadata.", + "write_boundary": "read-only external metadata; no issue comment, PR, or todo write", + }, + { + "command": "loopx value-connectors github-public-probe --url --fetch-metadata --format json", + "purpose": "Use the compatibility CLI to fetch the issue-fix-owned public GitHub probe packet.", + "write_boundary": "public metadata read only; no issue bodies, comments, PRs, account changes, or writes", + }, + { + "command": "loopx value-connectors github-reply-monitor --issue-url --after-comment-url --fetch-metadata --format json", + "purpose": "Use the compatibility CLI to detect public maintainer replies through the issue-fix provider.", + "write_boundary": "public comment metadata read only; no comment bodies, thread bump, or external write", + }, + { + "command": "loopx content-ops issue-fix-intake --format json", + "purpose": "Project public issue metadata into an issue-fix intake packet.", + "write_boundary": "fixture-only; no external read or write", + }, +] + ISSUE_FIX_CATALOG_ENTRY: dict[str, Any] = { "id": "issue-fix", "origin": "builtin", @@ -25,26 +62,7 @@ ), "entry_command": "loopx issue-fix workflow-plan --url --format json", "commands": [ - { - "command": "loopx content-ops issue-fix-metadata-preview --url --fetch-metadata --format json", - "purpose": "Fetch body-free public GitHub issue/PR metadata.", - "write_boundary": "read-only external metadata; no issue comment, PR, or todo write", - }, - { - "command": "loopx value-connectors github-public-probe --url --fetch-metadata --format json", - "purpose": "Use the compatibility CLI to fetch the issue-fix-owned public GitHub probe packet.", - "write_boundary": "public metadata read only; no issue bodies, comments, PRs, account changes, or writes", - }, - { - "command": "loopx value-connectors github-reply-monitor --issue-url --after-comment-url --fetch-metadata --format json", - "purpose": "Use the compatibility CLI to detect public maintainer replies through the issue-fix provider.", - "write_boundary": "public comment metadata read only; no comment bodies, thread bump, or external write", - }, - { - "command": "loopx content-ops issue-fix-intake --format json", - "purpose": "Project public issue metadata into an issue-fix intake packet.", - "write_boundary": "fixture-only; no external read or write", - }, + *_COMPATIBILITY_COMMANDS, { "command": "loopx issue-fix workflow-plan --url --repo-path --repository-context-json --format json", "purpose": "Compose metadata, repository context, intake, feasibility, validation labels, and PR review readiness blockers.", @@ -271,3 +289,8 @@ "while keeping external PR/comment actions explicit." ), } + + +ISSUE_FIX_CORE_CATALOG_ENTRY = ISSUE_FIX_CATALOG_ENTRY | { + "commands": ISSUE_FIX_CATALOG_ENTRY["commands"][len(_COMPATIBILITY_COMMANDS):], +} diff --git a/loopx/capabilities/issue_fix/pr_gate_reconcile.py b/loopx/capabilities/issue_fix/pr_gate_reconcile.py index fd37b4ee93..b4476bba76 100644 --- a/loopx/capabilities/issue_fix/pr_gate_reconcile.py +++ b/loopx/capabilities/issue_fix/pr_gate_reconcile.py @@ -11,10 +11,6 @@ from ...control_plane.todos.todo_semantics import todo_item_task_class from ...control_plane.todos.mutation_api import complete_goal_todo from ...control_plane.todos.list_readback import list_goal_todos -from .pr_lifecycle import ( - TERMINAL_PR_STATES, - build_issue_fix_pr_lifecycle_monitor_packet, -) from .pr_lifecycle_rollout import append_pr_merge_rollout_event from .pr_review_ack import ( load_issue_fix_pr_review_ack_receipts, @@ -78,6 +74,8 @@ def reconcile_issue_fix_pr_gate( execute: bool = False, generated_at: str | None = None, ) -> dict[str, Any]: + from .pr_lifecycle import TERMINAL_PR_STATES, build_issue_fix_pr_lifecycle_monitor_packet + lifecycle = build_issue_fix_pr_lifecycle_monitor_packet( url=url, provider_payload=provider_payload, @@ -234,6 +232,8 @@ def reconcile_issue_fix_pr_review( "skip_reason": context_status, } + from .pr_lifecycle import TERMINAL_PR_STATES, build_issue_fix_pr_lifecycle_monitor_packet + lifecycle = build_issue_fix_pr_lifecycle_monitor_packet( url=url, provider_payload=provider_payload, diff --git a/loopx/capabilities/issue_fix/pr_wait_reconcile.py b/loopx/capabilities/issue_fix/pr_wait_reconcile.py index 27bbd65b0a..a01be1b51b 100644 --- a/loopx/capabilities/issue_fix/pr_wait_reconcile.py +++ b/loopx/capabilities/issue_fix/pr_wait_reconcile.py @@ -21,7 +21,6 @@ append_rollout_event, build_rollout_event, rollout_event_log_path, ) from ...control_plane.todos.list_readback import list_goal_todos -from . import pr_lifecycle from .pr_lifecycle_rollout import append_pr_merge_rollout_event @@ -71,6 +70,8 @@ def _reconcile_locked( }) results: list[dict[str, Any]] = [] for target in plan["targets"]: + from . import pr_lifecycle + reference = {"repo": target["repo"], "number": target["number"]} result = {"pr_ref": target["pr_ref"], "todo_ids": target["todo_ids"], "state": "FAILED", "merge_event_recorded": False} diff --git a/loopx/cli_commands/start_goal.py b/loopx/cli_commands/start_goal.py index 50982b6b18..7771228ddb 100644 --- a/loopx/cli_commands/start_goal.py +++ b/loopx/cli_commands/start_goal.py @@ -9,6 +9,7 @@ from ..bootstrap_command_pack import ( START_GOAL_CAPABILITY_ROUTES, START_GOAL_HOST_SURFACES, + GoalCapabilityUnavailable, build_start_goal_guided_packet, build_start_goal_host_surface_selection_packet, render_start_goal_guided_markdown, @@ -396,8 +397,8 @@ def handle_start_goal_command( print_payload(host_surface_mismatch, args.format, _render_start_goal_markdown) return 2 display_name = args.display_name - if not args.host_surface: - try: + try: + if not args.host_surface: payload = build_start_goal_host_surface_selection_packet( project=Path(args.project), goal_id=args.goal_id, @@ -413,29 +414,31 @@ def handle_start_goal_command( display_name=display_name, runtime_root_arg=runtime_root_arg, ) - except EffectRuntimeStartupError as exc: - payload = _effect_runtime_startup_failure_payload(exc) - print_payload(payload, args.format, _render_start_goal_markdown) - return 1 + else: + payload = build_start_goal_guided_packet( + project=Path(args.project), + goal_id=args.goal_id, + agent_id=args.agent_id, + thread_id=current_host_thread_id(args), + new_peer=new_peer, + cli_bin=args.cli_bin, + host_surface=args.host_surface, + goal_text=goal_text, + available_capabilities=args.available_capabilities, + capability_route=capability_route, + fine_grained=fine_grained, + include_command_pack_detail=bool(args.include_command_pack_detail), + runtime_root_arg=runtime_root_arg, + display_name=display_name, + ) + except GoalCapabilityUnavailable as exc: + payload = { + "ok": False, + "schema_version": "loopx_start_goal_guided_v0", + "error": str(exc), + } print_payload(payload, args.format, _render_start_goal_markdown) - return 0 - try: - payload = build_start_goal_guided_packet( - project=Path(args.project), - goal_id=args.goal_id, - agent_id=args.agent_id, - thread_id=current_host_thread_id(args), - new_peer=new_peer, - cli_bin=args.cli_bin, - host_surface=args.host_surface, - goal_text=goal_text, - available_capabilities=args.available_capabilities, - capability_route=capability_route, - fine_grained=fine_grained, - include_command_pack_detail=bool(args.include_command_pack_detail), - runtime_root_arg=runtime_root_arg, - display_name=display_name, - ) + return 2 except EffectRuntimeStartupError as exc: payload = _effect_runtime_startup_failure_payload(exc) print_payload(payload, args.format, _render_start_goal_markdown) diff --git a/loopx/cli_commands/starter_bootstrap.py b/loopx/cli_commands/starter_bootstrap.py index 3d21efbca3..947d04dc2c 100644 --- a/loopx/cli_commands/starter_bootstrap.py +++ b/loopx/cli_commands/starter_bootstrap.py @@ -9,6 +9,8 @@ render_agent_onboarding_markdown, ) from ..bootstrap_command_pack import ( + SCHEMA_VERSION as BOOTSTRAP_COMMAND_PACK_SCHEMA_VERSION, + GoalCapabilityUnavailable, build_loopx_bootstrap_command_pack, render_loopx_bootstrap_command_pack_markdown, ) @@ -92,20 +94,32 @@ def handle_loopx_bootstrap_command_pack_command( *, runtime_root_arg: str | None = None, ) -> int: - payload = build_loopx_bootstrap_command_pack( - project=Path(args.project), - goal_id=args.goal_id, - agent_id=args.agent_id, - thread_id=current_host_thread_id(args), - new_peer=bool(getattr(args, "new_peer", False)), - cli_bin=args.cli_bin, - host_surface=args.host_surface, - goal_text=args.goal_text, - available_capabilities=args.available_capabilities, - capability_route=args.capability_route, - fine_grained=bool(args.fine_grained), - runtime_root_arg=runtime_root_arg, - ) + try: + payload = build_loopx_bootstrap_command_pack( + project=Path(args.project), + goal_id=args.goal_id, + agent_id=args.agent_id, + thread_id=current_host_thread_id(args), + new_peer=bool(getattr(args, "new_peer", False)), + cli_bin=args.cli_bin, + host_surface=args.host_surface, + goal_text=args.goal_text, + available_capabilities=args.available_capabilities, + capability_route=args.capability_route, + fine_grained=bool(args.fine_grained), + runtime_root_arg=runtime_root_arg, + ) + except GoalCapabilityUnavailable as exc: + payload = { + "ok": False, + "schema_version": BOOTSTRAP_COMMAND_PACK_SCHEMA_VERSION, + "error": str(exc), + } + if bool(getattr(args, "message_only", False)): + print(str(exc)) + else: + print_payload(payload, args.format, lambda value: str(value["error"])) + return 2 if bool(getattr(args, "message_only", False)): print(str(payload.get("message") or "")) return 0 diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index 2b74f7f1d8..e7a8d9d530 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -938,6 +938,17 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: result = handle_agent_turn_recall_command( args, registry_path=registry_path, output_format=output_format, print_payload=print_payload, ) + elif args.command == "issue-fix": + from .capabilities.issue_fix.cli import handle_issue_fix_command + from .cli_commands.lark_inbox import build_lark_issue_fix_reviewer_provider_hooks + + result = handle_issue_fix_command( + args, registry_path=registry_path, runtime_root_arg=args.runtime_root, + reviewer_provider_hooks_factory=lambda: build_lark_issue_fix_reviewer_provider_hooks( + runtime_root_arg=args.runtime_root, + ), + output_format=output_format, print_payload=print_payload, + ) elif args.command == "pr-review": from .cli_commands.pr_review import handle_pr_review_command from .paths import effective_runtime_root @@ -1025,7 +1036,7 @@ def main(argv: list[str] | None = None) -> int: def _run_command(command: str | None, raw_argv: list[str]) -> int: - if command in {"agent-turn-recall", "pr-review"} and _standalone_core(): + if command in {"agent-turn-recall", "pr-review", "issue-fix"} and _standalone_core(): parser, subparsers = build_cli_parser() if command == "agent-turn-recall": from .capabilities.agent_turn_recall.catalog_entry import RECALL_INSTALL_HINT, agent_turn_recall_installed @@ -1033,12 +1044,18 @@ def _run_command(command: str | None, raw_argv: list[str]) -> int: if not agent_turn_recall_installed(builtin_cli_present=False): parser.error(f"agent-turn-recall is unavailable in the standalone core. {RECALL_INSTALL_HINT}") from .capabilities.agent_turn_recall.cli import register_agent_turn_recall_commands as register - else: + elif command == "pr-review": from .capabilities.pr_review_queue.catalog_entry import PR_REVIEW_INSTALL_HINT, pull_request_review_installed if not pull_request_review_installed(builtin_cli_present=False): parser.error(f"pr-review is unavailable in the standalone core. {PR_REVIEW_INSTALL_HINT}") from .cli_commands.pr_review import register_pr_review_command as register + else: + from .capabilities.issue_fix.catalog_entry import ISSUE_FIX_INSTALL_HINT, issue_fix_workflow_installed + + if not issue_fix_workflow_installed(builtin_cli_present=False): + parser.error(f"issue-fix is unavailable in the standalone core. {ISSUE_FIX_INSTALL_HINT}") + from .capabilities.issue_fix.cli import register_issue_fix_commands as register register(subparsers, add_subcommand_format) return _dispatch_selected(parse_cli_args(parser, raw_argv), raw_argv) diff --git a/loopx/control_plane/goals/start_contract.py b/loopx/control_plane/goals/start_contract.py index 303d4e99d3..461e880613 100644 --- a/loopx/control_plane/goals/start_contract.py +++ b/loopx/control_plane/goals/start_contract.py @@ -179,7 +179,7 @@ def build_goal_start_contract( "after PR creation verify reviewer-request, then monitor one PR state bucket" ), } - }, + } if issue_fix_commands else {}, "connected_at_preview_time": connected, "stop_conditions": [ "private material requested before a public-safe todo can be written", diff --git a/packages/loopx-capability-issue-fix/README.md b/packages/loopx-capability-issue-fix/README.md new file mode 100644 index 0000000000..ba97c2603a --- /dev/null +++ b/packages/loopx-capability-issue-fix/README.md @@ -0,0 +1,29 @@ +# LoopX Issue Fix for Core + +Add the existing `loopx issue-fix` commands to a standalone Core installation. +Use the wheel built from the same release as Core. Install it in the Core +environment and inspect the catalog before using the workflow. + +```sh +python packages/loopx-core/prepare.py \ + --distribution loopx-capability-issue-fix --output /tmp/loopx-issue-fix-source +uv build --wheel /tmp/loopx-issue-fix-source --out-dir /tmp/loopx-issue-fix-dist +uv pip install --python "$LOOPX_CORE_PYTHON" /tmp/loopx-issue-fix-dist/loopx_capability_issue_fix-*.whl +loopx capability show issue-fix --format json +loopx issue-fix --help +``` + +Set `LOOPX_CORE_PYTHON` to the interpreter in the installed Core environment. +Use that same environment for the CLI. A guided start selects this workflow +only when the caller passes `--capability-route issue-fix`. The +`repo-branch-fixture` subcommand exercises the offline validation loop in a +temporary local repository. Real repository actions use existing evidence and +authority requirements. + +Removing the wheel leaves original Goal and work state intact. Core retains its +existing PR dependency observations and acknowledgement recovery. Ordinary +LoopX also supplies the existing `content-ops` and `value-connectors` +compatibility commands. + +See the [Issue Fix capability](../../loopx/capabilities/issue_fix/README.md) for +the workflow, authority and evidence gates. diff --git a/packages/loopx-capability-issue-fix/pyproject.toml b/packages/loopx-capability-issue-fix/pyproject.toml new file mode 100644 index 0000000000..60f4fcc69a --- /dev/null +++ b/packages/loopx-capability-issue-fix/pyproject.toml @@ -0,0 +1,22 @@ +[build-system] +requires = ["setuptools==83.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "loopx-capability-issue-fix" +dynamic = ["version", "dependencies"] +description = "Built-in issue-fix workflow for a matching LoopX Core installation." +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.issue_fix"] + +[tool.setuptools.package-data] +"loopx.capabilities.issue_fix" = ["docs/*.md", "docs/protocols/*.md"] diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index 28c0da6049..0ce76a0c0f 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -48,9 +48,11 @@ The installed-only qualification in exercises setup, independent result validation, process loss, replay and refusal. No model service, credentials or paid task execution is supplied by this wheel. -Goal-start help and preview use issue-fix command metadata without importing -its execution providers. An explicit `--capability-route issue-fix` retains -the existing candidate-preflight contract. The installed context qualification +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 +PR-wait observations, confirmed review reconciliation, and their state. +The installed context qualification in [`test_installed_core_context.py`](../../tests/control_plane/test_installed_core_context.py) executes the existing `quota context-project`, `context-read` and `context-hook` commands: incomplete delivery cannot establish a baseline, revisions preserve @@ -70,6 +72,22 @@ wheel](../loopx-capability-pull-request-review/README.md) is installed. Core retains its catalog and settings. The add-on provides the existing `pr-review` command on explicit use. Removing it preserves review settings and checkpoints. +### Standard CLI composition + +Build the three optional wheels from the same checkout as Core. Set +`LOOPX_CORE_PYTHON` to the interpreter of that Core environment and install the +chosen capabilities there. This example installs all three. + +```sh +for capability in agent-turn-recall pull-request-review issue-fix; do + distribution="loopx-capability-$capability" + python packages/loopx-core/prepare.py --distribution "$distribution" --output "/tmp/$distribution-source" + uv build --wheel "/tmp/$distribution-source" --out-dir /tmp/loopx-standard-wheels +done +uv pip install --no-index --python "$LOOPX_CORE_PYTHON" /tmp/loopx-standard-wheels/loopx_capability_*.whl +loopx capability list --format json +``` + The candidate owns the same `loopx` import namespace and console command as the ordinary distribution. Do not co-install or overlay them. Return to the ordinary installation by switching back to its environment; preserve task state and diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index d21b04aeb5..0fe74cd8e7 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -18,11 +18,20 @@ SOURCE_SUFFIXES = {".py", ".ts", ".json", ".mjs", ".js", ".md", ".toml"} RECALL_DISTRIBUTION = "loopx-capability-agent-turn-recall" PR_REVIEW_DISTRIBUTION = "loopx-capability-pull-request-review" +ISSUE_FIX_DISTRIBUTION = "loopx-capability-issue-fix" PR_REVIEW_DIRECTORY = Path("loopx/capabilities/pr_review_queue") PR_REVIEW_CORE_FILES = { "__init__.py", "catalog_entry.py", "goal_configuration.py", "machine_defaults.py", "order.py", "scheduling.py", "README.md", } +ISSUE_FIX_DIRECTORY = Path("loopx/capabilities/issue_fix") +# Generic PR dependencies and existing acknowledgements retain their readback +# and continuation even when the authoring workflow is absent. +ISSUE_FIX_CORE_FILES = { + "__init__.py", "catalog_entry.py", "command_templates.py", "README.md", "README.zh-CN.md", + "github_public.py", "metadata_preview.py", "pr_gate_reconcile.py", "pr_lifecycle.py", + "pr_lifecycle_rollout.py", "pr_review_ack.py", "pr_wait_hook.py", "pr_wait_reconcile.py", +} CAPABILITY_ENTRY_MODULES = { RECALL_DISTRIBUTION: { Path("loopx/capabilities/agent_turn_recall/cli.py"), @@ -34,20 +43,30 @@ Path("loopx/pr_review_merge_readiness.py"), PR_REVIEW_DIRECTORY / "core.py", }, + ISSUE_FIX_DISTRIBUTION: { + ISSUE_FIX_DIRECTORY / name for name in ("cli.py", "candidate_preflight.py", "workflow_plan.py", "acceptance_loop.py") + }, } -def _optional_capability_sources(sources: list[Path]) -> dict[str, set[Path]]: - tracked = set(sources) - review_sources = { +def _implementation_paths(sources: list[Path], directory: Path, core_files: set[str]) -> set[Path]: + return { path for path in sources - if path.is_relative_to(PR_REVIEW_DIRECTORY) - and path.relative_to(PR_REVIEW_DIRECTORY).as_posix() not in PR_REVIEW_CORE_FILES + if path.is_relative_to(directory) + and path.relative_to(directory).as_posix() not in core_files and path.suffix in SOURCE_SUFFIXES } + + +def _optional_capability_sources(sources: list[Path]) -> dict[str, set[Path]]: + tracked = set(sources) return { RECALL_DISTRIBUTION: tracked & CAPABILITY_ENTRY_MODULES[RECALL_DISTRIBUTION], - PR_REVIEW_DISTRIBUTION: review_sources | (tracked & CAPABILITY_ENTRY_MODULES[PR_REVIEW_DISTRIBUTION]), + PR_REVIEW_DISTRIBUTION: ( + _implementation_paths(sources, PR_REVIEW_DIRECTORY, PR_REVIEW_CORE_FILES) + | (tracked & CAPABILITY_ENTRY_MODULES[PR_REVIEW_DISTRIBUTION]) + ), + ISSUE_FIX_DISTRIBUTION: _implementation_paths(sources, ISSUE_FIX_DIRECTORY, ISSUE_FIX_CORE_FILES), } diff --git a/tests/test_core_issue_fix_distribution.py b/tests/test_core_issue_fix_distribution.py new file mode 100644 index 0000000000..f624d5f524 --- /dev/null +++ b/tests/test_core_issue_fix_distribution.py @@ -0,0 +1,167 @@ +"""Installed Issue Fix selection and Core's existing PR recovery behavior.""" + +import json +import os +import subprocess +from pathlib import Path + +import pytest + +from loopx import __version__ +from loopx.control_plane.todos.mutation_api import add_goal_todo +from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime, promoted_create_fixture +from tests.control_plane.host_process_fixture import write_python_host_fixture +from tests.test_core_distribution import REPOSITORY, _environment, _prepare_module, _run, core_python as core_python + +DISTRIBUTION = "loopx-capability-issue-fix" +ISSUE_FIX_ENABLED = os.environ.get("LOOPX_ISSUE_FIX_TEST_ENABLED") == "1" + + +def test_issue_fix_stages_the_workflow_without_wait_or_ledger_owners(tmp_path): + source = _prepare_module().prepare_capability_source(tmp_path / "issue-fix", DISTRIBUTION) + owners = source / "loopx/capabilities/issue_fix" + for name in ("cli.py", "candidate_preflight.py", "acceptance_loop.py", "workflow_plan.py"): + assert (owners / name).read_bytes() == (REPOSITORY / owners.relative_to(source) / name).read_bytes() + for name in ("catalog_entry.py", "__init__.py", "pr_wait_reconcile.py", "pr_review_ack.py"): + assert not (owners / name).exists() + assert not (source / "loopx/domain_packs/issue_fix.py").exists() + assert (source / "requires-core.txt").read_text().strip() == f"loopx-core=={__version__}" + + +def _guided_args(project: Path, *, host_surface: str | None = "shell") -> list[str]: + arguments = [ + "--runtime-root", str(project / "runtime"), "--format", "json", + "start-goal", "--guided", "--project", str(project), + "--goal-text", "Generate a checked inventory report.", + ] + if host_surface: + arguments.extend(["--host-surface", host_surface]) + return arguments + + +def test_installed_issue_fix_is_quiet_until_selected(core_python, tmp_path): + probe = ''' +import json, sys +from importlib.metadata import distribution +from importlib.util import find_spec +from loopx.entrypoint import main + +installed = sys.argv[2] == "True" +assert (find_spec("loopx.capabilities.issue_fix.cli") is not None) is installed +if installed: + workflow = distribution("loopx-capability-issue-fix") + core = distribution("loopx-core") + assert workflow.version == core.version and f"loopx-core=={core.version}" in workflow.requires + members = {entry.as_posix() for entry in workflow.files if entry.parts[0] == "loopx"} + assert members.isdisjoint(entry.as_posix() for entry in core.files) + assert "loopx/capabilities/issue_fix/cli.py" in members +assert main(json.loads(sys.argv[1])) == 0 +for name in ("cli", "workflow_plan", "candidate_preflight", "acceptance_loop", "pr_lifecycle"): + assert "loopx.capabilities.issue_fix." + name not in sys.modules, name +''' + catalog_args = ["capability", "show", "issue-fix", "--format", "json"] + discovered = subprocess.run( + [core_python, "-I", "-c", probe, json.dumps(catalog_args), str(ISSUE_FIX_ENABLED)], + cwd=tmp_path, env=_environment(core_python), capture_output=True, text=True, timeout=45, + ) + assert discovered.returncode == 0, discovered.stderr + capability = json.loads(discovered.stdout)["capability"] + assert capability["provider_state"]["ready"] is ISSUE_FIX_ENABLED + assert capability["commands"] and all( + row["command"].startswith("loopx issue-fix ") for row in capability["commands"] + ) + + args = _guided_args(tmp_path) + packet = json.loads(_run(core_python, args, tmp_path).stdout) + assert packet["goal_text"] == "Generate a checked inventory report." + assert packet["guided_transaction"]["writes_now"] is False + assert packet["command_pack"]["goal_start_contract"]["domain_route_hints"] == {} + assert "issue_fix_workflow_plan_template" not in packet["command_pack"]["commands"] + assert "issue-fix workflow-plan" not in packet["message"] + if not ISSUE_FIX_ENABLED: + command = _run(core_python, ["issue-fix", "--help"], tmp_path, expected=2) + assert DISTRIBUTION in command.stderr + for start_args in (args, _guided_args(tmp_path, host_surface=None)): + refusal = _run(core_python, [*start_args, "--capability-route", "issue-fix"], tmp_path, expected=2) + assert DISTRIBUTION in json.loads(refusal.stdout)["error"] + assert not refusal.stderr + bootstrap = _run(core_python, [ + "--format", "json", "bootstrap-command-pack", "--project", str(tmp_path), + "--capability-route", "issue-fix", + ], tmp_path, expected=2) + assert DISTRIBUTION in json.loads(bootstrap.stdout)["error"] + assert not list(tmp_path.iterdir()) + + +@pytest.mark.skipif(not ISSUE_FIX_ENABLED, reason="requires the matching Issue Fix wheel") +def test_installed_issue_fix_uses_original_admission_and_validated_git_branch(core_python, tmp_path): + selected = json.loads(_run( + core_python, [*_guided_args(tmp_path), "--capability-route", "issue-fix"], tmp_path, + ).stdout) + route = selected["guided_transaction"]["selected_capability_route"] + assert route["capability_id"] == "issue-fix" + assert route["candidate_preflight"]["required_before_implementation"] is True + assert selected["guided_transaction"]["writes_now"] is False + + artifact = json.loads(_run( + core_python, ["issue-fix", "repo-branch-fixture", "--format", "json"], tmp_path, + ).stdout) + assert artifact["ok"] is True + verified = artifact["validated_fix_artifact"] + assert verified["repro_before"]["passed"] is False + assert verified["validation_after"]["passed"] is True + assert verified["repo_branch"]["branch_created"] is True + assert verified["repo_branch"]["external_remote_used"] is False + + +@pytest.mark.skipif(ISSUE_FIX_ENABLED, reason="qualifies Core without the workflow wheel") +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_core_retains_bound_pr_wait_and_reloads_only_due_observation(core_python, tmp_path, monkeypatch, provider): + isolate_sqlite_runtime(tmp_path, monkeypatch) + registry, runtime, _ = promoted_create_fixture(tmp_path, provider=provider) + config = json.loads(registry.read_text()) + config["goals"][0]["available_capabilities"] = ["external_evidence_poll"] + config["goals"][0]["quota"] = {"compute": 0} + registry.write_text(json.dumps(config), encoding="utf-8") + prefix = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + heartbeat = [*prefix, "heartbeat-prequota", "-g", "goal-a", "-a", "agent-a"] + + idle = subprocess.run( + [core_python, "-I", "-c", + "import json,sys;from loopx.entrypoint import main;" + "assert main(json.loads(sys.argv[1]))==0;" + "assert 'loopx.capabilities.issue_fix.pr_lifecycle' not in sys.modules", + json.dumps(heartbeat)], + cwd=tmp_path, env=_environment(core_python), capture_output=True, text=True, timeout=45, + ) + assert idle.returncode == 0, (idle.stdout, idle.stderr) + + todo_id = add_goal_todo( + registry_path=registry, goal_id="goal-a", role="agent", claimed_by="agent-a", + text="Recheck the report after its source update merges.", resume_when="pr_merged:owner/repo#42", + )["todo_id"] + executable_dir = tmp_path / "gh-fixture" + executable_dir.mkdir() + calls = tmp_path / "observation-calls" + write_python_host_fixture(executable_dir / "gh", f'''#!{core_python} +import json +from pathlib import Path +import sys +assert sys.argv[1:7] == ["pr", "view", "42", "--repo", "owner/repo", "--json"] +with Path({str(calls)!r}).open("a") as marker: + marker.write("once\\n") +print(json.dumps({{"state": "MERGED", "mergedAt": "2026-10-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/42"}})) +''') + # Isolate the child's gh process while preserving Node on PATH. + environment = {"PATH": str(executable_dir) + os.pathsep + _environment(core_python)["PATH"]} + first = json.loads(_run(core_python, heartbeat, tmp_path, environment=environment).stdout) + assert first["checks"]["pr_dependencies"]["merged_count"] == 1 + assert first["quota_spend_required"] is False + todo = json.loads(_run( + core_python, [*prefix, "todo", "list", "--goal-id", "goal-a", "--todo-id", todo_id], tmp_path, + ).stdout)["todo"] + assert todo["resume_ready"] is True + replay = json.loads(_run(core_python, heartbeat, tmp_path, environment=environment).stdout) + assert replay["checks"]["pr_dependencies"]["external_read_count"] == 0 + assert calls.read_text().splitlines() == ["once"] From 68d42770cd4ad6b3e8599ce8b8228a60b0345946 Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 08:14:02 +0800 Subject: [PATCH 6/6] Install the selected Standard capabilities as a Core extra Signed-off-by: cicolord --- .github/workflows/package-smoke.yml | 22 +++-- .../rfcs/monorepo-distribution-split-v0.md | 4 +- .../monorepo-distribution-split-v0.zh-CN.md | 3 +- packages/loopx-core/README.md | 26 ++++-- packages/loopx-core/prepare.py | 13 ++- packages/loopx-core/pyproject.toml | 5 +- tests/test_core_standard_distribution.py | 90 +++++++++++++++++++ 7 files changed, 144 insertions(+), 19 deletions(-) create mode 100644 tests/test_core_standard_distribution.py diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index 279e566234..a5c34e4dd2 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -19,6 +19,7 @@ on: - "packages/loopx-capability-issue-fix/**" - "tests/test_core_pr_review_distribution.py" - "tests/test_core_issue_fix_distribution.py" + - "tests/test_core_standard_distribution.py" push: branches: - main @@ -39,6 +40,7 @@ on: - "packages/loopx-capability-issue-fix/**" - "tests/test_core_pr_review_distribution.py" - "tests/test_core_issue_fix_distribution.py" + - "tests/test_core_standard_distribution.py" permissions: contents: read @@ -83,9 +85,9 @@ jobs: run: | uv run --extra test python packages/loopx-core/prepare.py \ --distribution loopx-capability-agent-turn-recall --output "$RUNNER_TEMP/recall-source" - uv build --wheel "$RUNNER_TEMP/recall-source" --out-dir "$RUNNER_TEMP/recall-dist" + uv build --wheel "$RUNNER_TEMP/recall-source" --out-dir "$RUNNER_TEMP/core-dist" uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ - "$RUNNER_TEMP"/recall-dist/loopx_capability_agent_turn_recall-*.whl + "$RUNNER_TEMP"/core-dist/loopx_capability_agent_turn_recall-*.whl LOOPX_RECALL_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_recall_distribution.py uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-agent-turn-recall uv run --extra test python -m pytest -q tests/test_core_distribution.py \ @@ -97,9 +99,9 @@ jobs: run: | uv run --extra test python packages/loopx-core/prepare.py \ --distribution loopx-capability-pull-request-review --output "$RUNNER_TEMP/review-source" - uv build --wheel "$RUNNER_TEMP/review-source" --out-dir "$RUNNER_TEMP/review-dist" + uv build --wheel "$RUNNER_TEMP/review-source" --out-dir "$RUNNER_TEMP/core-dist" uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ - "$RUNNER_TEMP"/review-dist/loopx_capability_pull_request_review-*.whl + "$RUNNER_TEMP"/core-dist/loopx_capability_pull_request_review-*.whl LOOPX_REVIEW_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_pr_review_distribution.py uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-pull-request-review uv run --extra test python -m pytest -q tests/test_core_pr_review_distribution.py -k discovers @@ -110,13 +112,13 @@ jobs: run: | uv run --extra test python packages/loopx-core/prepare.py \ --distribution loopx-capability-issue-fix --output "$RUNNER_TEMP/issue-fix-source" - uv build --wheel "$RUNNER_TEMP/issue-fix-source" --out-dir "$RUNNER_TEMP/issue-fix-dist" + uv build --wheel "$RUNNER_TEMP/issue-fix-source" --out-dir "$RUNNER_TEMP/core-dist" uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ - "$RUNNER_TEMP"/issue-fix-dist/loopx_capability_issue_fix-*.whl + "$RUNNER_TEMP"/core-dist/loopx_capability_issue_fix-*.whl LOOPX_ISSUE_FIX_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_issue_fix_distribution.py - uv pip install --python "$LOOPX_CORE_TEST_PYTHON" \ - "$RUNNER_TEMP"/recall-dist/loopx_capability_agent_turn_recall-*.whl \ - "$RUNNER_TEMP"/review-dist/loopx_capability_pull_request_review-*.whl + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-issue-fix + uv pip install --offline --no-index --find-links "$RUNNER_TEMP/core-dist" --reinstall-package loopx-core \ + --python "$LOOPX_CORE_TEST_PYTHON" 'loopx-core[standard]' LOOPX_ISSUE_FIX_TEST_ENABLED=1 LOOPX_REVIEW_TEST_ENABLED=1 LOOPX_RECALL_TEST_ENABLED=1 \ uv run --extra test python -m pytest -q \ tests/test_core_issue_fix_distribution.py tests/test_core_pr_review_distribution.py \ @@ -124,6 +126,8 @@ jobs: uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" \ loopx-capability-issue-fix loopx-capability-pull-request-review loopx-capability-agent-turn-recall uv run --extra test python -m pytest -q tests/test_core_issue_fix_distribution.py -k 'quiet or retains_bound' + LOOPX_STANDARD_TEST_WHEELHOUSE="$RUNNER_TEMP/core-dist" uv run --extra test python -m pytest -q \ + tests/test_core_standard_distribution.py codex-provider-routing: name: loopx-codex-provider-routing diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index d55736218e..10f6b92060 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -416,7 +416,9 @@ are supplied when applicable; authority is never inferred from prompt text. The Standard CLI composition has three source-built capability wheel candidates, `loopx-capability-agent-turn-recall`, `loopx-capability-pull-request-review`, and `loopx-capability-issue-fix`. -Install each alongside the matching Core release. Core and each add-on own +Install them together with `loopx-core[standard]` or add each alongside the +matching Core release. The extra pins these three packages to the Core version. +Core and each add-on own disjoint files and keep existing capability IDs, configuration and runtime owners. Independent provider packages use the public capability boundary above. 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 fb4dc06856..46be0f56a5 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -287,7 +287,8 @@ Capability 指令仅在适用时提供;authority 不能从 prompt 文字推导 Standard CLI 装配有三个可从源码构建的能力 wheel 候选,即 `loopx-capability-agent-turn-recall`、`loopx-capability-pull-request-review` -和 `loopx-capability-issue-fix`。三个能力可分别装入同版本的 Core 环境。Core 与各可选包 +和 `loopx-capability-issue-fix`。用 `loopx-core[standard]` 一次安装三个能力,也可分别安装。 +这个 extra 将三个包锁定到 Core 的同一版本。Core 与各可选包 各自拥有互不重叠的文件,沿用既有能力 ID、配置和运行时 owner。独立 provider 包仍按 上文公共能力边界接入。 diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index 0ce76a0c0f..c6c60344c6 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -74,18 +74,32 @@ command on explicit use. Removing it preserves review settings and checkpoints. ### Standard CLI composition -Build the three optional wheels from the same checkout as Core. Set -`LOOPX_CORE_PYTHON` to the interpreter of that Core environment and install the -chosen capabilities there. This example installs all three. +Install `loopx-core[standard]` to select Agent Turn Recall, Pull Request Review +and Issue Fix together. Build the three companion wheels into the same +directory as the Core wheel, using the same checkout. Set `LOOPX_CORE_PYTHON` +to the interpreter of a new environment or the matching Core environment. ```sh for capability in agent-turn-recall pull-request-review issue-fix; do distribution="loopx-capability-$capability" python packages/loopx-core/prepare.py --distribution "$distribution" --output "/tmp/$distribution-source" - uv build --wheel "/tmp/$distribution-source" --out-dir /tmp/loopx-standard-wheels + uv build --wheel "/tmp/$distribution-source" --out-dir /tmp/loopx-core-dist done -uv pip install --no-index --python "$LOOPX_CORE_PYTHON" /tmp/loopx-standard-wheels/loopx_capability_*.whl -loopx capability list --format json +uv pip install --no-index --find-links /tmp/loopx-core-dist \ + --reinstall-package loopx-core --python "$LOOPX_CORE_PYTHON" 'loopx-core[standard]' +"$LOOPX_CORE_PYTHON" -I -m loopx.entrypoint capability list --format json +``` + +The reinstall option reads the selected wheel's metadata when an earlier +source build of the same version is already installed. + +Each ability can also be installed on its own. Use the existing commands and +Goal settings to select a workflow. To return to Core-only installation, +uninstall the three companion wheels in the same environment: + +```sh +uv pip uninstall --python "$LOOPX_CORE_PYTHON" \ + loopx-capability-agent-turn-recall loopx-capability-pull-request-review loopx-capability-issue-fix ``` The candidate owns the same `loopx` import namespace and console command as the diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index 0fe74cd8e7..dd370059a0 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -19,6 +19,11 @@ RECALL_DISTRIBUTION = "loopx-capability-agent-turn-recall" PR_REVIEW_DISTRIBUTION = "loopx-capability-pull-request-review" ISSUE_FIX_DISTRIBUTION = "loopx-capability-issue-fix" +STANDARD_CAPABILITY_DISTRIBUTIONS = ( + RECALL_DISTRIBUTION, + PR_REVIEW_DISTRIBUTION, + ISSUE_FIX_DISTRIBUTION, +) PR_REVIEW_DIRECTORY = Path("loopx/capabilities/pr_review_queue") PR_REVIEW_CORE_FILES = { "__init__.py", "catalog_entry.py", "goal_configuration.py", "machine_defaults.py", @@ -81,7 +86,13 @@ def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: and not path.as_posix().startswith(EXCLUDED_TREES)] if not sources or not (repository / "loopx/entrypoint.py").is_file(): raise ValueError("a complete LoopX source checkout is required") - return _stage_source(output, repository, "loopx-core", sources) + output = _stage_source(output, repository, "loopx-core", sources) + version = run_path(str(repository / "loopx/__init__.py"))["__version__"] + (output / "requires-standard.txt").write_text( + "".join(f"{distribution}=={version}\n" for distribution in STANDARD_CAPABILITY_DISTRIBUTIONS), + encoding="utf-8", + ) + return output def _stage_source(output: Path, repository: Path, distribution: str, sources: list[Path]) -> Path: diff --git a/packages/loopx-core/pyproject.toml b/packages/loopx-core/pyproject.toml index 18055fa421..0ed0b226f3 100644 --- a/packages/loopx-core/pyproject.toml +++ b/packages/loopx-core/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "loopx-core" -dynamic = ["version"] +dynamic = ["version", "optional-dependencies"] description = "Standalone LoopX CLI and durable task runtime without the workspace." readme = "README.md" requires-python = ">=3.11" @@ -18,6 +18,9 @@ loopx = "loopx.entrypoint:main" [tool.setuptools.dynamic] version = {attr = "loopx.__version__"} +[tool.setuptools.dynamic.optional-dependencies] +standard = {file = "requires-standard.txt"} + [tool.setuptools.packages.find] include = ["loopx*"] diff --git a/tests/test_core_standard_distribution.py b/tests/test_core_standard_distribution.py new file mode 100644 index 0000000000..198ba99688 --- /dev/null +++ b/tests/test_core_standard_distribution.py @@ -0,0 +1,90 @@ +"""Exercise the Standard installation over the same pending Core task.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +from tests.test_core_distribution import _assert_committed, _environment, _run +from tests.test_core_distribution import task as task + + +STANDARD_DISTRIBUTIONS = ( + "loopx-capability-agent-turn-recall", + "loopx-capability-pull-request-review", + "loopx-capability-issue-fix", +) + + +@pytest.fixture +def standard_wheelhouse(): + wheelhouse = os.environ.get("LOOPX_STANDARD_TEST_WHEELHOUSE") + if not wheelhouse: + pytest.skip("set LOOPX_STANDARD_TEST_WHEELHOUSE to the directory of matching wheels") + return Path(wheelhouse).resolve(strict=True) + + +@pytest.fixture +def core_python(tmp_path, standard_wheelhouse): + 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")) + _install(python, standard_wheelhouse, "loopx-core") + return python + + +def _install(python, wheelhouse, requirement, *options): + subprocess.run(["uv", "pip", "install", "--offline", "--no-index", "--find-links", str(wheelhouse), + "--python", python, *options, requirement], check=True, timeout=45) + + +def _installed_loopx_packages(python, workspace): + script = """ +import json +from importlib.metadata import distributions +print(json.dumps({d.metadata["Name"]: d.version for d in distributions() + if d.metadata["Name"].startswith("loopx")})) +""" + result = subprocess.run([python, "-I", "-c", script], cwd=workspace, env=_environment(python), + capture_output=True, text=True, check=True, timeout=30) + return json.loads(result.stdout) + + +def test_standard_installs_only_the_selected_capabilities_and_recovers_the_same_task( + core_python, standard_wheelhouse, task, +): + workspace, runtime, registry, arguments = task + core = _installed_loopx_packages(core_python, workspace) + assert core.keys() == {"loopx-core"} + original = registry.read_bytes() + + _install(core_python, standard_wheelhouse, "loopx-core[standard]", "--reinstall-package", "loopx-core") + assert _installed_loopx_packages(core_python, workspace) == { + **core, **dict.fromkeys(STANDARD_DISTRIBUTIONS, core["loopx-core"]), + } + assert registry.read_bytes() == original + script = """ +import json, sys +from loopx.entrypoint import main + +assert main(json.loads(sys.argv[1])) == 0 +for module in ("loopx.capabilities.agent_turn_recall.core", + "loopx.capabilities.pr_review_queue.core", + "loopx.capabilities.issue_fix.workflow_plan"): + assert module not in sys.modules, module +""" + completed = subprocess.run([core_python, "-I", "-c", script, json.dumps(arguments)], + cwd=workspace, env=_environment(core_python), + capture_output=True, text=True, timeout=90) + assert completed.returncode == 0, (completed.stdout, completed.stderr) + turn_key = _assert_committed(core_python, workspace, runtime, json.loads(completed.stdout)) + + subprocess.run(["uv", "pip", "uninstall", "--python", core_python, *STANDARD_DISTRIBUTIONS], + check=True, timeout=45) + assert _installed_loopx_packages(core_python, workspace) == core + replay = json.loads(_run(core_python, [*arguments, "--resume-turn-key", turn_key], workspace).stdout) + assert replay["replayed"] and not any(replay["effects"].values()) + assert _assert_committed(core_python, workspace, runtime, replay) == turn_key