From d4f8ff786cac30064b3d4fb33f9ef017c39d76bd Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 02:15:51 +0800 Subject: [PATCH 1/7] 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 d50944a530..c0b0dc8198 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -450,6 +450,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 71f657f544..17e5420cfe 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -311,6 +311,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 f384764e3d..c38d614016 100644 --- a/loopx/capabilities/agent_turn_recall/runtime.py +++ b/loopx/capabilities/agent_turn_recall/runtime.py @@ -7,24 +7,23 @@ 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 ...paths import PATH_SEGMENT_UNSAFE_RE -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" @@ -274,6 +273,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 3cc7d0b67c..0a268c917e 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -67,6 +67,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 674859f5e1..441fb4f1bc 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 c636c1bd84..835f1f05ea 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 @@ -342,6 +347,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 @@ -611,6 +628,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 d4865aedc7f5747e52d4825f9e21fec54e34b0ef Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 02:22:27 +0800 Subject: [PATCH 2/7] 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 c1b7f234f770da1c959f86b70062adf72e7a8efa Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 04:20:51 +0800 Subject: [PATCH 3/7] 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 cd0f1efaa8..72fb7db8f1 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 c0b0dc8198..c208bc4204 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -450,14 +450,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 17e5420cfe..efe190bf15 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -311,10 +311,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 c38d614016..35fd55c867 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: @@ -273,15 +274,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( @@ -289,6 +282,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 23dba82cac..52eb6a527f 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -987,6 +987,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, @@ -1072,6 +1078,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 0a268c917e..ed7b1188ce 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -68,10 +68,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 @@ -86,6 +87,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 441fb4f1bc..6298bc6536 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. @@ -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 835f1f05ea..252f22b9d4 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -353,9 +353,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 6957a1b1cb010640b28f09028c109ef2b0b6cd1b Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 04:53:32 +0800 Subject: [PATCH 4/7] 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 72fb7db8f1..1aeb205b96 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 c208bc4204..25be49c6fd 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -450,18 +450,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 efe190bf15..9faf4b780f 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -311,12 +311,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 c0e77f6a98..20647c8ee9 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 52eb6a527f..ec13147dc1 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -993,6 +993,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, @@ -1078,15 +1086,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 47fb79f7c3..c70ac9a8a0 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, PackagePath +from importlib.metadata import Distribution, PackageNotFoundError, PackagePath, distribution +from importlib.util import find_spec import json import os from pathlib import Path @@ -48,6 +49,37 @@ def verified_distribution_console(recorded: Path) -> Path | None: return None +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 = { + distribution_record_path(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 ed7b1188ce..10827a0a6f 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -74,6 +74,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 6298bc6536..a9783bd593 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 252f22b9d4..491dd70e9b 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 d48cc37d023955f268b4dcfa6307df9f48a0da11 Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 05:17:17 +0800 Subject: [PATCH 5/7] 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 | 55 ++++-- 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 | 44 +++-- loopx/cli_runtime.py | 21 ++- loopx/control_plane/goals/start_contract.py | 2 +- .../renderers/start_goal_markdown.py | 8 +- 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 ++++++++++++++++++ 19 files changed, 494 insertions(+), 123 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 1aeb205b96..f1c88f34cf 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 25be49c6fd..2299fcd662 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -450,20 +450,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 9faf4b780f..bb4ec5439a 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -311,15 +311,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 4b0c78d680..73126880f1 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 @@ -384,6 +385,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) @@ -825,16 +827,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 { @@ -876,6 +892,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, @@ -909,9 +933,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="", ) registry_path = Path(str(inspection["registry"])) registry_goal = next( @@ -987,7 +1011,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 "", @@ -1115,9 +1140,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, @@ -1259,9 +1282,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: @@ -1352,9 +1375,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, 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 2ac7adc625..8cd81c2343 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.", @@ -272,3 +290,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 e8177cb621..7eed44e745 100644 --- a/loopx/capabilities/issue_fix/pr_gate_reconcile.py +++ b/loopx/capabilities/issue_fix/pr_gate_reconcile.py @@ -12,10 +12,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, @@ -79,6 +75,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, @@ -238,6 +236,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 a8fd8ffdfe..d763a15bfe 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 @@ -83,6 +82,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 f94993221b..85b44fa207 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, ) @@ -98,21 +100,33 @@ def handle_loopx_bootstrap_command_pack_command( runtime_root_arg: str | None = None, explicit_project_registry: Path | 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, - explicit_project_registry=explicit_project_registry, - ) + 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, + explicit_project_registry=explicit_project_registry, + ) + 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 ec13147dc1..66da938dd0 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -993,6 +993,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 @@ -1086,7 +1097,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 @@ -1094,12 +1105,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/loopx/presentation/renderers/start_goal_markdown.py b/loopx/presentation/renderers/start_goal_markdown.py index 131fa71f60..7f5741ce1d 100644 --- a/loopx/presentation/renderers/start_goal_markdown.py +++ b/loopx/presentation/renderers/start_goal_markdown.py @@ -405,6 +405,8 @@ def render_loopx_bootstrap_command_pack_markdown(payload: dict[str, Any]) -> str goal_start = _dict_field(payload, "goal_start_contract") activation = _dict_field(payload, "host_loop_activation") ordering = _dict_field(goal_start, "priority_ordering") + 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")}` @@ -472,11 +474,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/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 10827a0a6f..222a86f9b8 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -57,9 +57,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 @@ -79,6 +81,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 a9783bd593..fa40cb447d 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 fc25ff2f9e161005a43cda74e9bcf762e371f358 Mon Sep 17 00:00:00 2001 From: cicolord Date: Thu, 19 Nov 2026 08:14:02 +0800 Subject: [PATCH 6/7] 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 f1c88f34cf..69b8b068d2 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 2299fcd662..d94d34903d 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -453,7 +453,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 bb4ec5439a..5d39b8c7c1 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -313,7 +313,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 222a86f9b8..cba9a0fcc2 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -83,18 +83,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 fa40cb447d..157ec1ea12 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 From d962de024cfd18048eca52a1a35b23c660730b23 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:46:24 +0800 Subject: [PATCH 7/7] fix(core): preserve doctor fingerprint, list installed commands, and isolate optional imports Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/capabilities/content_ops/cli.py | 27 ++++-- loopx/capabilities/issue_fix/github_public.py | 2 + .../issue_fix/repository_snapshot.py | 2 +- .../native_chat/github_pr_evidence.py | 2 +- .../native_chat/steward_monitor_signals.py | 2 +- loopx/capabilities/reward_memory/cli.py | 16 +++- loopx/cli_commands/update_artifact.py | 6 +- loopx/cli_runtime.py | 20 ++++- .../extensions/lark/reviewer_notification.py | 17 ++-- loopx/release_manifest.py | 49 ++++++++--- packages/loopx-core/prepare.py | 10 ++- ...st_reward_memory_field_vocabulary_owner.py | 13 ++- tests/test_core_distribution.py | 85 ++++++++++++++++++- tests/test_core_issue_fix_distribution.py | 5 +- tests/test_core_pr_review_distribution.py | 5 +- tests/test_core_recall_distribution.py | 4 + tests/test_core_standard_distribution.py | 69 +++++++++++++++ tests/test_distribution_runtime_identity.py | 70 +++++++++++++++ 18 files changed, 360 insertions(+), 44 deletions(-) diff --git a/loopx/capabilities/content_ops/cli.py b/loopx/capabilities/content_ops/cli.py index 33d6e3c72b..e724a80c65 100644 --- a/loopx/capabilities/content_ops/cli.py +++ b/loopx/capabilities/content_ops/cli.py @@ -8,10 +8,6 @@ from pathlib import Path from typing import Any -from ..issue_fix.content_ops_cli import ( - handle_content_ops_issue_fix_command, - register_content_ops_issue_fix_commands, -) from .item_lifecycle import ( apply_content_ops_item_event, build_content_ops_item_packet, @@ -48,6 +44,16 @@ MAX_INPUT_BYTES = 16 * 1024 * 1024 +def _optional_issue_fix_content_ops_cli() -> Any | None: + try: + from ..issue_fix import content_ops_cli + except ModuleNotFoundError as exc: + if exc.name == "loopx.capabilities.issue_fix.content_ops_cli": + return None + raise + return content_ops_cli + + def _input_byte_limit(text: str) -> int: # An explicit, positive byte count; there is no unbounded setting. if not text.isdecimal() or int(text) < 1: @@ -184,7 +190,11 @@ def register_content_ops_commands( default="2026-06-23T00:00:00Z", help="Public-safe generated_at timestamp for the exploration plan.", ) - register_content_ops_issue_fix_commands(content_ops_sub, add_subcommand_format) + issue_fix_cli = _optional_issue_fix_content_ops_cli() + if issue_fix_cli is not None: + issue_fix_cli.register_content_ops_issue_fix_commands( + content_ops_sub, add_subcommand_format + ) observe_parser = content_ops_sub.add_parser( "observe-public-handle", help="Observe a public platform handle as metadata-only source_item_v0.", @@ -584,7 +594,12 @@ def read_json(path_text: str) -> dict[str, Any]: return _load_json_object(path_text, args.max_input_bytes) try: - issue_fix_result = handle_content_ops_issue_fix_command(args) + issue_fix_cli = _optional_issue_fix_content_ops_cli() + issue_fix_result = ( + issue_fix_cli.handle_content_ops_issue_fix_command(args) + if issue_fix_cli is not None + else None + ) if issue_fix_result is not None: payload, renderer = issue_fix_result elif args.content_ops_command in {"media", "generation", "image"}: diff --git a/loopx/capabilities/issue_fix/github_public.py b/loopx/capabilities/issue_fix/github_public.py index 1cdbd0b01d..7f599badee 100644 --- a/loopx/capabilities/issue_fix/github_public.py +++ b/loopx/capabilities/issue_fix/github_public.py @@ -2,6 +2,7 @@ import hashlib import json +import re import shutil import subprocess from datetime import datetime, timezone @@ -37,6 +38,7 @@ ) ALLOWED_GITHUB_REF_TYPES = {"issue", "pull", "discussion"} +_REPO_PATTERN = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") MAINTAINER_ASSOCIATIONS = {"COLLABORATOR", "MEMBER", "OWNER"} GITHUB_COMMENT_BODY_KEYS = { "body", diff --git a/loopx/capabilities/issue_fix/repository_snapshot.py b/loopx/capabilities/issue_fix/repository_snapshot.py index 3f30fc94f7..7649a7b838 100644 --- a/loopx/capabilities/issue_fix/repository_snapshot.py +++ b/loopx/capabilities/issue_fix/repository_snapshot.py @@ -8,6 +8,7 @@ from datetime import datetime from typing import Any +from .github_public import _REPO_PATTERN as _REPO_PATTERN from .metrics_supplement import SUPPLEMENT_SCHEMA_VERSION @@ -16,7 +17,6 @@ RECORD_SCHEMA_VERSION = "issue_fix_repository_snapshot_record_v0" ISSUE_CLOSE_ACTIVITY_SCHEMA_VERSION = "issue_fix_issue_close_activity_v0" -_REPO_PATTERN = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") _REF_NUMBER_PATTERN = re.compile(r"(?:issues|pull)_(\d+)") _FAILED_CHECK_CONCLUSIONS = { "ACTION_REQUIRED", diff --git a/loopx/capabilities/native_chat/github_pr_evidence.py b/loopx/capabilities/native_chat/github_pr_evidence.py index a9f5c5b436..c2f547bfe4 100644 --- a/loopx/capabilities/native_chat/github_pr_evidence.py +++ b/loopx/capabilities/native_chat/github_pr_evidence.py @@ -10,7 +10,7 @@ import subprocess from typing import Any, Callable, Mapping, Sequence -from ..issue_fix.repository_snapshot import _REPO_PATTERN as _REPO_SLUG_RE +from ..issue_fix.github_public import _REPO_PATTERN as _REPO_SLUG_RE from ..pr_review_queue.review_body import ( author_owned_review_title_matches, check_review_body, diff --git a/loopx/capabilities/native_chat/steward_monitor_signals.py b/loopx/capabilities/native_chat/steward_monitor_signals.py index f8dfee061d..8674f6bd23 100644 --- a/loopx/capabilities/native_chat/steward_monitor_signals.py +++ b/loopx/capabilities/native_chat/steward_monitor_signals.py @@ -10,7 +10,7 @@ from ...chat_store import _atomic_write_json from ...control_plane.runtime.time import now_utc -from ..issue_fix.repository_snapshot import _REPO_PATTERN +from ..issue_fix.github_public import _REPO_PATTERN from .steward_commands import NativeStewardCommandError, native_command from .steward_monitor_turns import ( FOLLOWUP_TARGET_PREFIX, diff --git a/loopx/capabilities/reward_memory/cli.py b/loopx/capabilities/reward_memory/cli.py index ac7b4b214b..23ac871eaf 100644 --- a/loopx/capabilities/reward_memory/cli.py +++ b/loopx/capabilities/reward_memory/cli.py @@ -6,7 +6,7 @@ from pathlib import Path from typing import Any, cast -from ..issue_fix.reward_memory import ingest_issue_fix_reward_memory_event +from ..issue_fix.catalog_entry import ISSUE_FIX_INSTALL_HINT from .architecture import ( build_reward_memory_architecture_packet, build_reward_memory_route_packet, @@ -41,6 +41,18 @@ ) +def _ingest_issue_fix_reward_memory_event(*args: Any, **kwargs: Any) -> dict[str, Any]: + try: + from ..issue_fix.reward_memory import ingest_issue_fix_reward_memory_event + except ModuleNotFoundError as exc: + if exc.name == "loopx.capabilities.issue_fix.reward_memory": + raise ValueError( + f"issue_fix_maintainer_feedback requires the optional issue-fix capability. {ISSUE_FIX_INSTALL_HINT}" + ) from exc + raise + return ingest_issue_fix_reward_memory_event(*args, **kwargs) + + def _render(payload: dict[str, object]) -> str: lines = ["# Reward Memory", ""] for key in ( @@ -389,7 +401,7 @@ def handle_reward_memory_command( if not isinstance(value, Mapping): raise ValueError(f"{key} must be an object") ingest_adapter = { - "issue_fix_maintainer_feedback": ingest_issue_fix_reward_memory_event, + "issue_fix_maintainer_feedback": _ingest_issue_fix_reward_memory_event, SCOPED_FEEDBACK_ADAPTER: ingest_scoped_feedback_reward_memory_event, }.get(str(adapter or "")) if ingest_adapter is None: diff --git a/loopx/cli_commands/update_artifact.py b/loopx/cli_commands/update_artifact.py index 7f30faf036..ab8e5cf1a1 100644 --- a/loopx/cli_commands/update_artifact.py +++ b/loopx/cli_commands/update_artifact.py @@ -28,7 +28,7 @@ from urllib.request import HTTPRedirectHandler, Request, build_opener from ..control_plane.content_digest import BARE_SHA256_PATTERN as HASH -from ..capabilities.issue_fix.repository_snapshot import _REPO_PATTERN as REPOSITORY_PATTERN +from ..capabilities.issue_fix.github_public import _REPO_PATTERN as REPOSITORY_PATTERN RUNTIME_ARTIFACT_SCHEMA_VERSION = "loopx_runtime_artifact_v1" QUALIFIED_DEFAULT_CONTRACT_FIELD = "qualified_default_contract" @@ -47,8 +47,8 @@ def standalone_source() -> str: for statement, owner_path, symbol, alias in ( ("from ..control_plane.content_digest import BARE_SHA256_PATTERN as HASH", "control_plane/content_digest.py", "BARE_SHA256_PATTERN", "HASH"), - ("from ..capabilities.issue_fix.repository_snapshot import _REPO_PATTERN as REPOSITORY_PATTERN", - "capabilities/issue_fix/repository_snapshot.py", "_REPO_PATTERN", "REPOSITORY_PATTERN"), + ("from ..capabilities.issue_fix.github_public import _REPO_PATTERN as REPOSITORY_PATTERN", + "capabilities/issue_fix/github_public.py", "_REPO_PATTERN", "REPOSITORY_PATTERN"), ): owner = (Path(__file__).resolve().parents[1] / owner_path).read_text(encoding="utf-8") assignments = [node for node in ast.parse(owner).body if isinstance(node, ast.Assign) diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index 66da938dd0..ec485f3e31 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -775,7 +775,9 @@ def _dispatch_common_command( print_payload( build_command_reference_payload( - available_commands=_SELECTED_COMMANDS if _standalone_core() else None, + available_commands=( + _available_selected_commands() if _standalone_core() else None + ), ), output_format(args), render_command_reference_markdown, ) @@ -941,6 +943,7 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: if guard_result is not None: return guard_result registry_path, registry_was_configured = resolve_cli_registry(args, raw_argv) + result: int | None if args.command == "workbench": from .cli_commands.workbench import handle_workbench_command @@ -1024,6 +1027,21 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: return result +def _available_selected_commands() -> frozenset[str]: + from .capabilities.agent_turn_recall.catalog_entry import agent_turn_recall_installed + from .capabilities.issue_fix.catalog_entry import issue_fix_workflow_installed + from .capabilities.pr_review_queue.catalog_entry import pull_request_review_installed + + commands = set(_SELECTED_COMMANDS) + if agent_turn_recall_installed(builtin_cli_present=False): + commands.add("agent-turn-recall") + if pull_request_review_installed(builtin_cli_present=False): + commands.add("pr-review") + if issue_fix_workflow_installed(builtin_cli_present=False): + commands.add("issue-fix") + return frozenset(commands) + + def _standalone_core() -> bool: if sys.modules.get("loopx.cli") is not None: return False diff --git a/loopx/extensions/lark/reviewer_notification.py b/loopx/extensions/lark/reviewer_notification.py index 5d015625dd..98692269c8 100644 --- a/loopx/extensions/lark/reviewer_notification.py +++ b/loopx/extensions/lark/reviewer_notification.py @@ -4,14 +4,11 @@ import re import subprocess from collections.abc import Mapping, Sequence -from typing import Any +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from ...capabilities.issue_fix.reviewer_notification import CommandRunner -from ...capabilities.issue_fix.reviewer_notification import ( - SAFE_LOCAL_KEY_PATTERN, - CommandRunner, - build_reviewer_notification_sink_result, - reviewer_notification_idempotency_key, -) from ...control_plane.runtime.public_safety import public_safe_compact_text from .identity_shapes import ( LARK_CHAT_ID_PATTERN, @@ -126,6 +123,12 @@ def lark_reviewer_notification_sink( execute: bool, runner: CommandRunner, ) -> dict[str, Any]: + from ...capabilities.issue_fix.reviewer_notification import ( + SAFE_LOCAL_KEY_PATTERN, + build_reviewer_notification_sink_result, + reviewer_notification_idempotency_key, + ) + sink_kind = "lark_chat" if sink.get("identity_scope") != "project_dedicated": return build_reviewer_notification_sink_result( diff --git a/loopx/release_manifest.py b/loopx/release_manifest.py index 763b841ef4..fe3b46fd0c 100644 --- a/loopx/release_manifest.py +++ b/loopx/release_manifest.py @@ -1,7 +1,7 @@ from __future__ import annotations from datetime import datetime, timezone -from importlib.metadata import PackageNotFoundError, distribution +from importlib.metadata import Distribution, PackageNotFoundError, PackagePath, distribution import hashlib import json import os @@ -10,7 +10,7 @@ from . import __version__ from .doctor_git import GitSourceState, git_source_metadata -from .python_install_owner import installed_loopx_distribution +from .python_install_owner import distribution_record_path, installed_loopx_distribution RELEASE_MANIFEST_SCHEMA_VERSION = "loopx_release_manifest_v0" @@ -306,31 +306,58 @@ def release_runtime_identity(release_root: Path | None = None) -> dict[str, str return identity +_CORE_COMPANION_DISTRIBUTIONS = ( + "loopx-workspace", + "loopx-capability-agent-turn-recall", + "loopx-capability-pull-request-review", + "loopx-capability-issue-fix", +) + + def _distribution_artifact_file(path: Path) -> bool: return "__pycache__" not in path.parts and path.suffix not in {".pyc", ".pyo"} +def _owned_runtime_files(installed: Distribution) -> dict[str, Path]: + direct_url = json.loads(installed.read_text("direct_url.json") or "{}") + if direct_url.get("dir_info", {}).get("editable") or installed.version != __version__: + return {} + return { + item.as_posix(): ( + distribution_record_path(item) + if isinstance(item, PackagePath) + else Path(item.locate()) + ) + for item in installed.files or () + if item.as_posix().startswith("loopx/") + and _distribution_artifact_file(Path(item.as_posix())) + } + + def _distribution_runtime_fingerprint() -> str | None: """Hash the actual imported, RECORD-owned wheel contents, not RECORD hashes. + Include verified, disjoint Core companion distributions when installed. Refuse editable, redirected, incomplete or ambiguous ownership. Bytecode caches are generated by Python and are not part of the installed artifact. """ try: installed = installed_loopx_distribution(distribution) - direct_url = json.loads(installed.read_text("direct_url.json") or "{}") - if direct_url.get("dir_info", {}).get("editable") or installed.version != __version__: - return None package_root = Path(__file__).resolve().parent - files = { - item.as_posix(): Path(item.locate()) - for item in installed.files or () - if item.as_posix().startswith("loopx/") - and _distribution_artifact_file(Path(item.as_posix())) - } + files = _owned_runtime_files(installed) module = files.get("loopx/release_manifest.py") if module is None or module.resolve() != Path(__file__).resolve(): return None + if getattr(installed, "name", None) == "loopx-core": + for name in _CORE_COMPANION_DISTRIBUTIONS: + try: + companion = distribution(name) + except PackageNotFoundError: + continue + owned = _owned_runtime_files(companion) + if not owned or files.keys() & owned.keys(): + return None + files.update(owned) entries = list(package_root.rglob("*")) if any(path.is_symlink() for path in entries): return None diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index 157ec1ea12..6e3267695c 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -27,15 +27,17 @@ 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", + "order.py", "review_body.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", + "__init__.py", "catalog_entry.py", "command_templates.py", "correction_settlement.py", + "correction_settlement_gates.py", "correction_settlement_input.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: { diff --git a/tests/architecture/test_reward_memory_field_vocabulary_owner.py b/tests/architecture/test_reward_memory_field_vocabulary_owner.py index 91cec1c923..c2159890ea 100644 --- a/tests/architecture/test_reward_memory_field_vocabulary_owner.py +++ b/tests/architecture/test_reward_memory_field_vocabulary_owner.py @@ -55,7 +55,7 @@ import pytest from loopx.capabilities.explore import todo_branch_plan, worker_branch_plan -from loopx.capabilities.issue_fix import pr_description +from loopx.capabilities.issue_fix import github_public, pr_description from loopx.capabilities.issue_fix import repository_commit_evidence as commit_evidence from loopx.capabilities.issue_fix import repository_snapshot from loopx.capabilities.issue_fix import reward_memory as issue_fix_reward_memory @@ -102,13 +102,17 @@ ), "_REPO_PATTERN": ( r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", - "loopx/capabilities/issue_fix/repository_snapshot.py", - repository_snapshot, + "loopx/capabilities/issue_fix/github_public.py", + github_public, [ + ( + "loopx/capabilities/issue_fix/repository_snapshot.py", + repository_snapshot, + ), ( "loopx/capabilities/issue_fix/repository_commit_evidence.py", commit_evidence, - ) + ), ], ), } @@ -331,6 +335,7 @@ def test_repo_shape_is_checked_by_the_producer_and_the_verifier() -> None: repository_snapshot._repo_parts("loopx-project-loopx") assert str(refused.value) == "repo must use owner/name" assert commit_evidence._REPO_PATTERN is repository_snapshot._REPO_PATTERN + assert repository_snapshot._REPO_PATTERN is github_public._REPO_PATTERN assert not commit_evidence._REPO_PATTERN.fullmatch("loopx-project/loopx/two") diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index 491dd70e9b..e76295bbe2 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -73,13 +73,96 @@ def test_core_staging_excludes_workspace_and_reuses_kernel_bytes(tmp_path): 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", + "order.py", "review_body.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() +def test_core_staging_has_zero_unconditional_optional_wheel_imports(tmp_path): + import ast + + prepare = _prepare_module() + staged = prepare.prepare_core_source(tmp_path / "source") + optional_sources = set().union(*prepare._optional_capability_sources( + prepare._tracked_loopx_sources(REPOSITORY) + ).values()) + + def _mod_name(path: Path) -> str: + parts = list(path.with_suffix("").parts) + return ".".join(parts[:-1] if parts[-1] == "__init__" else parts) + + optional_modules = {_mod_name(p) for p in optional_sources if p.suffix == ".py"} + + def _imported_targets(node: ast.AST, mod_parts: list[str]) -> list[str]: + if isinstance(node, ast.Import): + return [alias.name for alias in node.names] + if isinstance(node, ast.ImportFrom): + base = mod_parts[:-node.level] if node.level else [] + mod = ".".join([*base, *([node.module] if node.module else [])]) + return [mod, *(f"{mod}.{a.name}" for a in node.names if mod)] + return [] + + def _scan(stmts: list[ast.stmt], mod_parts: list[str], offenders: list[str], rel: str) -> None: + for stmt in stmts: + if isinstance(stmt, (ast.Import, ast.ImportFrom)): + for target in _imported_targets(stmt, mod_parts): + if target in optional_modules: + offenders.append(f"{rel}:{stmt.lineno}->{target}") + elif isinstance(stmt, ast.ClassDef): + _scan(stmt.body, mod_parts, offenders, rel) + elif isinstance(stmt, (ast.If, ast.For, ast.AsyncFor, ast.With, ast.AsyncWith, ast.While)): + if isinstance(stmt, ast.If) and ast.unparse(stmt.test) in {"TYPE_CHECKING", "typing.TYPE_CHECKING"}: + continue + _scan(stmt.body, mod_parts, offenders, rel) + if not isinstance(stmt, (ast.With, ast.AsyncWith)): + _scan(stmt.orelse, mod_parts, offenders, rel) + elif isinstance(stmt, ast.Try): + handlers = [ast.unparse(h.type) if h.type else "" for h in stmt.handlers] + if any("ModuleNotFoundError" in h or "ImportError" in h for h in handlers): + continue + _scan(stmt.body, mod_parts, offenders, rel) + _scan(stmt.orelse, mod_parts, offenders, rel) + _scan(stmt.finalbody, mod_parts, offenders, rel) + + offenders: list[str] = [] + for py_file in sorted((staged / "loopx").rglob("*.py")): + rel = py_file.relative_to(staged) + parts = list(rel.with_suffix("").parts) + mod_parts = parts[:-1] if parts[-1] == "__init__" else parts + _scan(ast.parse(py_file.read_text(encoding="utf-8")).body, mod_parts, offenders, rel.as_posix()) + assert offenders == [] + + +def test_installed_core_retains_module_imports_without_optional_wheels(core_python, tmp_path): + script = ''' +import importlib, importlib.metadata as m +try: + m.distribution("loopx-capability-issue-fix") +except m.PackageNotFoundError: + pass +else: + raise SystemExit(0) +for name in ( + "loopx.cli_commands.update_artifact", + "loopx.capabilities.reward_memory.cli", + "loopx.capabilities.content_ops.cli", + "loopx.extensions.lark.reviewer_notification", + "loopx.capabilities.issue_fix.pr_lifecycle", + "loopx.capabilities.native_chat.github_pr_evidence", +): + importlib.import_module(name) +from loopx.cli_commands.update_artifact import standalone_source +assert "REPOSITORY_PATTERN = " in standalone_source() +''' + checked = subprocess.run( + [core_python, "-I", "-c", script], cwd=tmp_path, + env=_environment(core_python), capture_output=True, text=True, timeout=45, + ) + assert checked.returncode == 0, (checked.stdout, checked.stderr) + + @pytest.fixture def core_python(tmp_path): value = os.environ.get("LOOPX_CORE_TEST_PYTHON") diff --git a/tests/test_core_issue_fix_distribution.py b/tests/test_core_issue_fix_distribution.py index f624d5f524..8786fd8669 100644 --- a/tests/test_core_issue_fix_distribution.py +++ b/tests/test_core_issue_fix_distribution.py @@ -22,7 +22,7 @@ def test_issue_fix_stages_the_workflow_without_wait_or_ledger_owners(tmp_path): 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"): + for name in ("catalog_entry.py", "__init__.py", "correction_settlement.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__}" @@ -70,6 +70,9 @@ def test_installed_issue_fix_is_quiet_until_selected(core_python, tmp_path): assert capability["commands"] and all( row["command"].startswith("loopx issue-fix ") for row in capability["commands"] ) + reference = json.loads(_run(core_python, ["commands", "--format", "json"], tmp_path).stdout) + commands = [entry["command"] for group in reference["groups"] for entry in group["commands"]] + assert ("loopx issue-fix" in commands) is ISSUE_FIX_ENABLED args = _guided_args(tmp_path) packet = json.loads(_run(core_python, args, tmp_path).stdout) diff --git a/tests/test_core_pr_review_distribution.py b/tests/test_core_pr_review_distribution.py index 40cd1b2085..b14f53c91c 100644 --- a/tests/test_core_pr_review_distribution.py +++ b/tests/test_core_pr_review_distribution.py @@ -18,7 +18,7 @@ def test_review_source_stages_the_existing_execution_owners(tmp_path): 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", + "order.py", "review_body.py", "scheduling.py", }) assert (review / "core.py").is_file() assert (review / "experiences/pr-5944-review-frame.md").is_file() @@ -71,6 +71,9 @@ def test_installed_core_discovers_review_without_execution_imports(core_python, capability = json.loads(discovered.stdout)["capability"] assert capability["provider_state"]["ready"] is REVIEW_ENABLED assert capability["provider_state"]["installed"] is REVIEW_ENABLED + reference = json.loads(_run(core_python, ["commands", "--format", "json"], tmp_path).stdout) + commands = [entry["command"] for group in reference["groups"] for entry in group["commands"]] + assert ("loopx pr-review --help" in commands) is REVIEW_ENABLED if not REVIEW_ENABLED: result = _run(core_python, ["pr-review", "--help"], tmp_path, expected=2) assert DISTRIBUTION in result.stderr diff --git a/tests/test_core_recall_distribution.py b/tests/test_core_recall_distribution.py index 770bed1bb3..8bf5e8ed6f 100644 --- a/tests/test_core_recall_distribution.py +++ b/tests/test_core_recall_distribution.py @@ -109,6 +109,10 @@ def test_installed_core_with_recall_wheel(core_python, task, tmp_path): 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 + reference = json.loads(_run(core_python, ["commands", "--format", "json"], workspace).stdout) + assert "loopx agent-turn-recall" in [ + entry["command"] for group in reference["groups"] for entry in group["commands"] + ] 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" diff --git a/tests/test_core_standard_distribution.py b/tests/test_core_standard_distribution.py index 198ba99688..3bff293ae8 100644 --- a/tests/test_core_standard_distribution.py +++ b/tests/test_core_standard_distribution.py @@ -88,3 +88,72 @@ def test_standard_installs_only_the_selected_capabilities_and_recovers_the_same_ 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 + + +def _command_entries(python, workspace) -> list[str]: + reference = json.loads(_run(python, ["commands", "--format", "json"], workspace).stdout) + return [entry["command"] for group in reference["groups"] for entry in group["commands"]] + + +def _installation_doctor(python, workspace, *, deep: bool = False) -> dict: + arguments = ["doctor", "--installation-only", *(["--deep"] if deep else []), "--format", "json"] + return json.loads(_run(python, arguments, workspace).stdout) + + +def test_standard_installation_distinguishes_doctor_fingerprint_and_commands( + core_python, standard_wheelhouse, tmp_path, +): + bare_doctor = _installation_doctor(core_python, tmp_path) + bare_fp = bare_doctor["service_runtime_identity"].get("package_fingerprint") + assert bare_doctor["ok"] is True + assert isinstance(bare_fp, str) and bare_fp.startswith("sha256:") + bare_commands = _command_entries(core_python, tmp_path) + assert "loopx agent-turn-recall" not in bare_commands + assert "loopx issue-fix" not in bare_commands + assert "loopx pr-review --help" not in bare_commands + + _install(core_python, standard_wheelhouse, "loopx-capability-issue-fix") + issue_fix_doctor = _installation_doctor(core_python, tmp_path) + issue_fix_fp = issue_fix_doctor["service_runtime_identity"].get("package_fingerprint") + assert issue_fix_doctor["ok"] is True + assert isinstance(issue_fix_fp, str) and issue_fix_fp.startswith("sha256:") + assert issue_fix_fp != bare_fp + issue_fix_commands = _command_entries(core_python, tmp_path) + assert "loopx issue-fix" in issue_fix_commands + assert "loopx agent-turn-recall" not in issue_fix_commands + assert "loopx pr-review --help" not in issue_fix_commands + + _install(core_python, standard_wheelhouse, "loopx-core[standard]", "--reinstall-package", "loopx-core") + standard_doctor = _installation_doctor(core_python, tmp_path) + standard_fp = standard_doctor["service_runtime_identity"].get("package_fingerprint") + assert standard_doctor["ok"] is True + assert isinstance(standard_fp, str) and standard_fp.startswith("sha256:") + assert standard_fp not in {bare_fp, issue_fix_fp} + deep_doctor = _installation_doctor(core_python, tmp_path, deep=True) + assert deep_doctor["ok"] is True + standard_commands = _command_entries(core_python, tmp_path) + assert "loopx agent-turn-recall" in standard_commands + assert "loopx issue-fix" in standard_commands + assert "loopx pr-review --help" in standard_commands + + # Tampered/unowned file under loopx/ must clear package_fingerprint even with [standard] installed. + probe = subprocess.run( + [core_python, "-I", "-c", "from pathlib import Path; import loopx; print(Path(loopx.__file__).parent)"], + cwd=tmp_path, env=_environment(core_python), capture_output=True, text=True, check=True, timeout=30, + ) + unowned = Path(probe.stdout.strip()) / "unowned_standard_probe.py" + unowned.write_text("# injected\n", encoding="utf-8") + try: + tampered_doctor = _installation_doctor(core_python, tmp_path) + assert "package_fingerprint" not in tampered_doctor["service_runtime_identity"] + finally: + unowned.unlink(missing_ok=True) + + subprocess.run(["uv", "pip", "uninstall", "--python", core_python, *STANDARD_DISTRIBUTIONS], + check=True, timeout=45) + restored_doctor = _installation_doctor(core_python, tmp_path) + assert restored_doctor["service_runtime_identity"].get("package_fingerprint") == bare_fp + restored_commands = _command_entries(core_python, tmp_path) + assert "loopx agent-turn-recall" not in restored_commands + assert "loopx issue-fix" not in restored_commands + assert "loopx pr-review --help" not in restored_commands diff --git a/tests/test_distribution_runtime_identity.py b/tests/test_distribution_runtime_identity.py index dbaee0d644..7a82739e8b 100644 --- a/tests/test_distribution_runtime_identity.py +++ b/tests/test_distribution_runtime_identity.py @@ -134,3 +134,73 @@ def test_record_root_alias_keeps_exact_physical_ownership(owned_package): name = item.as_posix() item.locate = lambda name=name: alias / name assert manifest.release_runtime_identity() == before + + +def test_core_companion_distributions_extend_and_fence_runtime_identity( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + root = tmp_path / "site-packages" + package = root / "loopx" + package.mkdir(parents=True) + files = { + "release_manifest.py": "core", + "capabilities/issue_fix/cli.py": "issue-fix", + "capabilities/pr_review_queue/core.py": "review", + } + for rel, content in files.items(): + target = package / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content) + + def _entry(rel: str): + return SimpleNamespace(as_posix=lambda rel=rel: "loopx/" + rel, + locate=lambda rel=rel: package / rel) + + dists = { + "loopx-core": SimpleNamespace( + name="loopx-core", + version=manifest.__version__, + files=[_entry("release_manifest.py")], + read_text=lambda _name: None, + ), + "loopx-capability-issue-fix": SimpleNamespace( + name="loopx-capability-issue-fix", + version=manifest.__version__, + files=[_entry("capabilities/issue_fix/cli.py")], + read_text=lambda _name: None, + ), + "loopx-capability-pull-request-review": SimpleNamespace( + name="loopx-capability-pull-request-review", + version=manifest.__version__, + files=[_entry("capabilities/pr_review_queue/core.py")], + read_text=lambda _name: None, + ), + } + + def _lookup(name: str): + if name not in dists: + raise manifest.PackageNotFoundError(name) + return dists[name] + + monkeypatch.setattr(manifest, "__file__", str(package / "release_manifest.py")) + monkeypatch.setattr(manifest, "distribution", _lookup) + monkeypatch.delenv("LOOPX_RELEASE_ROOT", raising=False) + + both_fp = manifest.release_runtime_identity()["package_fingerprint"] + assert both_fp.startswith("sha256:") + + # Mismatched companion version or overlapping RECORD entry must fail closed. + dists["loopx-capability-pull-request-review"].version = "0.0.0" + assert "package_fingerprint" not in manifest.release_runtime_identity() + + dists.pop("loopx-capability-pull-request-review") + (package / "capabilities/pr_review_queue/core.py").unlink() + single_fp = manifest.release_runtime_identity()["package_fingerprint"] + assert single_fp.startswith("sha256:") and single_fp != both_fp + + (package / "capabilities/issue_fix/cli.py").write_text("tampered") + tampered_fp = manifest.release_runtime_identity()["package_fingerprint"] + assert tampered_fp != single_fp + + dists["loopx-capability-issue-fix"].files.append(_entry("release_manifest.py")) + assert "package_fingerprint" not in manifest.release_runtime_identity()