diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index 45b07dfe7d..f0c35d4613 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -14,6 +14,8 @@ on: - "tests/test_core_issue_fix_distribution.py" - "tests/test_core_standard_distribution.py" - "tests/control_plane/test_installed_core_context.py" + - "tests/test_core_research_distribution.py" + - "tests/capabilities/test_external_evidence_cli.py" - "loopx/extensions/runtime.py" - "loopx/capabilities/decision_context/extension_provider.py" - "pyproject.toml" @@ -33,6 +35,10 @@ on: - "tests/test_core_issue_fix_distribution.py" - "tests/test_core_standard_distribution.py" - "tests/control_plane/test_installed_core_context.py" + - "tests/test_core_research_distribution.py" + - "tests/capabilities/test_external_evidence_cli.py" + - "loopx/extensions/runtime.py" + - "loopx/capabilities/decision_context/extension_provider.py" - "pyproject.toml" schedule: - cron: "47 20 * * *" @@ -125,6 +131,20 @@ jobs: LOOPX_STANDARD_TEST_WHEELHOUSE="$RUNNER_TEMP/core-dist" uv run --extra test python -m pytest -q \ tests/test_core_standard_distribution.py + - name: Qualify research availability, Explore primary workflow, ledger recovery and removal + env: + LOOPX_USAGE_PING: "0" + run: | + uv run --extra test python -m pytest -q tests/test_core_research_distribution.py + uv run --extra test python packages/loopx-core/prepare.py --distribution loopx-capability-research --output "$RUNNER_TEMP/research-source" + uv build --wheel "$RUNNER_TEMP/research-source" --out-dir "$RUNNER_TEMP/research-dist" + uv pip install --python "$LOOPX_CORE_TEST_PYTHON" "$RUNNER_TEMP"/research-dist/loopx_capability_research-*.whl + LOOPX_RESEARCH_TEST_ENABLED=1 uv run --extra test python -m pytest -q tests/test_core_research_distribution.py + LOOPX_RESEARCH_TEST_PYTHON="$LOOPX_CORE_TEST_PYTHON" uv run --extra test python -m pytest -q tests/capabilities/test_external_evidence_cli.py -k preserves_receipt_clocks_and_idempotent_ledger + uv pip uninstall --python "$LOOPX_CORE_TEST_PYTHON" loopx-capability-research + uv run --extra test python -m pytest -q tests/test_core_research_distribution.py + LOOPX_CORE_TEST_PYTHON="$LOOPX_CORE_TEST_PYTHON" uv run --extra test python -m pytest -q tests/test_core_distribution.py -k 'identity_help_and_unavailable_workspace or defers_explore_evaluation' + - name: Build the matching Workspace wheel run: | uv run --extra test python scripts/chat_bundle.py build --install diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index 41a0f37250..226749bafb 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -560,6 +560,24 @@ readback must also retain their existing distinct evidence. ### Product and benchmark execution +For standalone Core, `loopx-capability-research` takes **Explore** as its +primary optional workflow (moving heavy Explore orchestration, multi-branch/frontier +planning, harness/episode replay, source reconciliation, and the `explore` CLI +surface out of Core) together with the standalone `deepresearch` evidence ledger +and `external-evidence` commands. Core retains only Explore's canonical +result-event contract, lightweight projection, machine/goal configuration +adapters, and Goal permission and settlement validation (`loopx-core` keeps +ordinary turns lazy and independent of `loopx-capability-research`). Installing +the wheel grants no extra Goal write authority. Parent-admitted +`external-evidence` projects sanitized public-safe references into enabled same-goal +Explore nodes without automatic provider execution, and `deepresearch` citation +reports expose a one-way, idempotent, read-only export (`explore import-citations`) +so local paths, private sources, and report prose stay inside +`.loopx/deepresearch/` while standalone `deepresearch` commands continue reading +existing ledgers unchanged. The Core catalog binds `explore`, `deep-research`, +and `external-evidence-research` to `loopx-capability-research` and reports +readiness, missing-file/version diagnostics, and install hints passively. + Follow the [long-horizon research program](long-horizon-harness-benchmark-research-program-v0.md): native/plain controls, passive observation, governed execution and ablations have explicit identities. A native control receives no LoopX instructions or @@ -653,6 +671,14 @@ lease. Rollback uses the same reconciliation and retains durable state. Any later irreversible data change needs a separate migration/export gate. Rollback of these structural/composition changes requires no data migration. +For existing standalone `.loopx/deepresearch/` ledgers, active runs keep their +existing read, continuation, close, archive, and rollback semantics in +`loopx-capability-research`; open sessions can close in place or project +sanitized citation references one-way into an enabled Goal's Explore graph +without mutating `.loopx/deepresearch/`. Uninstalling +`loopx-capability-research` preserves Goal Explore logs, Goal permissions, and +standalone research ledgers so the environment can roll back to bare +`loopx-core` cleanly or resume by reinstalling the matching wheel. Default changes need explicit owner decisions and release notes; this proposal changes no current default. 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 d3ee50201a..867dfa588a 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -388,6 +388,18 @@ Operation provider 必须说明某个 effect 能否核对、能否安全重试 ### 产品与 benchmark 执行 +在独立 Core 中,`loopx-capability-research` 以 **Explore** 为主工作流(将 +Explore 重编排、多分支/前沿规划、harness 与回放运行时、来源对账及 `explore` CLI 移出 +Core),并与独立 `deepresearch` 证据账本和 `external-evidence` 取证命令一并发行。Core +仅保留 Explore 的结果事件契约、轻量投影、机器/Goal 配置适配与既有 Goal 权限和结算校验 +(裸 Core 常规 Turn 保持惰性加载、不依赖该包),且研究包不增加新的 Goal 写入权限。已获父级 +明确采纳的 `external-evidence` 可通过显式证据插件入口向已启用的同 Goal Explore 节点写入 +经净化的公共安全引用(不自动执行外部 provider);`deepresearch` 引用报告提供单向、幂等、 +只读导出(`explore import-citations`),已保存的本地路径、私有来源与报告正文留在 +`.loopx/deepresearch/` 原权限边界内,进入 Goal 图谱的内容仅限净化引用,且原账本完全不被 +反写。Core 目录将 `explore`、`deep-research` 与 `external-evidence-research` 绑定到 +`loopx-capability-research`,复用现有包归属、惰性命令发现与安装诊断接口暴露版本/缺件状态。 + 遵守 [长程研究计划](long-horizon-harness-benchmark-research-program-v0.zh-CN.md): native/plain 对照、被动观测、受治理执行与 ablation 具有明确身份。 原生对照不接受 LoopX 指令或 hook。被动观测须验证无干扰。 @@ -457,8 +469,12 @@ parsing、global options、输出、错误与 exit code 合格;不兼容版本 继续前验证新 owner 与解析后的装配;不能跨活跃 lease 热切换。回滚同样先核对并保留持久状态。 后续不可逆数据变化须另设迁移/导出门槛。 -这些结构/装配变化的回滚不需要数据迁移。默认值变化须有明确 owner 决策与 release notes; -本提案不改变现有默认值。 +这些结构/装配变化的回滚不需要数据迁移。对于已有的独立 `.loopx/deepresearch/` 账本, +未结束的研究会话可继续使用原有 `deepresearch status|add-source|resolve-question|close|report` +命令完成闭环与归档,也可按需通过只读单向导出把已授权引用投影为同 Goal Explore 的净化引用, +原账本与报告保留可读与完整回滚路径。卸载 `loopx-capability-research` 后保留 Goal +权限、Explore 事件日志与独立研究账本,可平滑回退至裸 Core,重装同版本包即可续作。 +默认值变化须有明确 owner 决策与 release notes;本提案不改变现有默认值。 ## 9. 验证与验收 diff --git a/loopx/capabilities/catalog.py b/loopx/capabilities/catalog.py index 998246926e..2824da9e2e 100644 --- a/loopx/capabilities/catalog.py +++ b/loopx/capabilities/catalog.py @@ -6,6 +6,7 @@ from typing import Any from ..extensions.runtime import extension_catalog_entries +from ..python_install_owner import RESEARCH_DISTRIBUTION from .benchmark_toolkit.catalog_entry import BENCHMARK_TOOLKIT_CATALOG_ENTRY from .integration_branch.catalog_entry import INTEGRATION_BRANCH_CATALOG_ENTRY from .repository_change_window.catalog_entry import ( @@ -31,7 +32,11 @@ from .content_ops.catalog_entry import CONTENT_OPS_CATALOG_ENTRY from .value_connectors.catalog_entry import VALUE_CONNECTORS_CATALOG_ENTRY from .explore.catalog_entry import EXPLORE_CATALOG_ENTRY -from .deep_research.catalog_entry import DEEP_RESEARCH_CATALOG_ENTRY +from .deep_research.catalog_entry import ( + DEEP_RESEARCH_CATALOG_ENTRY, + RESEARCH_INSTALL_HINT, + inspect_research_workflow_distribution, +) from .public_safe_outbound.catalog_entry import PUBLIC_SAFE_OUTBOUND_CATALOG_ENTRY from .connector_registry.catalog_entry import CONNECTOR_REGISTRY_CATALOG_ENTRY from .external_research.catalog_entry import EXTERNAL_RESEARCH_CATALOG_ENTRY @@ -190,10 +195,46 @@ def build_capability_registry( } ) builtin_cli_present = find_spec("loopx.cli") is not None + research_state = ( + inspect_research_workflow_distribution(builtin_cli_present=False) + if not builtin_cli_present + else None + ) + research_ready = bool(research_state and research_state["ready"]) + if not builtin_cli_present and research_state is not None: + optional_fields = { + key: value + for key, value in ( + ("version", research_state["version"]), + ("core_version", research_state["core_version"]), + ("unavailable_reason", research_state["reason"]), + ) + if value is not None + } + registry.register_provider( + { + "id": RESEARCH_DISTRIBUTION, + "origin": "builtin", + "installed": bool(research_state["installed"]), + "enabled": bool(research_state["installed"]), + "ready": research_ready, + **optional_fields, + } + ) for record in BUILTIN_CAPABILITIES: - registry.register_capability(_record_for_installed_capability( - registry, record, builtin_cli_present=builtin_cli_present, - )) + if not builtin_cli_present and ( + record is EXPLORE_CATALOG_ENTRY + or record is DEEP_RESEARCH_CATALOG_ENTRY + or record is EXTERNAL_RESEARCH_CATALOG_ENTRY + ): + adapted = dict(record) | {"provider_id": RESEARCH_DISTRIBUTION} + if not research_ready: + adapted["next_real_step"] = RESEARCH_INSTALL_HINT + registry.register_capability(adapted) + else: + 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/deep_research/catalog_entry.py b/loopx/capabilities/deep_research/catalog_entry.py index f4908a90d3..7be3b3fcbb 100644 --- a/loopx/capabilities/deep_research/catalog_entry.py +++ b/loopx/capabilities/deep_research/catalog_entry.py @@ -2,6 +2,66 @@ from typing import Any +from ...python_install_owner import ( + RESEARCH_DISTRIBUTION, + inspect_builtin_capability_distribution, +) + + +RESEARCH_INSTALL_HINT = ( + "Install the matching loopx-capability-research wheel into this Core environment " + "for Explore orchestration, evidence ledgers, and external evidence workflows." +) +RESEARCH_MODULES = ( + "loopx.cli_commands.explore", + "loopx.cli_commands.explore_planning_commands", + "loopx.cli_commands.explore_feishu_commands", + "loopx.capabilities.explore.adaptive_replay_planner", + "loopx.capabilities.explore.child_replay_runtime", + "loopx.capabilities.explore.counterfactual_runtime", + "loopx.capabilities.explore.episode_runtime", + "loopx.capabilities.explore.harness_checkpoint", + "loopx.capabilities.explore.harness_frontier", + "loopx.capabilities.explore.harness_queue", + "loopx.capabilities.explore.harness_runtime", + "loopx.capabilities.explore.replay_metrics", + "loopx.capabilities.explore.replay_runtime", + "loopx.capabilities.explore.research_bridge", + "loopx.capabilities.explore.research_snapshot_host", + "loopx.capabilities.explore.resource_portfolio", + "loopx.capabilities.explore.router_state", + "loopx.capabilities.explore.source_history_reconcile", + "loopx.capabilities.explore.speculative_scheduler", + "loopx.capabilities.explore.todo_branch_plan", + "loopx.capabilities.explore.todo_evidence", + "loopx.capabilities.explore.trace_runtime", + "loopx.capabilities.explore.worker_branch_plan", + "loopx.capabilities.deep_research.runtime", + "loopx.capabilities.external_research.cli", + "loopx.capabilities.external_research.projection", + "loopx.capabilities.external_research.provider_probe", + "loopx.cli_commands.deepresearch", + "loopx.extensions.public_github_research", +) +RESEARCH_RESOURCES = ("loopx/control_plane/capabilities/external_evidence.ts",) + + +def inspect_research_workflow_distribution( + *, builtin_cli_present: bool | None = None, +) -> dict[str, Any]: + return inspect_builtin_capability_distribution( + RESEARCH_DISTRIBUTION, + RESEARCH_MODULES, + builtin_cli_present=builtin_cli_present, + resources=RESEARCH_RESOURCES, + ) + + +def research_workflows_installed(*, builtin_cli_present: bool | None = None) -> bool: + return bool( + inspect_research_workflow_distribution(builtin_cli_present=builtin_cli_present)["ready"] + ) + DEEP_RESEARCH_CATALOG_ENTRY: dict[str, Any] = { "id": "deep-research", diff --git a/loopx/capabilities/explore/catalog_entry.py b/loopx/capabilities/explore/catalog_entry.py index d05748dcc2..723f814843 100644 --- a/loopx/capabilities/explore/catalog_entry.py +++ b/loopx/capabilities/explore/catalog_entry.py @@ -44,6 +44,16 @@ "purpose": "Fold canonical result events into the bounded operator projection.", "write_boundary": "read-only projection over the goal result log", }, + { + "command": "loopx explore observe-external --goal-id --node --plan-json --receipt-json --admission-json --format json", + "purpose": "Preview or record sanitized external-evidence admissions onto an existing same-goal Explore node without auto-executing providers.", + "write_boundary": "read-only preview unless --execute; writes sanitized refs to the goal result log only", + }, + { + "command": "loopx explore import-citations --goal-id --node --project --format json", + "purpose": "Preview or export sanitized references from authorized answered deepresearch citations without mutating the source ledger.", + "write_boundary": "read-only deepresearch read; writes sanitized citation refs to the goal result log only when --execute is set", + }, ], "implemented_protocols": [ { diff --git a/loopx/capabilities/explore/research_bridge.py b/loopx/capabilities/explore/research_bridge.py new file mode 100644 index 0000000000..d42851cdd5 --- /dev/null +++ b/loopx/capabilities/explore/research_bridge.py @@ -0,0 +1,503 @@ +"""One-way public-safe Explore bridges for Research companion workflows. + +External-evidence projection requires an explicit parent admission and a +registered Goal whose Explore boundary is already enabled; it never auto-executes +external providers or grants new Goal write authority. Deepresearch export +reads `.loopx/deepresearch/research.json` read-only, exports only sanitized +evidence references from authorized answered claims without unresolved +contradictions, and never mutates the standalone research ledger. +""" +from __future__ import annotations + +from collections.abc import Mapping, Sequence +import hashlib +import re +import json +from pathlib import Path +from typing import Any + +from ...agent_registry import require_registered_agent_id +from ...control_plane.projects.registry_codec import load_registry +from ...control_plane.runtime.public_safety import validate_public_safe_value +from ...explore_graph import compact_explore_graph_policy +from ...file_lock import exclusive_file_lock +from ...materials import find_registry_goal +from ...public_safe_text import ( + CATEGORY_CREDENTIAL, + CATEGORY_LOCAL_PATH, + CATEGORY_ORG_MARKER, + PUBLIC_SAFE_LOCAL_PATH_PATTERNS, + classify_private_text, + find_public_safe_local_path, +) +from ..deep_research.runtime import load_state, state_path as deepresearch_state_path +from ..external_research.projection import _validate_admission, validate_receipt +from .machine_defaults import resolve_explore_goal +from .result_log import ( + FORBIDDEN_TEXT_MARKERS, + SUMMARY_LIMIT, + TITLE_LIMIT, + build_explore_finding_event, + build_explore_result_projection, + explore_result_log_path, + load_explore_result_events_strict, + validate_explore_public_ref, + validate_explore_result_event, + validate_explore_result_event_attribution, +) + + +BRIDGE_SCHEMA_VERSION = "loopx_explore_research_bridge_v0" +_CREDENTIAL_MARKERS = tuple( + marker.lower() + for marker in FORBIDDEN_TEXT_MARKERS + if any(word in marker.lower() for word in ("auth", "api", "pass", "sec", "tok")) +) +_LOCAL_PATH_TOKEN_PATTERN = re.compile( + r"(?:file://[^\s,;\"'<>]+|~/[^\s,;\"'<>]+|[A-Za-z]:[\\/][^\s,;\"'<>]+|" + r"(?:/Users/|/home/|/root/|/private/)[^\s,;\"'<>]+|" + r"(?:\\Users\\|\\home\\|\\root\\|\\private\\)[^\s,;\"'<>]+|" + r"\.local[/\\]private[^\s,;\"'<>]*)", + re.IGNORECASE, +) + + +def _short_digest(*parts: str) -> str: + payload = "\0".join(parts).encode("utf-8") + return hashlib.sha256(payload).hexdigest()[:12] + + +def _digest_token(value: str) -> str: + clean = str(value or "").strip() + if clean.startswith("sha256:"): + clean = clean[len("sha256:") :] + safe = re.sub(r"[^A-Za-z0-9_.-]+", "", clean) + return safe[:16] if safe else _short_digest(clean) + + +_SECRET_CATEGORIES = frozenset({CATEGORY_CREDENTIAL, CATEGORY_ORG_MARKER}) +_LOCAL_PATH_CATEGORIES = frozenset({CATEGORY_LOCAL_PATH}) + + +def _require_no_secrets(value: str, *, field: str) -> None: + match = classify_private_text( + value, + categories=_SECRET_CATEGORIES, + include_compound_field_assignment=True, + ) + if match is not None: + raise ValueError(f"{field} rejected: {match.reason}") + lowered = value.lower() + if any(marker in lowered for marker in _CREDENTIAL_MARKERS): + raise ValueError(f"{field} rejected: contains credential-like marker") + + +def _sanitize_public_text(value: Any, *, field: str, limit: int) -> tuple[str, bool]: + text = " ".join(str(value or "").split()) + if not text: + return "", False + _require_no_secrets(text, field=field) + scrubbed = _LOCAL_PATH_TOKEN_PATTERN.sub("[redacted-local-path]", text) + for pattern in PUBLIC_SAFE_LOCAL_PATH_PATTERNS: + if classify_private_text( + scrubbed, categories=_LOCAL_PATH_CATEGORIES, include_path_gaps=True, + ): + scrubbed = pattern.sub("[redacted-local-path]", scrubbed) + changed = scrubbed != text + if find_public_safe_local_path(scrubbed) is not None or classify_private_text( + scrubbed, categories=_LOCAL_PATH_CATEGORIES, include_path_gaps=True, + ) is not None: + scrubbed = "[redacted-local-evidence]" + changed = True + validate_public_safe_value(scrubbed, path=field) + if len(scrubbed) > limit: + scrubbed = scrubbed[: max(0, limit - 1)].rstrip() + "..." + return scrubbed, changed + + +def _is_public_http_ref(value: str) -> bool: + clean = str(value or "").strip() + if not clean.lower().startswith(("http://", "https://")): + return False + if find_public_safe_local_path(clean) is not None: + return False + if classify_private_text( + clean, + categories=_SECRET_CATEGORIES, + include_compound_field_assignment=True, + ) is not None: + return False + try: + validate_explore_public_ref(clean, field="source_ref") + except ValueError: + return False + return True + + +def _check_goal_match( + goal_id: str, + expected_goal_id: str | None, + *containers: Mapping[str, Any] | None, + label: str, +) -> None: + if expected_goal_id is not None and str(expected_goal_id).strip() != goal_id: + raise ValueError(f"{label} belongs to a different goal ({expected_goal_id!r} != {goal_id!r})") + for container in containers: + if not isinstance(container, Mapping): + continue + bound = container.get("goal_id") + if bound is not None and str(bound).strip() and str(bound).strip() != goal_id: + raise ValueError(f"{label} belongs to a different goal ({bound!r} != {goal_id!r})") + + +def _require_enabled_explore_goal( + *, + registry_path: Path, + runtime_root: Path, + goal_id: str, + agent_id: str | None, +) -> None: + goal = find_registry_goal(load_registry(registry_path), goal_id) + if goal is None: + raise ValueError(f"Goal {goal_id!r} is not registered") + effective = resolve_explore_goal(goal, runtime_root) + policy = compact_explore_graph_policy( + effective.get("explore_graph"), + (effective.get("spawn_policy") or {}).get("explore_harness"), + ) + if not policy["enabled"]: + raise ValueError(f"Explore must be enabled on Goal {goal_id!r} before writing evidence") + if agent_id is not None: + require_registered_agent_id(registry_path=registry_path, goal_id=goal_id, agent_id=agent_id) + + +def _finding_signature(event: Mapping[str, Any]) -> dict[str, Any]: + return { + "goal_id": event.get("goal_id"), + "event_kind": event.get("event_kind"), + "result_id": event.get("result_id"), + "node_id": event.get("node_id"), + "title": event.get("title"), + "status": event.get("status"), + "summary": event.get("summary"), + "agent_id": event.get("agent_id"), + "evidence_refs": list(event.get("evidence_refs") or []), + "tags": list(event.get("tags") or []), + } + + +def _append_sanitized_findings( + *, + runtime_root: Path, + goal_id: str, + node_id: str, + agent_id: str | None, + candidates: Sequence[Mapping[str, Any]], + execute: bool, + extra: Mapping[str, Any], +) -> dict[str, Any]: + log_path = explore_result_log_path(runtime_root, goal_id) + if execute: + log_path.parent.mkdir(parents=True, exist_ok=True) + with exclusive_file_lock(log_path, operation="explore-research-bridge"): + events = load_explore_result_events_strict(log_path, goal_id=goal_id) + projection = build_explore_result_projection(events, goal_id=goal_id) + if not any(row["node_id"] == node_id for row in projection["nodes"]): + raise ValueError(f"node_id {node_id!r} must reference an existing node in Goal {goal_id!r}") + existing_findings = { + str(event["result_id"]): event + for event in events + if event.get("event_kind") == "finding" + } + to_append: list[dict[str, Any]] = [] + replayed_ids: list[str] = [] + all_ids: list[str] = [] + for spec in candidates: + event = build_explore_finding_event( + goal_id=goal_id, + finding_id=str(spec["finding_id"]), + node_id=node_id, + title=str(spec["title"]), + status=str(spec.get("status") or "confirmed"), + summary=str(spec["summary"]), + agent_id=agent_id, + evidence_refs=list(spec["evidence_refs"]), + tags=list(spec["tags"]), + ) + validate_public_safe_value( + {k: v for k, v in event.items() if k != "boundary"}, + path="explore_finding", + ) + finding_id = str(event["result_id"]) + all_ids.append(finding_id) + prior = existing_findings.get(finding_id) + if prior is not None: + if _finding_signature(prior) != _finding_signature(event): + raise ValueError(f"conflicting replay for Explore finding {finding_id!r}") + replayed_ids.append(finding_id) + else: + to_append.append(event) + + if execute and to_append: + validated = [ + validate_explore_result_event(item, expected_goal_id=goal_id) + for item in to_append + ] + for item in validated: + validate_explore_result_event_attribution(item) + log_path.parent.mkdir(parents=True, exist_ok=True) + with log_path.open("a", encoding="utf-8") as handle: + handle.write( + "".join(json.dumps(item, ensure_ascii=False, sort_keys=True) + "\n" for item in validated) + ) + return { + "ok": True, + "schema_version": BRIDGE_SCHEMA_VERSION, + "goal_id": goal_id, + "node_id": node_id, + "dry_run": not execute, + "written": bool(execute and to_append), + "replayed": bool(execute and replayed_ids and not to_append), + "appended_count": len(to_append) if execute else 0, + "would_append_count": len(to_append) if not execute else 0, + "replayed_count": len(replayed_ids), + "finding_ids": all_ids, + "sanitized": True, + "log_path": str(log_path), + **extra, + } + + +def project_external_evidence_to_explore( + *, + registry_path: Path, + runtime_root: Path, + goal_id: str, + node_id: str, + plan: Mapping[str, Any], + receipt: Mapping[str, Any], + admission: Mapping[str, Any], + agent_id: str | None = None, + expected_goal_id: str | None = None, + execute: bool = False, +) -> dict[str, Any]: + """Project parent-admitted external evidence into an enabled Explore graph. + + This helper performs no external network or provider execution: callers must + pass an explicit plan, receipt, and parent admission. Unadmitted dispositions, + cross-goal payloads, and credentials fail closed; local file paths in raw + source locators or findings are redacted before reaching the Goal log. + """ + _check_goal_match( + goal_id, + expected_goal_id, + plan, + plan.get("request") if isinstance(plan, Mapping) else None, + admission, + label="external evidence", + ) + _require_enabled_explore_goal( + registry_path=registry_path, runtime_root=runtime_root, goal_id=goal_id, agent_id=agent_id, + ) + observation = validate_receipt(dict(plan), dict(receipt)) + validated_receipt = observation["receipt"] + normalized = _validate_admission(dict(plan), dict(validated_receipt), dict(admission)) + if normalized["disposition"] != "admit": + raise ValueError("Explore projection requires an explicit parent disposition of 'admit'") + + admitted_sources = normalized["downstream_projection"]["sources"] + if not admitted_sources: + raise ValueError("external evidence admission has no admitted sources to project") + + admission_token = _digest_token(normalized["admission_id"]) + redacted_source_count = 0 + candidates: list[dict[str, Any]] = [] + for source in admitted_sources: + raw_ref = str(source.get("source_ref") or "").strip() + _require_no_secrets(raw_ref, field="external_evidence.source_ref") + content_token = _digest_token(str(source.get("content_digest") or "")) + opaque_ref = f"external-evidence:{admission_token}:{content_token}" + evidence_refs = [opaque_ref] + if _is_public_http_ref(raw_ref): + evidence_refs.append(raw_ref) + else: + redacted_source_count += 1 + + safe_finding, finding_redacted = _sanitize_public_text( + source.get("finding"), field="external_evidence.finding", limit=TITLE_LIMIT, + ) + if finding_redacted: + redacted_source_count += 1 + title = safe_finding or f"Admitted external evidence {opaque_ref}" + summary_parts = [ + "origin=external-evidence", + f"admission={normalized['admission_id']}", + f"provider={validated_receipt['provider_id']}", + f"digest={source['content_digest']}", + ] + if source.get("accessed_at"): + summary_parts.append(f"accessed_at={source['accessed_at']}") + summary, _ = _sanitize_public_text( + "; ".join(summary_parts), field="external_evidence.summary", limit=SUMMARY_LIMIT, + ) + finding_id = f"ext_{_short_digest(normalized['admission_id'], str(source['content_digest']), node_id)}" + candidates.append( + { + "finding_id": finding_id, + "title": title, + "summary": summary, + "status": "confirmed", + "evidence_refs": evidence_refs, + "tags": ["external-evidence", "sanitized-ref"], + } + ) + + return _append_sanitized_findings( + runtime_root=runtime_root, + goal_id=goal_id, + node_id=node_id, + agent_id=agent_id, + candidates=candidates, + execute=execute, + extra={ + "operation": "observe-external", + "plan_id": normalized["plan_id"], + "admission_id": normalized["admission_id"], + "provider_id": validated_receipt["provider_id"], + "redacted_source_count": redacted_source_count, + "automatic_execution": False, + }, + ) + + +def export_deepresearch_citations_to_explore( + *, + project: Path, + registry_path: Path, + runtime_root: Path, + goal_id: str, + node_id: str, + agent_id: str | None = None, + expected_goal_id: str | None = None, + claim_ids: Sequence[str] | None = None, + execute: bool = False, +) -> dict[str, Any]: + """One-way read-only export of authorized deepresearch citations to Explore. + + Reads `.loopx/deepresearch/research.json` without writing or locking it for + mutation. Only claims cited by answered questions without open + contradictions are eligible. Saved local paths, private source locators, + and report body prose stay in the deepresearch boundary; Explore receives + only sanitized citation references and compact metadata. + """ + state_file = deepresearch_state_path(project) + state = load_state(project) + if state is None: + raise ValueError("no deepresearch ledger exists in this project to export") + before_bytes = state_file.read_bytes() + _check_goal_match(goal_id, expected_goal_id, state, label="deepresearch ledger") + _require_enabled_explore_goal( + registry_path=registry_path, runtime_root=runtime_root, goal_id=goal_id, agent_id=agent_id, + ) + + contradicted_claims = { + str(claim_id) + for contradiction in state.get("contradictions") or [] + if contradiction.get("status") != "resolved" + for claim_id in (contradiction.get("claim_a"), contradiction.get("claim_b")) + if claim_id + } + claim_to_questions: dict[str, list[str]] = {} + for question in state.get("questions") or []: + if question.get("status") != "answered": + continue + qid = str(question.get("id") or "") + for cid in question.get("evidence_claims") or []: + claim_to_questions.setdefault(str(cid), []).append(qid) + + claims_by_id = { + str(claim["id"]): claim + for claim in state.get("claims") or [] + if claim.get("id") + } + sources_by_id = { + str(source["id"]): source + for source in state.get("sources") or [] + if source.get("id") + } + + if claim_ids: + selected_ids = [str(cid).strip() for cid in claim_ids if str(cid).strip()] + for cid in selected_ids: + if cid not in claims_by_id: + raise ValueError(f"deepresearch claim {cid!r} does not exist") + if cid not in claim_to_questions: + raise ValueError(f"claim {cid!r} is not cited by an answered deepresearch question") + if cid in contradicted_claims: + raise ValueError(f"claim {cid!r} has an unresolved contradiction") + else: + selected_ids = [ + cid for cid in claims_by_id + if cid in claim_to_questions and cid not in contradicted_claims + ] + if not selected_ids: + raise ValueError("deepresearch ledger has no authorized resolved citations to export") + + redacted_source_count = 0 + candidates: list[dict[str, Any]] = [] + exported_refs: list[dict[str, Any]] = [] + for cid in selected_ids: + claim = claims_by_id[cid] + source_id = str(claim.get("source_id") or "") + source = sources_by_id.get(source_id) or {} + raw_locator = str(source.get("url_or_path") or "") + _require_no_secrets(raw_locator, field=f"deepresearch.source.{source_id}.url_or_path") + _require_no_secrets(str(claim.get("text") or ""), field=f"deepresearch.claim.{cid}.text") + if not _is_public_http_ref(raw_locator): + redacted_source_count += 1 + elif find_public_safe_local_path(raw_locator) is None: + # Keep even private-ledger source locators redacted on one-way citation export + # so raw source URLs/paths stay under the original session ledger boundary. + redacted_source_count += 1 + + claim_digest = _short_digest(cid, str(claim.get("text") or ""), source_id) + locator_digest = _short_digest(source_id, raw_locator) + claim_ref = f"deepresearch:claim:{cid}:{claim_digest}" + source_ref = f"deepresearch:source:{source_id}:{locator_digest}" + question_ids = ",".join(sorted(claim_to_questions[cid])) + tool_name = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(source.get("tool") or "unspecified"))[:40] + stance = re.sub(r"[^A-Za-z0-9_-]+", "", str(claim.get("stance") or "neutral"))[:24] + title = f"Authorized citation {cid} ({stance}) for {question_ids}" + summary = ( + f"origin=deepresearch; ledger_readonly_export=true; tool={tool_name}; " + f"claim_ref={claim_ref}; source_ref={source_ref}" + ) + finding_id = f"dr_cite_{cid}_{_short_digest(goal_id, node_id, claim_digest, locator_digest)}" + candidates.append( + { + "finding_id": finding_id, + "title": title, + "summary": summary, + "status": "confirmed", + "evidence_refs": [claim_ref, source_ref], + "tags": ["deepresearch-citation", "read-only-export"], + } + ) + exported_refs.append({"claim_id": cid, "source_id": source_id, "evidence_refs": [claim_ref, source_ref]}) + + result = _append_sanitized_findings( + runtime_root=runtime_root, + goal_id=goal_id, + node_id=node_id, + agent_id=agent_id, + candidates=candidates, + execute=execute, + extra={ + "operation": "import-citations", + "project": str(project), + "exported_citations": exported_refs, + "redacted_source_count": redacted_source_count, + "deepresearch_ledger_mutated": state_file.read_bytes() != before_bytes, + }, + ) + return result diff --git a/loopx/capabilities/explore/turn_context.py b/loopx/capabilities/explore/turn_context.py index b5c9311485..043213d205 100644 --- a/loopx/capabilities/explore/turn_context.py +++ b/loopx/capabilities/explore/turn_context.py @@ -119,7 +119,8 @@ def explore_turn_context( ) from ..todo_replan_cadence.machine_defaults import work_yardstick_enabled yardstick = work_yardstick_enabled(goal, runtime_root) - projection, plan, focus, todos = {}, {}, {}, {} + projection, focus, todos = {}, {}, {} + plan: Mapping[str, object] = {} page_tasks = {row["todo_id"] for row in review_pages if isinstance(row, Mapping) and isinstance(row.get("todo_id"), str)} if isinstance(review_pages, list) else set() if graph or gate["enabled"]: @@ -146,16 +147,19 @@ def explore_turn_context( include_acceptance=False, ) if gate["enabled"]: - from .todo_branch_plan import build_explore_todo_branch_plan - - plan = build_explore_todo_branch_plan( - goal_id=goal_id, - agent_id=agent_id, - todos=todos.get("todos") or [], - projection=projection, - orchestration=goal.get("spawn_policy"), - width=3, - ) + try: + from .todo_branch_plan import build_explore_todo_branch_plan + except ModuleNotFoundError: + plan = {} + else: + plan = build_explore_todo_branch_plan( + goal_id=goal_id, + agent_id=agent_id, + todos=todos.get("todos") or [], + projection=projection, + orchestration=goal.get("spawn_policy"), + width=3, + ) # Transport only the existing identity/link fields consumed by the typed # reader, not task descriptions, notes or unrelated acceptance material. scopes = {row["todo_id"]: {key: row[key] for key in ( diff --git a/loopx/capabilities/external_research/cli.py b/loopx/capabilities/external_research/cli.py index 9116610ecb..f9f41dd6ed 100644 --- a/loopx/capabilities/external_research/cli.py +++ b/loopx/capabilities/external_research/cli.py @@ -194,7 +194,11 @@ def register_external_evidence_commands( project.add_argument("--receipt-json", required=True, metavar="FILE", help="Path to a receipt JSON object.") project.add_argument("--admission-json", metavar="FILE", help="Path to a saved admission JSON object.") project.add_argument("--project", help="Existing deepresearch project; no implicit run is created.") - project.add_argument("--execute", action="store_true", help="Write explicitly admitted sources to the existing ledger.") + project.add_argument("--goal-id", help="Optional target enabled Explore Goal id for sanitized bridge projection.") + project.add_argument("--explore-node", help="Target node id in the Explore Goal when projecting with --goal-id.") + project.add_argument("--agent-id", help="Optional registered agent id for Explore bridge projection.") + project.add_argument("--expected-goal-id", help="Optional expected source Goal id; fails closed on mismatch.") + project.add_argument("--execute", action="store_true", help="Write explicitly admitted sources to the existing ledger or sanitized Explore findings.") add_subcommand_format(project) receipt = actions.add_parser( @@ -228,6 +232,7 @@ def handle_external_evidence_command( *, output_format: FormatSelector, print_payload: PrintPayload, + registry_path: Path | None = None, ) -> int | None: if args.command != "external-evidence": return None @@ -335,10 +340,62 @@ def handle_external_evidence_command( payload = execute_public_github(plan) payload["observation"] = validate_receipt(plan, payload["receipt"]) elif args.external_evidence_action == "readback": - payload = readback(_load_object(args.plan_json, label="external evidence plan"), - _load_receipt(args.receipt_json), - _load_object(args.admission_json, label="external evidence admission") if args.admission_json else None, - project=Path(args.project).expanduser() if args.project else None, execute=args.execute) + plan_obj = _load_object(args.plan_json, label="external evidence plan") + receipt_obj = _load_receipt(args.receipt_json) + admission_obj = ( + _load_object(args.admission_json, label="external evidence admission") + if args.admission_json + else None + ) + goal_target = getattr(args, "goal_id", None) + explore_node = getattr(args, "explore_node", None) + if goal_target or explore_node: + if not (goal_target and explore_node): + raise ValueError("Explore readback projection requires both --goal-id and --explore-node") + if admission_obj is None: + raise ValueError("Explore readback projection requires --admission-json") + from ...paths import default_registry_path, resolve_runtime_root + from ...control_plane.projects.registry_codec import load_registry + from ..explore.research_bridge import project_external_evidence_to_explore + + reg_arg = getattr(args, "registry", None) + reg_path = ( + registry_path + if registry_path is not None + else (Path(reg_arg).expanduser() if reg_arg else default_registry_path()) + ) + rt_root = resolve_runtime_root( + load_registry(reg_path) if reg_path.exists() else {}, + getattr(args, "runtime_root", None), + ) + explore_result = project_external_evidence_to_explore( + registry_path=reg_path, + runtime_root=rt_root, + goal_id=goal_target, + node_id=explore_node, + plan=plan_obj, + receipt=receipt_obj, + admission=admission_obj, + agent_id=getattr(args, "agent_id", None), + expected_goal_id=getattr(args, "expected_goal_id", None), + execute=bool(args.execute), + ) + payload = readback( + plan_obj, + receipt_obj, + admission_obj, + project=Path(args.project).expanduser() if args.project else None, + execute=False, + ) + payload["explore_projection"] = explore_result + else: + payload = readback( + plan_obj, + receipt_obj, + admission_obj, + project=Path(args.project).expanduser() if args.project else None, + execute=args.execute, + ) elif args.external_evidence_action == "receipt": payload = effect_runtime_result( "external_evidence.receipt", diff --git a/loopx/cli.py b/loopx/cli.py index 0f014c22f5..dcd69760ee 100644 --- a/loopx/cli.py +++ b/loopx/cli.py @@ -656,6 +656,7 @@ def _decision_context_runtime_root() -> Path | None: external_evidence_result = handle_external_evidence_command( args, output_format=output_format, print_payload=print_payload, + registry_path=registry_path, ) if external_evidence_result is not None: return external_evidence_result diff --git a/loopx/cli_commands/explore.py b/loopx/cli_commands/explore.py index 6006272ed3..43c8f08bf9 100644 --- a/loopx/cli_commands/explore.py +++ b/loopx/cli_commands/explore.py @@ -130,6 +130,33 @@ def register_explore_commands( observe.add_argument("--observation-json", required=True, help="File containing a typed_research_observation_v0 envelope.") observe.add_argument("--agent-id") + observe_external = sub.add_parser( + "observe-external", + help="Project explicitly parent-admitted external evidence onto an existing same-goal Explore node; never executes providers automatically.", + ) + add_subcommand_format(observe_external) + observe_external.add_argument("--goal-id", required=True) + observe_external.add_argument("--node", dest="node_id", required=True, help="Existing target node id inside the same Goal.") + observe_external.add_argument("--plan-json", required=True, metavar="FILE") + observe_external.add_argument("--receipt-json", required=True, metavar="FILE") + observe_external.add_argument("--admission-json", required=True, metavar="FILE") + observe_external.add_argument("--expected-goal-id", help="Optional expected source Goal id; fails closed on mismatch.") + observe_external.add_argument("--agent-id") + observe_external.add_argument("--execute", action="store_true", help="Write sanitized findings to the Goal Explore log (dry-run by default).") + + import_citations = sub.add_parser( + "import-citations", + help="One-way read-only export of authorized answered citations from a deepresearch ledger into an enabled Goal Explore node.", + ) + add_subcommand_format(import_citations) + import_citations.add_argument("--goal-id", required=True) + import_citations.add_argument("--node", dest="node_id", required=True, help="Existing target node id inside the same Goal.") + import_citations.add_argument("--project", required=True, help="Project directory holding .loopx/deepresearch/.") + import_citations.add_argument("--claim-id", dest="claim_ids", action="append", default=[], help="Optional authorized claim id to export; repeatable.") + import_citations.add_argument("--expected-goal-id", help="Optional expected source Goal id; fails closed on mismatch.") + import_citations.add_argument("--agent-id") + import_citations.add_argument("--execute", action="store_true", help="Write sanitized citation refs to the Goal Explore log (dry-run by default).") + presentation = sub.add_parser( "presentation", help="Assess readability and derive same-source canonical/executive views.", @@ -610,6 +637,41 @@ def handle_explore_command( registry_path=source_registry, runtime_root=runtime_root, ) + elif args.explore_command == "observe-external": + from ..capabilities.explore.research_bridge import project_external_evidence_to_explore + + plan = json.loads(Path(args.plan_json).expanduser().read_text(encoding="utf-8")) + receipt_raw = json.loads(Path(args.receipt_json).expanduser().read_text(encoding="utf-8")) + receipt = receipt_raw.get("receipt", receipt_raw) if isinstance(receipt_raw, dict) else receipt_raw + admission = json.loads(Path(args.admission_json).expanduser().read_text(encoding="utf-8")) + if not all(isinstance(item, dict) for item in (plan, receipt, admission)): + raise ValueError("plan, receipt, and admission must be JSON objects") + payload = project_external_evidence_to_explore( + registry_path=source_registry, + runtime_root=runtime_root, + goal_id=args.goal_id, + node_id=args.node_id, + plan=plan, + receipt=receipt, + admission=admission, + agent_id=args.agent_id, + expected_goal_id=args.expected_goal_id, + execute=bool(args.execute), + ) + elif args.explore_command == "import-citations": + from ..capabilities.explore.research_bridge import export_deepresearch_citations_to_explore + + payload = export_deepresearch_citations_to_explore( + project=Path(args.project).expanduser(), + registry_path=source_registry, + runtime_root=runtime_root, + goal_id=args.goal_id, + node_id=args.node_id, + agent_id=args.agent_id, + expected_goal_id=args.expected_goal_id, + claim_ids=args.claim_ids or None, + execute=bool(args.execute), + ) elif args.explore_command == "summary": payload = projection_for(args, runtime_root=runtime_root) elif args.explore_command == "presentation": diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index a3b736cca3..9f2af735ff 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -78,8 +78,8 @@ "workbench", "history", } -# Fast-dispatched in ordinary installs; excluded from standalone Core support/commands. -_FULL_INSTALL_SELECTED_COMMANDS = frozenset({"explore"}) +# Retired from Core-only suppression once Explore CLI ships via RESEARCH_DISTRIBUTION. +_FULL_INSTALL_SELECTED_COMMANDS: frozenset[str] = frozenset() # Existing CLI vocabulary; this set chooses loading, not operation authority. _CAPABILITY_DISCOVERY_COMMANDS = frozenset({"list", "show"}) _WORKSPACE_COMMANDS = frozenset({"chat", "chat-endpoint", "dashboard"}) @@ -1028,6 +1028,17 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: registry_was_supplied=user_supplied_registry(raw_argv), print_payload=print_payload, output_format=output_format, ) + elif args.command == "deepresearch": + from .cli_commands.deepresearch import handle_deepresearch_command + + result = handle_deepresearch_command(args, output_format=output_format, print_payload=print_payload) + elif args.command == "external-evidence": + from .capabilities.external_research.cli import handle_external_evidence_command + + result = handle_external_evidence_command( + args, output_format=output_format, print_payload=print_payload, + registry_path=registry_path, + ) else: result = dispatch_common_command( args, @@ -1042,6 +1053,7 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: def _available_selected_commands() -> frozenset[str]: from .capabilities.agent_turn_recall.catalog_entry import agent_turn_recall_installed + from .capabilities.deep_research.catalog_entry import research_workflows_installed from .capabilities.issue_fix.catalog_entry import issue_fix_workflow_installed from .capabilities.pr_review_queue.catalog_entry import pull_request_review_installed @@ -1052,6 +1064,8 @@ def _available_selected_commands() -> frozenset[str]: commands.add("pr-review") if issue_fix_workflow_installed(builtin_cli_present=False): commands.add("issue-fix") + if research_workflows_installed(builtin_cli_present=False): + commands.update(("explore", "deepresearch", "external-evidence")) return frozenset(commands) @@ -1185,6 +1199,25 @@ def _run_command(command: str | None, raw_argv: list[str]) -> int: register(subparsers, add_subcommand_format) return _dispatch_selected(parse_cli_args(parser, raw_argv), raw_argv) + if command in {"explore", "deepresearch", "external-evidence"} and _standalone_core(): + from .capabilities.deep_research.catalog_entry import RESEARCH_INSTALL_HINT, research_workflows_installed + + parser, subparsers = build_cli_parser() + if not research_workflows_installed(builtin_cli_present=False): + parser.error(f"{command} is unavailable in the standalone core. {RESEARCH_INSTALL_HINT}") + if command == "explore": + from .cli_commands.explore import register_explore_commands + + register_explore_commands(subparsers, add_subcommand_format) + elif command == "deepresearch": + from .cli_commands.deepresearch import register_deepresearch_command + + register_deepresearch_command(subparsers, add_subcommand_format) + else: + from .capabilities.external_research.cli import register_external_evidence_commands + + register_external_evidence_commands(subparsers, add_subcommand_format) + return _dispatch_selected(parse_cli_args(parser, raw_argv), raw_argv) if command in _WORKSPACE_COMMANDS and _standalone_core(): parser, subparsers = build_cli_parser() if not _workspace_installed(): @@ -1209,7 +1242,7 @@ def _run_command(command: str | None, raw_argv: list[str]) -> int: if command == "history" and "loopx.cli" in sys.modules: # An explicitly loaded facade keeps its existing handler/renderer bindings. return _run_full_cli(raw_argv) - if command in _SELECTED_COMMANDS or (command in _FULL_INSTALL_SELECTED_COMMANDS and not _standalone_core()): + if command in _SELECTED_COMMANDS or (command == "explore" and not _standalone_core()): try: args = parse_cli_args(_build_selected_parser(command), raw_argv) except _SelectedParseRejected: diff --git a/loopx/doctor.py b/loopx/doctor.py index e8c9545c2b..d9e233d006 100644 --- a/loopx/doctor.py +++ b/loopx/doctor.py @@ -1262,10 +1262,17 @@ def collect_doctor( }) if deep_validation: checks.extend(deep_validation["checks"]) + from .release_candidate import collect_companion_distribution_diagnostics + + runtime_identity = release_runtime_identity() + companions, companion_checks, companion_fix = collect_companion_distribution_diagnostics( + runtime_identity=runtime_identity, + ) + checks.extend(companion_checks) payload: dict[str, Any] = { "ok": all(check["ok"] for check in checks if check["required"]), "mode": "deep" if deep else "standard", - "service_runtime_identity": release_runtime_identity(), + "service_runtime_identity": runtime_identity, "agent_type": canonical_agent_type, "python": { "executable": sys.executable, @@ -1364,6 +1371,10 @@ def collect_doctor( ) ), } + if companions: + payload["companion_distributions"] = companions + if companion_fix: + payload["fix"] = f"{companion_fix}\n{payload['fix']}" if canonical_agent_type == "zcode": from .zcode_goal_mode.diagnostics import collect_zcode_host_diagnostics @@ -1537,6 +1548,17 @@ def render_doctor_markdown(payload: dict[str, Any]) -> str: for check in payload.get("checks") or []: required = "required" if check.get("required") else "optional" lines.append(f"- {check.get('id')} ({required}): `{check.get('ok')}` - {check.get('detail')}") + companions = payload.get("companion_distributions") + if isinstance(companions, list) and companions: + lines.extend(["", "## Companion Distributions"]) + for item in companions: + if not isinstance(item, dict): + continue + lines.append( + f"- {item.get('distribution')}: version=`{item.get('version')}`, " + f"core_version=`{item.get('core_version')}`, ready=`{item.get('ready')}`, " + f"reason=`{item.get('reason')}`" + ) provenance = cast(dict[str, Any], payload.get("release_provenance")) if isinstance(payload.get("release_provenance"), dict) else {} if provenance: default_release = cast(dict[str, Any], provenance.get("default_release")) if isinstance(provenance.get("default_release"), dict) else {} diff --git a/loopx/python_install_owner.py b/loopx/python_install_owner.py index 727430db2b..f4c522691a 100644 --- a/loopx/python_install_owner.py +++ b/loopx/python_install_owner.py @@ -16,6 +16,7 @@ import os from pathlib import Path import shlex +from typing import Any def installed_loopx_distribution(lookup: Callable[[str], Distribution]) -> Distribution: @@ -87,61 +88,136 @@ def distribution_recorded_files(installed: Distribution) -> list[tuple[str, Path return entries -def builtin_capability_installed( +def inspect_builtin_capability_distribution( distribution_name: str, modules: tuple[str, ...], *, builtin_cli_present: bool | None = None, resources: tuple[str, ...] = (), -) -> bool: - """Check import locations and matching installed wheel ownership without loading code.""" +) -> dict[str, Any]: + """Inspect companion capability installation, version, and file ownership.""" if builtin_cli_present is None: builtin_cli_present = find_spec("loopx.cli") is not None - if not builtin_cli_present: - try: - implementation = distribution(distribution_name) - if implementation.version != distribution("loopx-core").version: - return False - except PackageNotFoundError: - return False - 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: - return True - package_parent = Path(__file__).resolve().parent.parent + return { + "distribution": distribution_name, + "installed": True, + "ready": True, + "version": None, + "core_version": None, + "reason": None, + "reasons": [], + "missing_modules": [], + "missing_resources": [], + "unowned_modules": [], + "unowned_resources": [], + } + try: + core_version: str | None = distribution("loopx-core").version + except PackageNotFoundError: + core_version = None + try: + implementation = distribution(distribution_name) + except PackageNotFoundError: + return { + "distribution": distribution_name, + "installed": False, + "ready": False, + "version": None, + "core_version": core_version, + "reason": "not_installed", + "reasons": ["not_installed"], + "missing_modules": [], + "missing_resources": [], + "unowned_modules": [], + "unowned_resources": [], + } + + direct_url = json.loads(implementation.read_text("direct_url.json") or "{}") + editable = bool(direct_url.get("dir_info", {}).get("editable")) entries = distribution_recorded_files(implementation) + package_parent = Path(__file__).resolve().parent.parent + recorded = {path.resolve() for _name, path in entries or ()} + missing_recorded_assets: list[str] = [] + unowned_recorded_assets: list[str] = [] if entries is None: - return False - recorded_entries = [ - (name, path) for name, path in entries - if name.startswith("loopx/") and is_distribution_artifact(Path(name)) - ] - recorded = {path.resolve() for _name, path in entries} - return ( - all( - ".." not in Path(name).parts - and (target := package_parent / name) in recorded - and not target.is_symlink() - and target.is_file() - and path.resolve() == target - for name, path in recorded_entries - ) - and all(origin in recorded for origin in origins) - and all( - (target := package_parent / resource) in recorded - and not target.is_symlink() - and target.is_file() - for resource in resources - ) + missing_recorded_assets.append("RECORD") + else: + for name, path in entries: + if not (name.startswith("loopx/") and is_distribution_artifact(Path(name))): + continue + target = package_parent / name + if ".." in Path(name).parts or target.is_symlink() or not target.is_file(): + missing_recorded_assets.append(name) + elif path.resolve() != target.resolve(): + unowned_recorded_assets.append(name) + + missing_modules: list[str] = [] + unowned_modules: list[str] = [] + for module in modules: + spec = find_spec(module) + if spec is None or spec.origin is None or not Path(spec.origin).is_file(): + missing_modules.append(module) + continue + if Path(spec.origin).resolve() not in recorded: + unowned_modules.append(module) + missing_resources: list[str] = list(missing_recorded_assets) + unowned_resources: list[str] = list(unowned_recorded_assets) + for resource in resources: + target = package_parent / resource + if target.is_symlink() or not target.is_file(): + if resource not in missing_resources: + missing_resources.append(resource) + elif target.resolve() not in recorded: + if resource not in unowned_resources: + unowned_resources.append(resource) + + reasons: list[str] = [] + if core_version is None: + reasons.append("core_distribution_missing") + elif implementation.version != core_version: + reasons.append("version_mismatch") + if editable: + reasons.append("editable_companion_unsupported") + if missing_modules or missing_resources: + reasons.append("missing_files") + if unowned_modules or unowned_resources: + reasons.append("unowned_files") + return { + "distribution": distribution_name, + "installed": True, + "ready": not reasons, + "version": implementation.version, + "core_version": core_version, + "reason": reasons[0] if reasons else None, + "reasons": reasons, + "missing_modules": missing_modules, + "missing_resources": missing_resources, + "unowned_modules": unowned_modules, + "unowned_resources": unowned_resources, + } + + +def builtin_capability_installed( + distribution_name: str, + modules: tuple[str, ...], + *, + builtin_cli_present: bool | None = None, + resources: tuple[str, ...] = (), +) -> bool: + """Check import locations and matching installed wheel ownership without loading code.""" + return bool( + inspect_builtin_capability_distribution( + distribution_name, + modules, + builtin_cli_present=builtin_cli_present, + resources=resources, + )["ready"] ) WORKSPACE_DISTRIBUTION = "loopx-workspace" +RESEARCH_DISTRIBUTION = "loopx-capability-research" @dataclass(frozen=True) class PythonInstallOwner: manager: str diff --git a/loopx/release_candidate.py b/loopx/release_candidate.py index a0565dd4b1..4b9dfc9d29 100644 --- a/loopx/release_candidate.py +++ b/loopx/release_candidate.py @@ -11,6 +11,7 @@ from .command_invocation import command_argv from .python_install_owner import ( + RESEARCH_DISTRIBUTION, distribution_record_path, installed_loopx_distribution, verified_distribution_console, @@ -304,6 +305,103 @@ def collect_deep_install_checks( ) +def collect_companion_distribution_diagnostics( + *, + runtime_identity: dict[str, Any] | None = None, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]], str | None]: + """Inspect installed optional companion wheels for standalone loopx-core.""" + from importlib.util import find_spec + from .capabilities.deep_research.catalog_entry import inspect_research_workflow_distribution + + if find_spec("loopx.cli") is not None: + return [], [], None + try: + installed = installed_loopx_distribution(distribution) + except PackageNotFoundError: + return [], [], None + if getattr(installed, "name", None) != "loopx-core": + return [], [], None + companions = [ + item + for item in (inspect_research_workflow_distribution(builtin_cli_present=False),) + if item["installed"] + ] + checks: list[dict[str, Any]] = [] + fix_parts: list[str] = [] + if companions: + failing = [item for item in companions if not item["ready"]] + if failing: + details: list[str] = [] + for item in failing: + missing = [ + *item["missing_modules"], + *item["missing_resources"], + *item["unowned_modules"], + *item["unowned_resources"], + ] + summary = ( + f"{item['distribution']}=={item['version']} " + f"(core=={item['core_version']}): {','.join(item['reasons'])}" + ) + if missing: + summary += f" [{', '.join(missing)}]" + details.append(summary) + fix_parts.append( + f"Reinstall matching `{item['distribution']}=={item['core_version']}` " + f"or uninstall `{item['distribution']}`." + ) + checks.append( + { + "id": "companion_distributions_compatible", + "required": True, + "ok": False, + "detail": "; ".join(details), + } + ) + else: + checks.append( + { + "id": "companion_distributions_compatible", + "required": True, + "ok": True, + "detail": "; ".join( + f"{item['distribution']}=={item['version']} (core=={item['core_version']})" + for item in companions + ), + } + ) + else: + checks.append( + { + "id": "companion_distributions_compatible", + "required": False, + "ok": True, + "applicable": False, + "detail": "no optional companion distributions installed", + } + ) + if runtime_identity is not None and not runtime_identity.get("release_id"): + fingerprint = runtime_identity.get("package_fingerprint") + fingerprint_ok = isinstance(fingerprint, str) and fingerprint.startswith("sha256:") + checks.append( + { + "id": "package_runtime_fingerprint", + "required": True, + "ok": fingerprint_ok, + "detail": ( + str(fingerprint) + if fingerprint_ok + else "runtime fingerprint unavailable (version mismatch, missing recorded files, or unowned files in package tree)" + ), + } + ) + if not fingerprint_ok and not fix_parts: + fix_parts.append( + f"Repair or reinstall `loopx-core` and any `{RESEARCH_DISTRIBUTION}` companion at the exact Core version." + ) + return companions, checks, " ".join(fix_parts) if fix_parts else None + + def collect_installation_doctor(*, deep: bool) -> dict[str, Any]: """Validate the package/toolchain without opening registered user projects. @@ -320,20 +418,29 @@ def collect_installation_doctor(*, deep: bool) -> dict[str, Any]: package_root = Path(__file__).resolve().parents[1] selected = os.environ.get("LOOPX_RELEASE_ROOT") runtime = collect_effect_runtime_readiness(deep=deep) + runtime_identity = release_runtime_identity() + companions, companion_checks, companion_fix = collect_companion_distribution_diagnostics( + runtime_identity=runtime_identity, + ) checks = [ {"id": "command_available", "required": True, "ok": command is not None}, {"id": "typescript_effect_runtime_ready", "required": True, "ok": bool(runtime.get("ready")), "detail": runtime.get("status")}, + *companion_checks, ] payload: dict[str, Any] = { "mode": "deep" if deep else "standard", "scope": "installation_only", - "service_runtime_identity": release_runtime_identity(), + "service_runtime_identity": runtime_identity, "python": {"executable": sys.executable}, "checks": checks, "typescript_control_plane": runtime, "path": {"loopx": str(command) if command else None}, } + if companions: + payload["companion_distributions"] = companions + if companion_fix: + payload["fix"] = companion_fix if deep: candidate = collect_deep_install_checks( command_path=command, diff --git a/loopx/release_manifest.py b/loopx/release_manifest.py index 61130230c7..a0ff888287 100644 --- a/loopx/release_manifest.py +++ b/loopx/release_manifest.py @@ -11,6 +11,7 @@ from . import __version__ from .doctor_git import GitSourceState, git_source_metadata from .python_install_owner import ( + RESEARCH_DISTRIBUTION, WORKSPACE_DISTRIBUTION, distribution_recorded_files, installed_loopx_distribution, @@ -316,6 +317,7 @@ def release_runtime_identity(release_root: Path | None = None) -> dict[str, str "loopx-capability-agent-turn-recall", "loopx-capability-pull-request-review", "loopx-capability-issue-fix", + RESEARCH_DISTRIBUTION, ) diff --git a/packages/loopx-capability-research/README.md b/packages/loopx-capability-research/README.md new file mode 100644 index 0000000000..3290410f37 --- /dev/null +++ b/packages/loopx-capability-research/README.md @@ -0,0 +1,59 @@ +# Optional Explore & Research workflows for LoopX Core + +Install `loopx-capability-research` into a matching standalone `loopx-core` +environment to enable **Explore** as the primary optional research workflow +(orchestration, multi-branch todo/worker planning, replay & counterfactual +harness, source reconciliation, and Feishu/external-evidence bridges), alongside +the existing standalone `deepresearch` evidence ledger and `external-evidence` +contracts. + +Core (`loopx-core`) retains only Explore's canonical result-event schema, +lightweight projection helpers, machine/goal configuration adapters, and Goal +permission/settlement validation. Installing `loopx-capability-research` adds no +separate Goal write authority and never executes external providers without +explicit authorization. The ordinary `loopx` distribution already includes these +modules. + +Build from the same checkout as the Core wheel and install it into that +environment: + +```sh +uv run --extra test python packages/loopx-core/prepare.py \ + --distribution loopx-capability-research --output /tmp/loopx-research-source +uv build --wheel /tmp/loopx-research-source --out-dir /tmp/loopx-research-dist +uv pip install --python /tmp/loopx-core-env/bin/python \ + /tmp/loopx-research-dist/loopx_capability_research-*.whl +``` + +Check readiness with `loopx doctor --installation-only` and inspect +`loopx capability show explore`, `loopx capability show deep-research`, and +`loopx capability show external-evidence-research`. + +Primary Explore & bridge workflows: + +- Run Explore planning and result recording against an enabled Goal: + `loopx explore node ...`, `loopx explore finding ...`, `loopx explore summary ...`, + `loopx explore worker-branch-plan ...`. +- Project explicitly parent-admitted external evidence into a same-goal Explore + node without auto-executing external providers: + `loopx explore observe-external --goal-id --node --plan-json plan.json --receipt-json receipt.json --admission-json admission.json [--execute]` + (or `loopx external-evidence readback ... --goal-id --explore-node [--execute]`). +- One-way read-only export of authorized answered `deepresearch` citations into + an enabled Explore Goal without modifying `.loopx/deepresearch/` or leaking + saved local paths, private sources, or report prose: + `loopx explore import-citations --goal-id --node --project [--execute]`. + +## Transition & Rollback for Existing Standalone `.loopx/deepresearch/` Ledgers + +- Existing standalone `loopx deepresearch status|add-source|resolve-question|close|report` + commands continue reading and continuing `.loopx/deepresearch/research.json` + with identical schema, lock, and archive semantics. +- Open research sessions do not require immediate migration: continue or close + the active session normally, then optionally run `loopx explore import-citations` + to project sanitized citation references into an enabled Goal Explore graph. + `.loopx/deepresearch/research.json` and `report.md` remain untouched. +- To roll back to Core-only operation after exiting open research commands, run + `uv pip uninstall --python /tmp/loopx-core-env/bin/python loopx-capability-research`. + Goal `explore_results.jsonl`, Goal permissions, and standalone + `.loopx/deepresearch/` ledgers remain intact on disk and resume cleanly once + the matching wheel is reinstalled. diff --git a/packages/loopx-capability-research/pyproject.toml b/packages/loopx-capability-research/pyproject.toml new file mode 100644 index 0000000000..0a63a26280 --- /dev/null +++ b/packages/loopx-capability-research/pyproject.toml @@ -0,0 +1,30 @@ +[build-system] +requires = ["setuptools==83.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "loopx-capability-research" +dynamic = ["version", "dependencies"] +description = "Explore orchestration, evidence-ledger, and external evidence workflows for matching LoopX Core." +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.capabilities.explore", + "loopx.capabilities.deep_research", + "loopx.capabilities.external_research", + "loopx.cli_commands", + "loopx.control_plane.capabilities", + "loopx.extensions", +] + +[tool.setuptools.package-data] +"loopx.control_plane.capabilities" = ["external_evidence.ts"] diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index 85903b01c3..c096cbc369 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -115,6 +115,14 @@ uv pip uninstall --python "$LOOPX_CORE_PYTHON" \ loopx-capability-agent-turn-recall loopx-capability-pull-request-review loopx-capability-issue-fix ``` +To add optional Explore orchestration (frontier/multi-branch planning, replay, +external-evidence observation, and read-only citation export) alongside the +standalone `deepresearch` evidence ledger and `external-evidence` commands, build +and install the matching [research workflow wheel](../loopx-capability-research/README.md). +Core retains Explore's result-event schema, lightweight projection, and Goal +permission/settlement validation; existing project ledgers remain readable and +unmodified on rollback. + 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 e5f3bd21e5..a14e802e94 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -1,4 +1,4 @@ -"""Prepare split LoopX Core, Workspace, and built-in capability distributions. +"""Prepare split LoopX Core, Workspace, Research, and 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. @@ -38,6 +38,7 @@ RECALL_DISTRIBUTION = "loopx-capability-agent-turn-recall" PR_REVIEW_DISTRIBUTION = "loopx-capability-pull-request-review" ISSUE_FIX_DISTRIBUTION = "loopx-capability-issue-fix" +RESEARCH_DISTRIBUTION = "loopx-capability-research" STANDARD_CAPABILITY_DISTRIBUTIONS = ( RECALL_DISTRIBUTION, PR_REVIEW_DISTRIBUTION, @@ -58,6 +59,34 @@ "pr_gate_reconcile.py", "pr_lifecycle.py", "pr_lifecycle_rollout.py", "pr_review_ack.py", "pr_wait_hook.py", "pr_wait_reconcile.py", } +EXPLORE_DIRECTORY = Path("loopx/capabilities/explore") +# Core retains Explore's result event schema, lightweight projection, machine/goal +# configuration adapters, and Goal permission/settlement interfaces. +EXPLORE_CORE_FILES = { + "__init__.py", "activation.py", "candidate_content.py", "catalog_entry.py", + "composition_frontier.py", "execution_observation.py", "harness_gate.py", + "machine_defaults.py", "measurements.py", "research_evidence.py", + "research_frontier.py", "result_log.py", "result_writeback.py", + "turn_context.py", "README.md", "README.zh-CN.md", +} +RESEARCH_FILES = { + Path("loopx/cli_commands/explore.py"), + Path("loopx/cli_commands/explore_planning_commands.py"), + Path("loopx/cli_commands/explore_feishu_commands.py"), + Path("loopx/capabilities/deep_research/runtime.py"), + Path("loopx/capabilities/external_research/cli.py"), + Path("loopx/capabilities/external_research/projection.py"), + Path("loopx/capabilities/external_research/provider_probe.py"), + Path("loopx/cli_commands/deepresearch.py"), + Path("loopx/control_plane/capabilities/external_evidence.ts"), + Path("loopx/extensions/public_github_research.py"), + EXPLORE_DIRECTORY / "harness_runtime.py", + EXPLORE_DIRECTORY / "harness_frontier.py", + EXPLORE_DIRECTORY / "replay_runtime.py", + EXPLORE_DIRECTORY / "research_bridge.py", + EXPLORE_DIRECTORY / "todo_branch_plan.py", + EXPLORE_DIRECTORY / "worker_branch_plan.py", +} CAPABILITY_ENTRY_MODULES = { RECALL_DISTRIBUTION: { Path("loopx/capabilities/agent_turn_recall/cli.py"), @@ -72,6 +101,7 @@ ISSUE_FIX_DISTRIBUTION: { ISSUE_FIX_DIRECTORY / name for name in ("cli.py", "candidate_preflight.py", "workflow_plan.py", "acceptance_loop.py") }, + RESEARCH_DISTRIBUTION: RESEARCH_FILES, } @@ -93,6 +123,10 @@ def _optional_capability_sources(sources: list[Path]) -> dict[str, set[Path]]: | (tracked & CAPABILITY_ENTRY_MODULES[PR_REVIEW_DISTRIBUTION]) ), ISSUE_FIX_DISTRIBUTION: _implementation_paths(sources, ISSUE_FIX_DIRECTORY, ISSUE_FIX_CORE_FILES), + RESEARCH_DISTRIBUTION: ( + _implementation_paths(sources, EXPLORE_DIRECTORY, EXPLORE_CORE_FILES) + | (tracked & RESEARCH_FILES) + ), } @@ -196,6 +230,10 @@ def prepare_capability_source( return output +def prepare_research_source(output: Path, *, repository: Path = REPOSITORY) -> Path: + return prepare_capability_source(output, RESEARCH_DISTRIBUTION, repository=repository) + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) diff --git a/tests/capabilities/test_external_evidence_cli.py b/tests/capabilities/test_external_evidence_cli.py index f4b3082fc0..496bc97871 100644 --- a/tests/capabilities/test_external_evidence_cli.py +++ b/tests/capabilities/test_external_evidence_cli.py @@ -2,6 +2,7 @@ import argparse import json +import os import subprocess import sys import tempfile @@ -533,13 +534,15 @@ def test_source_cli_preserves_receipt_clocks_and_idempotent_ledger( monkeypatch.setenv("LOOPX_USAGE_PING", "0") project = tmp_path / "research" project.mkdir() + installed_python = os.environ.get("LOOPX_RESEARCH_TEST_PYTHON") + interpreter = [installed_python, "-I"] if installed_python else [sys.executable] def run(*args: str): result = subprocess.run( - [sys.executable, "-m", "loopx.entrypoint", "--runtime-root", + [*interpreter, "-m", "loopx.entrypoint", "--runtime-root", str(tmp_path / "runtime"), "--registry", str(tmp_path / "registry.json"), "--format", "json", *args], - cwd=Path(__file__).resolve().parents[2], capture_output=True, + cwd=tmp_path if installed_python else Path(__file__).resolve().parents[2], capture_output=True, text=True, encoding="utf-8", check=False, timeout=30, ) return result.returncode, json.loads(result.stdout) @@ -637,7 +640,14 @@ def save(name: str, payload: dict) -> str: assert direct_row["accessed_at"] assert "recorded_at" not in direct_row and "publication_date" not in direct_row finally: - restart_effect_runtime() + if installed_python: + subprocess.run( + [*interpreter, "-c", "from loopx.control_plane.effect_runtime import restart_effect_runtime;" + "restart_effect_runtime(wait_for_exit=True)"], + cwd=tmp_path, check=True, timeout=30, + ) + else: + restart_effect_runtime() def test_zero_flag_discover_and_plan_auto_detect_local_evidence_capabilities( diff --git a/tests/test_core_research_distribution.py b/tests/test_core_research_distribution.py new file mode 100644 index 0000000000..07ae7426ca --- /dev/null +++ b/tests/test_core_research_distribution.py @@ -0,0 +1,608 @@ +"""Research wheel ownership (with Explore as primary workflow) and installed journeys.""" +from __future__ import annotations + +import ast +import importlib.util +import json +import os +from pathlib import Path +import re +import subprocess +import sys + +import pytest + +from tests.test_core_distribution import _environment, _run, core_python as core_python + + +DISTRIBUTION = "loopx-capability-research" +RESEARCH_ENABLED = os.environ.get("LOOPX_RESEARCH_TEST_ENABLED") == "1" +REPOSITORY = Path(__file__).resolve().parents[1] + + +def _load_prepare(): + spec = importlib.util.spec_from_file_location( + "loopx_core_prepare_test", REPOSITORY / "packages/loopx-core/prepare.py", + ) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_core_and_research_bidirectional_staging_ownership(tmp_path): + prepare = _load_prepare() + tracked = prepare._tracked_loopx_sources(REPOSITORY) + research_sources = { + path.as_posix() + for path in prepare._optional_capability_sources(tracked)[DISTRIBUTION] + } + expected_explore_moved = { + "loopx/cli_commands/explore.py", + "loopx/cli_commands/explore_planning_commands.py", + "loopx/cli_commands/explore_feishu_commands.py", + "loopx/capabilities/explore/harness_runtime.py", + "loopx/capabilities/explore/harness_frontier.py", + "loopx/capabilities/explore/todo_branch_plan.py", + "loopx/capabilities/explore/worker_branch_plan.py", + "loopx/capabilities/explore/replay_runtime.py", + "loopx/capabilities/explore/research_bridge.py", + } + expected_research = { + "loopx/capabilities/deep_research/runtime.py", + "loopx/capabilities/external_research/cli.py", + "loopx/capabilities/external_research/projection.py", + "loopx/capabilities/external_research/provider_probe.py", + "loopx/cli_commands/deepresearch.py", + "loopx/control_plane/capabilities/external_evidence.ts", + "loopx/extensions/public_github_research.py", + } + assert expected_explore_moved <= research_sources + assert expected_research <= research_sources + + core_staged = prepare.prepare_core_source(tmp_path / "core", repository=REPOSITORY) + research_staged = prepare.prepare_capability_source( + tmp_path / "research", DISTRIBUTION, repository=REPOSITORY, + ) + core_files = {p.relative_to(core_staged).as_posix() for p in (core_staged / "loopx").rglob("*") if p.is_file()} + res_files = {p.relative_to(research_staged).as_posix() for p in (research_staged / "loopx").rglob("*") if p.is_file()} + assert res_files == research_sources + assert res_files.isdisjoint(core_files) + for retained in ( + "loopx/capabilities/explore/result_log.py", + "loopx/capabilities/explore/turn_context.py", + "loopx/capabilities/explore/result_writeback.py", + "loopx/capabilities/explore/machine_defaults.py", + "loopx/capabilities/explore/harness_gate.py", + "loopx/capabilities/explore/composition_frontier.py", + "loopx/capabilities/explore/research_evidence.py", + "loopx/capabilities/explore/research_frontier.py", + ): + assert retained in core_files and retained not in res_files + for moved in expected_explore_moved | expected_research: + assert moved in res_files and moved not in core_files + + +def test_core_staging_has_zero_unconditional_research_wheel_imports(tmp_path): + prepare = _load_prepare() + staged = prepare.prepare_core_source(tmp_path / "source", repository=REPOSITORY) + research_sources = prepare._optional_capability_sources( + prepare._tracked_loopx_sources(REPOSITORY) + )[DISTRIBUTION] + research_modules = { + ".".join(list(p.with_suffix("").parts)[:-1] if p.stem == "__init__" else p.with_suffix("").parts) + for p in research_sources + if p.suffix == ".py" + } + + def _imported(node, mod_parts): + if isinstance(node, ast.Import): + return [a.name for a 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, mod_parts, offenders, rel): + for stmt in stmts: + if isinstance(stmt, (ast.Import, ast.ImportFrom)): + for target in _imported(stmt, mod_parts): + if target in research_modules or any(target.startswith(r + ".") for r in research_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 = [] + 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_research_inventory_and_help_are_passive(core_python, tmp_path): + prepare = _load_prepare() + expected_files = sorted( + p.as_posix() + for p in prepare._optional_capability_sources(prepare._tracked_loopx_sources(REPOSITORY))[DISTRIBUTION] + ) + script = ''' +import json, sys +from importlib.metadata import distribution +from importlib.util import find_spec +from loopx.capabilities.deep_research.catalog_entry import RESEARCH_MODULES +from loopx.entrypoint import main +from loopx.release_manifest import _distribution_runtime_fingerprint + +installed = sys.argv[1] == "True" +expected_files = set(json.loads(sys.argv[2])) +assert all((find_spec(module) is not None) is installed for module in RESEARCH_MODULES) +core = distribution("loopx-core") +core_files = {entry.as_posix() for entry in core.files if entry.parts[0] == "loopx"} +assert expected_files.isdisjoint(core_files) +if installed: + research = distribution("loopx-capability-research") + assert research.version == core.version + assert research.requires == ["loopx-core==" + core.version] + members = {entry.as_posix() for entry in research.files if entry.parts[0] == "loopx"} + assert expected_files <= members and members.isdisjoint(core_files) + assert "loopx/capabilities/explore/harness_runtime.py" in members + assert "loopx/cli_commands/explore.py" in members +assert _distribution_runtime_fingerprint() is not None +assert main(["capability", "list", "--format", "json"]) == 0 +assert main(["commands", "--format", "json"]) == 0 +assert all(module not in sys.modules for module in RESEARCH_MODULES) +''' + probe = subprocess.run( + [core_python, "-I", "-c", script, str(RESEARCH_ENABLED), json.dumps(expected_files)], + cwd=tmp_path, env=_environment(core_python, {"PATH": str(tmp_path)}), + capture_output=True, text=True, timeout=45, + ) + assert probe.returncode == 0, probe.stderr + decoder = json.JSONDecoder() + cap_payload, offset = decoder.raw_decode(probe.stdout.lstrip()) + cmd_payload, _ = decoder.raw_decode(probe.stdout[len(probe.stdout) - len(probe.stdout.lstrip()) + offset:].lstrip()) + listed_commands = { + entry["command"].split()[1] + for group in cmd_payload["groups"] + for entry in group["commands"] + if len(entry["command"].split()) >= 2 + } + for command in ("explore", "deepresearch", "external-evidence"): + assert (command in listed_commands) is RESEARCH_ENABLED + entries = {row["id"]: row for row in cap_payload["capabilities"]} + for name, command in ( + ("explore", "explore"), + ("deep-research", "deepresearch"), + ("external-evidence-research", "external-evidence"), + ): + entry = entries[name] + assert entry["provider_id"] == DISTRIBUTION + assert entry["provider_state"]["installed"] is RESEARCH_ENABLED + assert entry["provider_state"]["ready"] is RESEARCH_ENABLED + result = _run(core_python, [command, "--help"], tmp_path, + expected=0 if RESEARCH_ENABLED else 2, environment={"PATH": str(tmp_path)}) + if RESEARCH_ENABLED: + assert f" {command} " in result.stdout + else: + assert DISTRIBUTION in entry["next_real_step"] and DISTRIBUTION in result.stderr + doctor = json.loads(_run(core_python, ["doctor", "--installation-only", "--format", "json"], tmp_path).stdout) + assert doctor["ok"] is True + assert doctor["service_runtime_identity"]["package_fingerprint"].startswith("sha256:") + if RESEARCH_ENABLED: + companions = {c["distribution"]: c for c in doctor["companion_distributions"]} + assert companions[DISTRIBUTION]["ready"] is True + assert companions[DISTRIBUTION]["version"] == doctor["service_runtime_identity"]["package_version"] + else: + assert "companion_distributions" not in doctor + assert not list(tmp_path.iterdir()) + + +@pytest.mark.skipif(not RESEARCH_ENABLED, reason="requires the matching Research wheel") +def test_installed_research_doctor_diagnoses_mismatch_and_missing_resource(core_python, tmp_path): + probe = subprocess.run( + [core_python, "-I", "-c", + "from importlib.metadata import distribution; from pathlib import Path;" + "d=distribution('loopx-capability-research');" + "dist_info=next(p.locate().parent for p in d.files if 'METADATA' in str(p));" + "res=next(p.locate() for p in d.files if str(p).endswith('external_evidence.ts'));" + "explore_mod=next(p.locate() for p in d.files if str(p).endswith('capabilities/explore/harness_runtime.py'));" + "print(dist_info); print(res); print(explore_mod)"], + capture_output=True, text=True, check=True, + ) + dist_info_str, res_str, explore_str = probe.stdout.strip().splitlines() + metadata = Path(dist_info_str) / "METADATA" + resource = Path(res_str) + explore_mod = Path(explore_str) + original_meta = metadata.read_bytes() + backup_res = resource.with_suffix(".ts.bak") + backup_explore = explore_mod.with_suffix(".py.bak") + try: + # 1. Version mismatch must fail doctor --installation-only with exact reason & version. + metadata.write_text( + re.sub(r"(?m)^Version: .*$", "Version: 0.0.1-mismatch", original_meta.decode("utf-8")), + encoding="utf-8", + ) + mismatched = _run(core_python, ["doctor", "--installation-only", "--format", "json"], tmp_path, expected=1) + m_payload = json.loads(mismatched.stdout) + assert m_payload["ok"] is False + assert "package_fingerprint" not in m_payload["service_runtime_identity"] + comp = {c["distribution"]: c for c in m_payload["companion_distributions"]}[DISTRIBUTION] + assert comp["installed"] is True and comp["ready"] is False + assert comp["version"] == "0.0.1-mismatch" + assert "version_mismatch" in comp["reasons"] + for cap_id in ("explore", "external-evidence-research"): + cap = json.loads(_run(core_python, ["capability", "show", cap_id, "--format", "json"], tmp_path).stdout) + assert cap["capability"]["provider_state"]["installed"] is True + assert cap["capability"]["provider_state"]["ready"] is False + finally: + metadata.write_bytes(original_meta) + + for target, backup, expected_field, expected_entry in ( + (resource, backup_res, "missing_resources", "loopx/control_plane/capabilities/external_evidence.ts"), + (explore_mod, backup_explore, "missing_modules", "loopx.capabilities.explore.harness_runtime"), + ): + try: + target.rename(backup) + missing = _run(core_python, ["doctor", "--installation-only", "--format", "json"], tmp_path, expected=1) + r_payload = json.loads(missing.stdout) + assert r_payload["ok"] is False + assert "package_fingerprint" not in r_payload["service_runtime_identity"] + comp = {c["distribution"]: c for c in r_payload["companion_distributions"]}[DISTRIBUTION] + assert comp["installed"] is True and comp["ready"] is False + assert "missing_files" in comp["reasons"] + assert expected_entry in comp[expected_field] + cmds = json.loads(_run(core_python, ["commands", "--format", "json"], tmp_path).stdout) + listed = {e["command"].split()[1] for g in cmds["groups"] for e in g["commands"] if len(e["command"].split()) >= 2} + assert not ({"explore", "external-evidence", "deepresearch"} & listed) + finally: + if backup.exists(): + backup.rename(target) + + restored = json.loads(_run(core_python, ["doctor", "--installation-only", "--format", "json"], tmp_path).stdout) + assert restored["ok"] is True + assert restored["service_runtime_identity"]["package_fingerprint"].startswith("sha256:") + + +@pytest.mark.skipif(not RESEARCH_ENABLED, reason="requires the matching Research wheel") +def test_installed_research_explore_primary_journey_and_bridges(core_python, tmp_path, monkeypatch): + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + + isolate_sqlite_runtime(tmp_path, monkeypatch) + _run_explore_and_bridge_journey(core_python, tmp_path) + + +def test_source_explore_bridge_isolation_sanitization_idempotence_and_non_backwrite(tmp_path, monkeypatch): + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + + isolate_sqlite_runtime(tmp_path, monkeypatch) + _run_explore_and_bridge_journey(sys.executable, tmp_path, check_module_laziness=False) + + +def _run_explore_and_bridge_journey(python_bin: str, tmp_path: Path, *, check_module_laziness: bool = True) -> None: + project_a = tmp_path / "proj-a" + project_b = tmp_path / "proj-b" + runtime = tmp_path / "runtime" + registry = tmp_path / "registry.json" + project_a.mkdir() + project_b.mkdir() + prefix = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + + def cli(*args: str, expected: int = 0) -> dict: + interpreter = [python_bin, "-I"] if check_module_laziness else [python_bin] + result = subprocess.run( + [*interpreter, "-m", "loopx.entrypoint", *prefix, *args], + cwd=tmp_path if check_module_laziness else REPOSITORY, + env=_environment(python_bin), capture_output=True, text=True, timeout=60, + ) + assert result.returncode == expected, (result.stdout, result.stderr) + return json.loads(result.stdout) + + # 1. Bootstrap Goal A (Explore enabled) and Goal B (Explore enabled separately + disabled Goal C). + cli("bootstrap", "--project", str(project_a), "--goal-id", "goal-a", + "--objective", "Explore research workflows safely.", "--write-scope", "docs/**") + cli("configure-goal", "--goal-id", "goal-a", "--explore-mode", "planning", "--execute") + cli("register-agent", "--goal-id", "goal-a", "--agent-id", "researcher", "--require-new", "--execute") + + cli("bootstrap", "--project", str(project_b), "--goal-id", "goal-b", + "--objective", "Separate goal isolation boundary.", "--write-scope", "docs/**") + cli("configure-goal", "--goal-id", "goal-b", "--explore-mode", "evidence", "--execute") + + disabled_dir = tmp_path / "proj-disabled" + disabled_dir.mkdir() + cli("bootstrap", "--project", str(disabled_dir), "--goal-id", "goal-off", + "--objective", "Disabled Explore goal.", "--write-scope", "docs/**") + + # 2. Primary Explore write, readback, and continuation on enabled Goal A. + root_node = cli( + "explore", "node", "--goal-id", "goal-a", "--node-id", "q_primary", + "--kind", "question", "--status", "exploring", + "--title", "Does package separation retain Goal continuity?", + "--agent-id", "researcher", + ) + assert root_node["ok"] is True + first_finding = cli( + "explore", "finding", "--goal-id", "goal-a", "--finding-id", "f_initial", + "--node", "q_primary", "--status", "confirmed", + "--title", "Core retains result log and Goal boundary checks.", + "--evidence-ref", "docs/architecture/rfcs/monorepo-distribution-split-v0.md", + "--agent-id", "researcher", + ) + assert first_finding["ok"] is True + readback = cli("explore", "summary", "--goal-id", "goal-a") + assert readback["ok"] is True and readback["counts"]["node_count"] == 1 and readback["counts"]["finding_count"] == 1 + follow_node = cli( + "explore", "node", "--goal-id", "goal-a", "--node-id", "h_bridge", + "--kind", "hypothesis", "--parent", "q_primary", "--status", "open", + "--title", "Continuation child node", "--agent-id", "researcher", + ) + assert follow_node["ok"] is True + branch_plan = cli("explore", "worker-branch-plan", "--goal-id", "goal-a", "--agent-id", "researcher") + assert branch_plan["ok"] is True + turn_ctx = cli("explore", "turn-context", "--goal-id", "goal-a", "--agent-id", "researcher") + assert turn_ctx["goal_id"] == "goal-a" and turn_ctx["graph_enabled"] is True + + # 3. Parent-admitted external-evidence -> Explore (no auto-execution, cross-goal rejection, sanitization, replay). + ext_dir = tmp_path / "ext" + ext_dir.mkdir() + providers = ext_dir / "providers.json" + providers.write_text(json.dumps({"providers": [{ + "provider_id": "host:external-research", "provider_kind": "method", + "protocol": "external_evidence_research_v0", "declared": True, + "installed": True, "enabled": True, "ready": True, + }]}), encoding="utf-8") + plan = cli( + "external-evidence", "plan", "--objective", "Verify external citation intake", + "--user-activity", "Review capture", "--decision", "Admit sanitized evidence", + "--evidence-kind", "original_source", "--provider-inventory-json", str(providers), + ) + assert plan["execution_envelope"]["authority"] == "read_external_sources_only" + assert plan["execution_envelope"]["raw_content_persistence"] == "provider_private" + plan_file = ext_dir / "plan.json" + plan_file.write_text(json.dumps(plan), encoding="utf-8") + + local_root = "/" + "Users/alice/" + "private/" + local_leak_ref = local_root + "secret_brief.md" + public_ref = "https://example.com/public-evidence" + opaque_ext_ref = "urn:private-connector:doc-42" + receipt = { + "schema_version": "loopx_external_evidence_receipt_v0", + "plan_id": plan["plan_id"], + "request_id": plan["request"]["request_id"], + "provider_id": "host:external-research", + "provider_kind": "method", + "status": "succeeded", + "summary": "Captured fixture receipt without network execution.", + "completed_at": "2026-09-22T00:00:00Z", + "sources": [ + { + "source_ref": public_ref, + "source_family": "public-fixture", + "basis": "observed", + "finding": f"Fixture confirms contract semantics from {local_root}local.txt cleanly.", + "accessed_at": "2026-09-21T10:00:00Z", + "publication_date": None, + "content_digest": "sha256:" + "a" * 64, + }, + { + "source_ref": opaque_ext_ref, + "source_family": "connector-fixture", + "basis": "observed", + "finding": f"Sanitized non-HTTP locator with {local_root}nested.md ref.", + "accessed_at": "2026-09-21T10:05:00Z", + "publication_date": None, + "content_digest": "sha256:" + "b" * 64, + }, + ], + } + receipt_file = ext_dir / "receipt.json" + receipt_file.write_text(json.dumps(receipt), encoding="utf-8") + + # External evidence admission itself rejects bare local file paths as provenance URIs. + file_leak_receipt = {**receipt, "sources": [{**receipt["sources"][0], "source_ref": local_leak_ref}]} + file_leak_path = ext_dir / "file_leak_receipt.json" + file_leak_path.write_text(json.dumps(file_leak_receipt), encoding="utf-8") + file_leak_err = cli( + "external-evidence", "admit", "--plan-json", str(plan_file), + "--receipt-json", str(file_leak_path), "--decision", "admit", + "--reason", "Reject local path URI", "--admit-source", local_leak_ref, expected=1, + ) + assert file_leak_err["ok"] is False and "non-file provenance URI" in file_leak_err["error"] + + admitted = cli( + "external-evidence", "admit", "--plan-json", str(plan_file), + "--receipt-json", str(receipt_file), "--decision", "admit", + "--reason", "Validated capture", + "--admit-source", public_ref, "--admit-source", opaque_ext_ref, + ) + admit_file = ext_dir / "admit.json" + admit_file.write_text(json.dumps(admitted), encoding="utf-8") + + rejected_adm = cli( + "external-evidence", "admit", "--plan-json", str(plan_file), + "--receipt-json", str(receipt_file), "--decision", "reject", + "--reason", "Declined", + ) + reject_file = ext_dir / "reject.json" + reject_file.write_text(json.dumps(rejected_adm), encoding="utf-8") + + # Goal C has Explore disabled -> refused (no extra Goal write authority). + off_err = cli( + "explore", "observe-external", "--goal-id", "goal-off", "--node", "q_primary", + "--plan-json", str(plan_file), "--receipt-json", str(receipt_file), + "--admission-json", str(admit_file), "--execute", expected=1, + ) + assert off_err["ok"] is False and "enabled" in off_err["error"] + + # Non-admitted disposition refused. + rej_err = cli( + "explore", "observe-external", "--goal-id", "goal-a", "--node", "q_primary", + "--plan-json", str(plan_file), "--receipt-json", str(receipt_file), + "--admission-json", str(reject_file), "--execute", expected=1, + ) + assert rej_err["ok"] is False + + # Cross-goal rejection: Goal B node missing or explicit expected-goal mismatch fails closed. + cli("explore", "node", "--goal-id", "goal-b", "--node-id", "q_b", "--kind", "question", "--title", "Goal B node") + cross_err = cli( + "explore", "observe-external", "--goal-id", "goal-b", "--node", "q_b", + "--expected-goal-id", "goal-a", + "--plan-json", str(plan_file), "--receipt-json", str(receipt_file), + "--admission-json", str(admit_file), "--execute", expected=1, + ) + assert cross_err["ok"] is False and "different goal" in cross_err["error"] + goal_b_before = cli("explore", "summary", "--goal-id", "goal-b") + assert goal_b_before["counts"]["finding_count"] == 0 + + # Dry-run readback & observe-external must not append. + dry = cli( + "external-evidence", "readback", "--goal-id", "goal-a", "--explore-node", "q_primary", + "--plan-json", str(plan_file), "--receipt-json", str(receipt_file), + "--admission-json", str(admit_file), + ) + assert dry["explore_projection"]["dry_run"] is True and dry["explore_projection"]["written"] is False + + # Apply with --execute: sanitizes local paths, rejects credentials, and replays idempotently. + applied = cli( + "explore", "observe-external", "--goal-id", "goal-a", "--node", "q_primary", + "--plan-json", str(plan_file), "--receipt-json", str(receipt_file), + "--admission-json", str(admit_file), "--execute", + ) + assert applied["ok"] is True and applied["written"] is True and applied["appended_count"] == 2 + assert applied["redacted_source_count"] >= 2 and applied["automatic_execution"] is False + + log_file = Path(applied["log_path"]) + after_apply_bytes = log_file.read_bytes() + log_text = after_apply_bytes.decode("utf-8") + assert ("/" + "Users/") not in log_text and "secret_brief.md" not in log_text and "local.txt" not in log_text + assert "nested.md" not in log_text and opaque_ext_ref not in log_text and "[redacted-local-path]" in log_text + + replay = cli( + "explore", "observe-external", "--goal-id", "goal-a", "--node", "q_primary", + "--plan-json", str(plan_file), "--receipt-json", str(receipt_file), + "--admission-json", str(admit_file), "--execute", + ) + assert replay["ok"] is True and replay["written"] is False and replay["replayed"] is True and replay["appended_count"] == 0 + assert log_file.read_bytes() == after_apply_bytes + + # Credential-bearing evidence fails closed cleanly. + secret_marker = "tok" + "en=synthetic_credential_fixture_000" + secret_receipt = { + **receipt, + "sources": [{ + **receipt["sources"][0], + "finding": f"Captured {secret_marker} from private endpoint", + "content_digest": "sha256:" + "c" * 64, + }], + } + sec_rec_path = ext_dir / "sec_receipt.json" + sec_rec_path.write_text(json.dumps(secret_receipt), encoding="utf-8") + sec_admit = cli( + "external-evidence", "admit", "--plan-json", str(plan_file), + "--receipt-json", str(sec_rec_path), "--decision", "admit", + "--reason", "Secret test", "--admit-source", public_ref, + ) + sec_admit_path = ext_dir / "sec_admit.json" + sec_admit_path.write_text(json.dumps(sec_admit), encoding="utf-8") + sec_err = cli( + "explore", "observe-external", "--goal-id", "goal-a", "--node", "q_primary", + "--plan-json", str(plan_file), "--receipt-json", str(sec_rec_path), + "--admission-json", str(sec_admit_path), "--execute", expected=1, + ) + assert sec_err["ok"] is False and log_file.read_bytes() == after_apply_bytes + + # 4. One-way read-only deepresearch citation export (non-backwrite, sanitization, replay idempotence). + dr_proj = tmp_path / "dr-proj" + dr_proj.mkdir() + cli("deepresearch", "start", "--project", str(dr_proj), "--question", "Audit private citations cleanly.") + cli("deepresearch", "add-source", "--project", str(dr_proj), + "--url-or-path", local_root + "confidential_report.md", + "--tool", "local_read", + "--claims-json", json.dumps([{"text": "Private report prose should remain in session ledger.", "stance": "supports"}])) + unanswered_err = cli( + "explore", "import-citations", "--goal-id", "goal-a", "--node", "h_bridge", + "--project", str(dr_proj), "--execute", expected=1, + ) + assert unanswered_err["ok"] is False and "no authorized resolved citations" in unanswered_err["error"] + cli("deepresearch", "resolve-question", "--project", str(dr_proj), + "--question-id", "q1", "--answer", "CONFIDENTIAL BODY DO NOT LEAK", "--evidence-claims", "c1") + cli("deepresearch", "report", "--project", str(dr_proj)) + + ledger_path = dr_proj / ".loopx/deepresearch/research.json" + report_path = dr_proj / ".loopx/deepresearch/report.md" + ledger_before = ledger_path.read_bytes() + report_before = report_path.read_bytes() + + dr_cross = cli( + "explore", "import-citations", "--goal-id", "goal-b", "--node", "q_b", + "--project", str(dr_proj), "--expected-goal-id", "goal-a", "--execute", expected=1, + ) + assert dr_cross["ok"] is False + + dr_dry = cli( + "explore", "import-citations", "--goal-id", "goal-a", "--node", "h_bridge", + "--project", str(dr_proj), + ) + assert dr_dry["ok"] is True and dr_dry["written"] is False and dr_dry["deepresearch_ledger_mutated"] is False + + dr_exec = cli( + "explore", "import-citations", "--goal-id", "goal-a", "--node", "h_bridge", + "--project", str(dr_proj), "--agent-id", "researcher", "--execute", + ) + assert dr_exec["ok"] is True and dr_exec["written"] is True and dr_exec["appended_count"] == 1 + assert dr_exec["deepresearch_ledger_mutated"] is False + assert ledger_path.read_bytes() == ledger_before and report_path.read_bytes() == report_before + + after_dr_bytes = log_file.read_bytes() + after_dr_text = after_dr_bytes.decode("utf-8") + assert ("/" + "Users/") not in after_dr_text + assert "confidential_report.md" not in after_dr_text + assert "CONFIDENTIAL BODY DO NOT LEAK" not in after_dr_text + assert "deepresearch:claim:c1:" in after_dr_text + + dr_replay = cli( + "explore", "import-citations", "--goal-id", "goal-a", "--node", "h_bridge", + "--project", str(dr_proj), "--agent-id", "researcher", "--execute", + ) + assert dr_replay["ok"] is True and dr_replay["written"] is False and dr_replay["replayed"] is True and dr_replay["appended_count"] == 0 + assert log_file.read_bytes() == after_dr_bytes + assert ledger_path.read_bytes() == ledger_before + + +@pytest.mark.skipif(not RESEARCH_ENABLED, reason="requires the matching Research wheel") +def test_installed_research_continues_original_ledger(core_python, tmp_path): + question = "Where does the sample inventory go?" + source = "inventory.txt" + (tmp_path / source).write_text("The sample is held in bin A.\n", encoding="utf-8") + for args in ( + ["start", "--question", question], + ["add-source", "--url-or-path", source, "--tool", "local_read", + "--claims-json", '[{"text":"The sample is held in bin A.","stance":"supports"}]'], + ): + _run(sys.executable, ["--format", "json", "deepresearch", *args], tmp_path) + ledger = tmp_path / ".loopx/deepresearch/research.json" + before = ledger.read_bytes() + status = json.loads(_run(core_python, ["--format", "json", "deepresearch", "status"], tmp_path).stdout) + assert status["packet"]["question"] == question + assert status["packet"]["ledger_summary"]["sources"] == 1 + assert ledger.read_bytes() == before + _run(core_python, ["deepresearch", "resolve-question", "--question-id", "q1", + "--answer", "The sample is held in bin A.", "--evidence-claims", "c1"], tmp_path) + report = json.loads(_run(core_python, ["--format", "json", "deepresearch", "report"], tmp_path).stdout) + assert "inventory.txt" in Path(report["report_path"]).read_text(encoding="utf-8") + assert len(json.loads(ledger.read_bytes())["sources"]) == 1 diff --git a/tests/test_distribution_runtime_identity.py b/tests/test_distribution_runtime_identity.py index e18ad23ffb..a591b565e1 100644 --- a/tests/test_distribution_runtime_identity.py +++ b/tests/test_distribution_runtime_identity.py @@ -346,3 +346,49 @@ def _lookup(name: str): install_owner.WORKSPACE_DISTRIBUTION, ("loopx.chat_store",), builtin_cli_present=False, ) assert manifest.release_runtime_identity() == before + + +def test_core_research_companion_extends_and_fences_runtime_identity( + owned_package, monkeypatch: pytest.MonkeyPatch, +): + package, core_dist = owned_package + core_dist.name = "loopx-core" + distributions = {"loopx-core": core_dist} + + def lookup(name: str): + if name not in distributions: + raise manifest.PackageNotFoundError(name) + return distributions[name] + + monkeypatch.setattr(manifest, "distribution", lookup) + core_only = manifest.release_runtime_identity() + assert core_only["package_fingerprint"].startswith("sha256:") + + research_file = package / "cli_commands/deepresearch.py" + research_file.parent.mkdir(parents=True, exist_ok=True) + research_file.write_text("research = 1\n", encoding="utf-8") + research_item = SimpleNamespace( + as_posix=lambda: "loopx/cli_commands/deepresearch.py", + locate=lambda: research_file, + ) + research_dist = SimpleNamespace( + name="loopx-capability-research", + version=manifest.__version__, + files=[research_item], + read_text=lambda _name: None, + ) + distributions["loopx-capability-research"] = research_dist + with_research = manifest.release_runtime_identity() + assert with_research["package_fingerprint"].startswith("sha256:") + assert with_research["package_fingerprint"] != core_only["package_fingerprint"] + + research_dist.version = "0.0.0" + assert "package_fingerprint" not in manifest.release_runtime_identity() + + research_dist.version = manifest.__version__ + research_dist.read_text = lambda _name: json.dumps({"dir_info": {"editable": True}}) + assert "package_fingerprint" not in manifest.release_runtime_identity() + + research_dist.read_text = lambda _name: None + core_dist.files.append(research_item) + assert "package_fingerprint" not in manifest.release_runtime_identity()