diff --git a/.github/workflows/package-smoke.yml b/.github/workflows/package-smoke.yml index f278b7fc61..45b07dfe7d 100644 --- a/.github/workflows/package-smoke.yml +++ b/.github/workflows/package-smoke.yml @@ -5,7 +5,10 @@ on: paths: - ".github/workflows/package-smoke.yml" - "packages/**" + - "apps/presentation/dashboard/**" + - "scripts/chat_bundle.py" - "tests/test_core_distribution.py" + - "tests/test_core_workspace_distribution.py" - "tests/test_core_recall_distribution.py" - "tests/test_core_pr_review_distribution.py" - "tests/test_core_issue_fix_distribution.py" @@ -20,8 +23,11 @@ on: paths: - ".github/workflows/package-smoke.yml" - "packages/**" + - "apps/presentation/dashboard/**" + - "scripts/chat_bundle.py" - "loopx/**" - "tests/test_core_distribution.py" + - "tests/test_core_workspace_distribution.py" - "tests/test_core_recall_distribution.py" - "tests/test_core_pr_review_distribution.py" - "tests/test_core_issue_fix_distribution.py" @@ -119,6 +125,16 @@ jobs: LOOPX_STANDARD_TEST_WHEELHOUSE="$RUNNER_TEMP/core-dist" uv run --extra test python -m pytest -q \ tests/test_core_standard_distribution.py + - name: Build the matching Workspace wheel + run: | + uv run --extra test python scripts/chat_bundle.py build --install + uv run --extra test python packages/loopx-core/prepare.py --distribution loopx-workspace --output "$RUNNER_TEMP/workspace-source" + uv build --wheel "$RUNNER_TEMP/workspace-source" --out-dir "$RUNNER_TEMP/workspace-dist" + printf 'LOOPX_CORE_TEST_WHEEL=%s\n' "$RUNNER_TEMP"/core-dist/loopx_core-*.whl >> "$GITHUB_ENV" + printf 'LOOPX_WORKSPACE_TEST_WHEEL=%s\n' "$RUNNER_TEMP"/workspace-dist/loopx_workspace-*.whl >> "$GITHUB_ENV" + - name: Qualify Workspace readback and removal on File and SQLite + run: uv run --extra test python -m pytest -q tests/test_core_workspace_distribution.py + codex-provider-routing: name: loopx-codex-provider-routing runs-on: ubuntu-latest diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index d94d34903d..7a69a30b11 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -254,6 +254,25 @@ This is an installation layout. CLI handlers and host facilities inside provider distributions keep the existing `packages//` convention; the capability-package row does not require one capability per provider. +The local [Workspace wheel](../../../packages/loopx-workspace/README.md) adds +Chat, Dashboard and the existing endpoint manager to the same release of +`loopx-core`. It carries the verified browser bundle and opens the registry and +runtime used by Core. Launch is explicit. Core help and task execution leave +Workspace unloaded, and the Workspace loads the assessment executor on a +research analysis request. Package smoke exercises a checked Core task, +readback after installing and restarting Workspace, and Core replay after +removal on File and SQLite. The native App, IM and split public release still +have their own R2/M3 acceptance. + +Workspace carries the native Steward session, monitor and report adapters +and the managed Session calendar because they use its original conversation +store. These adapters reuse the Core command parsers and execution owners. +Standalone Core observes pending requests and results at Turn start +through the shared Inbox owner. Peers can request, adopt and return work +through that owner. Only returns to an original Workspace conversation use its +session store. Inbox read routes and receipts retain their scoped identities +when Workspace is added or removed. + Authority does not move: the kernel remains the only writer of Goal/Todo/claim/ lease/quota/effect state. A capability package may only register providers, capability contracts and CLI subcommands through `CapabilityRegistry`; it never 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 5d39b8c7c1..50dfc4502b 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -168,6 +168,19 @@ Host 承担记账;必要的权限、预算、不确定性与恢复决策仍在 可选 provider 发行物继续遵守 `packages//` 惯例;capability 包这一行不要求每个 provider 都创建一个 capability。 +[本地 Workspace wheel](../../../packages/loopx-workspace/README.md) 为同版本的 +`loopx-core` 加装 Chat、Dashboard 和已有的端点管理命令。它附带经过验证的浏览器资源, +并打开 Core 原先使用的 registry 和运行时状态。服务由用户显式启动。Core 帮助和任务执行 +不会加载 Workspace,工作区在收到研究分析请求时才加载评估执行器。打包验收覆盖 File +和 SQLite 上由 Core 完成并独立验收的任务、安装和重启 Workspace 后的读回,以及卸载后 +从 Core 重放原结果。原生 App、IM 和公开拆包发布仍需各自完成 R2/M3 验收。 + +管家的原生会话、监控和报告适配器,以及托管会话的日历,使用 Workspace 的原会话存储, +随 Workspace 发行,复用 Core 的命令解析和执行入口。独立 Core 在 Turn 开始时通过共用收件箱 +发现待处理的请求和结果。 +普通 Agent 通过同一实现提交、接受协作请求并回传结果。回传到 Workspace 原会话时才使用 +对应的会话存储。加装或卸载 Workspace 时,收件箱读取入口及回执继续沿用原有作用域和身份。 + 权威不移动:内核仍是 Goal/Todo/claim/lease/quota/effect 状态的唯一写者。capability 包只能通过 `CapabilityRegistry` 注册 provider、capability 契约和 CLI 子命令,绝不 import 内核私有模块。 ### 治理与运行时所有权 diff --git a/loopx/capabilities/manager_context/__init__.py b/loopx/capabilities/manager_context/__init__.py index 36335ad65c..060dee0218 100644 --- a/loopx/capabilities/manager_context/__init__.py +++ b/loopx/capabilities/manager_context/__init__.py @@ -6,9 +6,7 @@ from pathlib import Path import re -from ...command_invocation import loopx_cli_argv from ...file_lock import exclusive_file_lock -from ...install_contract import render_host_cli_command from ...control_plane.collaboration import conversation_scope from ...control_plane.collaboration.source_grant_observation import ( POLICY_SCHEMA as POLICY_SCHEMA, @@ -41,6 +39,8 @@ pending as pending, ) +from ...control_plane.collaboration.inbox_turn_start import turn_start_hook as turn_start_hook + INSTRUCTION = ( "Read this owner-supplied context before choosing work. Assess it against the current " "Goal, evidence, commitments and costs; honor explicit owner constraints and decide the plan. " @@ -227,95 +227,6 @@ def publication_plan(): } -def turn_start_hook( - runtime_root: Path, registry_path: Path, goal_id: str, agent_id: str, *, model_read: bool = False -): - from ...control_plane.capability_hooks import ( - TurnStartHookRegistration, - TURN_START_HOOK_RESULT_SCHEMA_VERSION, - ) - - snapshot = None - - def produce(): - nonlocal snapshot - try: - from ...control_plane.collaboration.inbox import read_inbox_transaction - from ...control_plane.collaboration.inbox import _pending_result - - with collaboration_goal_scope( - registry_path, goal_id=goal_id, agents=(agent_id,), - ) as goal_scope: - observed = read_inbox_transaction(runtime_root, { - "operation": "turn_start", "goal_id": goal_id, "agent_id": agent_id, - "read_command": command, - }, scope=goal_scope) - observed.update(goal_id=goal_id, agent_id=agent_id) - inbox = _pending_result(runtime_root, observed, goal_scope, None) - snapshot = observed["context"] - agenda = snapshot["unfinished_delegations"] - count = ( - max(len(inbox["items"]), agenda["incoming_count"]) - + max(len(inbox.get("peer_returns", {}).get("items", [])), agenda["outgoing_count"]) - + len(inbox.get("native_child_results", {}).get("items", [])) - + int(inbox.get("native_child_results", {}).get("unavailable_count", 0)) - + int(inbox.get("native_child_results", {}).get("scan_complete") is False) - + len(inbox.get("operation_handoffs", [])) - ) - incomplete = not agenda["scan_complete"] - count += int(incomplete) - status, error = ("observed" if count else "empty"), None - except (OSError, ValueError): - count, status, error = 0, "unavailable", "manager_context_unreadable" - return { - "schema_version": TURN_START_HOOK_RESULT_SCHEMA_VERSION, - "hook_id": "manager.context_inbox", - "capability_id": "manager-context", - "phase": "turn_start", - "status": status, - "observation_count": count, - "agent_read_required": count > 0, - "external_reads_performed": False, - "external_writes_performed": False, - "local_private_state_mutated": False, - "private_content_returned": False, - "provider_payload_returned": False, - "error_code": error, - } - - command = render_host_cli_command( - [ - *loopx_cli_argv(), - "--registry", - str(registry_path), - "--runtime-root", - str(runtime_root), - "manager-inbox", - "read", - "--attention-only", - *(["--format", "markdown"] if model_read else []), - "--goal-id", - goal_id, - "--agent-id", - agent_id, - ] - ) - return TurnStartHookRegistration( - hook_id="manager.context_inbox", - capability_id="manager-context", - requested_read_scope=("owner_private_context_inbox",), - requested_write_scope=(), - producer=produce, - context_reader=lambda: snapshot, - required_read={ - "kind": "operator_inbox", - "command": command, - "reason": "Review owner context and decide whether the current plan should change; no priority is imposed.", - "ordering": "before_work", - }, - ) - - def evidence_scope_readback(runtime_root: Path, channel: str, *, registry_path: Path | None = None) -> dict: """Observe this audience's typed read grant, separately from delivery. diff --git a/loopx/capabilities/manager_context/roundtrip.py b/loopx/capabilities/manager_context/roundtrip.py index 96a14a4225..ab841426f1 100644 --- a/loopx/capabilities/manager_context/roundtrip.py +++ b/loopx/capabilities/manager_context/roundtrip.py @@ -52,8 +52,6 @@ from ...control_plane.content_digest import BARE_SHA256_PATTERN from ...control_plane.collaboration.source_chat_observation import original_delivery_facts from ..native_chat.file_discovery import file_change_fingerprint -from ...chat import ChatMessagePayloadConflictError -from ...chat_store import TERMINAL_TURN_STATES class ReturnResolutionBlocked(ValueError, RuntimeError): """A return cannot be resolved; ``reason`` is the provider-neutral code. @@ -477,6 +475,8 @@ def project_chat_session_snapshot(root, store, session_id, *, registry, snapshot["report_message_id"] = report_message_id snapshot["active_turn"] = None elif turn is not None: + from ...chat_store import TERMINAL_TURN_STATES + status = turn["status"] snapshot["selected_turn"] = {"turn_id": turn_id, "status": status, "terminal": status in TERMINAL_TURN_STATES} error = turn.get("error") @@ -758,6 +758,8 @@ def __call__(self, attempt): def _deliver_return(host, path, sender, frozen_route): + from ...chat import ChatMessagePayloadConflictError + store, cancelled = host["store"], host["cancelled"] with _return_source(host, path, frozen_route) as facts: plan = _return_transaction(host, path, "prepare", {"facts": facts}) diff --git a/loopx/capabilities/native_chat/steward_commands.py b/loopx/capabilities/native_chat/steward_commands.py index 180ea6e08f..13bd8cb61b 100644 --- a/loopx/capabilities/native_chat/steward_commands.py +++ b/loopx/capabilities/native_chat/steward_commands.py @@ -98,13 +98,16 @@ def native_command(controller: Any, argv: list[str]) -> dict[str, Any]: {"ok": False, "error_code": error_code, "error": str(exc)} ) from exc - from ...cli import build_parser + if not argv or argv[0] not in {"quota", "todo", "task-lease"}: + raise ValueError("unsupported native steward operation") + + from ...cli_runtime import _build_selected_parser from ...cli_rollout import append_cli_rollout_event from ...cli_commands.quota import handle_quota_command from ...cli_commands.todo import handle_todo_command from ...cli_commands.task_lease import handle_task_lease_command - args = build_parser().parse_args(["--format", "json", *argv]) + args = _build_selected_parser(argv[0]).parse_args(["--format", "json", *argv]) code: int | None result: dict[str, Any] = {} kwargs: dict[str, Any] = {"registry_path": controller.registry_path, @@ -116,10 +119,8 @@ def native_command(controller: Any, argv: list[str]) -> dict[str, Any]: elif args.command == "quota": code = handle_quota_command(args, **kwargs, append_cli_rollout_event=append_cli_rollout_event) - elif args.command == "task-lease": - code = handle_task_lease_command(args, **kwargs, output_format=lambda *_a, **_kw: "json") else: - raise ValueError("unsupported native steward operation") + code = handle_task_lease_command(args, **kwargs, output_format=lambda *_a, **_kw: "json") if code or result.get("ok") is not True: raise NativeStewardCommandError(result) return result diff --git a/loopx/capabilities/native_chat/steward_monitor.py b/loopx/capabilities/native_chat/steward_monitor.py index 97d9a13120..0f51743929 100644 --- a/loopx/capabilities/native_chat/steward_monitor.py +++ b/loopx/capabilities/native_chat/steward_monitor.py @@ -274,7 +274,7 @@ def _commit_poll( def _native_poll(self, argv: Sequence[str]) -> dict[str, object]: """Use the native poll owner; a Chat observation is no heartbeat task.""" - from ...cli import build_parser + from ...cli_runtime import _build_selected_parser from ...cli_commands.lark_inbox import ( build_lark_operator_inbox_urgency_projector, ) @@ -285,7 +285,7 @@ def _native_poll(self, argv: Sequence[str]) -> dict[str, object]: from ...quota import record_quota_monitor_poll from ..explore.composition_frontier import project_live_explore_composition_frontier - args = build_parser().parse_args(["--format", "json", *argv]) + args = _build_selected_parser("quota").parse_args(["--format", "json", *argv]) admission = prepare_quota_command_context( args, registry_path=self.controller.registry_path, diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py index 37b5713be4..dd036ae051 100644 --- a/loopx/capabilities/native_chat/steward_turn.py +++ b/loopx/capabilities/native_chat/steward_turn.py @@ -931,7 +931,7 @@ def _settle_stopped_report_candidate( stopped_proof: dict[str, Any], raw_candidate: dict[str, Any], ) -> dict[str, Any]: - from ...cli import build_parser + from ...cli_runtime import _build_selected_parser from ...cli_commands.turn import handle_turn_command from ...control_plane.turn_driver import inspect_loopx_turn_journal from ..periodic_report.private_generation import validate_private_generation @@ -957,7 +957,7 @@ def _settle_stopped_report_candidate( "--turn-instance-id", saved_instance_id, "--todo-id", todo["todo_id"], "--execute"] if request.get("validation_command") is not None: argv += ["--validation-command-json", json.dumps(request["validation_command"])] - args = build_parser().parse_args(argv) + args = _build_selected_parser("turn").parse_args(argv) args.host, args.session_scope = "codex-app-server", "agent" result: dict[str, Any] = {} host_runner = self._build_replay_runner(_normalize_report_kernel_candidate(raw_candidate)) @@ -982,7 +982,7 @@ def recover_report_settlement(self, actor: dict[str, Any], window: dict[str, Any journal owner must authorize a no-host continuation; its existing effect readbacks reconcile ambiguous writeback/debit outcomes. """ - from ...cli import build_parser + from ...cli_runtime import _build_selected_parser from ...cli_commands.turn import handle_turn_command from ...control_plane.turn_driver import inspect_loopx_turn_journal from ...control_plane.turn_driver.journal_store import find_loopx_turn_key_by_settlement_identity @@ -1049,7 +1049,7 @@ def no_model(*_args): if contract_recovery is not None else no_model ) - args = build_parser().parse_args(["turn", "run-once", "--goal-id", actor["goal_id"], + args = _build_selected_parser("turn").parse_args(["turn", "run-once", "--goal-id", actor["goal_id"], "--agent-id", actor["agent_id"], "--project", admitted["workspace_path"], "--host", "generic-cli", "--resume-turn-key", key, "--retry-failed-turn", "--execute"]) args.host, args.session_scope = "codex-app-server", "agent" @@ -1318,7 +1318,7 @@ def _steward_followup_context(self, actor: Mapping[str, Any], session_id: str, def _governance_replan_context(self, actor: Mapping[str, Any], authority: Mapping[str, Any]) -> dict[str, Any]: """Project public-safe review/writeback/vision context for text-only Steward replanning.""" - from ...cli import build_parser + from ...cli_runtime import _build_selected_parser from ...cli_commands.quota_native_context import read_replan_view from ...control_plane.goals.goal_frontier import latest_agent_vision_from_status_payload from ...control_plane.todos.list_readback import list_goal_todos @@ -1340,7 +1340,7 @@ def _read_stage(cmd_str: Any) -> dict[str, Any] | None: try: tokens = shlex.split(cmd_str) q_idx = tokens.index("quota") - parsed = build_parser().parse_args(tokens[q_idx:]) + parsed = _build_selected_parser("quota").parse_args(tokens[q_idx:]) view = read_replan_view(parsed) if isinstance(view, Mapping) and view.get("ok") is True: return dict(view) @@ -1502,7 +1502,7 @@ def _apply_steward_user_actions(self, actor: Mapping[str, Any], actions: Sequenc def execute(self, *, session_id: str, turn_id: str, adapter: Any, event_sink: Any, context: dict[str, Any]) -> dict[str, Any]: """Run in the original Chat worker, through all native settlement owners.""" - from ...cli import build_parser + from ...cli_runtime import _build_selected_parser from ...cli_commands.turn import handle_turn_command from ...control_plane.turn_driver.host_candidate import extract_turn_authority, render_prompt, parse_model_json, build_result from .antigravity_adapter import AntigravityAdapter @@ -1795,7 +1795,7 @@ def launch(): argv += ["--todo-id", request["todo_id"]] if request["validation_command"] is not None: argv += ["--validation-command-json", json.dumps(request["validation_command"])] - args = build_parser().parse_args(argv) + args = _build_selected_parser("turn").parse_args(argv) # This connection is host-owned, not a command path supplied by a model. # The kernel records the actual app-server host and independent profile. args.host, args.session_scope = "codex-app-server", "agent" diff --git a/loopx/chat/action_normalization.py b/loopx/chat/action_normalization.py index 3d0f1fa8f6..cc3fd73ce5 100644 --- a/loopx/chat/action_normalization.py +++ b/loopx/chat/action_normalization.py @@ -7,7 +7,7 @@ from typing import Any, Mapping from ..agent_registry import registered_agent_ids_for_goal -from ..capabilities.issue_fix.repository_snapshot import _REPO_PATTERN +from ..capabilities.issue_fix.github_public import _REPO_PATTERN from ..control_plane.content_digest import BARE_SHA256_PATTERN from ..control_plane.runtime.time import now_utc, parse_timestamp, utc_isoformat from ..control_plane.todos.contract import require_supported_todo_resume_when diff --git a/loopx/chat/todo_action_contracts.py b/loopx/chat/todo_action_contracts.py index b4f0822652..e9e08aecd6 100644 --- a/loopx/chat/todo_action_contracts.py +++ b/loopx/chat/todo_action_contracts.py @@ -8,7 +8,7 @@ from typing import NoReturn, Protocol, runtime_checkable from ..chat_store import TERMINAL_TURN_STATES -from .action_store_common import is_str_dict, require_str_dict +from ..control_plane.collaboration.action_store_common import is_str_dict, require_str_dict CANONICAL_UPDATE_BASIS_SCHEMA_VERSION = "loopx_chat_canonical_update_basis_v0" CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION = "loopx_chat_canonical_terminal_basis_v0" diff --git a/loopx/chat/todo_action_create.py b/loopx/chat/todo_action_create.py index 20b38eb977..76bb64e76b 100644 --- a/loopx/chat/todo_action_create.py +++ b/loopx/chat/todo_action_create.py @@ -11,7 +11,7 @@ read_canonical_todos_if_promoted, ) from ..control_plane.todos.mutation_api import update_goal_todo -from .action_store_common import _opaque_id, is_str_dict, require_str_dict +from ..control_plane.collaboration.action_store_common import _opaque_id, is_str_dict, require_str_dict from .todo_action_contracts import ( ChatTodoActionHost, as_optional_str, diff --git a/loopx/chat/todo_action_tasks.py b/loopx/chat/todo_action_tasks.py index f1ed833e1f..0df6788d1e 100644 --- a/loopx/chat/todo_action_tasks.py +++ b/loopx/chat/todo_action_tasks.py @@ -15,7 +15,7 @@ from ..control_plane.todos.mutation_api import update_goal_todo from ..control_plane.work_items.task_lease import lease_is_active from ..file_lock import exclusive_cross_runtime_file_lock -from .action_store_common import _opaque_id, is_str_dict, require_str_dict +from ..control_plane.collaboration.action_store_common import _opaque_id, is_str_dict, require_str_dict from .todo_action_contracts import ( ChatTodoActionHost, GoalCommitSubmitController, diff --git a/loopx/chat/todo_action_updates.py b/loopx/chat/todo_action_updates.py index 19b2e75226..51b60b6905 100644 --- a/loopx/chat/todo_action_updates.py +++ b/loopx/chat/todo_action_updates.py @@ -11,7 +11,13 @@ from ..control_plane.todos.completion_validation import COMPLETION_VALIDATION_IN_PROGRESS from ..control_plane.todos.mutation_api import complete_goal_todo, update_goal_todo from ..control_plane.todos.provider_projection import projection_delivery_requires_ack -from .action_store_common import ActionConflictError, _canonical_digest, _opaque_id, is_str_dict, require_str_dict +from ..control_plane.collaboration.action_store_common import ( + ActionConflictError, + _canonical_digest, + _opaque_id, + is_str_dict, + require_str_dict, +) from .todo_action_contracts import ( CANONICAL_TERMINAL_BASIS_SCHEMA_VERSION, CANONICAL_UPDATE_BASIS_SCHEMA_VERSION, diff --git a/loopx/chat_action_store.py b/loopx/chat_action_store.py index 0305686bc5..9a71d28469 100644 --- a/loopx/chat_action_store.py +++ b/loopx/chat_action_store.py @@ -8,10 +8,10 @@ from pathlib import Path import uuid -from .chat import action_store_common as _common -from .chat import action_store_operations as _operations -from .chat import action_store_review_cards as _review_cards -from .chat.action_store_common import ( +from .control_plane.collaboration import action_store_common as _common +from .control_plane.collaboration import action_store_operations as _operations +from .control_plane.collaboration import action_store_review_cards as _review_cards +from .control_plane.collaboration.action_store_common import ( AUTHENTICATED_LARK_CARD_CALLBACK, CHAT_ACTION_PROPOSAL_SCHEMA_VERSION, CHAT_ACTION_STORE_SCHEMA_VERSION, diff --git a/loopx/chat_store.py b/loopx/chat_store.py index 4530e44993..c3c42ac5d8 100644 --- a/loopx/chat_store.py +++ b/loopx/chat_store.py @@ -10,7 +10,6 @@ import json import os from pathlib import Path -import re import threading from typing import Any, Iterator import uuid @@ -37,12 +36,16 @@ AcceptedManagedTurn, plan_managed_turn_acceptance, ) +from .control_plane.collaboration.source_chat_observation import ( + CHAT_SESSION_SCHEMA_VERSION, + CHAT_TURN_SCHEMA_VERSION, + _opaque_id, + _read_json, +) from .file_lock import exclusive_file_lock, try_exclusive_file_lock, write_json_atomic CHAT_STORE_SCHEMA_VERSION = "loopx_chat_store_v1" -CHAT_SESSION_SCHEMA_VERSION = "loopx_chat_session_state_v1" -CHAT_TURN_SCHEMA_VERSION = "loopx_chat_turn_state_v1" CHAT_EVENT_SCHEMA_VERSION = "loopx_chat_event_v1" CHAT_MESSAGE_SCHEMA_VERSION = "loopx_chat_message_v1" CHAT_INGRESS_SCHEMA_VERSION = "loopx_chat_ingress_receipt_v1" @@ -54,7 +57,6 @@ TERMINAL_EVENT_KINDS = {"turn.completed", "turn.failed", "turn.interrupted"} REPLAY_ONLY_EVENT_KINDS = {"answer.delta", "assistant.delta", "agent.phase", "turn.activity"} -_OPAQUE_ID = re.compile(r"^[A-Za-z0-9._-]{1,160}$") _SESSION_RELEASE_UNSET = object() # Keep active steward and project conversation journals warm across multi-MB image histories. @@ -74,13 +76,6 @@ def _instant(value: Any) -> datetime | None: return None -def _opaque_id(value: Any, *, field: str) -> str: - token = str(value or "").strip() - if not _OPAQUE_ID.fullmatch(token): - raise ValueError(f"{field} must be a compact opaque id") - return token - - def _upstream_id(value: Any) -> str: token = str(value or "").strip() if not token or len(token) > 1024 or any(ord(character) < 32 for character in token): @@ -88,14 +83,6 @@ def _upstream_id(value: Any) -> str: return token -def _read_json(path: Path) -> dict[str, Any]: - try: - payload = json.loads(path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return {} - return payload if isinstance(payload, dict) else {} - - def _read_jsonl( path: Path, *, raise_on_error: bool = False, strict: bool = False, ) -> list[dict[str, Any]]: diff --git a/loopx/cli_commands/manager_inbox.py b/loopx/cli_commands/manager_inbox.py index 2d191e97a3..2deb0ff458 100644 --- a/loopx/cli_commands/manager_inbox.py +++ b/loopx/cli_commands/manager_inbox.py @@ -4,12 +4,7 @@ import os from pathlib import Path from ..agent_registry import registered_agent_ids_for_goal -from ..capabilities.manager_context import ( - acknowledge, - configure_delivery_target, - configure_delivery_scope, - configure_evidence_scope, -) +from ..control_plane.collaboration.inbox import acknowledge from ..control_plane.projects.registry_codec import load_project_registry from ..control_plane.collaboration.peers import InboxReadResponseAmbiguous from ..presentation.answer_instruction import collaboration_answer_instruction @@ -346,6 +341,8 @@ def handle_manager_inbox(args, registry_path, runtime_root): if args.manager_inbox_action != "configure-delivery-scope" and (local_delivery_scope is not None or sender_id is not None): raise ValueError("--local-delivery-scope and --sender-id are only supported for configure-delivery-scope") if args.manager_inbox_action == "configure-delivery-scope": + from ..capabilities.manager_context import configure_delivery_scope + result = configure_delivery_scope(runtime_root, channel=args.channel_id or "", local_delivery_scope=local_delivery_scope or "", sender_id=sender_id, execute=args.execute) @@ -376,6 +373,8 @@ def handle_manager_inbox(args, registry_path, runtime_root): print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 if args.manager_inbox_action == "configure-read-scope": + from ..capabilities.manager_context import configure_evidence_scope + result = configure_evidence_scope( runtime_root, registry_path, @@ -387,6 +386,8 @@ def handle_manager_inbox(args, registry_path, runtime_root): print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 if args.manager_inbox_action in {"grant-delivery-target", "revoke-delivery-target"}: + from ..capabilities.manager_context import configure_delivery_target + result = configure_delivery_target( runtime_root, registry_path, diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index 582d8cc188..2418cf90c8 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -90,7 +90,7 @@ def dispatch_quota_turn_start_hooks( from ..capabilities.decision_context.turn_start_hook import ( extend_turn_start_dispatch as extend_decision_context, ) - from ..capabilities.manager_context import turn_start_hook + from ..control_plane.collaboration.inbox_turn_start import turn_start_hook from ..capabilities.semantic_preference.agent_preferences import ( extend_turn_start_dispatch as extend_preferences, ) diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index ec485f3e31..fd39807cc9 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -81,6 +81,7 @@ } # Existing CLI vocabulary; this set chooses loading, not operation authority. _CAPABILITY_DISCOVERY_COMMANDS = frozenset({"list", "show"}) +_WORKSPACE_COMMANDS = frozenset({"chat", "chat-endpoint", "dashboard"}) class LoopXArgumentParser(argparse.ArgumentParser): @@ -773,14 +774,14 @@ def _dispatch_common_command( build_command_reference_payload, render_command_reference_markdown, ) - print_payload( - build_command_reference_payload( - available_commands=( - _available_selected_commands() if _standalone_core() else None - ), - ), output_format(args), - render_command_reference_markdown, - ) + available_commands: frozenset[str] | None = None + if _standalone_core(): + selected = set(_available_selected_commands()) + if _workspace_installed(): + selected |= _WORKSPACE_COMMANDS + available_commands = frozenset(selected) + print_payload(build_command_reference_payload(available_commands=available_commands), + output_format(args), render_command_reference_markdown) return 0 if args.command == "delegation": from .cli_commands.delegation import handle_delegation @@ -1015,6 +1016,14 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: args, registry_path=registry_path, output_format=output_format, print_payload=print_payload, runtime_root=effective_runtime_root(registry_path, args.runtime_root) if registry_path.exists() else None, ) + elif args.command in _WORKSPACE_COMMANDS: + from .cli_commands.support_control import handle_support_control_command + + result = handle_support_control_command( + args, registry_path=registry_path, + registry_was_supplied=user_supplied_registry(raw_argv), + print_payload=print_payload, output_format=output_format, + ) else: result = dispatch_common_command( args, @@ -1062,6 +1071,39 @@ def _standalone_core() -> bool: return False +def _workspace_installed() -> bool: + from .python_install_owner import WORKSPACE_DISTRIBUTION, builtin_capability_installed + + return builtin_capability_installed( + WORKSPACE_DISTRIBUTION, + ( + "loopx.chat", + "loopx.chat_loopx_mode", + "loopx.chat_manager", + "loopx.chat_runtime", + "loopx.chat_server", + "loopx.chat_store", + "loopx.dashboard_launcher", + "loopx.cli_commands.support_control_chat", + "loopx.cli_commands.support_control_chat_endpoint", + "loopx.capabilities.native_chat.session_calendar_tasks", + "loopx.capabilities.native_chat.steward_managed_mode", + "loopx.capabilities.native_chat.steward_monitor", + "loopx.capabilities.native_chat.steward_reports", + "loopx.capabilities.native_chat.steward_turn", + "loopx.extensions.lark.steward_reports", + "loopx.presentation.research_analysis_api", + "loopx.presentation.runtime_workspace", + ), + builtin_cli_present=False, + resources=( + "loopx/chat/endpoints.py", + "loopx/chat/lark_api.py", + "loopx/control_plane/collaboration/steward_reports.ts", + ), + ) + + def _run_full_cli(raw_argv: list[str]) -> int: try: from .cli import main as cli_main @@ -1086,8 +1128,9 @@ def main(argv: list[str] | None = None) -> int: from .help_surface import render_concise_help, top_level_help_requested if top_level_help_requested(raw_argv): + standalone = _standalone_core() print(render_concise_help(sys.argv[0] if argv is None else "loopx", - standalone_core=_standalone_core()), end="") + standalone_core=standalone, workspace_installed=standalone and _workspace_installed()), end="") return 0 command = _top_level_command(raw_argv) if command is None and _standalone_core(): @@ -1138,6 +1181,17 @@ 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 _WORKSPACE_COMMANDS and _standalone_core(): + parser, subparsers = build_cli_parser() + if not _workspace_installed(): + parser.error( + "this command is unavailable in the standalone core; " + "install the matching loopx-workspace wheel in this environment" + ) + from .cli_commands.support_control_chat import register_chat_and_dashboard_commands + + register_chat_and_dashboard_commands(subparsers, add_subcommand_format) + return _dispatch_selected(parse_cli_args(parser, raw_argv), raw_argv) if command == "version": version_exports = sys.modules.get("loopx.cli_commands") # Inspect bound exports without triggering the lazy facade. Explicit diff --git a/loopx/chat/action_store_common.py b/loopx/control_plane/collaboration/action_store_common.py similarity index 99% rename from loopx/chat/action_store_common.py rename to loopx/control_plane/collaboration/action_store_common.py index 57f6e3e304..9feac3583a 100644 --- a/loopx/chat/action_store_common.py +++ b/loopx/control_plane/collaboration/action_store_common.py @@ -12,7 +12,7 @@ import re from typing import Protocol, TypeAlias, TypeGuard -from ..public_safe_text import OPAQUE_ID_PATTERN as _OPAQUE_ID +from ...public_safe_text import OPAQUE_ID_PATTERN as _OPAQUE_ID JsonPrimitive: TypeAlias = None | bool | int | float | str JsonValue: TypeAlias = JsonPrimitive | list["JsonValue"] | dict[str, "JsonValue"] @@ -239,7 +239,7 @@ def parse_utc_timestamp(value: object, *, error: str) -> datetime: def current_utc_now() -> str: """Read `_utc_now` through `loopx.chat_action_store` so monkeypatches apply.""" - from .. import chat_action_store as facade + from ... import chat_action_store as facade return facade._utc_now() @@ -252,7 +252,7 @@ def store_lock( agent_id: str | None = "loopx-chat", ) -> Iterator[Path]: """Acquire `exclusive_file_lock` through `loopx.chat_action_store`.""" - from .. import chat_action_store as facade + from ... import chat_action_store as facade if agent_id is None: with facade.exclusive_file_lock(path, operation=operation) as locked: diff --git a/loopx/chat/action_store_operations.py b/loopx/control_plane/collaboration/action_store_operations.py similarity index 99% rename from loopx/chat/action_store_operations.py rename to loopx/control_plane/collaboration/action_store_operations.py index f2a7ce4c54..8b851d3ac3 100644 --- a/loopx/chat/action_store_operations.py +++ b/loopx/control_plane/collaboration/action_store_operations.py @@ -325,7 +325,7 @@ def agent_operation_plan( proposal: Mapping[str, object], **request: object ) -> JsonDict: """One typed decision, using the existing canonical JSON byte format.""" - from ..control_plane.effect_runtime import ( + from ..effect_runtime import ( EffectRuntimeRemoteError, effect_runtime_result, ) diff --git a/loopx/chat/action_store_review_cards.py b/loopx/control_plane/collaboration/action_store_review_cards.py similarity index 100% rename from loopx/chat/action_store_review_cards.py rename to loopx/control_plane/collaboration/action_store_review_cards.py diff --git a/loopx/control_plane/collaboration/inbox_turn_start.py b/loopx/control_plane/collaboration/inbox_turn_start.py new file mode 100644 index 0000000000..3283d350b9 --- /dev/null +++ b/loopx/control_plane/collaboration/inbox_turn_start.py @@ -0,0 +1,99 @@ +"""Turn-start observation of an Agent's durable Inbox.""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from ...command_invocation import loopx_cli_argv +from ...install_contract import render_host_cli_command +from .goal_instance_scope import collaboration_goal_scope + +if TYPE_CHECKING: + from ..capability_hooks import TurnStartHookRegistration + + +def turn_start_hook( + runtime_root: Path, registry_path: Path, goal_id: str, agent_id: str, *, model_read: bool = False +) -> TurnStartHookRegistration: + """Observe scoped pending work using the original Inbox operation and route.""" + from ..capability_hooks import TURN_START_HOOK_RESULT_SCHEMA_VERSION, TurnStartHookRegistration + + snapshot = None + + def produce(): + nonlocal snapshot + try: + from .inbox import _pending_result, read_inbox_transaction + + with collaboration_goal_scope( + registry_path, goal_id=goal_id, agents=(agent_id,), + ) as goal_scope: + observed = read_inbox_transaction(runtime_root, { + "operation": "turn_start", "goal_id": goal_id, "agent_id": agent_id, + "read_command": command, + }, scope=goal_scope) + observed.update(goal_id=goal_id, agent_id=agent_id) + inbox = _pending_result(runtime_root, observed, goal_scope, None) + snapshot = observed["context"] + agenda = snapshot["unfinished_delegations"] + count = ( + max(len(inbox["items"]), agenda["incoming_count"]) + + max(len(inbox.get("peer_returns", {}).get("items", [])), agenda["outgoing_count"]) + + len(inbox.get("native_child_results", {}).get("items", [])) + + int(inbox.get("native_child_results", {}).get("unavailable_count", 0)) + + int(inbox.get("native_child_results", {}).get("scan_complete") is False) + + len(inbox.get("operation_handoffs", [])) + ) + incomplete = not agenda["scan_complete"] + count += int(incomplete) + status, error = ("observed" if count else "empty"), None + except (OSError, ValueError): + count, status, error = 0, "unavailable", "manager_context_unreadable" + return { + "schema_version": TURN_START_HOOK_RESULT_SCHEMA_VERSION, + "hook_id": "manager.context_inbox", + "capability_id": "manager-context", + "phase": "turn_start", + "status": status, + "observation_count": count, + "agent_read_required": count > 0, + "external_reads_performed": False, + "external_writes_performed": False, + "local_private_state_mutated": False, + "private_content_returned": False, + "provider_payload_returned": False, + "error_code": error, + } + + command = render_host_cli_command( + [ + *loopx_cli_argv(), + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "manager-inbox", + "read", + "--attention-only", + *(["--format", "markdown"] if model_read else []), + "--goal-id", + goal_id, + "--agent-id", + agent_id, + ] + ) + return TurnStartHookRegistration( + hook_id="manager.context_inbox", + capability_id="manager-context", + requested_read_scope=("owner_private_context_inbox",), + requested_write_scope=(), + producer=produce, + context_reader=lambda: snapshot, + required_read={ + "kind": "operator_inbox", + "command": command, + "reason": "Review owner context and decide whether the current plan should change; no priority is imposed.", + "ordering": "before_work", + }, + ) diff --git a/loopx/control_plane/collaboration/source_chat_observation.py b/loopx/control_plane/collaboration/source_chat_observation.py index 8dff1ce0db..a4a11a3915 100644 --- a/loopx/control_plane/collaboration/source_chat_observation.py +++ b/loopx/control_plane/collaboration/source_chat_observation.py @@ -4,13 +4,36 @@ with their existing typed owners. No model or peer supplies this address. """ +from __future__ import annotations + from collections.abc import Callable +import json from pathlib import Path -from typing import Any +import re +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from ...chat_store import ChatSessionStore + + +CHAT_SESSION_SCHEMA_VERSION = "loopx_chat_session_state_v1" +CHAT_TURN_SCHEMA_VERSION = "loopx_chat_turn_state_v1" +_OPAQUE_ID = re.compile(r"^[A-Za-z0-9._-]{1,160}$") + + +def _opaque_id(value: Any, *, field: str) -> str: + token = str(value or "").strip() + if not _OPAQUE_ID.fullmatch(token): + raise ValueError(f"{field} must be a compact opaque id") + return token + -from ...chat_store import ( - CHAT_SESSION_SCHEMA_VERSION, CHAT_TURN_SCHEMA_VERSION, ChatSessionStore, _opaque_id, _read_json, -) +def _read_json(path: Path) -> dict[str, Any]: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return payload if isinstance(payload, dict) else {} def _source_chat_root(coordination_root: Path, route: dict[str, Any]) -> Path: diff --git a/loopx/help_surface.py b/loopx/help_surface.py index 26d7a0bc0e..b762a0e029 100644 --- a/loopx/help_surface.py +++ b/loopx/help_surface.py @@ -467,9 +467,12 @@ def top_level_help_requested(argv: list[str]) -> bool: return True -def render_concise_help(program: str = "loopx", *, standalone_core: bool = False) -> str: +def render_concise_help( + program: str = "loopx", *, standalone_core: bool = False, workspace_installed: bool = False, +) -> str: program = _program_name(program) if standalone_core: + workspace = [" loopx dashboard Open the local workspace."] if workspace_installed else [] return "\n".join([ "LoopX keeps long-running agent work moving with durable state and evidence.", "", "Usage:", f" {program} [global options] [command options]", @@ -484,6 +487,7 @@ def render_concise_help(program: str = "loopx", *, standalone_core: bool = False " loopx turn inspect-journal --help", " Inspect an original attempt before resuming it.", " loopx status Read current work and its next action.", + *workspace, " loopx doctor --installation-only", " Check this installation.", "", "Global options: --registry PATH --runtime-root PATH --format markdown|json --cli-bin PROGRAM", diff --git a/loopx/presentation/research_analysis_api.py b/loopx/presentation/research_analysis_api.py index 665b0af98d..1294c25704 100644 --- a/loopx/presentation/research_analysis_api.py +++ b/loopx/presentation/research_analysis_api.py @@ -4,17 +4,32 @@ reads and disconnected clients do not create or retry jobs; cancellation still belongs to the provider. There is no second scheduler or assessment authority. """ +from importlib import import_module from urllib.parse import parse_qs, urlparse -from ..capabilities.benchmark_toolkit import trajectory_assessment_store as store from ..feedback import validate_goal_id from ..control_plane.effect_runtime import EffectRuntimeRejected from .goal_source_routing import goal_source_catalog, linked_goal_source RESEARCH_ANALYSIS_PATH = "/api/chat/research-analysis" +_ASSESSMENT_PACKAGE = "loopx.capabilities.benchmark_toolkit" +_ASSESSMENT_STORE = f"{_ASSESSMENT_PACKAGE}.trajectory_assessment_store" class ResearchAnalysisRequestMixin: + def _research_analysis_store(self): + try: + return import_module(_ASSESSMENT_STORE) + except ModuleNotFoundError as exc: + if exc.name not in {_ASSESSMENT_PACKAGE, _ASSESSMENT_STORE}: + raise + self._send_error( + "Research analysis needs the Benchmark Toolkit. Use an installation that includes it.", + status=503, + error_code="research_analysis_unavailable", + ) + return None + def _research_analysis_owner_goal(self, goal_id): linked = linked_goal_source(self.server, goal_id) return linked[1].source.goal_id if linked is not None else goal_id @@ -31,7 +46,7 @@ def _research_analysis_query(self, goal_id=None): raise ValueError("Analysis source identity changed") return query - def _research_analysis_verify_source_goal(self, runtime, goal_id, pack_id, pack=None): + def _research_analysis_verify_source_goal(self, runtime, goal_id, pack_id, pack=None, *, store): linked = linked_goal_source(self.server, goal_id) if getattr(self.server, "analysis_source_namespace", None) is not None or linked is not None: owner_goal_id = self._research_analysis_owner_goal(goal_id) @@ -66,6 +81,7 @@ def _research_analysis_scope(self, goal_id, *, cancel=False): return self._goal_result_scope(goal_id) def _research_analysis_read(self): + store = None try: query = self._research_analysis_query() usage_turn = urlparse(self.path).path.endswith("/usage-turn") @@ -84,6 +100,9 @@ def _research_analysis_read(self): runtime = self._research_analysis_scope(goal_id) if runtime is None: return + store = self._research_analysis_store() + if store is None: + return owner_goal_id = self._research_analysis_owner_goal(goal_id) if "compare_pack_id" in values: if "pack_id" not in values: @@ -92,15 +111,15 @@ def _research_analysis_read(self): pack_id=values["pack_id"], output_language=language) right = store.inspect_pack(runtime_root=runtime, owner_goal_id=owner_goal_id, pack_id=values["compare_pack_id"], output_language=language) - self._research_analysis_verify_source_goal(runtime, goal_id, values["pack_id"], left) - self._research_analysis_verify_source_goal(runtime, goal_id, values["compare_pack_id"], right) + self._research_analysis_verify_source_goal(runtime, goal_id, values["pack_id"], left, store=store) + self._research_analysis_verify_source_goal(runtime, goal_id, values["compare_pack_id"], right, store=store) result = {"ok": True, "comparison": store.compare_captured_usage(left, right)} elif usage_turn: - self._research_analysis_verify_source_goal(runtime, goal_id, values["pack_id"]) + self._research_analysis_verify_source_goal(runtime, goal_id, values["pack_id"], store=store) result = store.read_usage_turn(runtime_root=runtime, owner_goal_id=owner_goal_id, output_language=language, **values) elif citation: - self._research_analysis_verify_source_goal(runtime, goal_id, values["pack_id"]) + self._research_analysis_verify_source_goal(runtime, goal_id, values["pack_id"], store=store) first = int(values.pop("first_line")) last = int(values.pop("last_line")) if first < 1 or last < first: @@ -115,21 +134,23 @@ def _research_analysis_read(self): output_language=language, include_native_outcome_samples=True, ) if pack_id else None if pack_id: - self._research_analysis_verify_source_goal(runtime, goal_id, pack_id, pack) + self._research_analysis_verify_source_goal(runtime, goal_id, pack_id, pack, store=store) result = {"ok": True, "catalog": catalog, "pack": pack} if hasattr(self.server, "analysis_execution_enabled"): result["execution_enabled"] = self.server.analysis_execution_enabled elif linked_goal_source(self.server, goal_id) is not None: result["execution_enabled"] = True self._send_json(result) - except store.PackUnavailable as exc: - self._send_error("The registered analysis source is unavailable.", status=409, error_code=exc.reason_code) - except (ValueError, TypeError, KeyError, EffectRuntimeRejected): - self._send_error("Analysis needs a registered source in this Goal.", status=400, error_code="research_analysis_scope_invalid") + except (ValueError, TypeError, KeyError, EffectRuntimeRejected) as exc: + if store is not None and isinstance(exc, store.PackUnavailable): + self._send_error("The registered analysis source is unavailable.", status=409, error_code=exc.reason_code) + else: + self._send_error("Analysis needs a registered source in this Goal.", status=400, error_code="research_analysis_scope_invalid") except (OSError, RuntimeError): self._send_error("Analysis could not be read. Research history remains available.", status=503, error_code="research_analysis_unavailable") def _research_analysis_write(self): + store = None try: if getattr(self.server, "analysis_source_namespace", None) is not None and self._research_analysis_query(): raise ValueError("Only the bound analysis source selector is accepted") @@ -151,17 +172,21 @@ def _research_analysis_write(self): runtime = self._research_analysis_scope(body["goal_id"], cancel=cancel) if runtime is None: return + store = self._research_analysis_store() + if store is None: + return args = dict(runtime_root=runtime, owner_goal_id=self._research_analysis_owner_goal(body["goal_id"]), pack_id=body["pack_id"], analysis_key=body["analysis_key"], output_language=body.get("output_language")) - self._research_analysis_verify_source_goal(runtime, body["goal_id"], body["pack_id"]) + self._research_analysis_verify_source_goal(runtime, body["goal_id"], body["pack_id"], store=store) # The server's existing threaded request is the asynchronous host. # Provider key/claim, source verification and cancellation # remain with benchmark-toolkit; nothing executes on GET. job = store.cancel_pack(**args) if cancel else store.execute_pack(**args, retry=body.get("retry", False)) self._send_json({"ok": True, "job": job}) - except store.PackUnavailable as exc: - self._send_error("Analysis source changed or is unavailable; refresh before retrying.", status=409, error_code=exc.reason_code) - except (ValueError, TypeError, KeyError, EffectRuntimeRejected): - self._send_error("Analysis request was not accepted. Refresh its source and retry.", status=400, error_code="research_analysis_request_invalid") + except (ValueError, TypeError, KeyError, EffectRuntimeRejected) as exc: + if store is not None and isinstance(exc, store.PackUnavailable): + self._send_error("Analysis source changed or is unavailable; refresh before retrying.", status=409, error_code=exc.reason_code) + else: + self._send_error("Analysis request was not accepted. Refresh its source and retry.", status=400, error_code="research_analysis_request_invalid") except (OSError, RuntimeError): self._send_error("Analysis did not complete. Read its status before retrying.", status=503, error_code="research_analysis_unavailable") diff --git a/loopx/python_install_owner.py b/loopx/python_install_owner.py index c70ac9a8a0..727430db2b 100644 --- a/loopx/python_install_owner.py +++ b/loopx/python_install_owner.py @@ -7,6 +7,7 @@ from __future__ import annotations +import csv from dataclasses import dataclass from collections.abc import Callable from importlib.metadata import Distribution, PackageNotFoundError, PackagePath, distribution @@ -49,13 +50,60 @@ def verified_distribution_console(recorded: Path) -> Path | None: return None +def is_distribution_artifact(path: Path) -> bool: + """Whether a recorded package path is an installed runtime artifact rather than bytecode.""" + return "__pycache__" not in path.parts and path.suffix not in {".pyc", ".pyo"} + + +def distribution_recorded_files(installed: Distribution) -> list[tuple[str, Path]] | None: + """Read raw wheel RECORD entries without filtering deleted files on disk.""" + try: + record_text = installed.read_text("RECORD") + except (OSError, ValueError): + return None + if record_text is None: + if installed.files is None: + return None + return [ + ( + item.as_posix(), + distribution_record_path(item) + if isinstance(item, PackagePath) + else Path(item.locate()), + ) + for item in installed.files + ] + try: + rows = list(csv.reader(record_text.splitlines())) + except csv.Error: + return None + entries: list[tuple[str, Path]] = [] + for row in rows: + if not row or not row[0]: + continue + item = PackagePath(row[0]) + item.dist = installed + entries.append((item.as_posix(), distribution_record_path(item))) + return entries + + 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.""" + 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 @@ -63,23 +111,37 @@ def builtin_capability_installed( ] if len(origins) != len(modules): return False - if builtin_cli_present is None: - builtin_cli_present = find_spec("loopx.cli") is not None if builtin_cli_present: return True - try: - implementation = distribution(distribution_name) - if implementation.version != distribution("loopx-core").version: - return False - except PackageNotFoundError: + package_parent = Path(__file__).resolve().parent.parent + entries = distribution_recorded_files(implementation) + if entries is None: return False - recorded = { - distribution_record_path(path).resolve() - for path in implementation.files or () - } - return all(origin in recorded for origin in origins) + 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 + ) + ) +WORKSPACE_DISTRIBUTION = "loopx-workspace" @dataclass(frozen=True) class PythonInstallOwner: manager: str diff --git a/loopx/release_manifest.py b/loopx/release_manifest.py index fe3b46fd0c..61130230c7 100644 --- a/loopx/release_manifest.py +++ b/loopx/release_manifest.py @@ -1,7 +1,7 @@ from __future__ import annotations from datetime import datetime, timezone -from importlib.metadata import Distribution, PackageNotFoundError, PackagePath, distribution +from importlib.metadata import Distribution, PackageNotFoundError, distribution import hashlib import json import os @@ -10,7 +10,12 @@ from . import __version__ from .doctor_git import GitSourceState, git_source_metadata -from .python_install_owner import distribution_record_path, installed_loopx_distribution +from .python_install_owner import ( + WORKSPACE_DISTRIBUTION, + distribution_recorded_files, + installed_loopx_distribution, + is_distribution_artifact, +) RELEASE_MANIFEST_SCHEMA_VERSION = "loopx_release_manifest_v0" @@ -307,30 +312,24 @@ def release_runtime_identity(release_root: Path | None = None) -> dict[str, str _CORE_COMPANION_DISTRIBUTIONS = ( - "loopx-workspace", + WORKSPACE_DISTRIBUTION, "loopx-capability-agent-turn-recall", "loopx-capability-pull-request-review", "loopx-capability-issue-fix", ) -def _distribution_artifact_file(path: Path) -> bool: - return "__pycache__" not in path.parts and path.suffix not in {".pyc", ".pyo"} - - def _owned_runtime_files(installed: Distribution) -> dict[str, Path]: direct_url = json.loads(installed.read_text("direct_url.json") or "{}") if direct_url.get("dir_info", {}).get("editable") or installed.version != __version__: return {} + entries = distribution_recorded_files(installed) + if entries is None: + return {} return { - item.as_posix(): ( - distribution_record_path(item) - if isinstance(item, PackagePath) - else Path(item.locate()) - ) - for item in installed.files or () - if item.as_posix().startswith("loopx/") - and _distribution_artifact_file(Path(item.as_posix())) + name: path + for name, path in entries + if name.startswith("loopx/") and is_distribution_artifact(Path(name)) } @@ -364,7 +363,7 @@ def _distribution_runtime_fingerprint() -> str | None: actual = { "loopx/" + path.relative_to(package_root).as_posix() for path in entries - if path.is_file() and _distribution_artifact_file(path.relative_to(package_root)) + if path.is_file() and is_distribution_artifact(path.relative_to(package_root)) } if actual != files.keys(): return None diff --git a/packages/README.md b/packages/README.md index ba612e0714..d0865324f9 100644 --- a/packages/README.md +++ b/packages/README.md @@ -32,6 +32,8 @@ Current co-located distributions, in directory order: - [`loopx-community-discussion`](loopx-community-discussion/README.md): public-safe community discussion scanner producing compact `discussion_fact_v0` facts; +- [`loopx-core`](loopx-core/README.md): standalone local task execution and + recovery with the existing CLI and typed runtime; - [`loopx-finance-execution`](loopx-finance-execution/README.md): optional simulator for the human-confirmed finance operation envelope; - [`loopx-finance-value-discovery`](loopx-finance-value-discovery/README.md): @@ -47,7 +49,9 @@ Current co-located distributions, in directory order: - [`loopx-text-stats`](loopx-text-stats/README.md): the Developer Book's zero-permission text-statistics companion, with a complete installable package and contract tests. It is a teaching distribution, not a default - capability or catalog entry. + capability or catalog entry; +- [`loopx-workspace`](loopx-workspace/README.md) adds local Chat and Dashboard + to the matching Core environment. Not every distribution is an extension: a package without `extension.toml` installs through its own Python or npm lifecycle and never enters diff --git a/packages/loopx-core/README.md b/packages/loopx-core/README.md index cba9a0fcc2..85903b01c3 100644 --- a/packages/loopx-core/README.md +++ b/packages/loopx-core/README.md @@ -57,6 +57,10 @@ The installed-only qualification in exercises setup, independent result validation, process loss, replay and refusal. No model service, credentials or paid task execution is supplied by this wheel. +To view the same work in your browser, install the matching +[`loopx-workspace` wheel](../loopx-workspace/README.md) in this environment and +start `loopx dashboard` with the original registry. + Ordinary Core goal previews omit Issue Fix command templates. Install the [matching workflow wheel](../loopx-capability-issue-fix/README.md) to select `--capability-route issue-fix` or run `loopx issue-fix`. Core retains existing @@ -123,7 +127,8 @@ It still retains built-in capability implementations, policy helpers and several host/CLI dependencies because the current imports are coupled. This makes it a workspace-free installation prerequisite, not a qualified minimal mechanism closure. Those dependencies are migration debt, not evidence that every -capability belongs in the kernel. Full workspace/meta-package splitting, -the remaining capability packages, other host/platform qualification and the +capability belongs in the kernel. Public split-package releases, +full workspace/meta-package splitting, independent capability packaging, +native/IM adoption and the complexity/coverage hypothesis remain separate work. Smaller installation or a passing process fixture alone does not establish model effectiveness. diff --git a/packages/loopx-core/prepare.py b/packages/loopx-core/prepare.py index 6e3267695c..e5f3bd21e5 100644 --- a/packages/loopx-core/prepare.py +++ b/packages/loopx-core/prepare.py @@ -1,4 +1,4 @@ -"""Prepare standalone Core and its matching built-in capability distributions. +"""Prepare split LoopX Core, Workspace, 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. @@ -6,15 +6,34 @@ from __future__ import annotations import argparse +import json import shutil import subprocess +import sys from pathlib import Path from runpy import run_path REPOSITORY = Path(__file__).resolve().parents[2] # These are distribution exclusions. -EXCLUDED_TREES = ("loopx/chat/", "loopx/web/", "loopx/canary/") -EXCLUDED_MODULES = {"loopx/cli.py", "loopx/chat.py"} +EXCLUDED_TREES = ("loopx/web/", "loopx/canary/") +WORKSPACE_DISTRIBUTION = "loopx-workspace" +WORKSPACE_MODULES = { + "loopx/chat.py", + # Native session adapters use the Workspace store and original conversation. + "loopx/capabilities/native_chat/session_calendar_tasks.py", + "loopx/capabilities/native_chat/steward_managed_mode.py", + "loopx/capabilities/native_chat/steward_monitor.py", + "loopx/capabilities/native_chat/steward_reports.py", + "loopx/capabilities/native_chat/steward_turn.py", + "loopx/dashboard_launcher.py", + "loopx/cli_commands/support_control_chat.py", + "loopx/cli_commands/support_control_chat_endpoint.py", + "loopx/control_plane/collaboration/steward_reports.ts", + "loopx/extensions/lark/steward_reports.py", + "loopx/presentation/research_analysis_api.py", + "loopx/presentation/runtime_workspace.py", +} +WORKSPACE_ASSETS = Path("loopx/web/chat") SOURCE_SUFFIXES = {".py", ".ts", ".json", ".mjs", ".js", ".md", ".toml"} RECALL_DISTRIBUTION = "loopx-capability-agent-turn-recall" PR_REVIEW_DISTRIBUTION = "loopx-capability-pull-request-review" @@ -77,14 +96,25 @@ def _optional_capability_sources(sources: list[Path]) -> dict[str, set[Path]]: } +def _workspace_source(path: Path) -> bool: + # Core owns typed action receipts, including operation handoffs read by its Inbox. + if path.as_posix() == "loopx/chat_action_store.py": + return False + return ( + path.as_posix() in WORKSPACE_MODULES + or path.is_relative_to("loopx/chat") + or (path.parent == Path("loopx") and path.name.startswith("chat_")) + ) + + def prepare_core_source(output: Path, *, repository: Path = REPOSITORY) -> Path: repository = repository.resolve() sources = _tracked_loopx_sources(repository) optional = set().union(*_optional_capability_sources(sources).values()) sources = [path for path in sources if path.suffix in SOURCE_SUFFIXES and path not in optional - and path.as_posix() not in EXCLUDED_MODULES - and not (path.parent == Path("loopx") and path.name.startswith("chat_")) + and path.as_posix() != "loopx/cli.py" + and not _workspace_source(path) and not path.as_posix().startswith(EXCLUDED_TREES)] if not sources or not (repository / "loopx/entrypoint.py").is_file(): raise ValueError("a complete LoopX source checkout is required") @@ -116,9 +146,10 @@ def _stage_source(output: Path, repository: Path, distribution: str, sources: li shutil.copyfile(package / name, output / name) for name in ("LICENSE", "LICENSE-MIT", "NOTICE"): shutil.copyfile(repository / name, output / name) - (output / "MANIFEST.in").write_text( - "recursive-include loopx *.py *.ts *.json *.mjs *.js *.md *.toml\n", encoding="utf-8", - ) + manifest = "recursive-include loopx *.py *.ts *.json *.mjs *.js *.md *.toml\n" + if distribution == WORKSPACE_DISTRIBUTION: + manifest += "graft loopx/web/chat\n" + (output / "MANIFEST.in").write_text(manifest, encoding="utf-8") return output @@ -129,6 +160,28 @@ def _tracked_loopx_sources(repository: Path) -> list[Path]: return [Path(name.decode("utf-8")) for name in names if name] +def prepare_workspace_source(output: Path, *, repository: Path = REPOSITORY) -> Path: + repository = repository.resolve() + sources = [path for path in _tracked_loopx_sources(repository) + if path.suffix in SOURCE_SUFFIXES and _workspace_source(path)] + if not WORKSPACE_MODULES <= {path.as_posix() for path in sources}: + raise ValueError("the complete LoopX Workspace source is required") + bundle = repository / WORKSPACE_ASSETS + if bundle.is_symlink() or not bundle.resolve().is_relative_to(repository): + raise ValueError("Workspace assets must stay inside the checkout") + verify = [sys.executable, str(repository / "scripts/chat_bundle.py"), "verify", "--source"] + subprocess.run([*verify, "--bundle", str(bundle)], cwd=repository, check=True) + manifest_path = WORKSPACE_ASSETS / "bundle-manifest.json" + manifest = json.loads((repository / manifest_path).read_text(encoding="utf-8")) + assets = [WORKSPACE_ASSETS / name for name in sorted(manifest["files"])] + output = _stage_source(output, repository, WORKSPACE_DISTRIBUTION, [*sources, manifest_path, *assets]) + subprocess.run([*verify, "--bundle", str(output / WORKSPACE_ASSETS)], cwd=repository, check=True) + version = run_path(str(repository / "loopx/__init__.py"))["__version__"] + (output / "VERSION").write_text(f"{version}\n", encoding="utf-8") + (output / "requires-core.txt").write_text(f"loopx-core=={version}\n", encoding="utf-8") + return output + + def prepare_capability_source( output: Path, distribution: str, *, repository: Path = REPOSITORY, ) -> Path: @@ -146,12 +199,14 @@ def prepare_capability_source( def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--distribution", choices=["loopx-core", *CAPABILITY_ENTRY_MODULES], default="loopx-core") + parser.add_argument("--distribution", choices=["loopx-core", WORKSPACE_DISTRIBUTION, *CAPABILITY_ENTRY_MODULES], default="loopx-core") args = parser.parse_args() - output = ( - prepare_core_source(args.output) if args.distribution == "loopx-core" - else prepare_capability_source(args.output, args.distribution) - ) + if args.distribution == "loopx-core": + output = prepare_core_source(args.output) + elif args.distribution == WORKSPACE_DISTRIBUTION: + output = prepare_workspace_source(args.output) + else: + output = prepare_capability_source(args.output, args.distribution) print(output) return 0 diff --git a/packages/loopx-workspace/README.md b/packages/loopx-workspace/README.md new file mode 100644 index 0000000000..08a21294b5 --- /dev/null +++ b/packages/loopx-workspace/README.md @@ -0,0 +1,43 @@ +# LoopX Workspace + +Add the local Chat and Dashboard to a matching source-built +[`loopx-core`](../loopx-core/README.md) environment. Both read the Core registry +and runtime state. Installing the wheel adds the commands and web assets. Start +the service explicitly when you want to use it. + +The Workspace wheel also owns the native Steward session, monitor and report +adapters and the managed Session calendar. Existing App and Lark bindings use +the same session store and typed Core authority. Standalone Core provides the +peer Inbox and its result readback. + +Build the frontend and the Workspace wheel from the same checkout. + +```sh +uv run --extra test python scripts/chat_bundle.py build --install +uv run --extra test python packages/loopx-core/prepare.py --distribution loopx-workspace --output /tmp/loopx-workspace-source +uv build --wheel /tmp/loopx-workspace-source --out-dir /tmp/loopx-workspace-dist +uv pip install --python /tmp/loopx-core-env/bin/python /tmp/loopx-workspace-dist/loopx_workspace-*.whl +``` + +Open the existing Dashboard with the registry used to run the task. + +```sh +/tmp/loopx-core-env/bin/loopx --registry .loopx/registry.json dashboard +``` + +If Core used an explicit `--runtime-root`, pass it here as well. The same +environment also provides `loopx chat` and `loopx chat-endpoint`. Use +`--no-open` on Chat or Dashboard to start the loopback service without opening +your browser. A host and its normal prerequisites are required to send a model +request. Existing work and checked results can be viewed without invoking a +model. + +Stop the local server before removing Workspace. Your existing Core commands +continue to use the same registry and task records. + +```sh +uv pip uninstall --python /tmp/loopx-core-env/bin/python loopx-workspace +``` + +This candidate covers the local browser surface. Split public releases, native +desktop installation and IM journeys retain their RFC acceptance requirements. diff --git a/packages/loopx-workspace/pyproject.toml b/packages/loopx-workspace/pyproject.toml new file mode 100644 index 0000000000..1578eb3da5 --- /dev/null +++ b/packages/loopx-workspace/pyproject.toml @@ -0,0 +1,26 @@ +[build-system] +requires = ["setuptools==83.0.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "loopx-workspace" +dynamic = ["version", "dependencies"] +description = "Local Chat and Dashboard for a matching standalone 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.chat", "loopx.chat.*", "loopx.cli_commands", "loopx.presentation", + "loopx.capabilities.native_chat", "loopx.control_plane.collaboration", "loopx.extensions.lark", +] + +[tool.setuptools.package-data] +loopx = ["web/chat/*.html", "web/chat/*.json", "web/chat/assets/*", "web/chat/manifest.webmanifest", "web/chat/pwa/*"] +"loopx.control_plane.collaboration" = ["steward_reports.ts"] diff --git a/tests/control_plane/test_chat_todo_actions_contract.py b/tests/control_plane/test_chat_todo_actions_contract.py index b757131552..180bd38d58 100644 --- a/tests/control_plane/test_chat_todo_actions_contract.py +++ b/tests/control_plane/test_chat_todo_actions_contract.py @@ -14,7 +14,7 @@ import pytest from loopx.chat import todo_action_contracts, todo_action_create, todo_action_tasks, todo_action_updates, todo_actions -from loopx.chat.action_store_common import ActionConflictError, _canonical_digest +from loopx.control_plane.collaboration.action_store_common import ActionConflictError, _canonical_digest from loopx.chat.todo_action_contracts import ( TodoRuntimeControllerProtocol, TodoTurnLoaderProtocol, diff --git a/tests/control_plane/test_installed_core_context.py b/tests/control_plane/test_installed_core_context.py index 2b63c24609..e0a74aac8f 100644 --- a/tests/control_plane/test_installed_core_context.py +++ b/tests/control_plane/test_installed_core_context.py @@ -122,32 +122,37 @@ def command(*args): assert (workspace / "host-invocations").read_text().splitlines() == ["called", "called"] -def test_installed_empty_operation_inbox_keeps_the_workspace_provider_unloaded(core_python, tmp_path): - """No action store means no operation handoff; a present store needs its provider.""" +def test_installed_operation_inbox_reads_core_store_only_when_present(core_python, tmp_path): + """Keep the optional path lazy; a persisted store remains readable without Workspace.""" script = ''' -import importlib.util, json, sys +import importlib.util, sys from pathlib import Path -assert importlib.util.find_spec("loopx.chat_action_store") is None +assert importlib.util.find_spec("loopx.chat_store") is None from loopx.control_plane.collaboration.operation_handoff import pending_operation_handoffs root = Path(sys.argv[1]) -empty = pending_operation_handoffs(root, "synthetic-goal", "synthetic-agent", cursor_scope="synthetic-scope") -assert empty == {"items": [], "pending_count": 0, "overflow": None, "next_cursor": None} +expected = {"items": [], "pending_count": 0, "overflow": None, "next_cursor": None} + +def read(): + return pending_operation_handoffs(root, "synthetic-goal", "synthetic-agent", cursor_scope="synthetic-scope") + +assert read() == expected assert "loopx.chat_action_store" not in sys.modules -store = root / "chat/actions/actions.json" -store.parent.mkdir(parents=True) +from loopx.chat_action_store import ChatActionStore +store = ChatActionStore(root / "chat" / "actions").path +before = store.read_bytes() +assert read() == expected and store.read_bytes() == before store.write_text("{}") try: - pending_operation_handoffs(root, "synthetic-goal", "synthetic-agent", cursor_scope="synthetic-scope") -except ModuleNotFoundError as error: - assert error.name == "loopx.chat_action_store" + read() +except ValueError as error: + assert "unsupported schema" in str(error) else: - raise AssertionError("a present operation store cannot silently disappear without its provider") -print(json.dumps({"empty": empty, "present_store_requires_provider": True})) + raise AssertionError("a malformed operation store cannot silently disappear") +assert store.read_text() == "{}" ''' result = subprocess.run([str(core_python), "-I", "-c", script, str(tmp_path / "runtime")], env=_environment(core_python), cwd=tmp_path, capture_output=True, text=True, timeout=45) assert result.returncode == 0, (result.stdout, result.stderr) - assert json.loads(result.stdout)["present_store_requires_provider"] is True def test_installed_context_recovers_partial_delivery_revisions_and_compaction(core_python, tmp_path): diff --git a/tests/control_plane/test_peer_source_store.py b/tests/control_plane/test_peer_source_store.py index fb3758b087..44fac51c71 100644 --- a/tests/control_plane/test_peer_source_store.py +++ b/tests/control_plane/test_peer_source_store.py @@ -11,7 +11,7 @@ import pytest -from canonical_authority_fixture import isolate_sqlite_runtime, promoted_create_fixture +from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime, promoted_create_fixture from loopx.capabilities.manager_context import POLICY_SCHEMA, _hash, _root, _write, register_ingress from loopx.chat.coordination import apply_context_handoff from loopx.chat_store import ChatSessionStore diff --git a/tests/test_chat_action_store_contract.py b/tests/test_chat_action_store_contract.py index 57cabb70f8..f33e39e2f5 100644 --- a/tests/test_chat_action_store_contract.py +++ b/tests/test_chat_action_store_contract.py @@ -30,9 +30,9 @@ def test_chat_action_store_modularization_zero_any_and_exports() -> None: root = Path(__file__).resolve().parents[1] / "loopx" limits = { "chat_action_store.py": 650, - "chat/action_store_common.py": 700, - "chat/action_store_review_cards.py": 700, - "chat/action_store_operations.py": 700, + "control_plane/collaboration/action_store_common.py": 700, + "control_plane/collaboration/action_store_review_cards.py": 700, + "control_plane/collaboration/action_store_operations.py": 700, } for filename, max_lines in limits.items(): source = (root / filename).read_text(encoding="utf-8") diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index e76295bbe2..1f8be4c08c 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -58,8 +58,9 @@ def test_core_staging_excludes_workspace_and_reuses_kernel_bytes(tmp_path): staged = _prepare_module().prepare_core_source(tmp_path / "source") for name in ("chat", "web", "canary", "cli.py", "chat.py"): assert not (staged / "loopx" / name).exists() - assert not list((staged / "loopx").glob("chat_*.py")) - for name in ("entrypoint.py", "control_plane/turn_driver/executor.py", + # Chat UI/store modules are excluded; the typed action authority is Core-owned. + assert {path.name for path in (staged / "loopx").glob("chat_*.py")} == {"chat_action_store.py"} + for name in ("entrypoint.py", "chat_action_store.py", "control_plane/turn_driver/executor.py", "control_plane/coordination/sqlite_authority_store.ts", "extensions/lark/extension.toml"): assert (staged / "loopx" / name).read_bytes() == (REPOSITORY / "loopx" / name).read_bytes() diff --git a/tests/test_core_workspace_distribution.py b/tests/test_core_workspace_distribution.py new file mode 100644 index 0000000000..55971901b8 --- /dev/null +++ b/tests/test_core_workspace_distribution.py @@ -0,0 +1,370 @@ +"""Exercise the split Workspace over work first accepted by an installed Core.""" + +from contextlib import contextmanager +from hashlib import sha256 +import http.client +import json +import os +from pathlib import Path +import re +import shutil +import socket +import subprocess +import sys +import time +from urllib.parse import urlencode +from zipfile import ZipFile + +import pytest + +from tests.control_plane.codex_checkpoint_fixture import reference_metadata_oracle, read_cli_policy_payload +from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime +from tests.control_plane.test_peer_source_store import source_request +from tests.test_core_distribution import AGENT, GOAL, _assert_committed, _environment, _run +from tests.test_core_distribution import task as task + + +@pytest.fixture +def wheels(): + core = os.environ.get("LOOPX_CORE_TEST_WHEEL") + workspace = os.environ.get("LOOPX_WORKSPACE_TEST_WHEEL") + if not core or not workspace: + pytest.skip("set LOOPX_CORE_TEST_WHEEL and LOOPX_WORKSPACE_TEST_WHEEL to the built artifacts") + return Path(core).resolve(strict=True), Path(workspace).resolve(strict=True) + + +@pytest.fixture +def core_python(tmp_path, wheels): + uv = shutil.which("uv") + assert uv, "uv is required to qualify a clean split installation" + environment = tmp_path / "environment" + subprocess.run([uv, "venv", "--python", sys.executable, str(environment)], check=True, timeout=45) + python = str(environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")) + subprocess.run([uv, "pip", "install", "--offline", "--python", python, str(wheels[0])], + check=True, timeout=45) + return python + + +def test_workspace_wheel_owns_the_complete_bundle_without_core_files(wheels): + core, workspace = wheels + with ZipFile(core) as core_zip, ZipFile(workspace) as workspace_zip: + assert not (set(core_zip.namelist()) & set(workspace_zip.namelist())) + prefix = "loopx/web/chat/" + manifest = json.loads(workspace_zip.read(prefix + "bundle-manifest.json")) + assets = {name.removeprefix(prefix) for name in workspace_zip.namelist() if name.startswith(prefix)} + assert assets == manifest["files"].keys() | {"bundle-manifest.json"} + assert all(sha256(workspace_zip.read(prefix + name)).hexdigest() == digest + for name, digest in manifest["files"].items()) + assert "loopx/chat_server.py" in workspace_zip.namelist() + assert "loopx/chat_store.py" not in core_zip.namelist() + assert "loopx/chat_action_store.py" in core_zip.namelist() + assert "loopx/dashboard_launcher.py" in workspace_zip.namelist() + assert { + "loopx/capabilities/native_chat/steward_turn.py", + "loopx/capabilities/native_chat/steward_managed_mode.py", + "loopx/capabilities/native_chat/steward_monitor.py", + "loopx/capabilities/native_chat/steward_reports.py", + "loopx/capabilities/native_chat/session_calendar_tasks.py", + "loopx/control_plane/collaboration/steward_reports.ts", + "loopx/extensions/lark/steward_reports.py", + } <= set(workspace_zip.namelist()) + assert "loopx/cli.py" not in workspace_zip.namelist() + assert "loopx/control_plane/turn_driver/executor.py" in core_zip.namelist() + assert "loopx/control_plane/collaboration/inbox_turn_start.py" in core_zip.namelist() + assert "loopx/control_plane/collaboration/steward_managed_mode.ts" in core_zip.namelist() + + +def test_core_requests_and_returns_peer_work_without_workspace(core_python, task): + workspace, runtime, registry, _ = task + route = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + source = "source-fixture" + # Core must still read the typed store left by a previously installed Workspace. + from loopx.chat_action_store import ChatActionStore + + actions = ChatActionStore(runtime / "chat" / "actions").path + original_actions = actions.read_bytes() + _run(core_python, [*route, "configure-goal", "--goal-id", GOAL, "--registered-agent", AGENT, + "--registered-agent", source, "--execute"], workspace) + brief = workspace / "brief.json" + brief.write_text(json.dumps({ + "schema_version": "collaboration_brief_v0", + "purpose": "Check the inventory totals", + "context": "Verify the supplied total independently.", + "constraints": [], + "inputs": [], + "acceptance": ["Return a checked total"], + "return_requirement": "Share the result with the original sender.", + }), encoding="utf-8") + + def inbox(action, agent, *args): + out = _run(core_python, [*route, "manager-inbox", action, "--goal-id", GOAL, + "--agent-id", agent, *args], workspace) + return json.loads(out.stdout) + + request_id = inbox("request", source, "--peer-agent-id", AGENT, "--operation-id", "core-peer-review", + "--brief-file", str(brief))["request_id"] + probe = ''' +import json, sys +from loopx.entrypoint import main + +assert main(json.loads(sys.argv[1])) == 0 +assert "loopx.capabilities.manager_context" not in sys.modules +assert "loopx.chat_store" not in sys.modules +''' + for agent in (AGENT, source): + arguments = [*route, "quota", "should-run", "--goal-id", GOAL, "--agent-id", agent, "--dry-run"] + result = subprocess.run([core_python, "-I", "-c", probe, json.dumps(arguments)], + cwd=workspace, env=_environment(core_python), capture_output=True, text=True, timeout=45) + assert result.returncode == 0, (result.stdout, result.stderr) + view = reference_metadata_oracle(json.loads(result.stdout)) + payload = read_cli_policy_payload(json.dumps(view), returncode=result.returncode) + hook = payload["turn_start_capability_hook_dispatch"] + assert any(read["hook_id"] == "manager.context_inbox" for read in hook["required_reads"]) + if agent == AGENT: + assert [row["request_id"] for row in inbox("read", agent)["items"]] == [request_id] + inbox("acknowledge", agent, "--request-id", request_id, "--decision", "adopt", + "--reason", "Review the fixture independently.") + inbox("report", agent, "--request-id", request_id, "--reply-text", "The checked total is 35.") + else: + row = inbox("read", agent)["peer_returns"]["items"][0] + assert row["request_id"] == request_id and row["text"] == "The checked total is 35." + assert actions.read_bytes() == original_actions + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_core_forwards_source_backed_peer_context_without_workspace(core_python, tmp_path, monkeypatch, provider): + isolate_sqlite_runtime(tmp_path, monkeypatch) + runtime, registry, store, session, turn, receipt = source_request(tmp_path, monkeypatch, provider=provider) + route = ["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json"] + brief = tmp_path / "forwarding-brief.json" + brief.write_text(json.dumps({ + "schema_version": "collaboration_brief_v0", + "purpose": "Check the exact source", + "context": "Preserve the original correction.", + "constraints": ["No work launch"], + "inputs": [], + "acceptance": ["Return evidence and unresolved gaps"], + "return_requirement": "Return to the requester.", + }), encoding="utf-8") + source_session = store._session_dir(session["session_id"]) + + def source_records(): + return {path.relative_to(source_session): path.read_bytes() + for path in source_session.rglob("*.json")} + + def inbox(action, agent, *args, expected=0): + out = _run(core_python, [*route, "manager-inbox", action, "--goal-id", "goal-a", + "--agent-id", agent, *args], tmp_path, expected=expected) + return json.loads(out.stdout) + + def forward(agent, *, expected=0): + return inbox("request", "agent-a", "--peer-agent-id", agent, + "--parent-request-id", receipt["request_id"], "--operation-id", f"review-{agent}", + "--brief-file", str(brief), expected=expected) + + before = source_records() + assert not _python_json(core_python, tmp_path, """ +import importlib.util, json +print(json.dumps(importlib.util.find_spec("loopx.chat_store") is not None)) +""") + assert inbox("read", "agent-a")["items"][0]["request_id"] == receipt["request_id"] + # The third agent is registered to the same Goal but outside the original audience grant. + denied = forward("third", expected=1) + assert "not authorized" in str(denied) + assert inbox("read", "third")["items"] == [] + child = forward("reviewer") + received = inbox("read", "reviewer")["items"] + assert len(received) == 1 + assert received[0]["request_id"] == child["request_id"] + assert received[0]["parent_request_id"] == receipt["request_id"] + assert received[0]["inherited_context"]["message"] == turn["message"] + assert source_records() == before + assert not (runtime / "chat").exists() + + +def _python_json(python, cwd, source): + result = subprocess.run([python, "-I", "-c", source], cwd=cwd, env=_environment(python), + capture_output=True, text=True, check=True, timeout=30) + return json.loads(result.stdout) + + +_RUNTIME_IDENTITY = "from loopx.release_manifest import release_runtime_identity; print(json.dumps(release_runtime_identity()))" + + +def _read(port, path, *, status=200): + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=20) + try: + connection.request("GET", path, headers={"Origin": f"http://127.0.0.1:{port}"}) + response = connection.getresponse() + body = response.read() + assert response.status == status, (path, response.status, body[:500]) + return body + finally: + connection.close() + + +@contextmanager +def _running_workspace(python, cwd, arguments, log_path, port): + with log_path.open("w", encoding="utf-8") as log, subprocess.Popen( + [python, "-I", "-X", "importtime", "-m", "loopx.entrypoint", *arguments], + cwd=cwd, env=_environment(python), stdout=log, stderr=log, + ) as process: + try: + deadline = time.monotonic() + 25 + while process.poll() is None and time.monotonic() < deadline: + try: + ready = json.loads(_read(port, "/api/chat/readiness")) + except (ConnectionError, TimeoutError): + time.sleep(0.1) + else: + assert ready["state"] == "ready" + yield ready["runtime_identity"] + return + pytest.fail(log_path.read_text(encoding="utf-8", errors="replace")[-4000:]) + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + process.kill() + + +def test_workspace_reads_the_original_task_and_core_replays_after_removal(core_python, task, wheels, tmp_path): + workspace, runtime, registry, arguments = task + before = _python_json(core_python, workspace, "import json; " + _RUNTIME_IDENTITY) + assert before["package_fingerprint"] + absent = _run(core_python, ["dashboard"], workspace, expected=2) + assert "install the matching loopx-workspace wheel" in absent.stderr + completed = json.loads(_run(core_python, arguments, workspace).stdout) + turn_key = _assert_committed(core_python, workspace, runtime, completed) + journal = runtime / "goals" / GOAL / "turns" / f"{turn_key.removeprefix('sha256:')}.json" + journal_bytes = journal.read_bytes() + todo_id = json.loads(journal_bytes)["plan"]["work_contract"]["selected_todo"]["todo_id"] + registry_bytes = registry.read_bytes() + + subprocess.run(["uv", "pip", "install", "--offline", "--python", core_python, str(wheels[1])], + check=True, timeout=45) + installed = _python_json(core_python, workspace, """import contextlib, importlib.metadata as m, importlib.util as u +import io, json, sys +from pathlib import Path +from loopx.entrypoint import main +core = m.distribution("loopx-core") +owner = m.distribution("loopx-workspace") +assert owner.requires == [f"loopx-core=={core.version}"] +assert u.find_spec("loopx.cli") is None +with contextlib.redirect_stdout(io.StringIO()): + assert main(["--help"]) == 0 + assert main(["commands", "--format", "json"]) == 0 +assert "loopx.chat" not in sys.modules +assert "loopx.chat_server" not in sys.modules +assert "loopx.chat_store" not in sys.modules +assert "loopx.dashboard_launcher" not in sys.modules +analysis = "loopx/capabilities/benchmark_toolkit/trajectory_assessment_store.py" +print(json.dumps({ + "module": str(Path(owner.locate_file("loopx/dashboard_launcher.py"))), + "chat_store": str(Path(owner.locate_file("loopx/chat_store.py"))), + "bundle_manifest": str(Path(owner.locate_file("loopx/web/chat/bundle-manifest.json"))), + "has_analysis": any(p.as_posix() == analysis for p in core.files), +})) +""") + combined = _python_json(core_python, workspace, "import json; " + _RUNTIME_IDENTITY) + assert combined["package_fingerprint"] != before["package_fingerprint"] + help_text = _run(core_python, ["--help"], workspace).stdout + assert "loopx dashboard" in help_text + endpoint_help = _run(core_python, ["chat-endpoint", "--help"], workspace).stdout + assert "chat-endpoint" in endpoint_help + + for label, suffix in (("chat_store", ".py.missing"), ("bundle_manifest", ".json.missing")): + target = Path(installed[label]) + backup = target.with_name(target.name + suffix) + target.rename(backup) + try: + assert "loopx dashboard" not in _run(core_python, ["--help"], workspace).stdout + commands_payload = json.loads(_run(core_python, ["commands", "--format", "json"], workspace).stdout) + listed_names = { + match[1] + for group in commands_payload["groups"] + for entry in group.get("commands", []) + if (match := re.match(r"loopx ([a-z0-9-]+)(?: |$)", entry.get("command", ""))) + } + assert not (listed_names & {"chat", "chat-endpoint", "dashboard"}) + partial_identity = _python_json(core_python, workspace, "import json; " + _RUNTIME_IDENTITY) + assert "package_fingerprint" not in partial_identity + for blocked in (["dashboard", "--help"], ["dashboard"], ["chat-endpoint", "--help"], ["chat"]): + denied = _run(core_python, blocked, workspace, expected=2) + assert "install the matching loopx-workspace wheel" in denied.stderr + finally: + backup.rename(target) + assert _python_json(core_python, workspace, "import json; " + _RUNTIME_IDENTITY) == combined + assert "loopx dashboard" in _run(core_python, ["--help"], workspace).stdout + assert "chat-endpoint" in _run(core_python, ["chat-endpoint", "--help"], workspace).stdout + assert "dashboard" in _run(core_python, ["dashboard", "--help"], workspace).stdout + native_spend = _python_json(core_python, workspace, f""" +import json +from pathlib import Path +from types import SimpleNamespace +from loopx.capabilities.native_chat.steward_commands import native_command + +controller = SimpleNamespace(registry_path=Path({str(registry)!r}), coordination_runtime_root=Path({str(runtime)!r})) +status = native_command(controller, ["quota", "status", "--goal-id", {GOAL!r}]) +print(json.dumps([row["quota"]["spent_slots"] for group in status["groups"].values() + for row in group if row["goal_id"] == {GOAL!r}])) +""") + assert native_spend == [1] + + route = ["--registry", str(registry), "--runtime-root", str(runtime)] + endpoint_list = json.loads(_run(core_python, [*route, "chat-endpoint", "list", "--format", "json"], workspace).stdout) + assert endpoint_list["ok"] and endpoint_list["endpoints"] == [] + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + options = ["--port", str(port), "--no-open", "--goal-id", GOAL, "--scan-path", str(workspace)] + for option in ("--codex-bin", "--claude-bin", "--kiro-cli-bin", "--lark-cli-bin"): + options.extend([option, str(tmp_path / "unconfigured-host")]) + history_query = urlencode({"goal_id": GOAL, "agent_id": AGENT}) + detail_query = urlencode({"goal_id": GOAL, "todo_id": todo_id}) + observed = [] + for command in ("dashboard", "chat"): + log = tmp_path / f"{command}.log" + argv = [*route, command, *options] + if command == "chat": + argv.append("--no-private-reactions") + with _running_workspace(core_python, workspace, argv, log, port) as identity: + assert identity == combined + html = _read(port, "/chat/") + script = re.search(rb'src="(/chat/assets/[^"]+\.js)"', html) + assert script and _read(port, script[1].decode()) + task_view = json.loads(_read(port, f"/api/chat/todo/detail?{detail_query}")) + assert task_view["todo_id"] == todo_id and task_view["status"] == "done" + completed_view = json.loads(_read(port, f"/api/chat/completed-todos?{history_query}")) + assert [(item["todo_id"], item["done"]) for item in completed_view["items"]] == [(todo_id, True)] + assert completed_view["items"][0]["evidence"] == ( + "LoopX Turn validated completion: Produced squared integers zero through seven." + ) + assert "benchmark_toolkit.trajectory_assessment_store" not in log.read_text(encoding="utf-8") + if not installed["has_analysis"]: + response = json.loads(_read(port, f"/api/chat/research-analysis?goal_id={GOAL}", status=503)) + assert response["error_code"] == "research_analysis_unavailable" + observed.append((task_view, completed_view)) + if command == "dashboard": + assert "Reusing existing LoopX Chat service" in _run(core_python, argv, workspace).stdout + module = Path(installed["module"]) + original = module.read_bytes() + try: + module.write_bytes(original + b"\n# Disposable service revision check.\n") + stale = _run(core_python, argv, workspace, expected=1) + assert "different installed runtime" in stale.stdout + finally: + module.write_bytes(original) + assert observed[0] == observed[1] + + subprocess.run(["uv", "pip", "uninstall", "--python", core_python, "loopx-workspace"], + check=True, timeout=45) + assert _python_json(core_python, workspace, "import json; " + _RUNTIME_IDENTITY) == before + assert "loopx dashboard" not in _run(core_python, ["--help"], workspace).stdout + _run(core_python, ["dashboard"], workspace, expected=2) + replay = json.loads(_run(core_python, [*arguments, "--resume-turn-key", turn_key], workspace).stdout) + assert not any(replay["effects"][name] for name in ("host_invoked", "state_written", "quota_spent")) + assert _assert_committed(core_python, workspace, runtime, replay) == turn_key + assert registry.read_bytes() == registry_bytes and journal.read_bytes() == journal_bytes diff --git a/tests/test_distribution_runtime_identity.py b/tests/test_distribution_runtime_identity.py index 7a82739e8b..e18ad23ffb 100644 --- a/tests/test_distribution_runtime_identity.py +++ b/tests/test_distribution_runtime_identity.py @@ -27,7 +27,7 @@ def owned_package(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): path.write_text(content) items = [SimpleNamespace(as_posix=lambda name=name: "loopx/" + name, locate=lambda name=name: package / name) for name in contents] - installed = SimpleNamespace(version=manifest.__version__, files=items, + installed = SimpleNamespace(name="loopx", version=manifest.__version__, files=items, read_text=lambda _name: None) monkeypatch.setattr(manifest, "__file__", str(package / "release_manifest.py")) monkeypatch.setattr(manifest, "distribution", lambda _name: installed) @@ -204,3 +204,145 @@ def _lookup(name: str): dists["loopx-capability-issue-fix"].files.append(_entry("release_manifest.py")) assert "package_fingerprint" not in manifest.release_runtime_identity() + + +@pytest.mark.parametrize("change", ["owned", "wrong_version", "overlap", "absent"]) +def test_matching_workspace_owns_only_its_records(owned_package, monkeypatch, change): + _package, core = owned_package + original = manifest.release_runtime_identity() + core.name = "loopx-core" + asset = core.files.pop() + workspace = SimpleNamespace(name="loopx-workspace", version=manifest.__version__, + files=[asset], read_text=lambda _name: None) + if change == "wrong_version": + workspace.version = "0.0.0" + elif change == "overlap": + workspace.files.append(core.files[0]) + + def lookup(name): + if name == "loopx-core": + return core + if name == "loopx-workspace" and change != "absent": + return workspace + raise manifest.PackageNotFoundError(name) + + monkeypatch.setattr(manifest, "distribution", lookup) + result = manifest.release_runtime_identity() + if change == "owned": + assert result == original + else: + assert "package_fingerprint" not in result + + +def test_builtin_capability_requires_every_recorded_artifact(owned_package, monkeypatch): + from loopx import python_install_owner as install_owner + + package, core = owned_package + core.name = "loopx-core" + owner_file = package / "python_install_owner.py" + owner_file.write_text("python") + asset = core.files.pop() + store_file = package / "chat_store.py" + store_file.write_text("store") + store_item = SimpleNamespace(as_posix=lambda: "loopx/chat_store.py", locate=lambda: store_file) + workspace = SimpleNamespace( + name=install_owner.WORKSPACE_DISTRIBUTION, + version=manifest.__version__, + files=[asset, store_item], + read_text=lambda _name: None, + ) + monkeypatch.setattr(install_owner, "__file__", str(owner_file)) + monkeypatch.setattr( + install_owner, + "distribution", + lambda name: core if name == "loopx-core" else workspace, + ) + monkeypatch.setattr( + install_owner, + "find_spec", + lambda module: SimpleNamespace(origin=str(store_file)) if module == "loopx.chat_store" else None, + ) + assert install_owner.builtin_capability_installed( + install_owner.WORKSPACE_DISTRIBUTION, ("loopx.chat_store",), builtin_cli_present=False, + ) + (package / "web/chat/index.html").unlink() + assert not install_owner.builtin_capability_installed( + install_owner.WORKSPACE_DISTRIBUTION, ("loopx.chat_store",), builtin_cli_present=False, + ) + + +def test_real_record_missing_asset_fails_closed_despite_filtered_dist_files( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + from importlib.metadata import Distribution, PackageNotFoundError + from loopx import python_install_owner as install_owner + + site = tmp_path / "site-packages" + package = site / "loopx" + (package / "web/chat").mkdir(parents=True) + files = { + "loopx/release_manifest.py": "python", + "loopx/python_install_owner.py": "owner", + "loopx/chat_store.py": "store", + "loopx/web/chat/bundle-manifest.json": '{"files":{}}', + } + for rel, content in files.items(): + (site / rel).write_text(content, encoding="utf-8") + + def _make_dist(name: str, owned: list[str]): + dist_info = site / f"{name.replace('-', '_')}-{manifest.__version__}.dist-info" + dist_info.mkdir(parents=True, exist_ok=True) + (dist_info / "METADATA").write_text( + f"Metadata-Version: 2.1\nName: {name}\nVersion: {manifest.__version__}\n", + encoding="utf-8", + ) + (dist_info / "RECORD").write_text( + "".join(f"{entry},,\n" for entry in owned), encoding="utf-8" + ) + return Distribution.at(dist_info) + + core = _make_dist("loopx-core", ["loopx/release_manifest.py", "loopx/python_install_owner.py"]) + workspace = _make_dist( + install_owner.WORKSPACE_DISTRIBUTION, + ["loopx/chat_store.py", "loopx/web/chat/bundle-manifest.json"], + ) + + def _lookup(name: str): + if name == "loopx-core": + return core + if name == install_owner.WORKSPACE_DISTRIBUTION: + return workspace + raise PackageNotFoundError(name) + + monkeypatch.setattr(manifest, "__file__", str(site / "loopx/release_manifest.py")) + monkeypatch.setattr(manifest, "distribution", _lookup) + monkeypatch.delenv("LOOPX_RELEASE_ROOT", raising=False) + monkeypatch.setattr(install_owner, "__file__", str(site / "loopx/python_install_owner.py")) + monkeypatch.setattr(install_owner, "distribution", _lookup) + monkeypatch.setattr( + install_owner, + "find_spec", + lambda module: SimpleNamespace(origin=str(site / "loopx/chat_store.py")) + if module == "loopx.chat_store" + else None, + ) + + before = manifest.release_runtime_identity() + assert before["package_fingerprint"].startswith("sha256:") + assert install_owner.builtin_capability_installed( + install_owner.WORKSPACE_DISTRIBUTION, ("loopx.chat_store",), builtin_cli_present=False, + ) + + bundle_manifest = site / "loopx/web/chat/bundle-manifest.json" + bundle_manifest.unlink() + assert all(p.as_posix() != "loopx/web/chat/bundle-manifest.json" for p in workspace.files or ()) + assert not install_owner.builtin_capability_installed( + install_owner.WORKSPACE_DISTRIBUTION, ("loopx.chat_store",), builtin_cli_present=False, + ) + assert "package_fingerprint" not in manifest.release_runtime_identity() + + bundle_manifest.write_text('{"files":{}}', encoding="utf-8") + assert install_owner.builtin_capability_installed( + install_owner.WORKSPACE_DISTRIBUTION, ("loopx.chat_store",), builtin_cli_present=False, + ) + assert manifest.release_runtime_identity() == before diff --git a/tests/test_native_steward_turn_host.py b/tests/test_native_steward_turn_host.py index c79ecb1f44..ac97de273e 100644 --- a/tests/test_native_steward_turn_host.py +++ b/tests/test_native_steward_turn_host.py @@ -10,7 +10,7 @@ from test_native_steward_managed_mode import original, storage from test_native_steward_private import steward as steward_fixture, finish -from loopx.cli import main +from loopx.entrypoint import main from loopx.capabilities.native_chat.steward_turn import StewardTurnHost from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime