diff --git a/loopx/control_plane/status/diagnose_projection.py b/loopx/control_plane/status/diagnose_projection.py new file mode 100644 index 0000000000..99d17d2de3 --- /dev/null +++ b/loopx/control_plane/status/diagnose_projection.py @@ -0,0 +1,259 @@ +"""Pure signal compaction and machine-signal classification for ``loopx diagnose``.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence + + +def _as_mapping(value: object) -> Mapping[str, object]: + return value if isinstance(value, Mapping) else {} + + +def _as_items(value: object) -> Sequence[object]: + if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)): + return value + return () + + +def _compact_text_signals( + value: object, + *, + limit: int = 3, +) -> dict[str, object]: + items = [text for item in _as_items(value) if (text := str(item).strip())] + bounded = items[: max(0, limit)] + return {"items": bounded, "truncated": len(items) > len(bounded), "total_count": len(items)} + + +def _first_text(summary: Mapping[str, object]) -> str | None: + for key in ("first_open_items", "items", "backlog_items"): + for item in _as_items(summary.get(key)): + if isinstance(item, Mapping) and item.get("text"): + return str(item.get("text")) + return str(summary.get("next")) if summary.get("next") else None + + +def _first_agent_todo_text( + quota: Mapping[str, object], + summary: Mapping[str, object], +) -> str | None: + selected = _as_mapping(quota.get("agent_lane_next_action")) + if selected.get("text"): + return str(selected.get("text")) + if selected.get("title"): + return str(selected.get("title")) + for item in _as_items(summary.get("first_executable_items")): + if isinstance(item, Mapping) and item.get("text"): + return str(item.get("text")) + return _first_text(summary) + + +def _open_count(summary: Mapping[str, object]) -> int: + for key in ("open_count", "open"): + value = summary.get(key) + if isinstance(value, int) and not isinstance(value, bool): + return value + return len(_as_items(summary.get("first_open_items")) or _as_items(summary.get("items"))) + + +def _attention_items(status_payload: Mapping[str, object]) -> list[Mapping[str, object]]: + queue = _as_mapping(status_payload.get("attention_queue")) + return [item for item in _as_items(queue.get("items")) if isinstance(item, Mapping)] + + +def _select_attention_item( + status_payload: Mapping[str, object], + *, + goal_id: str | None, +) -> Mapping[str, object] | None: + items = _attention_items(status_payload) + if goal_id: + return next((item for item in items if str(item.get("goal_id") or "") == goal_id), None) + return items[0] if items else None + + +def _goal_ids_from_items(items: Sequence[Mapping[str, object]], *, limit: int) -> list[str]: + ids: list[str] = [] + bounded = max(1, limit) + for item in items: + candidate = str(item.get("goal_id") or "").strip() + if candidate and candidate not in ids: + ids.append(candidate) + if len(ids) >= bounded: + break + return ids + + +def _goal_ids_for_packet( + status_payload: Mapping[str, object], + *, + goal_id: str | None, + limit: int, +) -> list[str]: + if goal_id: + return [goal_id] + return _goal_ids_from_items(_attention_items(status_payload), limit=limit) + + +def _unregistered_goal_ids(status_payload: Mapping[str, object]) -> set[str]: + history = _as_mapping(status_payload.get("run_history")) + return { + gid + for goal in _as_items(history.get("goals")) + if isinstance(goal, Mapping) + and goal.get("registry_member") is False + and (gid := str(goal.get("id") or "")) + } + + +def _todo_summary( + quota: Mapping[str, object], + item: Mapping[str, object], + *, + role: str, +) -> Mapping[str, object]: + return _as_mapping(quota.get(f"{role}_todo_summary")) or _as_mapping(item.get(f"{role}_todos")) + + +def _interaction_user_required(quota: Mapping[str, object]) -> bool: + contract = _as_mapping(quota.get("interaction_contract")) + user_channel = _as_mapping(contract.get("user_channel")) + if user_channel.get("action_required") is not None: + return bool(user_channel.get("action_required")) + return bool(quota.get("requires_user_action") or quota.get("notify_user_on_gate")) + + +def _quota_user_action_required(quota: Mapping[str, object]) -> bool: + if quota.get("action_required") is not None: + return bool(quota.get("action_required")) + return _interaction_user_required(quota) + + +def _quota_user_open_count(quota: Mapping[str, object]) -> int: + value = quota.get("open_count") + if isinstance(value, int) and not isinstance(value, bool): + return value + return _open_count(_as_mapping(quota.get("user_todo_summary"))) + + +def _machine_signal( + *, + status_payload: Mapping[str, object], + item: Mapping[str, object] | None, + quota: Mapping[str, object], +) -> str: + if not status_payload.get("ok"): + return "status_health_attention" + if item is None: + return "not_connected_or_not_projected" + if not quota.get("ok", True): + return "quota_attention" + user_summary = _todo_summary(quota, item, role="user") + if _quota_user_action_required(quota) or _open_count(user_summary) > 0: + return "user_or_controller_attention" + for flag, signal in ( + ("capability_repair_allowed", "capability_repair_attention"), + ("self_repair_allowed", "self_repair_attention"), + ("recovery_delivery_allowed", "recovery_attention"), + ): + if quota.get(flag): + return signal + if quota.get("should_run") and quota.get("normal_delivery_allowed", True): + return "agent_work_attention" + if quota.get("safe_bypass_allowed"): + return "safe_bypass_attention" + if item.get("waiting_on") == "external_evidence": + return "external_evidence_attention" + return "no_immediate_agent_delivery_signal" + + +def _first_user_question(quota: Mapping[str, object], item: Mapping[str, object]) -> str | None: + for key in ("operator_question", "gate_prompt"): + if quota.get(key): + return str(quota.get(key)) + if item.get(key): + return str(item.get(key)) + return _first_text(_todo_summary(quota, item, role="user")) + + +def _compact_scheduler_hint(scheduler_hint: Mapping[str, object]) -> dict[str, object]: + """Summarize scheduler-cadence hints without mutating source dictionaries.""" + if not scheduler_hint: + return {} + canonical_app_automation = _as_mapping(scheduler_hint.get("app_automation")) + app_automation = canonical_app_automation or _as_mapping(scheduler_hint.get("codex_app")) + app_key = "app_automation" if canonical_app_automation else "codex_app" + stateful_backoff = _as_mapping(app_automation.get("stateful_backoff")) + reset_policy = _as_mapping(scheduler_hint.get("reset_policy")) + unchanged_poll = _as_mapping(scheduler_hint.get("unchanged_poll")) + reset_key = "app_automation_initial_rrule" if canonical_app_automation else "codex_app_initial_rrule" + return { + "schema_version": "diagnose_scheduler_hint_summary_v0", + "action": scheduler_hint.get("action"), + "cadence_class": scheduler_hint.get("cadence_class"), + "reason": scheduler_hint.get("reason"), + app_key: { + "apply": app_automation.get("apply"), + "host_action": app_automation.get("host_action"), + "recommended_rrule": app_automation.get("recommended_rrule"), + "recommended_interval_minutes": app_automation.get("recommended_interval_minutes"), + "current_rrule": stateful_backoff.get("current_rrule"), + "apply_needed": stateful_backoff.get("apply_needed"), + "no_spend_for_cadence_change": app_automation.get("no_spend_for_cadence_change"), + }, + "unchanged_poll": { + "final_quota_replan_check_enabled": unchanged_poll.get("final_quota_replan_check_enabled"), + "final_quota_replan_check_action": unchanged_poll.get("final_quota_replan_check_action"), + }, + "reset_policy": {"reset_token": reset_policy.get("reset_token"), reset_key: reset_policy.get(reset_key)}, + } + + +def _compact_quota_signals(quota: Mapping[str, object]) -> dict[str, object]: + keys = ( + "ok", "decision", "should_run", "state", "effective_action", "actionable_by_codex", + "normal_delivery_allowed", "recovery_delivery_allowed", "capability_repair_allowed", + "self_repair_allowed", "safe_bypass_allowed", "safe_bypass_kind", "requires_user_action", + "recommended_action", "reason", "agent_identity", "agent_lane_next_action", + "agent_scoped_user_gate_override", "agent_scoped_user_action_override", + "agent_scope_frontier", "goal_frontier_projection", "autonomous_replan_decision", + ) + signals: dict[str, object] = {key: quota.get(key) for key in keys if key in quota} + signals["action_required"] = _quota_user_action_required(quota) + signals["open_count"] = _quota_user_open_count(quota) + scheduler_hint = _compact_scheduler_hint(_as_mapping(quota.get("scheduler_hint"))) + if scheduler_hint: + signals["scheduler_hint"] = scheduler_hint + return signals + + +def _compact_interaction_contract(contract: Mapping[str, object]) -> dict[str, object]: + compact: dict[str, object] = {str(key): value for key, value in contract.items()} + compact["agent_channel"] = { + str(k): v + for k, v in _as_mapping(contract.get("agent_channel")).items() + if k not in {"action_portfolio_ref", "suggested_action_count"} + } + compact["cli_channel"] = { + str(k): v + for k, v in _as_mapping(contract.get("cli_channel")).items() + if k not in {"selection_policy_ref", "selection_command"} + } + return compact + + +def _goal_list_view(packet: dict[str, object], *, selected: bool) -> dict[str, object]: + """Avoid repeating the selected work's source-read plan in the overview.""" + if not selected: + return packet + contract = _as_mapping(packet.get("interaction_contract")) + agent_channel = _as_mapping(contract.get("agent_channel")) + if not agent_channel.get("required_reads") and not agent_channel.get("work_context"): + return packet + overview_contract = {str(key): value for key, value in contract.items()} + overview_contract["agent_channel"] = { + str(key): value + for key, value in agent_channel.items() + if key not in {"required_reads", "work_context"} + } + return {**packet, "interaction_contract": overview_contract} diff --git a/loopx/diagnose.py b/loopx/diagnose.py index 1dec44675d..dc966ff752 100644 --- a/loopx/diagnose.py +++ b/loopx/diagnose.py @@ -1,25 +1,55 @@ +"""Agent-facing LoopX diagnosis packet builder.""" + from __future__ import annotations -import shlex +from collections.abc import Mapping, Sequence from pathlib import Path -from typing import Any +import shlex -from .control_plane.scheduler.execution_context import ( - GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT, - render_scheduler_execution_args, -) -from .control_plane.status.contract_projection import STATUS_CONTRACT_SIGNAL_LIMIT from .control_plane.goals.orphaned_goal_state import ( - ORPHANED_GOAL_STATE_CONNECTION, + ORPHANED_GOAL_STATE_CONNECTION as ORPHANED_GOAL_STATE_CONNECTION, ORPHANED_GOAL_STATE_REASON, orphaned_goal_state_gate, orphaned_goal_state_projection, ) +from .control_plane.scheduler.execution_context import ( + GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT, + render_scheduler_execution_args, +) +from .control_plane.status.contract_projection import ( + STATUS_CONTRACT_SIGNAL_LIMIT as STATUS_CONTRACT_SIGNAL_LIMIT, +) +from .control_plane.status.diagnose_projection import ( + _as_items as _as_items, + _as_mapping as _as_mapping, + _attention_items as _attention_items, + _compact_interaction_contract as _compact_interaction_contract, + _compact_quota_signals as _compact_quota_signals, + _compact_scheduler_hint as _compact_scheduler_hint, + _compact_text_signals as _compact_text_signals, + _first_agent_todo_text as _first_agent_todo_text, + _first_text as _first_text, + _first_user_question as _first_user_question, + _goal_ids_for_packet as _goal_ids_for_packet, + _goal_ids_from_items as _goal_ids_from_items, + _goal_list_view as _goal_list_view, + _interaction_user_required as _interaction_user_required, + _machine_signal as _machine_signal, + _open_count as _open_count, + _quota_user_action_required as _quota_user_action_required, + _quota_user_open_count as _quota_user_open_count, + _select_attention_item as _select_attention_item, + _todo_summary as _todo_summary, + _unregistered_goal_ids as _unregistered_goal_ids, +) from .control_plane.todos.contract import normalize_required_capabilities from .paths import registry_project_root -from .presentation.markdown import as_dict as _as_dict -from .presentation.markdown import as_list as _as_list -from .presentation.markdown import markdown_scalar +from .presentation.renderers.diagnose_markdown import ( + USER_DIAGNOSE_PROMPT as USER_DIAGNOSE_PROMPT, + _goal_frontier_projection_line as _goal_frontier_projection_line, + _scheduler_hint_line as _scheduler_hint_line, + render_diagnosis_markdown as render_diagnosis_markdown, +) from .project_prompt import render_available_capability_args from .quota import build_quota_should_run from .status import collect_status @@ -30,16 +60,6 @@ "inspect the listed orphaned state and preview its backup; do not bootstrap " "until an operator explicitly resolves it" ) - - -USER_DIAGNOSE_PROMPT = ( - "请诊断这个项目的 LoopX 运转情况。不要让我手动跑 shell 命令;如果 " - "`loopx` 不在 PATH,请先安装/修复。然后运行 `loopx diagnose` " - "读取诊断证据包,结合项目上下文自己判断:它是否可以自主推进、当前卡在哪、" - "需要我回答什么、以及你下一步会做什么。" -) - - AGENT_REASONING_CHECKLIST = [ "判断 LoopX 本身是否健康:registry/status/quota 是否能读,是否存在 stale projection 或 contract error。", "判断当前 goal 是否已连接:若没有 registry goal 或 attention item,先接入而不是猜任务。", @@ -50,117 +70,36 @@ ] -def _compact_text_signals(value: Any, *, limit: int = STATUS_CONTRACT_SIGNAL_LIMIT) -> dict[str, Any]: - items = [str(item).strip() for item in _as_list(value) if str(item).strip()] - bounded = items[: max(0, limit)] - return { - "items": bounded, - "truncated": len(items) > len(bounded), - "total_count": len(items), - } - - -def _first_text(summary: dict[str, Any]) -> str | None: - for key in ("first_open_items", "items", "backlog_items"): - for item in _as_list(summary.get(key)): - if isinstance(item, dict) and item.get("text"): - return str(item.get("text")) - if summary.get("next"): - return str(summary.get("next")) - return None - - -def _first_agent_todo_text(quota: dict[str, Any], summary: dict[str, Any]) -> str | None: - selected = _as_dict(quota.get("agent_lane_next_action")) - if selected.get("text"): - return str(selected.get("text")) - if selected.get("title"): - return str(selected.get("title")) - for item in _as_list(summary.get("first_executable_items")): - if isinstance(item, dict) and item.get("text"): - return str(item.get("text")) - return _first_text(summary) - - -def _open_count(summary: dict[str, Any]) -> int: - for key in ("open_count", "open"): - value = summary.get(key) - if isinstance(value, int): - return value - return len(_as_list(summary.get("first_open_items")) or _as_list(summary.get("items"))) - - -def _attention_items(status_payload: dict[str, Any]) -> list[dict[str, Any]]: - queue = _as_dict(status_payload.get("attention_queue")) - return [item for item in _as_list(queue.get("items")) if isinstance(item, dict)] - - -def _select_attention_item( - status_payload: dict[str, Any], - *, - goal_id: str | None, -) -> dict[str, Any] | None: - items = _attention_items(status_payload) - if goal_id: - for item in items: - if str(item.get("goal_id") or "") == goal_id: - return item - return None - return items[0] if items else None - - -def _goal_ids_for_packet(status_payload: dict[str, Any], *, goal_id: str | None, limit: int) -> list[str]: - if goal_id: - return [goal_id] - ids: list[str] = [] - for item in _attention_items(status_payload): - candidate = str(item.get("goal_id") or "").strip() - if candidate and candidate not in ids: - ids.append(candidate) - if len(ids) >= max(1, limit): - break - return ids - - def _orphaned_goal_state_for_diagnosis( - status_payload: dict[str, Any], + status_payload: Mapping[str, object], *, registry_path: Path, goal_id: str, -) -> dict[str, Any] | None: +) -> dict[str, object] | None: """Detect an orphan only when the status snapshot says the Goal is unregistered.""" - - history = _as_dict(status_payload.get("run_history")) - for goal in _as_list(history.get("goals")): - if not isinstance(goal, dict) or str(goal.get("id") or "") != goal_id: - continue - if goal.get("registry_member") is not False: - return None - return orphaned_goal_state_projection( - registry_project_root(registry_path), - goal_id, - ) - return None + if goal_id not in _unregistered_goal_ids(status_payload): + return None + projection = orphaned_goal_state_projection(registry_project_root(registry_path), goal_id) + return dict(projection) if projection is not None else None def _quota_for_goal( - status_payload: dict[str, Any], + status_payload: dict[str, object], goal_id: str, *, agent_id: str | None, - available_capabilities: Any = None, -) -> dict[str, Any]: + available_capabilities: object = None, +) -> dict[str, object]: try: - return build_quota_should_run( + result = build_quota_should_run( status_payload, goal_id=goal_id, agent_id=agent_id, available_capabilities=available_capabilities, - scheduler_execution_context=( - GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT - ), + scheduler_execution_context=GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT, ) - except Exception as exc: # noqa: BLE001 - diagnosis packets should preserve compact failure context. + return dict(result) + except Exception as exc: # diagnosis packets should preserve compact failure context. return { "ok": False, "goal_id": goal_id, @@ -172,303 +111,74 @@ def _quota_for_goal( } -def _todo_summary(quota: dict[str, Any], item: dict[str, Any], *, role: str) -> dict[str, Any]: - key = f"{role}_todo_summary" - fallback = f"{role}_todos" - return _as_dict(quota.get(key)) or _as_dict(item.get(fallback)) - - -def _interaction_user_required(quota: dict[str, Any]) -> bool: - contract = _as_dict(quota.get("interaction_contract")) - user_channel = _as_dict(contract.get("user_channel")) - if user_channel.get("action_required") is not None: - return bool(user_channel.get("action_required")) - return bool(quota.get("requires_user_action") or quota.get("notify_user_on_gate")) - - -def _quota_user_action_required(quota: dict[str, Any]) -> bool: - if quota.get("action_required") is not None: - return bool(quota.get("action_required")) - return _interaction_user_required(quota) - - -def _quota_user_open_count(quota: dict[str, Any]) -> int: - value = quota.get("open_count") - if isinstance(value, int): - return value - return _open_count(_as_dict(quota.get("user_todo_summary"))) - - -def _machine_signal(*, status_payload: dict[str, Any], item: dict[str, Any] | None, quota: dict[str, Any]) -> str: - if not status_payload.get("ok"): - return "status_health_attention" - if item is None: - return "not_connected_or_not_projected" - if not quota.get("ok", True): - return "quota_attention" - user_summary = _todo_summary(quota, item, role="user") - if _quota_user_action_required(quota) or _open_count(user_summary) > 0: - return "user_or_controller_attention" - if quota.get("capability_repair_allowed"): - return "capability_repair_attention" - if quota.get("self_repair_allowed"): - return "self_repair_attention" - if quota.get("recovery_delivery_allowed"): - return "recovery_attention" - if quota.get("should_run") and quota.get("normal_delivery_allowed", True): - return "agent_work_attention" - if quota.get("safe_bypass_allowed"): - return "safe_bypass_attention" - if item.get("waiting_on") == "external_evidence": - return "external_evidence_attention" - return "no_immediate_agent_delivery_signal" - - -def _first_user_question(quota: dict[str, Any], item: dict[str, Any]) -> str | None: - for key in ("operator_question", "gate_prompt"): - if quota.get(key): - return str(quota.get(key)) - if item.get(key): - return str(item.get(key)) - return _first_text(_todo_summary(quota, item, role="user")) - - def _agent_commands( *, goal_id: str | None, registry_path: Path, limit: int, agent_id: str | None, - available_capabilities: Any = None, + available_capabilities: object = None, + capability_args: str | None = None, ) -> list[str]: registry_arg = shlex.quote(str(registry_path)) - diagnose = f"loopx --registry {registry_arg} diagnose" - status = f"loopx --registry {registry_arg} status" agent_arg = f" --agent-id {shlex.quote(agent_id)}" if agent_id else "" - capability_args = render_available_capability_args(available_capabilities) + caps_arg = ( + capability_args + if capability_args is not None + else render_available_capability_args(available_capabilities) + ) scheduler_args = render_scheduler_execution_args( scheduler_execution_context=GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT, ) goal_arg = f" --goal-id {shlex.quote(goal_id)}" if goal_id else "" + bounded_limit = max(1, limit) commands = [ - f"{diagnose}{goal_arg}{agent_arg}{capability_args} --limit {max(1, limit)}", - f"{status}{goal_arg}{agent_arg} --limit {max(1, limit)}", + f"loopx --registry {registry_arg} diagnose{goal_arg}{agent_arg}{caps_arg} --limit {bounded_limit}", + f"loopx --registry {registry_arg} status{goal_arg}{agent_arg} --limit {bounded_limit}", ] if goal_id: quoted_goal = shlex.quote(goal_id) commands.append( f"loopx --registry {registry_arg} --format json quota should-run " - f"--goal-id {quoted_goal}{agent_arg}{capability_args}{scheduler_args}" + f"--goal-id {quoted_goal}{agent_arg}{caps_arg}{scheduler_args}" + ) + commands.append( + f"loopx --registry {registry_arg} history --goal-id {quoted_goal} --limit {bounded_limit}" ) - commands.append(f"loopx --registry {registry_arg} history --goal-id {quoted_goal} --limit {max(1, limit)}") return commands -def _compact_quota_signals(quota: dict[str, Any]) -> dict[str, Any]: - keys = ( - "ok", - "decision", - "should_run", - "state", - "effective_action", - "actionable_by_codex", - "normal_delivery_allowed", - "recovery_delivery_allowed", - "capability_repair_allowed", - "self_repair_allowed", - "safe_bypass_allowed", - "safe_bypass_kind", - "requires_user_action", - "recommended_action", - "reason", - "agent_identity", - "agent_lane_next_action", - "agent_scoped_user_gate_override", - "agent_scoped_user_action_override", - "agent_scope_frontier", - "goal_frontier_projection", - "autonomous_replan_decision", - ) - signals = {key: quota.get(key) for key in keys if key in quota} - signals["action_required"] = _quota_user_action_required(quota) - signals["open_count"] = _quota_user_open_count(quota) - scheduler_hint = _compact_scheduler_hint(_as_dict(quota.get("scheduler_hint"))) - if scheduler_hint: - signals["scheduler_hint"] = scheduler_hint - return signals - - -def _compact_interaction_contract(contract: dict[str, Any]) -> dict[str, Any]: - compact = dict(contract) - agent_channel = _as_dict(contract.get("agent_channel")) - cli_channel = _as_dict(contract.get("cli_channel")) - for field in ("action_portfolio_ref", "suggested_action_count"): - agent_channel.pop(field, None) - for field in ("selection_policy_ref", "selection_command"): - cli_channel.pop(field, None) - compact["agent_channel"] = agent_channel - compact["cli_channel"] = cli_channel - return compact - - -def _goal_list_view(packet: dict[str, Any], *, selected: bool) -> dict[str, Any]: - """Avoid repeating the selected work's source-read plan in the overview.""" - if not selected: - return packet - contract = _as_dict(packet.get("interaction_contract")) - agent_channel = _as_dict(contract.get("agent_channel")) - if not agent_channel.get("required_reads") and not agent_channel.get("work_context"): - return packet - overview_contract = dict(contract) - overview_agent_channel = dict(agent_channel) - overview_agent_channel.pop("required_reads", None) - overview_agent_channel.pop("work_context", None) - overview_contract["agent_channel"] = overview_agent_channel - return {**packet, "interaction_contract": overview_contract} - - -def _compact_scheduler_hint(scheduler_hint: dict[str, Any]) -> dict[str, Any]: - if not scheduler_hint: - return {} - canonical_app_automation = _as_dict(scheduler_hint.get("app_automation")) - legacy_codex_app = _as_dict(scheduler_hint.get("codex_app")) - app_automation = canonical_app_automation or legacy_codex_app - app_key = "app_automation" if canonical_app_automation else "codex_app" - stateful_backoff = _as_dict(app_automation.get("stateful_backoff")) - reset_policy = _as_dict(scheduler_hint.get("reset_policy")) - unchanged_poll = _as_dict(scheduler_hint.get("unchanged_poll")) - compact = { - "schema_version": "diagnose_scheduler_hint_summary_v0", - "action": scheduler_hint.get("action"), - "cadence_class": scheduler_hint.get("cadence_class"), - "reason": scheduler_hint.get("reason"), - app_key: { - "apply": app_automation.get("apply"), - "host_action": app_automation.get("host_action"), - "recommended_rrule": app_automation.get("recommended_rrule"), - "recommended_interval_minutes": app_automation.get("recommended_interval_minutes"), - "current_rrule": stateful_backoff.get("current_rrule"), - "apply_needed": stateful_backoff.get("apply_needed"), - "no_spend_for_cadence_change": app_automation.get("no_spend_for_cadence_change"), - }, - "unchanged_poll": { - "final_quota_replan_check_enabled": unchanged_poll.get( - "final_quota_replan_check_enabled" - ), - "final_quota_replan_check_action": unchanged_poll.get( - "final_quota_replan_check_action" - ), - }, - "reset_policy": { - "reset_token": reset_policy.get("reset_token"), - }, - } - reset_key = ( - "app_automation_initial_rrule" - if canonical_app_automation - else "codex_app_initial_rrule" - ) - compact["reset_policy"][reset_key] = reset_policy.get(reset_key) - return compact - - -def _goal_frontier_projection_line(goal_frontier: dict[str, Any]) -> str | None: - if not goal_frontier: - return None - normalized_progress = ( - goal_frontier.get("normalized_progress") - if isinstance(goal_frontier.get("normalized_progress"), dict) - else {} - ) - remaining = ( - goal_frontier.get("remaining_advancement_frontier") - if isinstance(goal_frontier.get("remaining_advancement_frontier"), dict) - else {} - ) - deferred_successors = ( - goal_frontier.get("deferred_successors") - if isinstance(goal_frontier.get("deferred_successors"), dict) - else {} - ) - monitor_only_lanes = ( - goal_frontier.get("monitor_only_lanes") - if isinstance(goal_frontier.get("monitor_only_lanes"), dict) - else {} - ) - acceptance_gaps = ( - goal_frontier.get("acceptance_gaps") - if isinstance(goal_frontier.get("acceptance_gaps"), list) - else [] - ) - autonomy_blockers = ( - goal_frontier.get("autonomy_blockers") - if isinstance(goal_frontier.get("autonomy_blockers"), list) - else [] - ) - return ( - "- goal_frontier_projection: " - f"replan_required={goal_frontier.get('replan_required')} " - f"user_open={normalized_progress.get('user_open_count')} " - f"agent_open={normalized_progress.get('agent_open_count')} " - f"current_agent_advancement={remaining.get('current_agent_claimed_advancement_count')} " - f"unclaimed_advancement={remaining.get('unclaimed_advancement_count')} " - f"other_agent_advancement={remaining.get('other_agent_claimed_advancement_count')} " - f"deferred_ready={deferred_successors.get('ready_count')} " - f"monitor_only={monitor_only_lanes.get('present')} " - f"acceptance_gaps={len(acceptance_gaps)} " - f"autonomy_blockers={len(autonomy_blockers)}" - ) - - -def _scheduler_hint_line(scheduler_hint: dict[str, Any]) -> str | None: - if not scheduler_hint: - return None - canonical_app_automation = _as_dict(scheduler_hint.get("app_automation")) - app_automation = canonical_app_automation or _as_dict( - scheduler_hint.get("codex_app") - ) - apply_label = ( - "app_automation_apply" if canonical_app_automation else "codex_app_apply" - ) - unchanged_poll = _as_dict(scheduler_hint.get("unchanged_poll")) - return ( - "- scheduler_hint: " - f"action={scheduler_hint.get('action')} " - f"cadence={scheduler_hint.get('cadence_class')} " - f"{apply_label}={app_automation.get('apply')} " - f"apply_needed={app_automation.get('apply_needed')} " - f"recommended_rrule={app_automation.get('recommended_rrule')} " - f"current_rrule={app_automation.get('current_rrule')} " - f"final_replan_check={unchanged_poll.get('final_quota_replan_check_enabled')} " - f"no_spend_for_cadence_change={app_automation.get('no_spend_for_cadence_change')}" - ) - - def _build_goal_packet( *, - status_payload: dict[str, Any], - item: dict[str, Any] | None, - quota: dict[str, Any], + status_payload: Mapping[str, object], + item: Mapping[str, object] | None, + quota: Mapping[str, object], registry_path: Path, limit: int, agent_id: str | None, - available_capabilities: Any = None, -) -> dict[str, Any]: + available_capabilities: object = None, + normalized_capabilities: Sequence[str] | None = None, + capability_args: str | None = None, +) -> dict[str, object]: goal_id = str((item or {}).get("goal_id") or quota.get("goal_id") or "") - item = item or {} - user_summary = _todo_summary(quota, item, role="user") - agent_summary = _todo_summary(quota, item, role="agent") - machine_signal = _machine_signal(status_payload=status_payload, item=item or None, quota=quota) + item_map = item or {} + user_summary = _todo_summary(quota, item_map, role="user") + agent_summary = _todo_summary(quota, item_map, role="agent") + capabilities = ( + list(normalized_capabilities) + if normalized_capabilities is not None + else normalize_required_capabilities(available_capabilities) + ) return { "goal_id": goal_id or None, "packet_role": "evidence_for_agent_reasoning", - "machine_signal": machine_signal, + "machine_signal": _machine_signal(status_payload=status_payload, item=item or None, quota=quota), "machine_signals_are_not_final_verdict": True, - "status": item.get("status"), - "waiting_on": item.get("waiting_on"), - "severity": item.get("severity"), - "recommended_action": quota.get("recommended_action") or item.get("recommended_action"), - "user_question": _first_user_question(quota, item), + "status": item_map.get("status"), + "waiting_on": item_map.get("waiting_on"), + "severity": item_map.get("severity"), + "recommended_action": quota.get("recommended_action") or item_map.get("recommended_action"), + "user_question": _first_user_question(quota, item_map), "todo_evidence": { "user_open_count": _open_count(user_summary), "agent_open_count": _open_count(agent_summary), @@ -477,17 +187,15 @@ def _build_goal_packet( }, "quota_signals": _compact_quota_signals(quota), "agent_id": agent_id, - "available_capabilities": normalize_required_capabilities(available_capabilities), - "interaction_contract": _compact_interaction_contract( - _as_dict(quota.get("interaction_contract")) - ), - "work_lane_contract": _as_dict(quota.get("work_lane_contract")), - "goal_boundary": _as_dict(quota.get("goal_boundary")), + "available_capabilities": capabilities, + "interaction_contract": _compact_interaction_contract(_as_mapping(quota.get("interaction_contract"))), + "work_lane_contract": dict(_as_mapping(quota.get("work_lane_contract"))), + "goal_boundary": dict(_as_mapping(quota.get("goal_boundary"))), "projection_warnings": { - "state_projection_gap": _as_dict(quota.get("state_projection_gap")), - "state_action_projection_warning": _as_dict(quota.get("state_action_projection_warning")), - "backlog_hygiene_warning": _as_dict(quota.get("backlog_hygiene_warning")), - "autonomous_replan_obligation": _as_dict(quota.get("autonomous_replan_obligation")), + "state_projection_gap": dict(_as_mapping(quota.get("state_projection_gap"))), + "state_action_projection_warning": dict(_as_mapping(quota.get("state_action_projection_warning"))), + "backlog_hygiene_warning": dict(_as_mapping(quota.get("backlog_hygiene_warning"))), + "autonomous_replan_obligation": dict(_as_mapping(quota.get("autonomous_replan_obligation"))), }, "agent_reasoning_checklist": AGENT_REASONING_CHECKLIST, "agent_commands": _agent_commands( @@ -496,21 +204,23 @@ def _build_goal_packet( limit=limit, agent_id=agent_id, available_capabilities=available_capabilities, + capability_args=capability_args, ), } def _apply_orphaned_goal_state_diagnosis( - packet: dict[str, Any], - projection: dict[str, Any], + packet: dict[str, object], + projection: Mapping[str, object], *, registry_path: Path, + project_root: Path | None = None, ) -> None: - commands = _as_list(packet.get("agent_commands")) + commands = _as_items(packet.get("agent_commands")) status_command = str(commands[1]) if len(commands) > 1 else "loopx status" gate = orphaned_goal_state_gate( - projection, - project=str(registry_project_root(registry_path)), + dict(projection), + project=str(project_root or registry_project_root(registry_path)), command_prefix="loopx", status_command=status_command, ) @@ -521,9 +231,7 @@ def _apply_orphaned_goal_state_diagnosis( "waiting_on": "operator", "severity": "high", "recommended_action": ORPHANED_GOAL_STATE_RECOMMENDED_ACTION, - "user_question": ( - "Resolve the orphaned Goal state before reconnecting this goal id." - ), + "user_question": "Resolve the orphaned Goal state before reconnecting this goal id.", "orphaned_goal_state": gate, "quota_signals": { "ok": False, @@ -538,8 +246,8 @@ def _apply_orphaned_goal_state_diagnosis( }, "agent_commands": [ str(route.get("command")) - for route in gate["resolution_routes"] - if isinstance(route, dict) and route.get("command") + for route in _as_items(gate.get("resolution_routes")) + if isinstance(route, Mapping) and route.get("command") ], } ) @@ -552,26 +260,34 @@ def collect_diagnosis( limit: int, goal_id: str | None = None, agent_id: str | None = None, - available_capabilities: Any = None, -) -> dict[str, Any]: + available_capabilities: object = None, +) -> dict[str, object]: + """Collect a structured, agent-facing diagnosis packet without repeating scans.""" limit = max(1, limit) registry_path = registry_path.expanduser() - status_payload = collect_status( - registry_path=registry_path, - runtime_root_override=runtime_root_override, - limit=limit, - goal_id=goal_id, - available_capabilities=available_capabilities, + status_payload = dict( + collect_status( + registry_path=registry_path, + runtime_root_override=runtime_root_override, + limit=limit, + goal_id=goal_id, + available_capabilities=available_capabilities, + ) ) - goal_ids = _goal_ids_for_packet(status_payload, goal_id=goal_id, limit=limit) - item_by_goal = { - str(item.get("goal_id") or ""): item - for item in _attention_items(status_payload) - if item.get("goal_id") + normalized_capabilities = normalize_required_capabilities(available_capabilities) + capability_args = render_available_capability_args(available_capabilities) + attention_items = _attention_items(status_payload) + goal_ids = [goal_id] if goal_id else _goal_ids_from_items(attention_items, limit=limit) + item_by_goal: dict[str, Mapping[str, object]] = { + gid: item + for item in attention_items + if (gid := str(item.get("goal_id") or "")) } - goal_packets = [] + unregistered_goals = _unregistered_goal_ids(status_payload) + project_root = registry_project_root(registry_path) if unregistered_goals else None + + goal_packets: list[dict[str, object]] = [] for current_goal_id in goal_ids: - item = item_by_goal.get(current_goal_id) quota = _quota_for_goal( status_payload, current_goal_id, @@ -580,28 +296,32 @@ def collect_diagnosis( ) packet = _build_goal_packet( status_payload=status_payload, - item=item, + item=item_by_goal.get(current_goal_id), quota=quota, registry_path=registry_path, limit=limit, agent_id=agent_id, - available_capabilities=available_capabilities, - ) - orphaned_goal_state = _orphaned_goal_state_for_diagnosis( - status_payload, - registry_path=registry_path, - goal_id=current_goal_id, + normalized_capabilities=normalized_capabilities, + capability_args=capability_args, ) - if orphaned_goal_state is not None: - _apply_orphaned_goal_state_diagnosis( - packet, - orphaned_goal_state, - registry_path=registry_path, - ) + if current_goal_id in unregistered_goals and project_root is not None: + orphaned_state = orphaned_goal_state_projection(project_root, current_goal_id) + if orphaned_state is not None: + _apply_orphaned_goal_state_diagnosis( + packet, + orphaned_state, + registry_path=registry_path, + project_root=project_root, + ) goal_packets.append(packet) - selected_item = _select_attention_item(status_payload, goal_id=goal_id) + + selected_item = ( + item_by_goal.get(goal_id) + if goal_id + else (attention_items[0] if attention_items else None) + ) selected_goal_id = str((selected_item or {}).get("goal_id") or (goal_ids[0] if goal_ids else "")) - selected = next((item for item in goal_packets if item.get("goal_id") == selected_goal_id), None) + selected = next((p for p in goal_packets if p.get("goal_id") == selected_goal_id), None) if selected is None: selected = _build_goal_packet( status_payload=status_payload, @@ -610,20 +330,16 @@ def collect_diagnosis( registry_path=registry_path, limit=limit, agent_id=agent_id, - available_capabilities=available_capabilities, + normalized_capabilities=normalized_capabilities, + capability_args=capability_args, ) - contract = _as_dict(status_payload.get("contract")) - contract_errors = _compact_text_signals(contract.get("errors")) - contract_warnings = _compact_text_signals(contract.get("warnings")) - diagnosis_blocked = any( - item.get("machine_signal") == ORPHANED_GOAL_STATE_CONNECTION - for item in goal_packets - ) - goal_overviews = [ - _goal_list_view(packet, selected=packet is selected) - for packet in goal_packets - ] - payload = { + + contract = _as_mapping(status_payload.get("contract")) + contract_errors = _compact_text_signals(contract.get("errors"), limit=STATUS_CONTRACT_SIGNAL_LIMIT) + contract_warnings = _compact_text_signals(contract.get("warnings"), limit=STATUS_CONTRACT_SIGNAL_LIMIT) + diagnosis_blocked = any(p.get("machine_signal") == ORPHANED_GOAL_STATE_CONNECTION for p in goal_packets) + goal_overviews = [_goal_list_view(p, selected=p is selected) for p in goal_packets] + payload: dict[str, object] = { "ok": bool(status_payload.get("ok")) and not diagnosis_blocked, "schema_version": DIAGNOSIS_SCHEMA_VERSION, "packet_kind": PACKET_KIND, @@ -632,13 +348,13 @@ def collect_diagnosis( "runtime_root": status_payload.get("runtime_root"), "goal_id": goal_id, "agent_id": agent_id, - "available_capabilities": normalize_required_capabilities(available_capabilities), + "available_capabilities": list(normalized_capabilities), "selected_goal_id": selected.get("goal_id"), "status_ok": status_payload.get("ok"), "goal_count": status_payload.get("goal_count"), "goal_packet_count": len(goal_packets), "run_count": status_payload.get("run_count"), - "attention_item_count": _as_dict(status_payload.get("attention_queue")).get("item_count"), + "attention_item_count": _as_mapping(status_payload.get("attention_queue")).get("item_count"), "selected": selected, "goals": goal_overviews, "status_summary": { @@ -649,141 +365,10 @@ def collect_diagnosis( "contract_warnings": contract_warnings["items"], "contract_warnings_total_count": contract_warnings["total_count"], "contract_warnings_truncated": contract_warnings["truncated"], - "global_registry": _as_dict(_as_dict(status_payload.get("global_registry")).get("summary")), + "global_registry": dict(_as_mapping(_as_mapping(status_payload.get("global_registry")).get("summary"))), }, "user_prompt": USER_DIAGNOSE_PROMPT, } if diagnosis_blocked: payload["diagnosis_blocked_by"] = ORPHANED_GOAL_STATE_CONNECTION return payload - - -def render_diagnosis_markdown(payload: dict[str, Any]) -> str: - selected = _as_dict(payload.get("selected")) - todo_evidence = _as_dict(selected.get("todo_evidence")) - quota = _as_dict(selected.get("quota_signals")) - status_summary = _as_dict(payload.get("status_summary")) - lines = [ - "# LoopX Diagnosis Packet", - "", - "This packet is evidence for the user's agent. LoopX is not making the final diagnosis.", - "", - f"- ok: `{payload.get('ok')}`", - f"- packet_kind: `{payload.get('packet_kind')}`", - f"- agent_must_reason: `{payload.get('agent_must_reason')}`", - f"- registry: `{payload.get('registry')}`", - f"- runtime_root: `{payload.get('runtime_root')}`", - f"- selected_goal_id: `{payload.get('selected_goal_id')}`", - f"- status_goals: `{payload.get('goal_count')}`", - f"- goal_packets: `{payload.get('goal_packet_count') or len(_as_list(payload.get('goals')))}`", - f"- runs: `{payload.get('run_count')}`", - "", - "## Machine Signals", - "", - f"- machine_signal: `{selected.get('machine_signal')}`", - f"- status: `{selected.get('status')}`", - f"- waiting_on: `{selected.get('waiting_on')}`", - f"- severity: `{selected.get('severity')}`", - f"- recommended_action: {markdown_scalar(selected.get('recommended_action'))}", - f"- user_question: {markdown_scalar(selected.get('user_question'))}", - f"- user_todo_open_count: `{todo_evidence.get('user_open_count')}`", - f"- agent_todo_open_count: `{todo_evidence.get('agent_open_count')}`", - ] - if todo_evidence.get("first_user_todo"): - lines.append(f"- first_user_todo: {markdown_scalar(todo_evidence.get('first_user_todo'))}") - if todo_evidence.get("first_agent_todo"): - lines.append(f"- first_agent_todo: {markdown_scalar(todo_evidence.get('first_agent_todo'))}") - if quota: - lines.extend( - [ - f"- quota_state: `{quota.get('state')}`", - f"- quota_should_run: `{quota.get('should_run')}`", - f"- effective_action: `{quota.get('effective_action')}`", - f"- action_required: `{quota.get('action_required')}`", - f"- open_count: `{quota.get('open_count')}`", - f"- requires_user_action: `{quota.get('requires_user_action')}`", - f"- normal_delivery_allowed: `{quota.get('normal_delivery_allowed')}`", - f"- self_repair_allowed: `{quota.get('self_repair_allowed')}`", - f"- safe_bypass_allowed: `{quota.get('safe_bypass_allowed')}`", - f"- quota_reason: {markdown_scalar(quota.get('reason'))}", - ] - ) - goal_frontier_line = _goal_frontier_projection_line( - _as_dict(quota.get("goal_frontier_projection")) - ) - if goal_frontier_line: - lines.append(goal_frontier_line) - scheduler_hint_line = _scheduler_hint_line(_as_dict(quota.get("scheduler_hint"))) - if scheduler_hint_line: - lines.append(scheduler_hint_line) - - orphaned_goal_state = _as_dict(selected.get("orphaned_goal_state")) - if orphaned_goal_state: - lines.extend( - [ - "", - "## Orphaned Goal State", - "", - f"- reason: {markdown_scalar(orphaned_goal_state.get('reason'))}", - "- state_file_routes: " - + ", ".join( - f"`{route}`" - for route in _as_list(orphaned_goal_state.get("state_file_routes")) - ), - "- forbidden_until_resolved: " - + ", ".join( - f"`{item}`" - for item in _as_list( - orphaned_goal_state.get("forbidden_until_resolved") - ) - ), - ] - ) - - contract_errors = _as_list(status_summary.get("contract_errors")) - contract_warnings = _as_list(status_summary.get("contract_warnings")) - if contract_errors or contract_warnings: - lines.extend(["", "## Status Contract Signals", ""]) - for item in contract_errors: - lines.append(f"- contract_error: {markdown_scalar(item)}") - if status_summary.get("contract_errors_truncated"): - lines.append( - f"- contract_errors_truncated: total={status_summary.get('contract_errors_total_count')}" - ) - for item in contract_warnings: - lines.append(f"- contract_warning: {markdown_scalar(item)}") - if status_summary.get("contract_warnings_truncated"): - lines.append( - f"- contract_warnings_truncated: total={status_summary.get('contract_warnings_total_count')}" - ) - - checklist = _as_list(selected.get("agent_reasoning_checklist")) - if checklist: - lines.extend(["", "## Agent Reasoning Checklist", ""]) - for item in checklist: - lines.append(f"- {markdown_scalar(item)}") - - commands = _as_list(selected.get("agent_commands")) - if commands: - lines.extend(["", "## Agent Commands", ""]) - lines.append("These are for the agent to run when it needs drill-down, not for the user to copy manually.") - for command in commands: - lines.append(f"- `{command}`") - - goals = _as_list(payload.get("goals")) - if goals: - lines.extend(["", "## Goal Packets", "", "| goal | machine signal | user todo | agent todo |", "| --- | --- | --- | --- |"]) - for goal in goals: - if not isinstance(goal, dict): - continue - evidence = _as_dict(goal.get("todo_evidence")) - lines.append( - "| " - f"`{goal.get('goal_id')}` | " - f"`{goal.get('machine_signal')}` | " - f"`{evidence.get('user_open_count')}` | " - f"`{evidence.get('agent_open_count')}` |" - ) - - lines.extend(["", "## User Prompt", "", str(payload.get("user_prompt") or USER_DIAGNOSE_PROMPT)]) - return "\n".join(lines) diff --git a/loopx/presentation/renderers/diagnose_markdown.py b/loopx/presentation/renderers/diagnose_markdown.py new file mode 100644 index 0000000000..1ce1bdea1c --- /dev/null +++ b/loopx/presentation/renderers/diagnose_markdown.py @@ -0,0 +1,232 @@ +"""Pure Markdown renderer for ``loopx diagnose`` evidence packets.""" + +from __future__ import annotations + +from collections.abc import Mapping + +from ...control_plane.status.diagnose_projection import _as_items, _as_mapping +from ..markdown import markdown_scalar + +USER_DIAGNOSE_PROMPT = ( + "请诊断这个项目的 LoopX 运转情况。不要让我手动跑 shell 命令;如果 " + "`loopx` 不在 PATH,请先安装/修复。然后运行 `loopx diagnose` " + "读取诊断证据包,结合项目上下文自己判断:它是否可以自主推进、当前卡在哪、" + "需要我回答什么、以及你下一步会做什么。" +) + + +def _goal_frontier_projection_line(goal_frontier: Mapping[str, object]) -> str | None: + """Format compact goal-frontier summary line when projection data is present.""" + if not goal_frontier: + return None + normalized_progress = _as_mapping(goal_frontier.get("normalized_progress")) + remaining = _as_mapping(goal_frontier.get("remaining_advancement_frontier")) + deferred_successors = _as_mapping(goal_frontier.get("deferred_successors")) + monitor_only_lanes = _as_mapping(goal_frontier.get("monitor_only_lanes")) + acceptance_gaps = _as_items(goal_frontier.get("acceptance_gaps")) + autonomy_blockers = _as_items(goal_frontier.get("autonomy_blockers")) + return ( + "- goal_frontier_projection: " + f"replan_required={goal_frontier.get('replan_required')} " + f"user_open={normalized_progress.get('user_open_count')} " + f"agent_open={normalized_progress.get('agent_open_count')} " + f"current_agent_advancement={remaining.get('current_agent_claimed_advancement_count')} " + f"unclaimed_advancement={remaining.get('unclaimed_advancement_count')} " + f"other_agent_advancement={remaining.get('other_agent_claimed_advancement_count')} " + f"deferred_ready={deferred_successors.get('ready_count')} " + f"monitor_only={monitor_only_lanes.get('present')} " + f"acceptance_gaps={len(acceptance_gaps)} " + f"autonomy_blockers={len(autonomy_blockers)}" + ) + + +def _scheduler_hint_line(scheduler_hint: Mapping[str, object]) -> str | None: + """Format compact scheduler-cadence hint line for diagnose Markdown.""" + if not scheduler_hint: + return None + canonical_app_automation = _as_mapping(scheduler_hint.get("app_automation")) + app_automation = canonical_app_automation or _as_mapping( + scheduler_hint.get("codex_app") + ) + apply_label = ( + "app_automation_apply" if canonical_app_automation else "codex_app_apply" + ) + unchanged_poll = _as_mapping(scheduler_hint.get("unchanged_poll")) + return ( + "- scheduler_hint: " + f"action={scheduler_hint.get('action')} " + f"cadence={scheduler_hint.get('cadence_class')} " + f"{apply_label}={app_automation.get('apply')} " + f"apply_needed={app_automation.get('apply_needed')} " + f"recommended_rrule={app_automation.get('recommended_rrule')} " + f"current_rrule={app_automation.get('current_rrule')} " + f"final_replan_check={unchanged_poll.get('final_quota_replan_check_enabled')} " + f"no_spend_for_cadence_change={app_automation.get('no_spend_for_cadence_change')}" + ) + + +def _append_machine_signals( + lines: list[str], + selected: Mapping[str, object], +) -> None: + todo_evidence = _as_mapping(selected.get("todo_evidence")) + quota = _as_mapping(selected.get("quota_signals")) + lines.extend( + [ + "", + "## Machine Signals", + "", + f"- machine_signal: `{selected.get('machine_signal')}`", + f"- status: `{selected.get('status')}`", + f"- waiting_on: `{selected.get('waiting_on')}`", + f"- severity: `{selected.get('severity')}`", + f"- recommended_action: {markdown_scalar(selected.get('recommended_action'))}", + f"- user_question: {markdown_scalar(selected.get('user_question'))}", + f"- user_todo_open_count: `{todo_evidence.get('user_open_count')}`", + f"- agent_todo_open_count: `{todo_evidence.get('agent_open_count')}`", + ] + ) + if todo_evidence.get("first_user_todo"): + lines.append(f"- first_user_todo: {markdown_scalar(todo_evidence.get('first_user_todo'))}") + if todo_evidence.get("first_agent_todo"): + lines.append(f"- first_agent_todo: {markdown_scalar(todo_evidence.get('first_agent_todo'))}") + if not quota: + return + lines.extend( + [ + f"- quota_state: `{quota.get('state')}`", + f"- quota_should_run: `{quota.get('should_run')}`", + f"- effective_action: `{quota.get('effective_action')}`", + f"- action_required: `{quota.get('action_required')}`", + f"- open_count: `{quota.get('open_count')}`", + f"- requires_user_action: `{quota.get('requires_user_action')}`", + f"- normal_delivery_allowed: `{quota.get('normal_delivery_allowed')}`", + f"- self_repair_allowed: `{quota.get('self_repair_allowed')}`", + f"- safe_bypass_allowed: `{quota.get('safe_bypass_allowed')}`", + f"- quota_reason: {markdown_scalar(quota.get('reason'))}", + ] + ) + goal_frontier_line = _goal_frontier_projection_line( + _as_mapping(quota.get("goal_frontier_projection")) + ) + if goal_frontier_line: + lines.append(goal_frontier_line) + scheduler_hint_line = _scheduler_hint_line(_as_mapping(quota.get("scheduler_hint"))) + if scheduler_hint_line: + lines.append(scheduler_hint_line) + + +def _append_orphaned_state( + lines: list[str], + selected: Mapping[str, object], +) -> None: + orphaned_goal_state = _as_mapping(selected.get("orphaned_goal_state")) + if not orphaned_goal_state: + return + routes = ", ".join( + f"`{route}`" for route in _as_items(orphaned_goal_state.get("state_file_routes")) + ) + forbidden = ", ".join( + f"`{item}`" + for item in _as_items(orphaned_goal_state.get("forbidden_until_resolved")) + ) + lines.extend( + [ + "", + "## Orphaned Goal State", + "", + f"- reason: {markdown_scalar(orphaned_goal_state.get('reason'))}", + f"- state_file_routes: {routes}", + f"- forbidden_until_resolved: {forbidden}", + ] + ) + + +def _append_contract_and_goals( + lines: list[str], + payload: Mapping[str, object], + selected: Mapping[str, object], +) -> None: + status_summary = _as_mapping(payload.get("status_summary")) + contract_errors = _as_items(status_summary.get("contract_errors")) + contract_warnings = _as_items(status_summary.get("contract_warnings")) + if contract_errors or contract_warnings: + lines.extend(["", "## Status Contract Signals", ""]) + lines.extend(f"- contract_error: {markdown_scalar(item)}" for item in contract_errors) + if status_summary.get("contract_errors_truncated"): + lines.append( + f"- contract_errors_truncated: total={status_summary.get('contract_errors_total_count')}" + ) + lines.extend( + f"- contract_warning: {markdown_scalar(item)}" for item in contract_warnings + ) + if status_summary.get("contract_warnings_truncated"): + lines.append( + f"- contract_warnings_truncated: total={status_summary.get('contract_warnings_total_count')}" + ) + + checklist = _as_items(selected.get("agent_reasoning_checklist")) + if checklist: + lines.extend(["", "## Agent Reasoning Checklist", ""]) + lines.extend(f"- {markdown_scalar(item)}" for item in checklist) + + commands = _as_items(selected.get("agent_commands")) + if commands: + lines.extend( + [ + "", + "## Agent Commands", + "", + "These are for the agent to run when it needs drill-down, not for the user to copy manually.", + *(f"- `{command}`" for command in commands), + ] + ) + + goals = _as_items(payload.get("goals")) + if goals: + lines.extend( + [ + "", + "## Goal Packets", + "", + "| goal | machine signal | user todo | agent todo |", + "| --- | --- | --- | --- |", + ] + ) + for goal in goals: + if not isinstance(goal, Mapping): + continue + evidence = _as_mapping(goal.get("todo_evidence")) + lines.append( + "| " + f"`{goal.get('goal_id')}` | " + f"`{goal.get('machine_signal')}` | " + f"`{evidence.get('user_open_count')}` | " + f"`{evidence.get('agent_open_count')}` |" + ) + + +def render_diagnosis_markdown(payload: Mapping[str, object]) -> str: + """Render an evidence-backed Markdown report for ``loopx diagnose``.""" + selected = _as_mapping(payload.get("selected")) + goal_packets = payload.get("goal_packet_count") or len(_as_items(payload.get("goals"))) + lines = [ + "# LoopX Diagnosis Packet", + "", + "This packet is evidence for the user's agent. LoopX is not making the final diagnosis.", + "", + f"- ok: `{payload.get('ok')}`", + f"- packet_kind: `{payload.get('packet_kind')}`", + f"- agent_must_reason: `{payload.get('agent_must_reason')}`", + f"- registry: `{payload.get('registry')}`", + f"- runtime_root: `{payload.get('runtime_root')}`", + f"- selected_goal_id: `{payload.get('selected_goal_id')}`", + f"- status_goals: `{payload.get('goal_count')}`", + f"- goal_packets: `{goal_packets}`", + f"- runs: `{payload.get('run_count')}`", + ] + _append_machine_signals(lines, selected) + _append_orphaned_state(lines, selected) + _append_contract_and_goals(lines, payload, selected) + lines.extend(["", "## User Prompt", "", str(payload.get("user_prompt") or USER_DIAGNOSE_PROMPT)]) + return "\n".join(lines) diff --git a/tests/control_plane/test_diagnose_contract.py b/tests/control_plane/test_diagnose_contract.py new file mode 100644 index 0000000000..8f26dcb49d --- /dev/null +++ b/tests/control_plane/test_diagnose_contract.py @@ -0,0 +1,327 @@ +"""Contract, zero-Any, MappingProxyType, and parity tests for loopx.diagnose.""" + +from __future__ import annotations + +import ast +import json +from pathlib import Path +from types import MappingProxyType +import pytest + +from loopx import diagnose +from loopx.cli import main +from loopx.control_plane.status import contract_projection, diagnose_projection +from loopx.control_plane.testing.canary_harness import import_fixture_authority +from loopx.presentation.renderers import diagnose_markdown + + +def test_diagnose_zero_any_budgets_and_identity() -> None: + for rel, max_loc in ( + ("loopx/diagnose.py", 550), + ("loopx/control_plane/status/diagnose_projection.py", 750), + ("loopx/presentation/renderers/diagnose_markdown.py", 750), + ("tests/control_plane/test_diagnose_contract.py", 400), + ): + src = (Path(__file__).resolve().parents[2] / rel).read_text(encoding="utf-8") + assert len(src.splitlines()) <= max_loc, rel + tree = ast.parse(src) + anys = [n for n in ast.walk(tree) if isinstance(n, ast.Name) and n.id == "Any"] + assert anys == [], rel + assert ("type: " + "ignore") not in src, rel + assert ("no" + "qa") not in src, rel + + assert diagnose.STATUS_CONTRACT_SIGNAL_LIMIT is contract_projection.STATUS_CONTRACT_SIGNAL_LIMIT + assert diagnose.USER_DIAGNOSE_PROMPT is diagnose_markdown.USER_DIAGNOSE_PROMPT + assert diagnose.render_diagnosis_markdown is diagnose_markdown.render_diagnosis_markdown + assert diagnose._scheduler_hint_line is diagnose_markdown._scheduler_hint_line + assert diagnose._goal_frontier_projection_line is diagnose_markdown._goal_frontier_projection_line + assert diagnose._compact_scheduler_hint is diagnose_projection._compact_scheduler_hint + assert diagnose._first_agent_todo_text is diagnose_projection._first_agent_todo_text + + +def test_mapping_proxy_projection_and_non_mutating_compaction() -> None: + assert diagnose._open_count(MappingProxyType({"open_count": True, "items": [{"text": "a"}]})) == 1 + assert diagnose._open_count(MappingProxyType({"open": 4})) == 4 + + source_agent = {"required_reads": ["GOAL.md"], "action_portfolio_ref": "drop", "suggested_action_count": 2} + source_cli = {"command": "loopx status", "selection_policy_ref": "drop", "selection_command": "drop"} + contract = MappingProxyType({"agent_channel": source_agent, "cli_channel": source_cli}) + compacted = diagnose._compact_interaction_contract(contract) + assert "action_portfolio_ref" in source_agent + assert "selection_policy_ref" in source_cli + assert compacted["agent_channel"] == {"required_reads": ["GOAL.md"]} + assert compacted["cli_channel"] == {"command": "loopx status"} + + packet: dict[str, object] = {"goal_id": "g1", "interaction_contract": compacted} + overview = diagnose._goal_list_view(packet, selected=True) + orig_ic = packet["interaction_contract"] + ov_ic = overview["interaction_contract"] + assert isinstance(orig_ic, dict) and orig_ic["agent_channel"] == {"required_reads": ["GOAL.md"]} + assert isinstance(ov_ic, dict) and ov_ic == { + "agent_channel": {}, + "cli_channel": {"command": "loopx status"}, + } + + hint = MappingProxyType( + { + "action": "hold", + "cadence_class": "idle", + "reason": "no new work", + "app_automation": { + "apply": "none", + "host_action": "keep", + "recommended_rrule": "FREQ=HOURLY", + "stateful_backoff": {"current_rrule": "FREQ=HOURLY", "apply_needed": False}, + "no_spend_for_cadence_change": True, + }, + "unchanged_poll": {"final_quota_replan_check_enabled": True, "final_quota_replan_check_action": "none"}, + "reset_policy": {"reset_token": "tok-1", "app_automation_initial_rrule": "FREQ=MINUTELY"}, + } + ) + compact_hint = diagnose._compact_scheduler_hint(hint) + assert "app_automation" in compact_hint and "codex_app" not in compact_hint + line = diagnose._scheduler_hint_line(compact_hint) + assert line is not None and "app_automation_apply=none" in line + + md = diagnose.render_diagnosis_markdown( + MappingProxyType( + { + "ok": False, + "packet_kind": diagnose.PACKET_KIND, + "agent_must_reason": True, + "registry": "registry.json", + "runtime_root": "rt", + "selected_goal_id": "g1", + "goal_count": 2, + "goal_packet_count": 1, + "run_count": 5, + "selected": { + "machine_signal": "user_or_controller_attention", + "status": "blocked", + "waiting_on": "operator", + "severity": "high", + "recommended_action": "Ask | operator", + "user_question": "Confirm?", + "todo_evidence": {"user_open_count": 1, "agent_open_count": 0, "first_user_todo": "Approve"}, + "quota_signals": { + "state": "hold", + "should_run": False, + "action_required": True, + "open_count": 1, + "goal_frontier_projection": { + "replan_required": False, + "normalized_progress": {"user_open_count": 1, "agent_open_count": 0}, + "acceptance_gaps": ("gap-1",), + "autonomy_blockers": (), + }, + "scheduler_hint": compact_hint, + }, + "orphaned_goal_state": { + "reason": "orphan", + "state_file_routes": ("ACTIVE_GOAL_STATE.md",), + "forbidden_until_resolved": ("bootstrap",), + }, + "agent_reasoning_checklist": ("step 1",), + "agent_commands": ("loopx status",), + }, + "status_summary": { + "contract_errors": ("err-1",), + "contract_errors_truncated": True, + "contract_errors_total_count": 4, + "contract_warnings": ("warn-1",), + "contract_warnings_truncated": True, + "contract_warnings_total_count": 5, + }, + "goals": ({"goal_id": "g1", "machine_signal": "user_or_controller_attention", "todo_evidence": {"user_open_count": 1, "agent_open_count": 0}},), + } + ) + ) + assert "goal_frontier_projection: replan_required=False" in md + assert "Ask \\| operator" in md + assert "contract_errors_truncated: total=4" in md + assert "## Orphaned Goal State" in md + + +def test_collect_diagnosis_isolates_quota_errors_and_handles_orphans( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + registry_path = tmp_path / ".loopx" / "registry.json" + registry_path.parent.mkdir(parents=True) + registry_path.write_text('{"goals": []}\n', encoding="utf-8") + + monkeypatch.setattr( + diagnose, + "collect_status", + lambda **_kw: { + "ok": True, + "runtime_root": "rt", + "goal_count": 2, + "run_count": 1, + "attention_queue": { + "item_count": 2, + "items": [ + {"goal_id": "g-good", "status": "ready", "waiting_on": "none", "severity": "info"}, + {"goal_id": "g-orphan", "status": "blocked", "waiting_on": "operator", "severity": "high"}, + ], + }, + "run_history": {"goals": [{"id": "g-orphan", "registry_member": False}]}, + "contract": {"summary": "ok", "errors": ["e1", "e2", "e3", "e4"], "warnings": []}, + "global_registry": {"summary": {"total": 1}}, + }, + ) + + def fake_quota( + _status: dict[str, object], + *, + goal_id: str, + **_kw: object, + ) -> dict[str, object]: + if goal_id == "g-good": + return { + "ok": True, + "goal_id": goal_id, + "should_run": True, + "interaction_contract": { + "agent_channel": {"required_reads": ["GOAL.md"], "action_portfolio_ref": "x"}, + "cli_channel": {"selection_policy_ref": "y"}, + }, + } + raise RuntimeError("boom quota") + + monkeypatch.setattr(diagnose, "build_quota_should_run", fake_quota) + monkeypatch.setattr( + diagnose, + "orphaned_goal_state_projection", + lambda _root, gid: {"reason": "orphan", "goal_id": gid} if gid == "g-orphan" else None, + ) + monkeypatch.setattr( + diagnose, + "orphaned_goal_state_gate", + lambda proj, **_kw: { + "reason": proj["reason"], + "state_file_routes": ["ACTIVE.md"], + "forbidden_until_resolved": ["bootstrap"], + "resolution_routes": [{"command": "loopx doctor"}], + }, + ) + + payload = diagnose.collect_diagnosis( + registry_path=registry_path, + runtime_root_override=None, + limit=5, + available_capabilities="web_search, web_search", + ) + assert payload["ok"] is False + assert payload["diagnosis_blocked_by"] == diagnose.ORPHANED_GOAL_STATE_CONNECTION + assert payload["available_capabilities"] == ["web_search"] + selected = payload["selected"] + assert isinstance(selected, dict) + sel_ic = selected["interaction_contract"] + assert isinstance(sel_ic, dict) and isinstance(sel_ic["agent_channel"], dict) + assert sel_ic["agent_channel"]["required_reads"] == ["GOAL.md"] + goals = payload["goals"] + assert isinstance(goals, list) and len(goals) == 2 + g0_ic = goals[0]["interaction_contract"] + assert isinstance(g0_ic, dict) and isinstance(g0_ic["agent_channel"], dict) + assert "required_reads" not in g0_ic["agent_channel"] + assert goals[1]["machine_signal"] == diagnose.ORPHANED_GOAL_STATE_CONNECTION + summary = payload["status_summary"] + assert isinstance(summary, dict) + assert summary["contract_errors_truncated"] is True + + # None projection on unregistered goal must fail safe without blocking normal packet. + orphan_calls: list[str] = [] + + def _none_projection(_root: Path, gid: str) -> dict[str, object] | None: + orphan_calls.append(gid) + return None + + monkeypatch.setattr(diagnose, "orphaned_goal_state_projection", _none_projection) + non_blocking = diagnose.collect_diagnosis( + registry_path=registry_path, + runtime_root_override=None, + limit=5, + ) + assert orphan_calls == ["g-orphan"] + assert non_blocking["ok"] is True + assert "diagnosis_blocked_by" not in non_blocking + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_diagnose_cli_keeps_active_goal_user_gate_over_health_finding( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + provider: str, +) -> None: + goal_id = "diagnose-precedence-goal" + user_gate_text = "[P0] Confirm user gate before health alert override." + project = tmp_path / f"project-{provider}" + runtime = tmp_path / f"runtime-{provider}" + project.mkdir(parents=True) + (project / "README.md").write_text("# Fixture\n", encoding="utf-8") + state_rel = f".codex/goals/{goal_id}/ACTIVE_GOAL_STATE.md" + state_path = project / state_rel + state_path.parent.mkdir(parents=True, exist_ok=True) + state_path.write_text( + "---\nstatus: active\nupdated_at: 2026-01-01T00:00:00+00:00\n---\n\n" + "# Fixture\n\n## User Todo\n\n" + f"- [ ] {user_gate_text}\n" + " \n", + encoding="utf-8", + ) + registry = project / ".loopx" / "registry.json" + registry.parent.mkdir(parents=True, exist_ok=True) + registry.write_text( + json.dumps( + { + "schema_version": 1, + "common_runtime_root": str(runtime), + "goals": [ + { + "id": goal_id, + "domain": "diagnose-fixture", + "status": "active", + "repo": str(project), + "state_file": state_rel, + "adapter": {"kind": "fixture_connected_delivery_v0", "status": "connected-delivery"}, + "quota": {"compute": 1.0, "window_hours": 24}, + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + import_fixture_authority(registry, goal_id, provider=provider) + (runtime / "registry.global.json").write_text( + json.dumps( + { + "schema_version": 1, + "goals": [ + { + "id": goal_id, + "state_file": str(tmp_path / "stale-missing.md"), + "source_registry": str(registry), + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + capsys.readouterr() + + assert main(["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", "status", "--goal-id", goal_id]) == 0 + status_payload = json.loads(capsys.readouterr().out) + goal_rows = [row for row in status_payload["attention_queue"]["items"] if row.get("goal_id") == goal_id] + assert [row.get("status") for row in goal_rows] == ["state_file_missing", "active_state_user_gate"] + + for args in (["diagnose", "--goal-id", goal_id], ["diagnose"]): + assert main(["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", *args]) == 0 + diag_payload = json.loads(capsys.readouterr().out) + selected = diag_payload["selected"] + assert selected["status"] == "active_state_user_gate" + assert selected["waiting_on"] == "controller" + assert user_gate_text in str(selected["user_question"])