From 73875782dbd12440af378771cb17108faa16ac88 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:07:31 +0800 Subject: [PATCH 1/2] perf(control-plane,cli): shrink todo/envelope wire bloat and defer heavy CLI imports Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/agent_registry.py | 2 +- loopx/capabilities/explore/harness_gate.py | 194 +++++++++++++++ .../capabilities/explore/todo_branch_plan.py | 19 +- loopx/capabilities/explore/turn_context.py | 8 +- .../explore/worker_branch_plan.py | 182 +------------- .../issue_fix/pr_gate_reconcile.py | 8 +- .../issue_fix/pr_lifecycle_rollout.py | 2 +- loopx/capabilities/issue_fix/pr_review_ack.py | 2 +- .../issue_fix/pr_wait_reconcile.py | 3 +- loopx/cli_commands/__init__.py | 233 +++++++++--------- loopx/cli_commands/explore.py | 78 +++--- loopx/cli_commands/explore_feishu_commands.py | 46 ++-- .../cli_commands/explore_planning_commands.py | 2 +- .../cli_commands/support_control_heartbeat.py | 27 +- .../cli_commands/support_control_registry.py | 2 +- loopx/cli_runtime.py | 15 ++ loopx/control_plane/quota/turn_envelope.py | 4 +- .../quota/turn_envelope_codec.ts | 7 +- loopx/control_plane/todos/list_readback.py | 7 +- loopx/control_plane/todos/read_projection.ts | 18 +- loopx/control_plane/todos/read_transaction.ts | 7 +- loopx/control_plane/todos/read_transport.ts | 2 +- .../lark/presentation/explore_results.py | 20 +- .../lark/presentation/explore_singleflight.py | 13 + loopx/heartbeat_prequota.py | 3 +- .../test_long_history_todo_reads.py | 109 +++++++- .../test_turn_envelope_budget_warning.py | 40 +++ tests/control_plane_ts/todo_read.test.ts | 229 +++++++++++++++++ tests/control_plane_ts/turn_envelope.test.ts | 32 +++ tests/test_cli_entrypoint.py | 100 ++++++++ 30 files changed, 997 insertions(+), 417 deletions(-) diff --git a/loopx/agent_registry.py b/loopx/agent_registry.py index 428a4fb881..c4d19a4a4a 100644 --- a/loopx/agent_registry.py +++ b/loopx/agent_registry.py @@ -94,7 +94,7 @@ def agent_profile_for_goal(goal: dict[str, Any] | None, agent_id: str | None) -> def load_goal_from_registry(registry_path: Path, goal_id: str) -> dict[str, Any] | None: from .control_plane.hook_runtime.request_scope import current_hook_request_scope - from .history import load_registry + from .control_plane.projects.registry_codec import load_registry from .registry import registry_goals scope = current_hook_request_scope() diff --git a/loopx/capabilities/explore/harness_gate.py b/loopx/capabilities/explore/harness_gate.py index 9844208067..4147d615bd 100644 --- a/loopx/capabilities/explore/harness_gate.py +++ b/loopx/capabilities/explore/harness_gate.py @@ -13,6 +13,200 @@ GATE_STATE_DISABLED = "disabled" GATE_STATE_ANALYSIS_ONLY = "analysis_only" GATE_STATE_COMMANDS_SUGGESTED = "commands_suggested" +MAX_BRANCH_WIDTH = 8 +WORKER_HARNESS_PROFILE_SCHEMA_VERSION = "loopx_explore_worker_harness_profile_v0" +DEFAULT_TODOS_PER_WORKER_BRANCH = 3 +MAX_TODOS_PER_WORKER_BRANCH = 8 +DEFAULT_WORKER_HARNESS_PROFILE = "generic" + +WORKER_HARNESS_PROFILES: dict[str, dict[str, Any]] = { + "generic": { + "schema_version": WORKER_HARNESS_PROFILE_SCHEMA_VERSION, + "profile": "generic", + "source": "loopx_explore_worker_branch_plan_default", + "design_intent": "Generic dry-run worker-lane planning without runtime policy assumptions.", + "branch_fill_policy": "bundle-by-affinity", + "concurrency_policy": { + "mode": "bounded_confidence_prefix", + "fixed_worker_count": False, + "does_not_force_requested_width": True, + }, + "duration_guard": { + "enabled": False, + "controlled_by_planner": False, + }, + "retry_policy": { + "enabled": False, + "controlled_by_planner": False, + }, + "infra_cooldown": { + "enabled": False, + "controlled_by_planner": False, + }, + "todo_batching_policy": { + "mode": "fixed_safety_ceiling", + "default_ceiling": DEFAULT_TODOS_PER_WORKER_BRANCH, + "external_ceiling_role": "planner_batch_ceiling", + }, + }, + "adaptive-resilient": { + "schema_version": WORKER_HARNESS_PROFILE_SCHEMA_VERSION, + "profile": "adaptive-resilient", + "source": "generalized_from_long_horizon_calibration_evidence", + "design_intent": ( + "Generalize the best observed harness traits without copying an experimental " + "N value, duration limit, or saturated-fill policy. Lane width uses " + "independent-lane admission -- the serial survival-product prefix was a " + "structural mismatch for parallel lanes and under-filled requested width " + "in early calibration." + ), + "branch_fill_policy": "value-first", + "marginal_score_floor": 0.72, + "todo_batching_policy": { + "mode": "adaptive_value_scheduled", + "default_ceiling": MAX_TODOS_PER_WORKER_BRANCH, + "external_ceiling_required": False, + "external_ceiling_role": "optional_safety_cap_only", + "intent": ( + "Let the planner decide whether to bundle extra todos into a worker lane " + "from marginal value, rather than forcing a per-worker todo count." + ), + }, + "concurrency_policy": { + "mode": "independent_lane_admission", + "fixed_worker_count": False, + "does_not_force_requested_width": True, + "worker_width_is_ceiling": True, + "branch_count_is_value_scheduled": True, + }, + "lane_start_stagger_seconds": 1.25, + "retry_policy": { + "enabled": True, + "uses_backoff": True, + "retryable_error_families": [ + "provider_service_unreachable", + "transient_infra_failure", + ], + }, + "infra_cooldown": { + "enabled": True, + "failure_threshold": 2, + "cooldown_epochs": 2, + "strict_skip_when_healthy_width_available": True, + }, + "duration_guard": { + "enabled": False, + "controlled_by_planner": False, + "reason": "Duration limits are runner policy, not part of the generalized harness design.", + }, + "coverage_floor": { + "enabled": False, + "reason": "An earlier coverage-floor calibration arm did not show enough value to become the default design.", + }, + }, + "moe-router": { + "schema_version": WORKER_HARNESS_PROFILE_SCHEMA_VERSION, + "profile": "moe-router", + "source": "moe_style_router_redesign", + "design_intent": ( + "MoE-style value-first routing under a fixed worker ceiling: task families " + "are the experts, todos are routed tokens. Width via independent-lane " + "admission (interference-priced, never a fill rule); coverage via an " + "aux-loss-free per-family bias that only reorders routing (DeepSeek-V3 " + "invariant: bias never touches value bookkeeping); bundle length via the " + "DSpark confident-prefix cutoff (arXiv:2607.05147) with per-family " + "accept-rate calibration plus a wall-clock straggler guard." + ), + "branch_fill_policy": "confident-prefix", + "marginal_score_floor": 0.72, + "bundle_confidence_threshold": 0.6, + # 2.5 x median permits a 2-deep bundle at uniform measured durations + # while still fencing slow families; 1.25 would cap everything at 1 + # and make the confident-prefix rule unreachable. + "bundle_straggler_factor": 2.5, + "todo_batching_policy": { + "mode": "confident_prefix_scheduled", + "default_ceiling": MAX_TODOS_PER_WORKER_BRANCH, + "external_ceiling_required": False, + "external_ceiling_role": "optional_safety_cap_only", + "intent": ( + "DSpark-faithful bundle sizing: append todos while calibrated per-todo " + "acceptance confidence clears the threshold; truncate at the first " + "below-threshold todo; cap the serial tail by predicted wall-clock." + ), + }, + "concurrency_policy": { + "mode": "independent_lane_admission", + "fixed_worker_count": False, + "does_not_force_requested_width": True, + "worker_width_is_ceiling": True, + "branch_count_is_value_scheduled": True, + }, + "opportunistic_lane_policy": { + "enabled": True, + "target_utilization_floor": 0.65, + "min_lane_value_floor": 0.01, + "min_lane_value_ratio": 0.2, + "intent": ( + "Keep the high-confidence core from the theta peak, " + "then admit additional positive-yield lanes up to a utilization floor " + "so B does not waste worker capacity after proving active-lane quality." + ), + }, + "router_policy": { + "enabled": True, + "state_schema": "loopx_explore_router_state_v0", + "bias_affects_routing_order_only": True, + "admission_uses_unbiased_value": True, + "experts": "affinity families (scope:artifacts/) declared via work-item write scopes", + }, + "lane_start_stagger_seconds": 1.25, + "retry_policy": { + "enabled": True, + "uses_backoff": True, + "retryable_error_families": [ + "provider_service_unreachable", + "transient_infra_failure", + ], + }, + "infra_cooldown": { + "enabled": True, + "failure_threshold": 2, + "cooldown_epochs": 2, + "strict_skip_when_healthy_width_available": True, + }, + "duration_guard": { + "enabled": False, + "controlled_by_planner": False, + "reason": "Duration limits are runner policy, not part of the harness design.", + }, + "coverage_floor": { + "enabled": False, + "reason": "Replaced by the aux-loss-free routing bias plus coverage recency bonus.", + }, + }, +} + + +def worker_harness_profile_names() -> tuple[str, ...]: + """Return available worker-harness profile identifiers in canonical sorted order.""" + + return tuple(sorted(WORKER_HARNESS_PROFILES)) + + +def resolve_todo_branch_plan_gate( + orchestration: Mapping[str, Any] | None, + *, + requested_width: int, +) -> dict[str, Any]: + """Resolve the shared explore-harness gate with the branch planner's lane ceiling.""" + + return resolve_explore_harness_gate( + orchestration, + requested_width=requested_width, + max_lanes=MAX_BRANCH_WIDTH, + max_lanes_label="max_branch_width", + ) def explore_harness_required_contract(*, default_profile: str) -> dict[str, Any]: diff --git a/loopx/capabilities/explore/todo_branch_plan.py b/loopx/capabilities/explore/todo_branch_plan.py index f603703ab6..6c08531268 100644 --- a/loopx/capabilities/explore/todo_branch_plan.py +++ b/loopx/capabilities/explore/todo_branch_plan.py @@ -23,8 +23,9 @@ from .harness_gate import ( GATE_STATE_ANALYSIS_ONLY, GATE_STATE_DISABLED, + MAX_BRANCH_WIDTH as MAX_BRANCH_WIDTH, explore_harness_required_contract, - resolve_explore_harness_gate as _resolve_explore_harness_gate, + resolve_todo_branch_plan_gate as resolve_todo_branch_plan_gate, ) from .speculative_scheduler import ( build_branch_plan_ab_result, @@ -42,7 +43,6 @@ TODO_BRANCH_PLAN_SCHEMA_VERSION = "loopx_explore_todo_branch_plan_v0" DEFAULT_BRANCH_WIDTH = 3 -MAX_BRANCH_WIDTH = 8 TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_:\-]{3,}") SHARED_DEPENDENCY_CAPABILITY_PREFIXES = ( "shared_artifact:", @@ -249,21 +249,6 @@ def _claim_command(*, goal_id: str, todo_id: str, agent_id: str | None) -> str | ) -def resolve_todo_branch_plan_gate( - orchestration: Mapping[str, Any] | None, - *, - requested_width: int, -) -> dict[str, Any]: - """Resolve the shared explore-harness gate with this planner's lane ceiling.""" - - return _resolve_explore_harness_gate( - orchestration, - requested_width=requested_width, - max_lanes=MAX_BRANCH_WIDTH, - max_lanes_label="max_branch_width", - ) - - def _disabled_todo_branch_plan( *, goal_id: str, diff --git a/loopx/capabilities/explore/turn_context.py b/loopx/capabilities/explore/turn_context.py index eba6171c18..b5c9311485 100644 --- a/loopx/capabilities/explore/turn_context.py +++ b/loopx/capabilities/explore/turn_context.py @@ -25,10 +25,7 @@ explore_result_log_path, load_explore_result_events_strict, ) -from .todo_branch_plan import ( - build_explore_todo_branch_plan, - resolve_todo_branch_plan_gate, -) +from .harness_gate import resolve_todo_branch_plan_gate def _policy(registry_path: Path, goal_id: str, runtime_root: Path | None = None) -> tuple[dict[str, Any], Any, dict[str, Any]]: @@ -146,8 +143,11 @@ def explore_turn_context( status="open", agent_id=agent_id, runtime_root_arg=str(runtime_root), + include_acceptance=False, ) if gate["enabled"]: + from .todo_branch_plan import build_explore_todo_branch_plan + plan = build_explore_todo_branch_plan( goal_id=goal_id, agent_id=agent_id, diff --git a/loopx/capabilities/explore/worker_branch_plan.py b/loopx/capabilities/explore/worker_branch_plan.py index 42cb086ecc..6e84248ac2 100644 --- a/loopx/capabilities/explore/worker_branch_plan.py +++ b/loopx/capabilities/explore/worker_branch_plan.py @@ -10,10 +10,16 @@ normalize_todo_id, ) from .harness_gate import ( + DEFAULT_TODOS_PER_WORKER_BRANCH, + DEFAULT_WORKER_HARNESS_PROFILE, GATE_STATE_ANALYSIS_ONLY, GATE_STATE_DISABLED, + MAX_TODOS_PER_WORKER_BRANCH, + WORKER_HARNESS_PROFILES, + WORKER_HARNESS_PROFILE_SCHEMA_VERSION as WORKER_HARNESS_PROFILE_SCHEMA_VERSION, explore_harness_required_contract, resolve_explore_harness_gate as _resolve_explore_harness_gate, + worker_harness_profile_names as worker_harness_profile_names, ) from .router_state import family_routing_terms, is_router_state from .resource_portfolio import ( @@ -51,185 +57,13 @@ WORKER_BRANCH_PLAN_SCHEMA_VERSION = "loopx_explore_worker_branch_plan_v0" -WORKER_HARNESS_PROFILE_SCHEMA_VERSION = "loopx_explore_worker_harness_profile_v0" -DEFAULT_TODOS_PER_WORKER_BRANCH = 3 -MAX_TODOS_PER_WORKER_BRANCH = 8 # Worker lanes are independent parallel worker processes; their width ceiling # must not inherit MAX_BRANCH_WIDTH=8 from the serial todo-branch planner # (that clamp silently capped a requested width of 10 at 8 in an early # long-horizon calibration run). MAX_WORKER_LANES = 16 -DEFAULT_WORKER_HARNESS_PROFILE = "generic" BRANCH_FILL_POLICIES = {"bundle-by-affinity", "value-first", "confident-prefix"} -WORKER_HARNESS_PROFILES: dict[str, dict[str, Any]] = { - "generic": { - "schema_version": WORKER_HARNESS_PROFILE_SCHEMA_VERSION, - "profile": "generic", - "source": "loopx_explore_worker_branch_plan_default", - "design_intent": "Generic dry-run worker-lane planning without runtime policy assumptions.", - "branch_fill_policy": "bundle-by-affinity", - "concurrency_policy": { - "mode": "bounded_confidence_prefix", - "fixed_worker_count": False, - "does_not_force_requested_width": True, - }, - "duration_guard": { - "enabled": False, - "controlled_by_planner": False, - }, - "retry_policy": { - "enabled": False, - "controlled_by_planner": False, - }, - "infra_cooldown": { - "enabled": False, - "controlled_by_planner": False, - }, - "todo_batching_policy": { - "mode": "fixed_safety_ceiling", - "default_ceiling": DEFAULT_TODOS_PER_WORKER_BRANCH, - "external_ceiling_role": "planner_batch_ceiling", - }, - }, - "adaptive-resilient": { - "schema_version": WORKER_HARNESS_PROFILE_SCHEMA_VERSION, - "profile": "adaptive-resilient", - "source": "generalized_from_long_horizon_calibration_evidence", - "design_intent": ( - "Generalize the best observed harness traits without copying an experimental " - "N value, duration limit, or saturated-fill policy. Lane width uses " - "independent-lane admission -- the serial survival-product prefix was a " - "structural mismatch for parallel lanes and under-filled requested width " - "in early calibration." - ), - "branch_fill_policy": "value-first", - "marginal_score_floor": 0.72, - "todo_batching_policy": { - "mode": "adaptive_value_scheduled", - "default_ceiling": MAX_TODOS_PER_WORKER_BRANCH, - "external_ceiling_required": False, - "external_ceiling_role": "optional_safety_cap_only", - "intent": ( - "Let the planner decide whether to bundle extra todos into a worker lane " - "from marginal value, rather than forcing a per-worker todo count." - ), - }, - "concurrency_policy": { - "mode": "independent_lane_admission", - "fixed_worker_count": False, - "does_not_force_requested_width": True, - "worker_width_is_ceiling": True, - "branch_count_is_value_scheduled": True, - }, - "lane_start_stagger_seconds": 1.25, - "retry_policy": { - "enabled": True, - "uses_backoff": True, - "retryable_error_families": [ - "provider_service_unreachable", - "transient_infra_failure", - ], - }, - "infra_cooldown": { - "enabled": True, - "failure_threshold": 2, - "cooldown_epochs": 2, - "strict_skip_when_healthy_width_available": True, - }, - "duration_guard": { - "enabled": False, - "controlled_by_planner": False, - "reason": "Duration limits are runner policy, not part of the generalized harness design.", - }, - "coverage_floor": { - "enabled": False, - "reason": "An earlier coverage-floor calibration arm did not show enough value to become the default design.", - }, - }, - "moe-router": { - "schema_version": WORKER_HARNESS_PROFILE_SCHEMA_VERSION, - "profile": "moe-router", - "source": "moe_style_router_redesign", - "design_intent": ( - "MoE-style value-first routing under a fixed worker ceiling: task families " - "are the experts, todos are routed tokens. Width via independent-lane " - "admission (interference-priced, never a fill rule); coverage via an " - "aux-loss-free per-family bias that only reorders routing (DeepSeek-V3 " - "invariant: bias never touches value bookkeeping); bundle length via the " - "DSpark confident-prefix cutoff (arXiv:2607.05147) with per-family " - "accept-rate calibration plus a wall-clock straggler guard." - ), - "branch_fill_policy": "confident-prefix", - "marginal_score_floor": 0.72, - "bundle_confidence_threshold": 0.6, - # 2.5 x median permits a 2-deep bundle at uniform measured durations - # while still fencing slow families; 1.25 would cap everything at 1 - # and make the confident-prefix rule unreachable. - "bundle_straggler_factor": 2.5, - "todo_batching_policy": { - "mode": "confident_prefix_scheduled", - "default_ceiling": MAX_TODOS_PER_WORKER_BRANCH, - "external_ceiling_required": False, - "external_ceiling_role": "optional_safety_cap_only", - "intent": ( - "DSpark-faithful bundle sizing: append todos while calibrated per-todo " - "acceptance confidence clears the threshold; truncate at the first " - "below-threshold todo; cap the serial tail by predicted wall-clock." - ), - }, - "concurrency_policy": { - "mode": "independent_lane_admission", - "fixed_worker_count": False, - "does_not_force_requested_width": True, - "worker_width_is_ceiling": True, - "branch_count_is_value_scheduled": True, - }, - "opportunistic_lane_policy": { - "enabled": True, - "target_utilization_floor": 0.65, - "min_lane_value_floor": 0.01, - "min_lane_value_ratio": 0.2, - "intent": ( - "Keep the high-confidence core from the theta peak, " - "then admit additional positive-yield lanes up to a utilization floor " - "so B does not waste worker capacity after proving active-lane quality." - ), - }, - "router_policy": { - "enabled": True, - "state_schema": "loopx_explore_router_state_v0", - "bias_affects_routing_order_only": True, - "admission_uses_unbiased_value": True, - "experts": "affinity families (scope:artifacts/) declared via work-item write scopes", - }, - "lane_start_stagger_seconds": 1.25, - "retry_policy": { - "enabled": True, - "uses_backoff": True, - "retryable_error_families": [ - "provider_service_unreachable", - "transient_infra_failure", - ], - }, - "infra_cooldown": { - "enabled": True, - "failure_threshold": 2, - "cooldown_epochs": 2, - "strict_skip_when_healthy_width_available": True, - }, - "duration_guard": { - "enabled": False, - "controlled_by_planner": False, - "reason": "Duration limits are runner policy, not part of the harness design.", - }, - "coverage_floor": { - "enabled": False, - "reason": "Replaced by the aux-loss-free routing bias plus coverage recency bonus.", - }, - }, -} - COMMON_TOPIC_TOKENS = { "add", "after", @@ -279,10 +113,6 @@ } -def worker_harness_profile_names() -> tuple[str, ...]: - return tuple(sorted(WORKER_HARNESS_PROFILES)) - - def _worker_harness_profile(profile: str | None) -> dict[str, Any]: normalized = str(profile or DEFAULT_WORKER_HARNESS_PROFILE).strip().lower().replace("_", "-") if normalized not in WORKER_HARNESS_PROFILES: diff --git a/loopx/capabilities/issue_fix/pr_gate_reconcile.py b/loopx/capabilities/issue_fix/pr_gate_reconcile.py index 7eed44e745..4bb07e3706 100644 --- a/loopx/capabilities/issue_fix/pr_gate_reconcile.py +++ b/loopx/capabilities/issue_fix/pr_gate_reconcile.py @@ -4,13 +4,12 @@ from pathlib import Path from typing import Any -from ...history import load_registry +from ...control_plane.projects.registry_codec import load_registry from ...paths import resolve_runtime_root from ...control_plane.todos.contract import ( normalize_todo_decision_scope, ) from ...control_plane.todos.todo_semantics import todo_item_task_class -from ...control_plane.todos.mutation_api import complete_goal_todo from ...control_plane.todos.list_readback import list_goal_todos from .pr_lifecycle_rollout import append_pr_merge_rollout_event from .pr_review_ack import ( @@ -53,6 +52,7 @@ def _pr_lifecycle_todo( role="user", todo_id=todo_id, project=project, + include_acceptance=False, ) todo = todo_payload.get("todo") if not isinstance(todo, dict): @@ -133,6 +133,8 @@ def reconcile_issue_fix_pr_gate( return receipt if not already_reconciled: + from ...control_plane.todos.mutation_api import complete_goal_todo + permalink = str(observation.get("permalink") or url) terminal_at = str( observation.get("merged_at") @@ -315,6 +317,8 @@ def reconcile_issue_fix_pr_review( return receipt if not already_reconciled: + from ...control_plane.todos.mutation_api import complete_goal_todo + permalink = str(observation.get("permalink") or url) terminal_at = str( observation.get("merged_at") diff --git a/loopx/capabilities/issue_fix/pr_lifecycle_rollout.py b/loopx/capabilities/issue_fix/pr_lifecycle_rollout.py index a7167d7662..b0d24006fe 100644 --- a/loopx/capabilities/issue_fix/pr_lifecycle_rollout.py +++ b/loopx/capabilities/issue_fix/pr_lifecycle_rollout.py @@ -3,7 +3,7 @@ from pathlib import Path from typing import Any -from ...history import load_registry +from ...control_plane.projects.registry_codec import load_registry from ...paths import resolve_runtime_root from ...rollout_event_log import ( append_rollout_event, diff --git a/loopx/capabilities/issue_fix/pr_review_ack.py b/loopx/capabilities/issue_fix/pr_review_ack.py index 0d1189b979..0205aad8c9 100644 --- a/loopx/capabilities/issue_fix/pr_review_ack.py +++ b/loopx/capabilities/issue_fix/pr_review_ack.py @@ -11,7 +11,7 @@ normalize_todo_bound_agent, ) from ...control_plane.todos.todo_semantics import todo_item_task_class -from ...history import load_registry +from ...control_plane.projects.registry_codec import load_registry from ...paths import resolve_runtime_root from ...rollout_event_log import ( append_rollout_event_once, diff --git a/loopx/capabilities/issue_fix/pr_wait_reconcile.py b/loopx/capabilities/issue_fix/pr_wait_reconcile.py index d763a15bfe..b0e4ff7837 100644 --- a/loopx/capabilities/issue_fix/pr_wait_reconcile.py +++ b/loopx/capabilities/issue_fix/pr_wait_reconcile.py @@ -14,7 +14,7 @@ from ...control_plane.effect_runtime import effect_runtime_result from ...control_plane.runtime.time import now_utc_iso from ...control_plane.todos.resume_condition import compact_todo_resume_items -from ...history import load_registry +from ...control_plane.projects.registry_codec import load_registry from ...file_lock import exclusive_file_lock, LockAcquisitionPolicy, LockAcquireTimeoutError from ...paths import resolve_runtime_root from ...rollout_event_log import ( @@ -67,6 +67,7 @@ def _reconcile_locked( runtime_root_arg=str(runtime), goal_id=goal_id, role="agent", + include_acceptance=False, )["todos"] ) compact = compact_todo_resume_items(todos) diff --git a/loopx/cli_commands/__init__.py b/loopx/cli_commands/__init__.py index 769bf2372f..7b1e8813dd 100644 --- a/loopx/cli_commands/__init__.py +++ b/loopx/cli_commands/__init__.py @@ -1,4 +1,3 @@ -# ruff: noqa: F401 """Modular CLI command registrations. Command modules expose two small functions: @@ -8,128 +7,114 @@ The top-level CLI keeps global options, registry fallback, and dispatch order. -The historical function re-exports remain available, but they are loaded only -when a caller requests one. Importing a command-owned submodule must not import -every other CLI command first. +The historical function re-exports remain available, but each requested symbol +loads only its owning command submodule rather than importing every CLI command. """ -_EXPORTS_LOADED = False +from importlib import import_module - -def _load_exports() -> None: - """Load the legacy function facade on first attribute access.""" - - global _EXPORTS_LOADED - if _EXPORTS_LOADED: - return - - from .turn import handle_turn_command, register_turn_commands - from .host_mode_plan import ( - handle_host_mode_plan_command, - register_host_mode_plan_command, - ) - from .benchmark_boundary import ( - handle_benchmark_boundary_command, - register_benchmark_boundary_commands, - ) - from .benchmark_dispatch import ( - handle_benchmark_command, - register_benchmark_command_group, - ) - from .benchmark_continuation import ( - handle_benchmark_continuation_command, - register_benchmark_continuation_commands, - ) - from .bootstrap_connect import ( - handle_bootstrap_connect_command, - register_bootstrap_connect_command, - ) - from .canary import handle_canary_command, register_canary_commands - from .authority_archive import handle_authority_archive_command, register_authority_archive_command - from .postgres import handle_postgres_command, register_postgres_commands - from .coordination_shadow import ( - handle_coordination_shadow_command, - register_coordination_shadow_command, - ) - from .capability import handle_capability_command, register_capability_commands - from .extension import handle_extension_command, register_extension_commands - from .doctor import handle_doctor_command, register_doctor_command - from .first_run_report import ( - handle_first_run_report_command, - register_first_run_report_command, - ) - from .dreaming import handle_dreaming_command, register_dreaming_commands - from .explore import handle_explore_command, register_explore_commands - from .handoff_mode import handle_handoff_mode_command, register_handoff_mode_command - from .history import handle_history_command, register_history_command - from .goal_channel import handle_goal_channel_command, register_goal_channel_commands - from .lark_inbox import ( - build_lark_issue_fix_reviewer_provider_hooks, - handle_lark_inbox_command, - register_lark_inbox_commands, - ) - from .lark_kanban import handle_lark_kanban_command, register_lark_kanban_commands - from .ml_experiment import handle_ml_experiment_command, register_ml_experiment_commands - from .project_lifecycle import ( - handle_project_lifecycle_command, - register_project_lifecycle_commands, - ) - from .project import handle_project_command, register_project_commands - from .preset import handle_preset_command, register_preset_commands - from .presentation import handle_presentation_command, register_presentation_commands - from .dash import handle_dash_command, register_dash_commands - from .pr_review import handle_pr_review_command, register_pr_review_command - from .deepresearch import handle_deepresearch_command, register_deepresearch_command - from .quota import handle_quota_command, register_quota_command - from .ready_score import handle_ready_score_command, register_ready_score_command - from .review_batch import handle_review_batch_command, register_review_batch_commands - from .registry_admin import ( - handle_registry_admin_command, - register_registry_admin_commands, - ) - from .slash_commands import handle_slash_commands_command, register_slash_commands_command - from .starter import ( - handle_demo_command, - handle_starter_command, - register_starter_commands, - ) - from .starter_bootstrap import ( - handle_codex_cli_bootstrap_message_command, - handle_loopx_bootstrap_command_pack_command, - handle_new_project_prompt_command, - handle_starter_bootstrap_command, - ) - from .starter_bootstrap_registration import register_starter_bootstrap_commands - from .summary_all import handle_summary_all_command, register_summary_all_command - from .status import ( - handle_check_command, - handle_diagnose_command, - handle_review_packet_command, - handle_status_command, - register_status_commands, - ) - from .support_control import ( - handle_support_control_command, - register_support_control_commands, - ) - from .authority_shadow import ( - handle_authority_shadow_command, - register_authority_shadow_command, - ) - from .task_lease import handle_task_lease_command, register_task_lease_command - from .todo import handle_todo_command - from .todo_registration import register_todo_command - from .version import handle_version_command, register_version_command - from .usage_ping import handle_usage_ping_command, register_usage_ping_command - from .worker_bridge import handle_worker_bridge_command, register_worker_bridge_commands - from .workflow_skills import ( - handle_workflow_skills_command, - register_workflow_skills_command, - ) - - namespace = locals() - globals().update({name: namespace[name] for name in __all__}) - _EXPORTS_LOADED = True +_EXPORT_SUBMODULES: dict[str, str] = { + "handle_turn_command": "turn", + "register_turn_commands": "turn", + "handle_host_mode_plan_command": "host_mode_plan", + "register_host_mode_plan_command": "host_mode_plan", + "handle_benchmark_boundary_command": "benchmark_boundary", + "register_benchmark_boundary_commands": "benchmark_boundary", + "handle_benchmark_command": "benchmark_dispatch", + "register_benchmark_command_group": "benchmark_dispatch", + "handle_benchmark_continuation_command": "benchmark_continuation", + "register_benchmark_continuation_commands": "benchmark_continuation", + "handle_bootstrap_connect_command": "bootstrap_connect", + "register_bootstrap_connect_command": "bootstrap_connect", + "handle_canary_command": "canary", + "register_canary_commands": "canary", + "handle_authority_archive_command": "authority_archive", + "register_authority_archive_command": "authority_archive", + "handle_postgres_command": "postgres", + "register_postgres_commands": "postgres", + "handle_coordination_shadow_command": "coordination_shadow", + "register_coordination_shadow_command": "coordination_shadow", + "handle_capability_command": "capability", + "register_capability_commands": "capability", + "handle_extension_command": "extension", + "register_extension_commands": "extension", + "handle_doctor_command": "doctor", + "register_doctor_command": "doctor", + "handle_first_run_report_command": "first_run_report", + "register_first_run_report_command": "first_run_report", + "handle_dreaming_command": "dreaming", + "register_dreaming_commands": "dreaming", + "handle_explore_command": "explore", + "register_explore_commands": "explore", + "handle_handoff_mode_command": "handoff_mode", + "register_handoff_mode_command": "handoff_mode", + "handle_history_command": "history", + "register_history_command": "history", + "handle_goal_channel_command": "goal_channel", + "register_goal_channel_commands": "goal_channel", + "build_lark_issue_fix_reviewer_provider_hooks": "lark_inbox", + "handle_lark_inbox_command": "lark_inbox", + "register_lark_inbox_commands": "lark_inbox", + "handle_lark_kanban_command": "lark_kanban", + "register_lark_kanban_commands": "lark_kanban", + "handle_ml_experiment_command": "ml_experiment", + "register_ml_experiment_commands": "ml_experiment", + "handle_project_lifecycle_command": "project_lifecycle", + "register_project_lifecycle_commands": "project_lifecycle", + "handle_project_command": "project", + "register_project_commands": "project", + "handle_preset_command": "preset", + "register_preset_commands": "preset", + "handle_presentation_command": "presentation", + "register_presentation_commands": "presentation", + "handle_dash_command": "dash", + "register_dash_commands": "dash", + "handle_pr_review_command": "pr_review", + "register_pr_review_command": "pr_review", + "handle_deepresearch_command": "deepresearch", + "register_deepresearch_command": "deepresearch", + "handle_quota_command": "quota", + "register_quota_command": "quota", + "handle_ready_score_command": "ready_score", + "register_ready_score_command": "ready_score", + "handle_review_batch_command": "review_batch", + "register_review_batch_commands": "review_batch", + "handle_registry_admin_command": "registry_admin", + "register_registry_admin_commands": "registry_admin", + "handle_slash_commands_command": "slash_commands", + "register_slash_commands_command": "slash_commands", + "handle_demo_command": "starter", + "handle_starter_command": "starter", + "register_starter_commands": "starter", + "handle_codex_cli_bootstrap_message_command": "starter_bootstrap", + "handle_loopx_bootstrap_command_pack_command": "starter_bootstrap", + "handle_new_project_prompt_command": "starter_bootstrap", + "handle_starter_bootstrap_command": "starter_bootstrap", + "register_starter_bootstrap_commands": "starter_bootstrap_registration", + "handle_summary_all_command": "summary_all", + "register_summary_all_command": "summary_all", + "handle_check_command": "status", + "handle_diagnose_command": "status", + "handle_review_packet_command": "status", + "handle_status_command": "status", + "register_status_commands": "status", + "handle_support_control_command": "support_control", + "register_support_control_commands": "support_control", + "handle_authority_shadow_command": "authority_shadow", + "register_authority_shadow_command": "authority_shadow", + "handle_task_lease_command": "task_lease", + "register_task_lease_command": "task_lease", + "handle_todo_command": "todo", + "register_todo_command": "todo_registration", + "handle_version_command": "version", + "register_version_command": "version", + "handle_usage_ping_command": "usage_ping", + "register_usage_ping_command": "usage_ping", + "handle_worker_bridge_command": "worker_bridge", + "register_worker_bridge_commands": "worker_bridge", + "handle_workflow_skills_command": "workflow_skills", + "register_workflow_skills_command": "workflow_skills", +} __all__ = [ "handle_turn_command", @@ -236,10 +221,12 @@ def _load_exports() -> None: def __getattr__(name: str) -> object: - if name not in __all__: + module_name = _EXPORT_SUBMODULES.get(name) + if module_name is None or name not in __all__: raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - _load_exports() - return globals()[name] + value = getattr(import_module(f".{module_name}", __name__), name) + globals()[name] = value + return value def __dir__() -> list[str]: diff --git a/loopx/cli_commands/explore.py b/loopx/cli_commands/explore.py index e5e938b46e..6006272ed3 100644 --- a/loopx/cli_commands/explore.py +++ b/loopx/cli_commands/explore.py @@ -22,40 +22,12 @@ explore_result_log_path, load_explore_result_events_strict, ) -from ..capabilities.explore.research_evidence import append_research_observation -from ..capabilities.explore.harness_gate import GATE_STATE_DISABLED -from ..capabilities.explore.resource_portfolio import parse_resource_counts -from ..capabilities.explore.source_history_reconcile import ( - reconcile_explore_source_history, -) -from ..capabilities.explore.todo_branch_plan import ( - build_explore_todo_branch_plan, - resolve_todo_branch_plan_gate, -) -from ..capabilities.explore.worker_branch_plan import ( - build_explore_worker_branch_plan, - resolve_explore_harness_gate, -) +from ..control_plane.projects.registry_codec import load_registry from ..control_plane.runtime.runtime_projection_route import ( compact_goal_source_runtime_route, resolve_goal_source_runtime_route, ) -from ..extensions.lark import LARK_EXTENSION_ID, LARK_PROJECTION_SINK_PERMISSION -from ..extensions.lark.presentation.explore_results import ( - lark_explore_schema_payload, - read_lark_explore_local_config, -) -from ..extensions.lark.presentation.explore_singleflight import ( - default_lark_explore_config_path, -) -from ..presentation.explore_views import build_explore_presentation_bundle -from ..extensions.runtime import ( - default_extension_state_file, - resolve_extension_activation, -) -from ..history import load_registry from ..paths import resolve_runtime_root -from ..control_plane.todos.list_readback import list_goal_todos from .explore_feishu_commands import ( FEISHU_SINK_EXPLORE_COMMANDS, handle_explore_feishu_command, @@ -534,6 +506,9 @@ def handle_explore_command( if args.explore_command in ( {"schema", "source-history-reconcile"} | FEISHU_SINK_EXPLORE_COMMANDS ): + from ..extensions.lark import LARK_EXTENSION_ID, LARK_PROJECTION_SINK_PERMISSION + from ..extensions.runtime import default_extension_state_file, resolve_extension_activation + activation = resolve_extension_activation( LARK_EXTENSION_ID, state_file=default_extension_state_file(runtime_root), @@ -553,12 +528,9 @@ def handle_explore_command( same_source = source_registry.resolve() == registry_path.resolve() projection_for = partial(_projection_for, registry=registry if same_source else None, source_registry=None if same_source else source_registry) - config_path = ( - Path(args.config_path).expanduser() - if getattr(args, "config_path", None) - else default_lark_explore_config_path(source_registry) - ) if args.explore_command == "schema": + from ..extensions.lark.presentation.explore_results import lark_explore_schema_payload + payload = lark_explore_schema_payload() elif args.explore_command == "turn-context": from ..capabilities.explore.turn_context import explore_turn_context @@ -627,6 +599,8 @@ def handle_explore_command( ) payload = _append_event_payload(event, runtime_root=runtime_root, goal_id=args.goal_id) elif args.explore_command == "observe": + from ..capabilities.explore.research_evidence import append_research_observation + observation = json.loads(Path(args.observation_json).read_text(encoding="utf-8")) if not isinstance(observation, dict): raise ValueError("research observation must be an object") @@ -639,6 +613,8 @@ def handle_explore_command( elif args.explore_command == "summary": payload = projection_for(args, runtime_root=runtime_root) elif args.explore_command == "presentation": + from ..presentation.explore_views import build_explore_presentation_bundle + projection = projection_for( args, runtime_root=runtime_root, @@ -646,6 +622,15 @@ def handle_explore_command( ) payload = build_explore_presentation_bundle(projection) elif args.explore_command == "source-history-reconcile": + from ..capabilities.explore.source_history_reconcile import reconcile_explore_source_history + from ..extensions.lark.presentation.explore_results import read_lark_explore_local_config + from ..extensions.lark.presentation.explore_singleflight import default_lark_explore_config_path + + config_path = ( + Path(args.config_path).expanduser() + if getattr(args, "config_path", None) + else default_lark_explore_config_path(source_registry) + ) local = read_lark_explore_local_config(config_path) result_records = ( local.get("result_records") @@ -702,6 +687,14 @@ def handle_explore_command( ) payload["out"] = str(out_path) elif args.explore_command == "todo-branch-plan": + from ..capabilities.explore.harness_gate import GATE_STATE_DISABLED + from ..capabilities.explore.resource_portfolio import parse_resource_counts + from ..capabilities.explore.todo_branch_plan import ( + build_explore_todo_branch_plan, + resolve_todo_branch_plan_gate, + ) + from ..control_plane.todos.list_readback import list_goal_todos + resource_capacities = parse_resource_counts( args.resource_capacity, flag_name="--resource-capacity", @@ -735,6 +728,7 @@ def handle_explore_command( role="agent", status="open", agent_id=args.agent_id, + include_acceptance=False, ) payload = build_explore_todo_branch_plan( goal_id=args.goal_id, @@ -755,6 +749,14 @@ def handle_explore_command( "todo_count": todo_payload.get("todo_count"), } elif args.explore_command == "worker-branch-plan": + from ..capabilities.explore.harness_gate import GATE_STATE_DISABLED + from ..capabilities.explore.resource_portfolio import parse_resource_counts + from ..capabilities.explore.worker_branch_plan import ( + build_explore_worker_branch_plan, + resolve_explore_harness_gate, + ) + from ..control_plane.todos.list_readback import list_goal_todos + resource_capacities = parse_resource_counts( args.resource_capacity, flag_name="--resource-capacity", @@ -788,6 +790,7 @@ def handle_explore_command( role="agent", status="open", agent_id=args.agent_id, + include_acceptance=False, ) router_state = None if getattr(args, "router_state", None): @@ -819,6 +822,13 @@ def handle_explore_command( "todo_count": todo_payload.get("todo_count"), } elif args.explore_command in FEISHU_SINK_EXPLORE_COMMANDS: + from ..extensions.lark.presentation.explore_singleflight import default_lark_explore_config_path + + config_path = ( + Path(args.config_path).expanduser() + if getattr(args, "config_path", None) + else default_lark_explore_config_path(source_registry) + ) payload = handle_explore_feishu_command( args, config_path=config_path, diff --git a/loopx/cli_commands/explore_feishu_commands.py b/loopx/cli_commands/explore_feishu_commands.py index 0a7c7a5b4f..7325e9b9bf 100644 --- a/loopx/cli_commands/explore_feishu_commands.py +++ b/loopx/cli_commands/explore_feishu_commands.py @@ -3,31 +3,19 @@ import argparse import json from pathlib import Path -from typing import Callable +from typing import TYPE_CHECKING, Callable from ..capabilities.explore.result_log import NODE_STATUSES -from ..extensions.lark.presentation.explore_results import ( +from ..extensions.lark.cli_transport import DEFAULT_CLI_BIN +from ..extensions.lark.presentation.explore_singleflight import ( DEFAULT_EXPLORE_BASE_NAME, EXPLORE_TABLE_KEYS, - LarkExploreConfig, - build_explore_result_card, - configure_lark_explore_visual_sink, - explore_visual_semantic_digest, - lark_explore_config_from_payload, - read_lark_explore_local_config, - setup_lark_explore_board, - sync_explore_results_to_lark, - sync_explore_visual_to_lark, - sync_explore_visuals_to_lark, - write_lark_explore_local_config, -) -from ..extensions.lark.presentation.explore_singleflight import ( - explore_feishu_sync_busy_packet, - explore_feishu_sync_singleflight, ) -from ..extensions.lark.cli_transport import DEFAULT_CLI_BIN from ..extensions.lark.presentation.sink_visibility import SINK_VISIBILITY_OWNER_ONLY, SINK_VISIBILITIES +if TYPE_CHECKING: + from ..extensions.lark.presentation.explore_results import LarkExploreConfig + SubcommandArg = Callable[[argparse.ArgumentParser], None] ProjectionFor = Callable[..., dict[str, object]] @@ -182,6 +170,12 @@ def register_explore_feishu_commands( def _target_config(args: argparse.Namespace, *, config_path: Path) -> LarkExploreConfig: + from ..extensions.lark.presentation.explore_results import ( + LarkExploreConfig, + lark_explore_config_from_payload, + read_lark_explore_local_config, + ) + stored = lark_explore_config_from_payload(read_lark_explore_local_config(config_path)) base_token = args.base_token or (stored.base_token if stored else None) table_ids = dict(stored.table_ids) if stored else {} @@ -206,6 +200,22 @@ def handle_explore_feishu_command( runtime_root: Path, projection_for: ProjectionFor, ) -> dict[str, object]: + from ..extensions.lark.presentation.explore_results import ( + build_explore_result_card, + configure_lark_explore_visual_sink, + explore_visual_semantic_digest, + read_lark_explore_local_config, + setup_lark_explore_board, + sync_explore_results_to_lark, + sync_explore_visual_to_lark, + sync_explore_visuals_to_lark, + write_lark_explore_local_config, + ) + from ..extensions.lark.presentation.explore_singleflight import ( + explore_feishu_sync_busy_packet, + explore_feishu_sync_singleflight, + ) + if args.explore_command == "feishu-setup": return setup_lark_explore_board( config_path=config_path, diff --git a/loopx/cli_commands/explore_planning_commands.py b/loopx/cli_commands/explore_planning_commands.py index 1237a2887b..6ae6858b27 100644 --- a/loopx/cli_commands/explore_planning_commands.py +++ b/loopx/cli_commands/explore_planning_commands.py @@ -3,7 +3,7 @@ import argparse from typing import Callable -from ..capabilities.explore.worker_branch_plan import ( +from ..capabilities.explore.harness_gate import ( DEFAULT_WORKER_HARNESS_PROFILE, worker_harness_profile_names, ) diff --git a/loopx/cli_commands/support_control_heartbeat.py b/loopx/cli_commands/support_control_heartbeat.py index f4128bab34..04bc3224df 100644 --- a/loopx/cli_commands/support_control_heartbeat.py +++ b/loopx/cli_commands/support_control_heartbeat.py @@ -10,15 +10,6 @@ registered_agent_ids_from_registry, require_registered_agent_id, ) -from ..control_plane.scheduler.execution_context import SchedulerRuntimeProfile -from ..execution_profile import execution_profile_turn_granularity -from ..heartbeat_prompt import ( - build_heartbeat_prompt, - build_heartbeat_prompt_error_payload, - project_heartbeat_agent_input, - render_heartbeat_prompt_markdown, -) -from .support_control_registry import resolve_heartbeat_active_state PrintPayload = Callable[ [dict[str, object], str, Callable[[dict[str, object]], str]], @@ -78,6 +69,16 @@ def handle_heartbeat_prompt_command( print_payload: PrintPayload, output_format: FormatSelector, ) -> int: + from ..control_plane.scheduler.execution_context import SchedulerRuntimeProfile + from ..execution_profile import execution_profile_turn_granularity + from ..heartbeat_prompt import ( + build_heartbeat_prompt, + build_heartbeat_prompt_error_payload, + project_heartbeat_agent_input, + render_heartbeat_prompt_markdown, + ) + from .support_control_registry import resolve_heartbeat_active_state + active_state = None resolved_active_state = None active_state_source = None @@ -335,9 +336,11 @@ def _verified_codex_resume(args: argparse.Namespace, registry: Path, agent_id: s """Select the short wake only for the Host's existing scoped conversation.""" session_id = getattr(args, "resume_codex_session_id", None) if not (session_id and args.thin and not args.bootstrap and args.turn_instance_id - and agent_id and args.runtime_root - and args.runtime_profile == SchedulerRuntimeProfile.GENERIC_CLI_AGENT_LOOP.value - and args.visible_goal_host is None): + and agent_id and args.runtime_root and args.visible_goal_host is None): + return False + from ..control_plane.scheduler.execution_context import SchedulerRuntimeProfile + + if args.runtime_profile != SchedulerRuntimeProfile.GENERIC_CLI_AGENT_LOOP.value: return False from ..control_plane.goals.first_party_host_admission import ( FirstPartyHostGoalAdmission, capture_first_party_host_goal_ref, diff --git a/loopx/cli_commands/support_control_registry.py b/loopx/cli_commands/support_control_registry.py index 0bfe047522..2227caca30 100644 --- a/loopx/cli_commands/support_control_registry.py +++ b/loopx/cli_commands/support_control_registry.py @@ -2,7 +2,7 @@ from pathlib import Path -from ..history import load_registry +from ..control_plane.projects.registry_codec import load_registry from ..paths import global_registry_path, resolve_runtime_root, select_default_runtime_root from ..registry import registry_goals, resolve_state_file diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index ec485f3e31..0dcad7da5d 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -75,6 +75,7 @@ "goal-acceptance", "goal-lifecycle", "host-mode-plan", + "explore", "capability", "workbench", "history", @@ -576,6 +577,10 @@ def _build_selected_parser(command: str) -> LoopXArgumentParser: from .cli_commands.history import register_history_command register_history_command(subparsers) + elif command == "explore": + from .cli_commands.explore import register_explore_commands + + register_explore_commands(subparsers, add_subcommand_format) else: # pragma: no cover - caller guards the private interface raise ValueError(f"unsupported selected command: {command}") return parser @@ -914,6 +919,16 @@ def _dispatch_common_command( print_payload=print_payload, append_cli_rollout_event=append_cli_rollout_event, ) + if args.command == "explore": + from .cli_commands.explore import handle_explore_command + + return handle_explore_command( + args, + registry_path=registry_path, + runtime_root_arg=args.runtime_root, + print_payload=print_payload, + output_format=output_format, + ) return None diff --git a/loopx/control_plane/quota/turn_envelope.py b/loopx/control_plane/quota/turn_envelope.py index 1294052695..11a3898b60 100644 --- a/loopx/control_plane/quota/turn_envelope.py +++ b/loopx/control_plane/quota/turn_envelope.py @@ -79,9 +79,9 @@ def pack_turn_source( ) -> dict[str, str] | None: """Use the lossless wire for bounded sources that compress well.""" raw = _encode_rpc_json(source) - if 16 * 1024 <= len(raw) <= 1024 * 1024: + if 16 * 1024 <= len(raw) <= 16 * 1024 * 1024: data = base64.b64encode(zlib.compress(raw, level=1)).decode("ascii") - if len(data) + 128 < len(raw) * max_encoded_fraction: + if len(data) <= 2 * 1024 * 1024 and len(data) + 128 < len(raw) * max_encoded_fraction: return {"encoding": "deflate-base64-json-v0", "data": data} return None diff --git a/loopx/control_plane/quota/turn_envelope_codec.ts b/loopx/control_plane/quota/turn_envelope_codec.ts index dad97b8939..ff51c19696 100644 --- a/loopx/control_plane/quota/turn_envelope_codec.ts +++ b/loopx/control_plane/quota/turn_envelope_codec.ts @@ -175,9 +175,10 @@ export function coldPath( export function decodeTurnSource(request: JsonObject, inlineField: "payload" | "source" | "context"): JsonObject { const transport = requireJsonObject(request.source_transport, "Turn composition source transport"); const { encoding, data } = transport; - const maxSourceBytes = 1024 * 1024; + const maxEncodedBytes = 2 * 1024 * 1024; + const maxSourceBytes = 64 * 1024 * 1024; if (Object.hasOwn(request, inlineField) || encoding !== "deflate-base64-json-v0" || - typeof data !== "string" || data.length > maxSourceBytes || + typeof data !== "string" || data.length > maxEncodedBytes || data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) { throw new EffectRuntimeRequestError("invalid Turn composition source transport"); } @@ -191,7 +192,7 @@ export function decodeTurnSource(request: JsonObject, inlineField: "payload" | " if (engine.bytesWritten !== compressed.length) throw new Error("trailing compressed source data"); source = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer)); } catch { - throw new EffectRuntimeRequestError("Turn composition source must be valid compressed JSON within 1 MiB"); + throw new EffectRuntimeRequestError("Turn composition source must be valid compressed JSON within 64 MiB"); } return requireJsonObject(source, "complete Turn decision source"); } diff --git a/loopx/control_plane/todos/list_readback.py b/loopx/control_plane/todos/list_readback.py index 3aa1a5226b..1c67b600ed 100644 --- a/loopx/control_plane/todos/list_readback.py +++ b/loopx/control_plane/todos/list_readback.py @@ -39,7 +39,10 @@ def list_goal_todos( include_archived: bool = False, read_scope: Literal["active", "completed_history"] = "active", json_references: bool = False, + include_acceptance: bool = True, ) -> dict[str, Any]: + if not isinstance(include_acceptance, bool): + raise ValueError("Todo include_acceptance must be a boolean") if full_text and (thin or json_references or summary): raise ValueError("Full Todo body reads cannot use compact presentation") if read_scope not in {"active", "completed_history"}: @@ -110,6 +113,8 @@ def list_goal_todos( "state_file": str(resolved_state_file), "project": str(resolved_project) if resolved_project else None}} if summary: params["query"]["summary"] = True + if not include_acceptance: + params["query"]["include_acceptance"] = False result = project_todo_read(params) if "payload" not in result: failure = result["canonical"] @@ -122,7 +127,7 @@ def list_goal_todos( payload = result["payload"] if full_text and payload.get("full_text") is not True: raise ValueError("Complete Todo body delivery is unsupported by this runtime") - if "canonical_acceptance" in result: + if include_acceptance and "canonical_acceptance" in result: from .goal_todo_projection import observe_todo_acceptance payload = observe_todo_acceptance(payload, result["canonical_acceptance"], registry_path=source_registry, goal_id=goal_id) diff --git a/loopx/control_plane/todos/read_projection.ts b/loopx/control_plane/todos/read_projection.ts index f2f9cf9cb8..d7d9be0528 100644 --- a/loopx/control_plane/todos/read_projection.ts +++ b/loopx/control_plane/todos/read_projection.ts @@ -264,6 +264,19 @@ export async function projectTodoReadGroup( orchestration: Object.fromEntries(Object.entries(projected.orchestration).map(([name, ordinals]) => [name, ordinals.map(i => compacts[i]!)]))}; } +export function includeTodoAcceptance(input: JsonObject, query: JsonObject = {}): boolean { + const top = input.include_acceptance === undefined + ? undefined + : requireBoolean(input.include_acceptance, "Todo read include_acceptance"); + const nested = query.include_acceptance === undefined + ? undefined + : requireBoolean(query.include_acceptance, "Todo list query include_acceptance"); + if (top !== undefined && nested !== undefined && top !== nested) { + throw new EffectRuntimeRequestError("Todo read include_acceptance conflicts with query.include_acceptance"); + } + return nested ?? top ?? true; +} + export async function projectCanonicalTodoFields( input: JsonObject, options?: TodoResumeRolloutReadOptions, @@ -280,6 +293,7 @@ export async function projectCanonicalTodoFields( const lineageFacts = input.lineage_facts ?? lineage.map(successionFacts); const includeArchived = input.include_archived === true || input.retained === true; const query = input.kind === "query" && input.selection == null ? object(input.query) : {}; + const includeAcceptance = includeTodoAcceptance(input, query); const detailId = query.agent_id == null && query.limit == null ? query.todo_id : null; const fields: JsonObject = {}, evaluations: JsonObject = {}; for (const role of ["user", "agent"]) { @@ -295,7 +309,9 @@ export async function projectCanonicalTodoFields( if (grouped.rejection) return grouped; const summary = requireJsonObject(grouped.summary, "canonical Todo summary"); if (role === "agent" && input.retained !== true) { - if (checksConfigured || Object.keys(object(acceptance.outcome_requirements)).length || acceptance.goal_objective) summary.goal_acceptance_contract = acceptance; + if (includeAcceptance && (checksConfigured || Object.keys(object(acceptance.outcome_requirements)).length || acceptance.goal_objective)) { + summary.goal_acceptance_contract = acceptance; + } const done = all.filter(row => archived.has(row.todo_id) && row.done === true && taskClass(row) === "advancement_task").length; if (done) {summary.archived_advancement_done_count = done; summary.advancement_done_count = Number(summary.advancement_done_count || 0) + done;} } diff --git a/loopx/control_plane/todos/read_transaction.ts b/loopx/control_plane/todos/read_transaction.ts index 2983163edd..6d6f7b545f 100644 --- a/loopx/control_plane/todos/read_transaction.ts +++ b/loopx/control_plane/todos/read_transaction.ts @@ -6,7 +6,7 @@ import {readCanonicalSnapshot} from "../coordination/canonical_snapshot_page.ts" import {readLocalCoordinationTodoSource} from "../coordination/local_authority_read.ts"; import {LOCAL_COORDINATION_TODO_SNAPSHOT_PAGE_REQUEST_SCHEMA, LOCAL_COORDINATION_TODO_LIST_RESULT_SCHEMA} from "../coordination/coordination_state_contract.generated.ts"; -import {projectCompletionEvidence, projectCanonicalTodoFields, selectTodoReadFields, projectTodoReadGroup, TODO_READ_RESULT} from "./read_projection.ts"; +import {includeTodoAcceptance, projectCompletionEvidence, projectCanonicalTodoFields, selectTodoReadFields, projectTodoReadGroup, TODO_READ_RESULT} from "./read_projection.ts"; import {id, canonicalTodoReadItems, structureCanonicalTodo} from "./read_codec.ts"; import {compactTodoReadSummary, compactThinTodoRead, compactTodoQueueSummary, todoReadProjectionContract} from "./read_presentation.ts"; import {projectTodoContextPage, SUMMARY_SOURCES, PLANNING_SOURCES} from "./context_projection.ts"; @@ -533,7 +533,8 @@ async function todoListPayload(input: JsonObject, original: JsonObject[], fields coverage: {scope: "goal_todo_query", expected_count: projection.uncapped_todo_count, included_count: projection.uncapped_todo_count, shown_count: shownCount, available_count: projection.uncapped_todo_count, omitted: []}}); - const completeSource = !query.role && !query.status && !query.todo_id && !query.agent_id && query.limit == null && + const includeAcceptance = includeTodoAcceptance(input, query); + const completeSource = includeAcceptance && !query.role && !query.status && !query.todo_id && !query.agent_id && query.limit == null && !query.thin && !query.json_references && !summary && !fullText && !includeArchived; const sourceFields = requireJsonObject(fields.fields, "canonical Todo fields"); const sourceIdentity = Object.fromEntries(["source_authority", "store_identity", "provider_revision", "cursor"].map(key => [key, canonical[key]])); @@ -546,7 +547,7 @@ async function todoListPayload(input: JsonObject, original: JsonObject[], fields {field, field_sha256: canonicalAuthoritySha256(sourceFields[field]), changes: [], python_values: []}])), selector: {roles, status: null, todo_id: null, agent_id: null, limit: null, source_name: sourceName, observed_at: input.observed_at, evaluated_at: input.evaluated_at}}]}}} : {}), - ...(canonical.goal_acceptance_oracle_observation_basis ? {canonical_acceptance: { + ...(includeAcceptance && canonical.goal_acceptance_oracle_observation_basis ? {canonical_acceptance: { goal_acceptance_contract: canonical.goal_acceptance_contract, goal_acceptance_oracle_observation_basis: canonical.goal_acceptance_oracle_observation_basis, }} : {})}; diff --git a/loopx/control_plane/todos/read_transport.ts b/loopx/control_plane/todos/read_transport.ts index 969175eb6d..884262627d 100644 --- a/loopx/control_plane/todos/read_transport.ts +++ b/loopx/control_plane/todos/read_transport.ts @@ -59,7 +59,7 @@ export async function readTodoRuntime(value: unknown): Promise { let bytes = decoded; if (input.kind === "quota_projection" && decoded.length > inlineBytes && decoded.length <= completeBytes) { bytes = gzipSync(decoded); - } else if (input.kind === "canonical_fields" && decoded.length >= 16 * 1024 && decoded.length <= 1024 * 1024) { + } else if (input.kind === "canonical_fields" && decoded.length >= 16 * 1024 && decoded.length <= completeBytes) { // Configured Goals expose the same acceptance document in both views. // Bound synchronous work and keep dense replies inline after base64 overhead. const acceptance = object(result.canonical).goal_acceptance_contract; diff --git a/loopx/extensions/lark/presentation/explore_results.py b/loopx/extensions/lark/presentation/explore_results.py index 6d1ed55568..1e5ad2741c 100644 --- a/loopx/extensions/lark/presentation/explore_results.py +++ b/loopx/extensions/lark/presentation/explore_results.py @@ -82,6 +82,14 @@ sync_explore_visual_to_lark as sync_explore_visual_to_lark, sync_explore_visuals_to_lark as sync_explore_visuals_to_lark, ) +from .explore_singleflight import ( + DEFAULT_EXPLORE_BASE_NAME, + EXPLORE_TABLE_KEYS, + EXPLORE_TABLE_NAMES, + TABLE_EDGES, + TABLE_FINDINGS, + TABLE_NODES, +) from .message_card import build_lark_markdown_reply_card from .sink_visibility import SINK_VISIBILITY_OWNER_ONLY, SINK_VISIBILITY_SHARED, SINK_VISIBILITIES @@ -91,18 +99,6 @@ LARK_EXPLORE_READBACK_VERSION = "loopx_lark_explore_readback_v0" LARK_EXPLORE_CARD_VERSION = "loopx_lark_explore_card_v0" -DEFAULT_EXPLORE_BASE_NAME = "LoopX Exploration Results" - -TABLE_NODES = "nodes" -TABLE_EDGES = "edges" -TABLE_FINDINGS = "findings" -EXPLORE_TABLE_KEYS = (TABLE_NODES, TABLE_EDGES, TABLE_FINDINGS) -EXPLORE_TABLE_NAMES = { - TABLE_NODES: "Nodes", - TABLE_EDGES: "Edges", - TABLE_FINDINGS: "Findings", -} - def _number_field(name: str, *, precision: int) -> dict[str, Any]: diff --git a/loopx/extensions/lark/presentation/explore_singleflight.py b/loopx/extensions/lark/presentation/explore_singleflight.py index f31389e62b..0a135e4422 100644 --- a/loopx/extensions/lark/presentation/explore_singleflight.py +++ b/loopx/extensions/lark/presentation/explore_singleflight.py @@ -10,6 +10,19 @@ from ....file_lock import try_exclusive_file_lock +DEFAULT_EXPLORE_BASE_NAME = "LoopX Exploration Results" + +TABLE_NODES = "nodes" +TABLE_EDGES = "edges" +TABLE_FINDINGS = "findings" +EXPLORE_TABLE_KEYS = (TABLE_NODES, TABLE_EDGES, TABLE_FINDINGS) +EXPLORE_TABLE_NAMES = { + TABLE_NODES: "Nodes", + TABLE_EDGES: "Edges", + TABLE_FINDINGS: "Findings", +} + + def default_lark_explore_config_path(registry_path: Path | None = None) -> Path: if registry_path is not None: expanded = registry_path.expanduser() diff --git a/loopx/heartbeat_prequota.py b/loopx/heartbeat_prequota.py index 335de95fec..7647571260 100644 --- a/loopx/heartbeat_prequota.py +++ b/loopx/heartbeat_prequota.py @@ -18,7 +18,7 @@ effect_runtime_result, ) from .control_plane.todos.list_readback import list_goal_todos -from .history import load_registry +from .control_plane.projects.registry_codec import load_registry from .paths import resolve_runtime_root @@ -107,6 +107,7 @@ def load_shared_todos() -> list[dict[str, Any]]: runtime_root_arg=str(runtime), goal_id=goal_id, role=None, + include_acceptance=False, ) cached = result["todos"] shared_todo_cache["todos"] = cached diff --git a/tests/control_plane/test_long_history_todo_reads.py b/tests/control_plane/test_long_history_todo_reads.py index 3eb17f44d1..aeea98a485 100644 --- a/tests/control_plane/test_long_history_todo_reads.py +++ b/tests/control_plane/test_long_history_todo_reads.py @@ -1,4 +1,5 @@ """Synthetic long-history shapes, without copying any live text or identities.""" +import hashlib from pathlib import Path import pytest @@ -7,12 +8,18 @@ build_runtime_shadow_source_snapshot, todo_partition_projector, ) +from loopx.control_plane.coordination.local_authority_shadow_projection import canonical_bytes +from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection from loopx.control_plane.testing.canary_harness import write_fixture_registry, run_json_cli_result from loopx.control_plane.todos.active_state_todo_parser import parse_active_state_todos, parse_todo_source from loopx.control_plane.todos.goal_todo_projection import todo_summaries_from_fields +from loopx.control_plane.todos.list_readback import list_goal_todos from loopx.control_plane.todos.todo_summary import compact_evaluated_todo_group from loopx.history import load_registry -from tests.control_plane.canonical_authority_fixture import initialize_canonical_authority +from tests.control_plane.canonical_authority_fixture import ( + initialize_canonical_authority, + isolate_sqlite_runtime, +) def _initialize_source_authority( @@ -113,3 +120,103 @@ def test_capture_preserves_archived_dependency_for_real_canonical_cli_read(tmp_p assert code == 0, completed assert completed["todos"] == [] assert not state.exists() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_list_goal_todos_include_acceptance_false_keeps_parity(tmp_path: Path, monkeypatch, provider: str) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + state, runtime, registry = tmp_path / "STATE.md", tmp_path / "runtime", tmp_path / "registry.json" + state.write_text("# Synthetic goal\n\n## Agent Todo\n\n- [ ] Active item\n", encoding="utf-8") + write_fixture_registry( + project=tmp_path, + runtime_root=runtime, + registry_path=registry, + goal_id="goal-a", + domain="acceptance-skip", + adapter_kind="generic_project_goal_v0", + state_file=str(state), + registered_agents=["agent-a"], + quota_allowed_slots=None, + ) + records = [{ + "schema_version": "todo_item_v0", + "todo_id": "todo_work", + "index": 1, + "role": "agent", + "status": "open", + "done": False, + "text": "Deliver verified feature", + "task_class": "advancement_task", + "archive_state": "active", + "source_section": "Agent Todo", + }] + projection = build_todo_runtime_shadow_projection(goal_id="goal-a", todos=records) + document = { + "objective": "Keep Todo parity while skipping acceptance payloads", + "non_goals": [], + "bindings": [], + "criteria": [{ + "id": "criterion-a", + "description": "Check stays enabled", + "validation_argv": ["true"], + "validation_timeout_seconds": 5, + "validation_files": [], + }], + } + projection["goal_acceptance"] = { + "schema_version": "loopx_goal_acceptance_v0", + "enabled": True, + "revision": 1, + "digest": hashlib.sha256(canonical_bytes(document)).hexdigest(), + "document": document, + "bindings": [], + "verification": None, + } + initialize_canonical_authority(runtime, "goal-a", projection, state_path=state, provider=provider) + state.unlink() + + for role in ("agent", None): + with_acceptance = list_goal_todos( + goal_id="goal-a", + role=role, + registry_path=registry, + runtime_root_arg=str(runtime), + include_acceptance=True, + ) + without_acceptance = list_goal_todos( + goal_id="goal-a", + role=role, + registry_path=registry, + runtime_root_arg=str(runtime), + include_acceptance=False, + ) + assert "goal_acceptance_contract" in with_acceptance["agent_todos"] + assert "goal_acceptance_contract" not in without_acceptance["agent_todos"] + def _stable(payload: dict) -> dict: + copied = dict(payload) + for lane in ("agent_todos", "user_todos"): + if lane in copied and isinstance(copied[lane], dict): + copied[lane] = { + key: value for key, value in copied[lane].items() if key != "goal_acceptance_contract" + } + envelope = dict(copied.get("projection_envelope") or {}) + for key in ("observed_at", "served_at"): + envelope.pop(key, None) + envelope["sources"] = [ + {k: v for k, v in source.items() if k != "last_read_at"} + for source in envelope.get("sources", []) + ] + copied["projection_envelope"] = envelope + return copied + + assert _stable(without_acceptance) == _stable(with_acceptance) + + with pytest.raises(ValueError, match="include_acceptance"): + list_goal_todos( + goal_id="goal-a", + role="agent", + registry_path=registry, + runtime_root_arg=str(runtime), + include_acceptance="false", # type: ignore[arg-type] + ) diff --git a/tests/control_plane/test_turn_envelope_budget_warning.py b/tests/control_plane/test_turn_envelope_budget_warning.py index 4884c94673..6afc816b86 100644 --- a/tests/control_plane/test_turn_envelope_budget_warning.py +++ b/tests/control_plane/test_turn_envelope_budget_warning.py @@ -2,12 +2,14 @@ from copy import deepcopy import json +import os import subprocess import sys import pytest from loopx.cli_commands.turn_rendering import render_loopx_turn_plan_markdown +from loopx.control_plane.quota import turn_envelope as turn from loopx.control_plane.quota.turn_envelope import ( build_turn_envelope, quota_action_signature_document, @@ -18,7 +20,9 @@ render_turn_envelope_markdown, ) from loopx.workflow_skill_install import workflow_skill_install +from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime from tests.control_plane.test_agent_context import POLICY, SCOPE, context +from tests.control_plane.test_replan_host_context_projection import _quota_payload from tests.test_loopx_turn_driver import _write_live_fixture from tests.test_turn_envelope import _full_decision @@ -226,3 +230,39 @@ def test_interaction_and_native_envelope_keep_hooks_and_one_exact_todo_read( assert quota_action_signature_document( source ) != turn_envelope_action_signature_document(tampered) + + +def test_pack_turn_source_and_compose_complete_handle_over_1_mib_sources(tmp_path, monkeypatch): + isolate_sqlite_runtime(tmp_path, monkeypatch) + source = deepcopy(_quota_payload()) + source["observations"] = [f"obs-{index}-" + "x" * 160 for index in range(7500)] + raw_bytes = len(_wire(source)) + assert raw_bytes > 1024 * 1024 + + packed = turn.pack_turn_source(source) + assert packed is not None + assert packed["encoding"] == "deflate-base64-json-v0" + assert len(packed["data"]) < 2 * 1024 * 1024 + + seen_calls = [] + original_rpc = turn.effect_runtime_projection_result + + def capture_rpc(method, params, **kwargs): + seen_calls.append((method, dict(params))) + return original_rpc(method, params, **kwargs) + + monkeypatch.setattr(turn, "effect_runtime_projection_result", capture_rpc) + compressed_composed = turn.compose_turn_decision(source) + assert len(seen_calls) == 1 + method, sent_params = seen_calls[0] + assert method == "quota.turn_envelope.evaluate" + assert sent_params["operation"] == "compose_complete" + assert "source_transport" in sent_params + assert "payload" not in sent_params + + monkeypatch.setattr(turn, "pack_turn_source", lambda *args, **kwargs: None) + inline_composed = turn.compose_turn_decision(source) + assert compressed_composed == inline_composed + + incompressible = {"blob": os.urandom(2 * 1024 * 1024).hex()} + assert turn.pack_turn_source(incompressible) is None diff --git a/tests/control_plane_ts/todo_read.test.ts b/tests/control_plane_ts/todo_read.test.ts index f01e132667..5db7078dde 100644 --- a/tests/control_plane_ts/todo_read.test.ts +++ b/tests/control_plane_ts/todo_read.test.ts @@ -5,7 +5,9 @@ import {syncBuiltinESMExports} from "node:module"; import {tmpdir} from "node:os"; import {join} from "node:path"; import test from "node:test"; +import {gunzipSync} from "node:zlib"; import {readTodo, TODO_READ_REQUEST} from "../../loopx/control_plane/todos/read_projection.ts"; +import {readTodoRuntime} from "../../loopx/control_plane/todos/read_transport.ts"; import {projectCanonicalQuotaBatch, readCanonicalTodoProjection, verifyCanonicalTodoAuthorityWitness} from "../../loopx/control_plane/todos/read_transaction.ts"; import {goalRolloutEventLogPath} from "../../loopx/control_plane/rollout_receipt_log.ts"; import {readAgent, readScope} from "../../loopx/control_plane/todos/read_codec.ts"; @@ -17,6 +19,7 @@ import {coordinationTodoReadModel} from "../../loopx/control_plane/coordination/ import {TODO_CANONICAL_READ_RECORD_SCHEMA} from "../../loopx/control_plane/coordination/coordination_state_contract.ts"; import {authorityProjectionFixture} from "./authority_projection_fixture.ts"; import {goalAcceptanceTodoDigest, normalizeGoalAcceptanceDocument} from "../../loopx/control_plane/goals/acceptance_contract.ts"; +import {refineGoalOutcome} from "../../loopx/control_plane/goals/outcome_requirements.ts"; const now = "2026-10-19T07:00:00Z"; const row = (todo_id: string, extra: JsonObject = {}): JsonObject => ({schema_version: "todo_item_v0", todo_id, @@ -641,3 +644,229 @@ for (const provider of ["file", "sqlite"] as const) { assert.equal(drifted.cursor, commit2.cursor); }); } + +for (const provider of ["file", "sqlite"] as const) { + test(`${provider} todo.read query include_acceptance=false omits acceptance payloads with exact todo parity`, async t => { + const root = await mkdtemp(join(tmpdir(), `loopx-todo-accept-${provider}-`)); + t.after(() => rm(root, {recursive: true, force: true})); + const state = join(root, "state.md"), goal = `goal-accept-${provider}`; + await writeFile(state, "# Synthetic Goal\n"); + if (provider === "sqlite") await selectLocalSqliteAuthority(root, goal, true); + const store = await openLocalAuthorityStore(root, goal); + const bound = row("todo_bound", {text: "Bound acceptance item"}); + const unbound = row("todo_unbound", {index: 2, text: "Unbound active item"}); + const document = normalizeGoalAcceptanceDocument({ + objective: "Keep acceptance evaluation intact without repeating acceptance payloads", + non_goals: [], + criteria: [{ + id: "criterion-a", + description: "Bound item remains checked", + validation_argv: ["python3", "check.py"], + validation_files: [{path: "check.py", sha256: "a".repeat(64)}], + oracle: {kind: "owner_pinned_oracle", source_id: "accept-checker", input_refs: [], output_refs: ["out.txt"]}, + }], + bindings: [{todo_id: "todo_bound", criterion_ids: ["criterion-a"]}], + }); + const acceptance = { + schema_version: "loopx_goal_acceptance_v0", + enabled: true, + revision: 1, + digest: canonicalAuthoritySha256(document), + document, + verification: null, + bindings: [{ + todo_id: "todo_bound", + todo_semantic_digest: goalAcceptanceTodoDigest(bound), + revision: 1, + criterion_ids: ["criterion-a"], + confirmed_by: "owner", + }], + }; + const baseProjection = authorityProjectionFixture(goal, [bound, unbound], [], "native", { + root_commitments: {objective: "Keep acceptance evaluation intact", acceptance: ["Bound item remains checked"]}, + goal_acceptance: acceptance, + }); + const goalOutcomes = refineGoalOutcome(baseProjection, goal, null, "owner", { + outcome_id: "outcome-a", + owner_agent_id: "owner", + objective: "Keep acceptance evaluation intact", + requirements: [{id: "req-a", description: "Bound item remains checked"}], + todo_ids: ["todo_bound"], + source: {ref: "message:1", summary: "Keep acceptance evaluation intact"}, + }); + const projection = authorityProjectionFixture(goal, [bound, unbound], [], "native", { + root_commitments: {objective: "Keep acceptance evaluation intact", acceptance: ["Bound item remains checked"]}, + goal_outcomes: goalOutcomes, + goal_acceptance: acceptance, + }); + const committed = await store.commitAuthority({ + expected_provider_revision: null, + operation_id: "seed-accept-skip", + events: [], + next_projection: projection, + receipts: [], + }); + assert.equal(committed.status, "applied"); + if (committed.status !== "applied") return; + const fence = await engageLegacyCoordinationWriterFence({ + schema_version: "loopx_legacy_coordination_writer_fence_engage_request_v0", + runtime_root: root, + goal_id: goal, + state_path: state, + fence: { + schema_version: "loopx_legacy_coordination_writer_fence_v0", + state: "engaged", + goal_id: goal, + fence_id: `accept-fence-${provider}`, + source_version: "fixture", + source_projection_sha256: canonicalAuthoritySha256(projection), + expected_shadow_provider_revision: committed.provider_revision, + }, + }); + assert.equal(fence.status, "applied"); + + for (const role of ["agent", null] as const) { + const baseRequest = { + schema_version: TODO_READ_REQUEST, + kind: "query", + source: {runtime_root: root, goal_id: goal}, + observed_at: Date.parse(now) / 1000, + evaluated_at: now, + query: { + goal_id: goal, + role, + status: null, + todo_id: null, + agent_id: null, + limit: null, + read_scope: "active", + json_references: false, + thin: false, + state_file: state, + project: root, + }, + }; + const withAcceptance = await readTodo(baseRequest); + assert.ok(withAcceptance.canonical_acceptance); + if (role === null) assert.ok(withAcceptance.source_projection); + else assert.equal(withAcceptance.source_projection, undefined); + + const nestedOff = await readTodo({ + ...baseRequest, + query: {...baseRequest.query, include_acceptance: false}, + }); + const topOff = await readTodo({ + ...baseRequest, + include_acceptance: false, + }); + + const fullPayload = withAcceptance.payload as JsonObject; + for (const stripped of [nestedOff, topOff]) { + assert.equal(stripped.canonical_acceptance, undefined); + assert.equal(stripped.source_projection, undefined); + const strippedPayload = stripped.payload as JsonObject; + assert.deepEqual(strippedPayload.todos, fullPayload.todos); + assert.deepEqual(strippedPayload.authority_read, fullPayload.authority_read); + assert.equal(strippedPayload.open_count, fullPayload.open_count); + for (const lane of ["agent_todos", "user_todos"] as const) { + const fullSummary = fullPayload[lane] as JsonObject | undefined; + const strippedSummary = strippedPayload[lane] as JsonObject | undefined; + if (!fullSummary) { + assert.equal(strippedSummary, undefined); + continue; + } + assert.equal(strippedSummary!.goal_acceptance_contract, undefined); + assert.deepEqual(strippedSummary!.items, fullSummary.items); + assert.deepEqual(strippedSummary!.first_executable_items, fullSummary.first_executable_items); + } + } + + await assert.rejects( + () => readTodo({...baseRequest, query: {...baseRequest.query, include_acceptance: "false"}}), + /include_acceptance/, + ); + await assert.rejects( + () => readTodo({...baseRequest, include_acceptance: false, query: {...baseRequest.query, include_acceptance: true}}), + /conflicts/, + ); + } + }); +} + +test("readTodoRuntime compresses >1 MiB canonical_fields responses cleanly", async t => { + const root = await mkdtemp(join(tmpdir(), "loopx-todo-large-gzip-")); + t.after(() => rm(root, {recursive: true, force: true})); + const state = join(root, "state.md"), goal = "goal-large-canonical"; + await writeFile(state, "# Large Synthetic Goal\n"); + const store = await openLocalAuthorityStore(root, goal); + const longText = "Preserve exact canonical fields across >1 MiB read compression. ".repeat(30); + const todos = Array.from({length: 600}, (_, index) => + row(`todo_large_${String(index).padStart(4, "0")}`, {index: index + 1, text: `${index}:${longText}`}), + ); + const document = normalizeGoalAcceptanceDocument({ + objective: "Compress >1 MiB canonical_fields responses when acceptance is attached", + non_goals: [], + criteria: [{id: "criterion-a", description: "Large response still gzips", validation_argv: ["true"]}], + bindings: [{todo_id: "todo_large_0000", criterion_ids: ["criterion-a"]}], + }); + const acceptance = { + schema_version: "loopx_goal_acceptance_v0", + enabled: true, + revision: 1, + digest: canonicalAuthoritySha256(document), + document, + verification: null, + bindings: [{ + todo_id: "todo_large_0000", + todo_semantic_digest: goalAcceptanceTodoDigest(todos[0]!), + revision: 1, + criterion_ids: ["criterion-a"], + confirmed_by: "owner", + }], + }; + const projection = authorityProjectionFixture(goal, todos, [], "native", {goal_acceptance: acceptance}); + const committed = await store.commitAuthority({ + expected_provider_revision: null, + operation_id: "seed-large-gzip", + events: [], + next_projection: projection, + receipts: [], + }); + assert.equal(committed.status, "applied"); + if (committed.status !== "applied") return; + const fence = await engageLegacyCoordinationWriterFence({ + schema_version: "loopx_legacy_coordination_writer_fence_engage_request_v0", + runtime_root: root, + goal_id: goal, + state_path: state, + fence: { + schema_version: "loopx_legacy_coordination_writer_fence_v0", + state: "engaged", + goal_id: goal, + fence_id: "large-gzip-fence", + source_version: "fixture", + source_projection_sha256: canonicalAuthoritySha256(projection), + expected_shadow_provider_revision: committed.provider_revision, + }, + }); + assert.equal(fence.status, "applied"); + + const request = { + schema_version: TODO_READ_REQUEST, + kind: "canonical_fields", + source: {runtime_root: root, goal_id: goal}, + observed_at: Date.parse(now) / 1000, + evaluated_at: now, + }; + const plain = await readTodo(request); + const plainBytes = Buffer.byteLength(JSON.stringify(plain), "utf8"); + assert.ok(plainBytes > 1024 * 1024, `expected >1 MiB canonical_fields payload, got ${plainBytes}`); + const packed = await readTodoRuntime(request); + const piece = packed.result_piece as JsonObject; + assert.ok(piece, JSON.stringify(packed)); + assert.equal(piece.content_encoding, "gzip"); + assert.equal(piece.decoded_byte_count, plainBytes); + assert.ok(Number(piece.byte_count) < 256 * 1024, `expected compact gzip piece, got ${piece.byte_count}`); + const decoded = JSON.parse(gunzipSync(Buffer.from(String(piece.data), "base64")).toString("utf8")); + assert.deepEqual(decoded, plain); +}); diff --git a/tests/control_plane_ts/turn_envelope.test.ts b/tests/control_plane_ts/turn_envelope.test.ts index 1dcaaafd01..da3b87f10f 100644 --- a/tests/control_plane_ts/turn_envelope.test.ts +++ b/tests/control_plane_ts/turn_envelope.test.ts @@ -3,6 +3,7 @@ import { AGENT_SCOPE_FRONTIER_ACTIONS } from "../../loopx/control_plane/agents/a import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import test from "node:test"; +import { deflateSync } from "node:zlib"; import { TURN_ACTION_ROUTES, @@ -10,6 +11,7 @@ import { ACTION_SIGNATURE_COVERAGE_V0, ACTION_SIGNATURE_COVERAGE_V3, buildTurnEnvelope, + decodeTurnSource, assertTurnEnvelopeConsumerVersion, evaluateTurnEnvelope, quotaActionSignatureDocument, @@ -2478,3 +2480,33 @@ test("C1 rejects dangling, chained, unsupported and conflicting outcome requirem }; assert.throws(() => evaluateTurnEnvelope({operation: "build", payload: dualReqs, scheduler_execution_args: ""}), EffectRuntimeRequestError); }); + +test("decodeTurnSource and compose_complete round-trip >1 MiB compressible sources and reject oversized transport", () => { + const source = payload(); + source.large_context_notes = Array.from({length: 16000}, (_, index) => + `Item ${index}: preserve complete compressed source parity across >1 MiB turn envelopes. `, + ); + const rawJson = Buffer.from(JSON.stringify(source), "utf8"); + assert.ok(rawJson.length > 1024 * 1024, `expected >1 MiB test source, got ${rawJson.length}`); + const encoded = deflateSync(rawJson, {level: 1}).toString("base64"); + assert.ok(encoded.length < 2 * 1024 * 1024); + const transport = {encoding: "deflate-base64-json-v0", data: encoded}; + + assert.deepEqual(decodeTurnSource({source_transport: transport}, "payload"), source); + const inline = evaluateTurnEnvelope({operation: "compose_complete", payload: source, scheduler_execution_args: ""}); + const transported = evaluateTurnEnvelope({ + operation: "compose_complete", + source_transport: transport, + scheduler_execution_args: "", + }); + assert.deepEqual(transported, inline); + + assert.throws( + () => decodeTurnSource({source_transport: {encoding: "deflate-base64-json-v0", data: "A".repeat(2 * 1024 * 1024 + 4)}}, "payload"), + /invalid Turn composition source transport/, + ); + assert.throws( + () => decodeTurnSource({source_transport: {encoding: "deflate-base64-json-v0", data: deflateSync(Buffer.from("{not-json", "utf8")).toString("base64")}}, "payload"), + /Turn composition source must be valid compressed JSON within 64 MiB/, + ); +}); diff --git a/tests/test_cli_entrypoint.py b/tests/test_cli_entrypoint.py index c3b44f6e8b..c420bdb0c3 100644 --- a/tests/test_cli_entrypoint.py +++ b/tests/test_cli_entrypoint.py @@ -2286,3 +2286,103 @@ def test_guided_core_preview_matches_complete_owner_without_writes(tmp_path): assert packet['goal_text'] == 'Report "inventory" and 总计.' assert packet['guided_transaction']['writes_now'] is False assert not list(project.iterdir()) and not (tmp_path / 'runtime').exists() + + +def test_cli_commands_package_loads_submodules_lazily(): + script = """ +import sys +import loopx.cli_commands as cmds + +assert len(cmds.__all__) == 100 +for mod in ("loopx.cli_commands.benchmark_dispatch", "loopx.cli_commands.quota", "loopx.cli_commands.explore"): + assert mod not in sys.modules, f"eager import leaked {mod}" + +handler = cmds.handle_version_command +assert callable(handler) +assert "loopx.cli_commands.benchmark_dispatch" not in sys.modules +assert "loopx.cli_commands.quota" not in sys.modules + +try: + getattr(cmds, "nonexistent_command_handler") +except AttributeError: + pass +else: + raise AssertionError("expected AttributeError for unknown cli_commands export") +""" + result = run_isolated_script(script) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("arguments", [ + ["explore", "--help"], + ["explore", "turn-context", "--help"], + ["heartbeat-prequota", "--help"], +]) +def test_selected_explore_and_heartbeat_prequota_help_match_without_full_cli(arguments): + selected = run_cli_main( + "loopx.entrypoint", + arguments, + forbidden_modules=( + "loopx.cli", + "loopx.chat", + "loopx.canary", + "loopx.history", + "loopx.capabilities.explore.worker_branch_plan", + "loopx.capabilities.explore.todo_branch_plan", + "loopx.extensions.lark.presentation.explore_results", + "loopx.extensions.lark.presentation.kanban", + ), + ) + full = run_cli_main("loopx.cli", arguments) + assert (selected.returncode, selected.stdout, selected.stderr) == (full.returncode, full.stdout, full.stderr) + assert selected.returncode == 0 + + +def test_selected_explore_turn_context_and_heartbeat_prequota_match_full_cli_lazily(tmp_path): + registry, runtime = write_command_fixture(tmp_path) + explore_args = [ + "--registry", str(registry), "--runtime-root", str(runtime), + "--format", "json", "explore", "turn-context", + "--goal-id", "perf-goal", "--agent-id", "perf-agent", + ] + selected_explore = run_cli_main( + "loopx.entrypoint", + explore_args, + forbidden_modules=( + "loopx.cli", + "loopx.chat", + "loopx.canary", + "loopx.history", + "loopx.capabilities.explore.worker_branch_plan", + "loopx.capabilities.explore.todo_branch_plan", + "loopx.capabilities.explore.research_evidence", + "loopx.extensions.lark.presentation.explore_results", + "loopx.extensions.lark.presentation.kanban", + ), + ) + full_explore = run_cli_main("loopx.cli", explore_args) + assert selected_explore.returncode == full_explore.returncode == 0, (selected_explore.stderr, full_explore.stderr) + assert json.loads(selected_explore.stdout) == json.loads(full_explore.stdout) + + prequota_args = [ + "--registry", str(registry), "--runtime-root", str(runtime), + "--format", "json", "heartbeat-prequota", + "--goal-id", "perf-goal", "--agent-id", "perf-agent", + ] + selected_prequota = run_cli_main( + "loopx.entrypoint", + prequota_args, + forbidden_modules=( + "loopx.cli", + "loopx.chat", + "loopx.canary", + "loopx.history", + "loopx.heartbeat_prompt", + "loopx.cli_commands.quota", + "loopx.cli_commands.benchmark_dispatch", + "loopx.cli_commands.explore", + ), + ) + full_prequota = run_cli_main("loopx.cli", prequota_args) + assert selected_prequota.returncode == full_prequota.returncode == 0, (selected_prequota.stderr, full_prequota.stderr) + assert json.loads(selected_prequota.stdout) == json.loads(full_prequota.stdout) From 2441f6d15f5fb7a7d52dc8e4b558c9ed9b24c6ff Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:52:07 +0800 Subject: [PATCH 2/2] fix(cli): keep standalone core explore unavailable while preserving ordinary lazy dispatch Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_runtime.py | 5 +++-- tests/test_cli_entrypoint.py | 22 ++++++++++++++++++++++ tests/test_core_distribution.py | 10 +++++++--- 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index 0dcad7da5d..2bb2400d7a 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -75,11 +75,12 @@ "goal-acceptance", "goal-lifecycle", "host-mode-plan", - "explore", "capability", "workbench", "history", } +# Fast-dispatched in ordinary installs; excluded from standalone Core support/commands. +_FULL_INSTALL_SELECTED_COMMANDS = frozenset({"explore"}) # Existing CLI vocabulary; this set chooses loading, not operation authority. _CAPABILITY_DISCOVERY_COMMANDS = frozenset({"list", "show"}) @@ -1166,7 +1167,7 @@ def _run_command(command: str | None, raw_argv: list[str]) -> int: if command == "history" and "loopx.cli" in sys.modules: # An explicitly loaded facade keeps its existing handler/renderer bindings. return _run_full_cli(raw_argv) - if command in _SELECTED_COMMANDS: + if command in _SELECTED_COMMANDS or (command in _FULL_INSTALL_SELECTED_COMMANDS and not _standalone_core()): try: args = parse_cli_args(_build_selected_parser(command), raw_argv) except _SelectedParseRejected: diff --git a/tests/test_cli_entrypoint.py b/tests/test_cli_entrypoint.py index c420bdb0c3..e89fb3174a 100644 --- a/tests/test_cli_entrypoint.py +++ b/tests/test_cli_entrypoint.py @@ -2386,3 +2386,25 @@ def test_selected_explore_turn_context_and_heartbeat_prequota_match_full_cli_laz full_prequota = run_cli_main("loopx.cli", prequota_args) assert selected_prequota.returncode == full_prequota.returncode == 0, (selected_prequota.stderr, full_prequota.stderr) assert json.loads(selected_prequota.stdout) == json.loads(full_prequota.stdout) + + +def test_standalone_core_excludes_explore_from_selected_commands_and_refuses_dispatch(monkeypatch, capsys): + import builtins + import loopx.cli_runtime as cli_runtime + + monkeypatch.setattr(cli_runtime, "_standalone_core", lambda: True) + assert "explore" not in cli_runtime._available_selected_commands() + + real_import = builtins.__import__ + + def _missing_full_cli(name, globals=None, locals=None, fromlist=(), level=0): + if name == "cli" and level == 1 and (globals or {}).get("__package__") == "loopx": + raise ModuleNotFoundError("No module named 'loopx.cli'", name="loopx.cli") + return real_import(name, globals, locals, fromlist, level) + + monkeypatch.setattr(builtins, "__import__", _missing_full_cli) + for argv in (["explore", "--help"], ["explore", "turn-context", "--goal-id", "g", "--agent-id", "a"]): + with pytest.raises(SystemExit) as exc: + cli_runtime.main(argv) + assert exc.value.code == 2 + assert "unavailable in the standalone core" in capsys.readouterr().err diff --git a/tests/test_core_distribution.py b/tests/test_core_distribution.py index e76295bbe2..5ca7276c93 100644 --- a/tests/test_core_distribution.py +++ b/tests/test_core_distribution.py @@ -254,13 +254,17 @@ def test_installed_core_identity_help_and_unavailable_workspace(core_python, tmp reference = json.loads(_run(core_python, ["commands", "--format", "json"], tmp_path).stdout) commands = [entry["command"] for group in reference["groups"] for entry in group["commands"]] assert "loopx configure-goal --help" in commands - assert not any(command.startswith(("loopx dashboard", "loopx chat", "loopx canary")) for command in commands) + assert not any( + command.startswith(("loopx dashboard", "loopx chat", "loopx canary", "loopx explore")) + for command in commands + ) _run(core_python, ["--version"], tmp_path, environment={"PATH": str(tmp_path)}) _run(core_python, ["--format", "json", "--version"], tmp_path) invalid = _run(core_python, ["--format", "invalid", "--version"], tmp_path, expected=2) assert "invalid choice" in invalid.stderr - refusal = _run(core_python, ["dashboard"], tmp_path, expected=2) - assert "unavailable in the standalone core" in refusal.stderr + for blocked in (["dashboard"], ["explore", "--help"], ["explore", "turn-context", "--goal-id", GOAL, "--agent-id", AGENT]): + refusal = _run(core_python, blocked, tmp_path, expected=2) + assert "unavailable in the standalone core" in refusal.stderr assert not list(tmp_path.iterdir())