From 7b360ac8ae516266b370553a7f0255454bad59a6 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:33:17 +0800 Subject: [PATCH 1/2] fix(antigravity): guide fixed-session in-place schedule patrol and bound Stop hooks Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/heartbeat-automation-prompt.md | 11 ++ loopx/agy_goal_mode/__init__.py | 73 +++++--- loopx/agy_goal_mode/host_runtime.py | 5 +- loopx/cli_commands/_host_thread.py | 3 + loopx/cli_commands/registry_admin.py | 43 +++++ loopx/cli_commands/slash_commands.py | 38 ++++- loopx/cli_commands/start_goal.py | 5 +- loopx/control_plane/heartbeat/builder.py | 14 ++ loopx/control_plane/heartbeat/rules.py | 22 +++ loopx/control_plane/heartbeat/task_body.py | 46 ++++- loopx/slash_command_install.py | 59 ++++++- loopx/thread_agent_binding.py | 17 +- .../references/heartbeat-hosts.md | 71 +++++--- .../references/start-and-connect.md | 9 +- tests/conftest.py | 3 + .../test_heartbeat_prompt_support.py | 50 ++++++ tests/test_agy_host_surface.py | 161 ++++++++++++++++++ tests/test_antigravity_host_runtime.py | 1 + tests/test_thread_agent_binding.py | 65 +++++++ 19 files changed, 630 insertions(+), 66 deletions(-) diff --git a/docs/heartbeat-automation-prompt.md b/docs/heartbeat-automation-prompt.md index cb871cc599..a016d66cbf 100644 --- a/docs/heartbeat-automation-prompt.md +++ b/docs/heartbeat-automation-prompt.md @@ -62,6 +62,17 @@ transport-neutral goal prompt and lets the goal runtime own inner iteration; see the host integration protocol instead of adapting this recurring automation contract. +Antigravity App (`--runtime-profile antigravity_app` or `--antigravity_app`) +keeps a fixed resident session patrolling in place rather than relying on +Codex's `automation_update`: bind the conversation's `Conversation ID` / +`ANTIGRAVITY_CONVERSATION_ID` with `bind-agent-thread --with-agy-hooks --execute` +and `sync-global`, perform repository work and `quota should-run` in an isolated +`.worktrees/` git worktree (leaving the primary checkout clean for +`workspace_guard`), and suspend between wakes via in-session +`schedule(DurationSeconds=max(180, interval * 60), TimerCondition="any", Prompt=...)` +(`180`s minimum floor; `3 -> 6 -> 10` minute unchanged backoff; no shell `sleep`, +and no `new-conversation` `sidecar.json` unless explicitly requested). + ### Native Goal bootstrap and live execution instructions Full, compact and brief automation use the same fully qualified notification/execution rule diff --git a/loopx/agy_goal_mode/__init__.py b/loopx/agy_goal_mode/__init__.py index da60243cca..16c399d578 100644 --- a/loopx/agy_goal_mode/__init__.py +++ b/loopx/agy_goal_mode/__init__.py @@ -19,6 +19,7 @@ AGY_INSTALL_SURFACE = "agy" ANTIGRAVITY_APP_INSTALL_SURFACE = "antigravity-app" ANTIGRAVITY_APP_AGENT_TYPE = "antigravity-app" +ANTIGRAVITY_CONVERSATION_ID_ENV = "ANTIGRAVITY_CONVERSATION_ID" # Every token normalize_agent_type and the slash-commands installer accept for # the Antigravity CLI surface. @@ -59,17 +60,22 @@ "`IsDaemon`, `ExactTiming`) that delivers its `Prompt` as a high-priority " "wakeup notification when it fires; `manage_task` lists or kills active " "schedules.", - "When a LoopX turn enters `waiting_external` (for example CI checks or PR " - "review waits), call `schedule(DurationSeconds=, " - "Prompt=...)` and end the turn immediately so the host wakes the session " - "reactively instead of running shell sleep polling loops.", + "In an Antigravity App fixed resident session (`antigravity-app`), arm " + "`schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), " + "TimerCondition=\"any\", Prompt=...)` (3-minute / 180s minimum floor; " + "unchanged-wait backoff `3 -> 6 -> 10` minutes) before ending every patrol " + "turn (including `waiting_external`, CI/PR waits, settled turns, or quiet " + "no-ops) unless `scheduler_hint.action=stop_until_explicit_resume`, so the " + "host wakes the same conversation reactively instead of running shell sleep " + "polling loops or spawning `new-conversation` sidecars.", "Background `run_command` tasks and `invoke_subagent` runs also resume the " "session reactively on completion or message arrival, so the agent does " "not need a polling loop inside a turn.", - "All native wakes live inside the running Antigravity process; for " - "background periodic heartbeats in Antigravity 2.0 (`antigravity-app`), " - "configure `sidecar.json` and optional `hooks.json` bound Stop recovery in " - "`~/.gemini/config`.", + "For fixed in-session patrols, bind the current `` " + "`Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`) via `bind-agent-thread` " + "+ `sync-global` and configure bound `hooks.json` `Stop` recovery in " + "`~/.gemini/config` without creating a `new-conversation` `sidecar.json`; " + "use `sidecar.json` only when explicitly requesting detached fresh-conversation ticks.", ) # Native goal primitive (built into the agy binary; live-verified on 1.1.18 in @@ -97,8 +103,8 @@ ANTIGRAVITY_APP_AGENT_TYPE_CATALOG_ENTRY: dict[str, Any] = { "display_name": "Antigravity App", "host_loop": ( - "Antigravity App native schedule timer closed loop + optional background " - "sidecar.json heartbeat and hooks.json bound Stop recovery" + "Antigravity App fixed-session in-place schedule timer closed loop + " + "hooks.json bound Stop recovery (or optional detached sidecar.json)" ), "entry": ( f"the LoopX skill installed in {ANTIGRAVITY_SKILLS_ROOT_LABEL} " @@ -262,7 +268,7 @@ def build_antigravity_hooks_template( resolve_local_executable: bool = True, ) -> dict[str, Any]: """Native Stop hook; installation alone never binds an arbitrary chat.""" - conversation_id = conversation_id or os.environ.get("ANTIGRAVITY_CONVERSATION_ID") + conversation_id = conversation_id or os.environ.get(ANTIGRAVITY_CONVERSATION_ID_ENV) args = _antigravity_provider_args( "stop-hook", cli_bin=cli_bin, @@ -392,30 +398,51 @@ def antigravity_app_activation_extras( "Prompt": wake_prompt, "TimerCondition": "any", }, + "min_duration_seconds": 180, + "backoff_progression_minutes": [3, 6, 10], "when_to_use": ( - "Call `schedule(DurationSeconds=..., Prompt=...)` and end the turn " - "whenever `waiting_external`, CI checks, or PR review gates block " - "immediate completion; never use shell sleep loops." + "Before ending every fixed-session patrol turn (after settlement, " + "on `waiting_external`/CI/PR review waits, or when idle/no-op) " + "unless `scheduler_hint.action=stop_until_explicit_resume`, call " + "`schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), " + "TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10` minute " + "unchanged backoff) and end the turn; never use shell sleep loops." ), }, + "fixed_session_patrol_contract": { + "mode": "in_place_resident_session", + "conversation_id_sources": [ + " Conversation ID", + ANTIGRAVITY_CONVERSATION_ID_ENV, + ], + "bind_and_hooks_sync_supported": True, + "detached_sidecar_required": False, + "isolated_worktree_root": ".worktrees/", + "min_duration_seconds": 180, + "backoff_progression_minutes": [3, 6, 10], + }, "sidecar_template": sidecar_template, "hooks_template": hooks_template, "missing_host_tool_gate": ( - "Antigravity App in-session `schedule(DurationSeconds=...)` timers fire " - "while the app session is active; for unattended background ticks, " - f"configure `sidecar.json` in `{ANTIGRAVITY_SIDECAR_CONFIG_LABEL}` " - f"and optional `hooks.json` in `{ANTIGRAVITY_HOOKS_CONFIG_LABEL}`." + "Antigravity App in-session `schedule(DurationSeconds>=180, " + "TimerCondition=\"any\", Prompt=...)` wakes this exact resident " + "conversation while the app session is active (with bound " + f"`{ANTIGRAVITY_HOOKS_CONFIG_LABEL}` `Stop` recovery for network EOFs); " + "only configure detached `sidecar.json` in " + f"`{ANTIGRAVITY_SIDECAR_CONFIG_LABEL}` when explicitly asked for " + "new-conversation background ticks." ), }, "extra_activation_steps": [ f"Install or refresh the Antigravity skill and optional MCP/hooks surface (`{cli_bin} slash-commands --install --surface antigravity-app --with-agy-mcp --with-agy-hooks` and `{cli_bin} workflow-skills --install --host-surface antigravity-app`).", - "When a turn enters `waiting_external` or waits on CI/review checks, suspend directly with the native `schedule(DurationSeconds=, Prompt=...)` tool and end the turn instead of polling in a shell loop.", - f"For background periodic heartbeats, write only `sidecar_template.sidecar_json` to `{ANTIGRAVITY_SIDECAR_CONFIG_LABEL}`. Preserve its existing id, model, permissions and host enable choice. Each fresh native heartbeat loads Core admission before work; do not persist an expanded execution body. Apply the bound `hooks_template` at the top level of hooks.json for bounded transport-error recovery; never wrap it in a `hooks` object.", + "For a fixed resident session, read `` `Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`), bind it via `bind-agent-thread --with-agy-hooks --execute` (plus `sync-global`) so `~/.gemini/config/hooks.json` carries the active `loopx` CLI and `--conversation-id`, run peer edits and `quota should-run` inside an isolated `.worktrees/` git worktree, and before ending every turn call `schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10`m backoff; no shell sleep or `new-conversation` sidecar).", + f"Only when explicitly requesting detached new-conversation ticks instead of fixed in-session patrol, write `sidecar_template.sidecar_json` to `{ANTIGRAVITY_SIDECAR_CONFIG_LABEL}` preserving its existing id, model, permissions and host enable choice. Apply bound `hooks_template` at the top level of hooks.json; never wrap it in a `hooks` object.", ], "host_scheduler_note": ( - "use the native `schedule(DurationSeconds=..., Prompt=...)` tool to suspend " - "and wake on `waiting_external` / CI waits, or configure `sidecar.json` for " - "background periodic heartbeats." + "for fixed in-session patrol, call `schedule(DurationSeconds>=180, " + "TimerCondition=\"any\", Prompt=...)` (`3 -> 6 -> 10`m backoff) before " + "ending every turn unless stopped; use `sidecar.json` only for explicit " + "detached new-conversation heartbeats." ), } diff --git a/loopx/agy_goal_mode/host_runtime.py b/loopx/agy_goal_mode/host_runtime.py index c9ccd9953d..f05523a01f 100644 --- a/loopx/agy_goal_mode/host_runtime.py +++ b/loopx/agy_goal_mode/host_runtime.py @@ -87,7 +87,10 @@ def bootstrap_prompt(args: argparse.Namespace) -> str: + "\nFollow task_body only when ok=true, including current scope, stop, " "settlement and scheduler backoff. Do not replay the failed user request, " "create another Goal/Agent, or reuse an old Turn receipt. Remain quiet " - "when the fresh user_channel requests no notification." + "when the fresh user_channel requests no notification. Before ending the " + "recovered turn (unless stopped), re-arm in-session " + "schedule(DurationSeconds>=180, TimerCondition='any', Prompt=...) with " + "the current backoff cadence instead of starting a new conversation." ) diff --git a/loopx/cli_commands/_host_thread.py b/loopx/cli_commands/_host_thread.py index e17c59cc9e..35111cb7e9 100644 --- a/loopx/cli_commands/_host_thread.py +++ b/loopx/cli_commands/_host_thread.py @@ -3,6 +3,7 @@ import argparse import os +from ..agy_goal_mode import ANTIGRAVITY_CONVERSATION_ID_ENV from ..kiro_cli_goal_mode import KIRO_CLI_AGENT_TYPE, KIRO_CLI_SESSION_ID_ENV # Host surface -> the environment variable that host exports for its own @@ -17,6 +18,8 @@ "codex-cli-tui": "CODEX_THREAD_ID", "trae_app": "TRAECLI_THREAD_ID", "traex-cli": "TRAECLI_THREAD_ID", + "antigravity-app": ANTIGRAVITY_CONVERSATION_ID_ENV, + "agy": ANTIGRAVITY_CONVERSATION_ID_ENV, KIRO_CLI_AGENT_TYPE: KIRO_CLI_SESSION_ID_ENV, } diff --git a/loopx/cli_commands/registry_admin.py b/loopx/cli_commands/registry_admin.py index 070ddafc36..a75a8c52af 100644 --- a/loopx/cli_commands/registry_admin.py +++ b/loopx/cli_commands/registry_admin.py @@ -383,6 +383,19 @@ def register_registry_admin_commands(subparsers: argparse._SubParsersAction) -> bind_thread_parser.add_argument("--host-surface", required=True, help="Host surface such as codex-app.") bind_thread_parser.add_argument("--agent-id", required=True, help="Already registered public-safe agent id.") bind_thread_parser.add_argument("--execute", action="store_true", help="Write the binding; otherwise preview only.") + bind_thread_parser.add_argument( + "--with-agy-hooks", + action="store_true", + help="Also preview or atomically write the bound Antigravity Stop recovery hook in hooks.json.", + ) + bind_thread_parser.add_argument( + "--agy-home", + help="Antigravity config home for --with-agy-hooks (defaults to AGY_HOME or ~/.gemini/config).", + ) + bind_thread_parser.add_argument( + "--cli-bin", + help="LoopX CLI executable path/name recorded in hooks.json when using --with-agy-hooks.", + ) unbind_thread_parser = subparsers.add_parser( "unbind-agent-thread", @@ -631,6 +644,14 @@ def handle_registry_admin_command( if args.command in {"bind-agent-thread", "unbind-agent-thread"}: try: + with_agy_hooks = bool( + args.command == "bind-agent-thread" + and getattr(args, "with_agy_hooks", False) + ) + if with_agy_hooks and args.host_surface not in {"agy", "antigravity-app"}: + raise ValueError( + "--with-agy-hooks requires --host-surface agy or antigravity-app" + ) global_path = explicit_global_registry(args.runtime_root) global_goal = _registry_goal(global_path, args.goal_id) source_registry = global_goal.get("source_registry") @@ -724,6 +745,28 @@ def handle_registry_admin_command( payload["error_kind"] = "thread_agent_binding_readback_failed" else: payload["global_sync"] = {"enabled": bool(args.execute), "wrote": False} + if with_agy_hooks: + from ..slash_command_install import sync_antigravity_hooks + + cli_bin = ( + getattr(args, "cli_bin", None) + or getattr(args, "control_cli_bin", None) + or "loopx" + ) + hooks_result = sync_antigravity_hooks( + cli_bin=cli_bin, + agy_home=getattr(args, "agy_home", None), + execute=bool(args.execute and payload.get("ok")), + goal_id=args.goal_id, + agent_id=args.agent_id, + runtime_root=str(global_path.parent), + conversation_id=args.thread_id, + registry=str(source_path), + ) + payload["antigravity_hooks"] = hooks_result + if hooks_result["status"].startswith(("blocked_", "skipped_")): + payload["ok"] = False + payload["error_kind"] = hooks_result["status"] except Exception as exc: payload = { "ok": False, diff --git a/loopx/cli_commands/slash_commands.py b/loopx/cli_commands/slash_commands.py index b0fcada137..93e5af025f 100644 --- a/loopx/cli_commands/slash_commands.py +++ b/loopx/cli_commands/slash_commands.py @@ -2,6 +2,7 @@ import argparse from collections.abc import Callable +from pathlib import Path from ..pi_goal_mode.installation import inspect_pi_installations, render_pi_installation_markdown from ..slash_command_install import install_slash_commands, render_slash_command_install_markdown @@ -132,7 +133,19 @@ def register_slash_commands_command( parser.add_argument( "--with-agy-hooks", action="store_true", - help="Optionally install a disabled Antigravity Stop recovery hook; bind a Goal, Agent and native conversation before enabling it.", + help="Optionally install an Antigravity Stop recovery hook; pass --goal-id, --agent-id, and --conversation-id (or bind via bind-agent-thread --with-agy-hooks) to enable it.", + ) + parser.add_argument( + "--goal-id", + help="Optional Goal id bound into the Antigravity Stop recovery hook when using --with-agy-hooks.", + ) + parser.add_argument( + "--agent-id", + help="Optional Agent id bound into the Antigravity Stop recovery hook when using --with-agy-hooks.", + ) + parser.add_argument( + "--conversation-id", + help="Optional Antigravity Conversation ID bound into the Stop recovery hook when using --with-agy-hooks.", ) parser.add_argument( "--opencode-home", @@ -173,6 +186,22 @@ def handle_slash_commands_command( print_payload(payload, output_format(args), render_pi_installation_markdown) return 0 if payload["ok"] else 1 if args.install or args.uninstall or args.dry_run: + effective_cli_bin = ( + args.cli_bin + if args.cli_bin != "loopx" + else (getattr(args, "control_cli_bin", None) or args.cli_bin) + ) + agy_goal_id = getattr(args, "goal_id", None) + agy_registry = ( + str(Path(args.registry).expanduser().resolve()) + if agy_goal_id and getattr(args, "registry", None) + else None + ) + agy_runtime_root = ( + str(Path(args.runtime_root).expanduser().resolve()) + if agy_goal_id and getattr(args, "runtime_root", None) + else None + ) payload = install_slash_commands( execute=bool((args.install or args.uninstall) and not args.dry_run), uninstall=bool(args.uninstall), @@ -180,7 +209,7 @@ def handle_slash_commands_command( with_agy_mcp=bool(getattr(args, "with_agy_mcp", False)), with_agy_hooks=bool(getattr(args, "with_agy_hooks", False)), surfaces=args.surface, - cli_bin=args.cli_bin, + cli_bin=effective_cli_bin, include_legacy_aliases=not bool(args.no_legacy_aliases), codex_home=args.codex_home, claude_home=args.claude_home, @@ -189,6 +218,11 @@ def handle_slash_commands_command( cursor_home=args.cursor_home, zcode_home=getattr(args, "zcode_home", None), agy_home=getattr(args, "agy_home", None), + agy_goal_id=agy_goal_id, + agy_agent_id=getattr(args, "agent_id", None), + agy_conversation_id=getattr(args, "conversation_id", None), + agy_runtime_root=agy_runtime_root, + agy_registry=agy_registry, pi_project=args.pi_project, pi_scope=args.pi_scope, ) diff --git a/loopx/cli_commands/start_goal.py b/loopx/cli_commands/start_goal.py index 3d6f732947..50982b6b18 100644 --- a/loopx/cli_commands/start_goal.py +++ b/loopx/cli_commands/start_goal.py @@ -209,8 +209,9 @@ def register_start_goal_command(subparsers: argparse._SubParsersAction) -> None: "--thread-id", help=( "Stable opaque host thread id used to reuse the bound agent lane. " - "Codex App defaults to CODEX_THREAD_ID and Trae App to " - "TRAECLI_THREAD_ID when available." + "Codex App defaults to CODEX_THREAD_ID, Trae App to " + "TRAECLI_THREAD_ID, and Antigravity to ANTIGRAVITY_CONVERSATION_ID " + "(or Conversation ID) when available." ), ) start_goal_parser.add_argument( diff --git a/loopx/control_plane/heartbeat/builder.py b/loopx/control_plane/heartbeat/builder.py index 967bf44202..844cedb511 100644 --- a/loopx/control_plane/heartbeat/builder.py +++ b/loopx/control_plane/heartbeat/builder.py @@ -18,6 +18,7 @@ VISIBLE_GOAL_SLOT_SPEND_SOURCE, ) from ..scheduler.execution_context import ( + HostSurface, SchedulerRuntimeProfile, render_scheduler_execution_args, ) @@ -544,6 +545,14 @@ def build_heartbeat_prompt( native_goal_host=native_goal_host, ark_managed_agent_goal=ark_managed_agent_goal, ) + is_antigravity_app = ( + runtime_profile == SchedulerRuntimeProfile.ANTIGRAVITY_APP.value + or ( + isinstance(scheduler_execution_context, dict) + and scheduler_execution_context.get("host_surface") + == HostSurface.ANTIGRAVITY_APP.value + ) + ) task_body = task_body_renderer( goal_id=goal_id, active_state=active_state_text, @@ -564,6 +573,11 @@ def build_heartbeat_prompt( brief_prompt_command=str(commands["brief_prompt_command"]), thin_prompt_command=str(commands["thin_prompt_command"]), **({"captured_context": True} if native_goal_host and effective_context_delivery == "on" else {}), + **( + {"antigravity_app": True} + if is_antigravity_app and not (traex_visible_goal or ark_managed_agent_goal or native_goal_host) + else {} + ), **reward_memory_rule_kwargs, ) task_body = bind_exact_turn_settlement_task_body( diff --git a/loopx/control_plane/heartbeat/rules.py b/loopx/control_plane/heartbeat/rules.py index d3e607f2c0..9ab736dd1f 100644 --- a/loopx/control_plane/heartbeat/rules.py +++ b/loopx/control_plane/heartbeat/rules.py @@ -85,6 +85,28 @@ "Bootstrap/min=floor; backoff. " + SCHEDULER_STOP_RULE + "Else RRULE/projected-fallback_hint/ack/fail." ) +ANTIGRAVITY_SCHEDULER_STOP_RULE = ( + "host_action=pause_or_delete_current_heartbeat: cancel schedule via manage_task, do not re-arm, end, no work/spend. " +) +ANTIGRAVITY_SCHEDULER_HINT_APPLICATION_RULE = ( + "Min=3m (DurationSeconds>=180); backoff 3->6->10m. " + + ANTIGRAVITY_SCHEDULER_STOP_RULE + + "Fixed session (no new-conversation sidecar unless asked): edit/guard in `.worktrees/`; " + "ack/fail if projected; end every turn with `schedule(DurationSeconds=max(180, interval*60), " + "TimerCondition=\"any\", Prompt=...)`, no shell sleep." +) +ANTIGRAVITY_SCHEDULER_HINT_COMPACT_RULE = ( + "Min=3m (DurationSeconds>=180); backoff 3->6->10m. " + + ANTIGRAVITY_SCHEDULER_STOP_RULE + + "Use `.worktrees/` (no new-conversation sidecar unless asked); ack/fail if projected; " + "end turn via `schedule(DurationSeconds=max(180, interval*60), TimerCondition=\"any\", Prompt=...)`, no sleep." +) +ANTIGRAVITY_SCHEDULER_HINT_THIN_RULE = ( + "Min=3m; backoff 3->6->10m. " + + ANTIGRAVITY_SCHEDULER_STOP_RULE + + "Edit in `.worktrees/` (no sidecar unless asked); ack/fail if projected; " + "end turn via `schedule(DurationSeconds=max(180, interval*60), TimerCondition=\"any\", Prompt=...)` (no sleep)." +) RUNTIME_CAPABILITY_PROJECTION_THIN_RULE = ( "Observed capabilities -> `--available-capability`; never user gates." ) diff --git a/loopx/control_plane/heartbeat/task_body.py b/loopx/control_plane/heartbeat/task_body.py index 6207ef80aa..7ca05e3fa1 100644 --- a/loopx/control_plane/heartbeat/task_body.py +++ b/loopx/control_plane/heartbeat/task_body.py @@ -6,6 +6,9 @@ from ...project_prompt import render_turn_bootstrap from .rules import ( + ANTIGRAVITY_SCHEDULER_HINT_APPLICATION_RULE, + ANTIGRAVITY_SCHEDULER_HINT_COMPACT_RULE, + ANTIGRAVITY_SCHEDULER_HINT_THIN_RULE, CODEX_NATIVE_GOAL_UNCHANGED_WAIT_RULE, DEFAULT_MATERIAL_QUEUE_RULE, DEFAULT_PERMISSION_RULE, @@ -99,6 +102,7 @@ def render_heartbeat_task_body( brief_prompt_command: str, thin_prompt_command: str, reward_memory_rule: str = REWARD_MEMORY_OUTCOME_RULE, + antigravity_app: bool = False, ) -> str: scope_block = f"\n{agent_scope_instruction}\n" if agent_scope_instruction else "" pr_review_pre_quota_block = ( @@ -107,6 +111,11 @@ def render_heartbeat_task_body( policy_tail = _render_compact_policy_tail( material_queue_rule=material_queue_rule, permission_rule=permission_rule, ) + scheduler_rule = ( + ANTIGRAVITY_SCHEDULER_HINT_APPLICATION_RULE + if antigravity_app + else SCHEDULER_HINT_APPLICATION_RULE + ) return f"""Advance `{goal_id}` using `{active_state}`. {scope_block} @@ -127,7 +136,7 @@ def render_heartbeat_task_body( {USER_TODO_FINAL_MESSAGE_RULE} {HOST_LOOP_QUOTA_DISPATCH_RULE} {HEARTBEAT_VISION_WRITEBACK_RULE_SHORT} -{SCHEDULER_HINT_APPLICATION_RULE} Scheduling grants no delivery permission. +{scheduler_rule} Scheduling grants no delivery permission. If the result says `should_run=false`: @@ -266,6 +275,7 @@ def render_brief_heartbeat_task_body( brief_prompt_command: str, thin_prompt_command: str, reward_memory_rule: str = REWARD_MEMORY_OUTCOME_COMPACT_RULE, + antigravity_app: bool = False, ) -> str: scope_block = f"\n{agent_scope_instruction}\n" if agent_scope_instruction else "" pr_review_pre_quota_block = ( @@ -275,6 +285,11 @@ def render_brief_heartbeat_task_body( material_queue_rule=material_queue_rule, permission_rule=permission_rule, ) + scheduler_rule = ( + ANTIGRAVITY_SCHEDULER_HINT_THIN_RULE + if antigravity_app + else SCHEDULER_HINT_THIN_RULE + ) return f"""Advance `{goal_id}` from `{active_state}`. Brief detail: @@ -294,7 +309,7 @@ def render_brief_heartbeat_task_body( {HEARTBEAT_NOTIFICATION_RULE_SHORT} {SCOPE_BOUNDED_WORK_RULE} {HEARTBEAT_VISION_WRITEBACK_RULE_SHORT} -{SCHEDULER_HINT_THIN_RULE} +{scheduler_rule} `should_run=false`: follow user channel; `monitor_quiet_skip` records receipt/stall. Wait: one allowed read-only poll; use current monitor/auxiliary @@ -336,6 +351,7 @@ def render_compact_heartbeat_task_body( brief_prompt_command: str, thin_prompt_command: str, reward_memory_rule: str = REWARD_MEMORY_OUTCOME_COMPACT_RULE, + antigravity_app: bool = False, ) -> str: scope_block = f"\n{agent_scope_instruction}\n" if agent_scope_instruction else "" pr_review_pre_quota_block = ( @@ -344,6 +360,11 @@ def render_compact_heartbeat_task_body( policy_tail = _render_compact_policy_tail( material_queue_rule=material_queue_rule, permission_rule=permission_rule, ) + scheduler_rule = ( + ANTIGRAVITY_SCHEDULER_HINT_COMPACT_RULE + if antigravity_app + else SCHEDULER_HINT_COMPACT_RULE + ) return f"""Advance `{goal_id}` using `{active_state}`. Detail: `{expanded_prompt_command}`. @@ -359,7 +380,7 @@ def render_compact_heartbeat_task_body( Preflight fail: quiet; no work/spend. -{SCHEDULER_HINT_COMPACT_RULE} +{scheduler_rule} {HOST_LOOP_QUOTA_DISPATCH_RULE} {HEARTBEAT_VISION_WRITEBACK_RULE_SHORT} {OPERATOR_LANGUAGE_RULE} @@ -665,6 +686,7 @@ def render_thin_heartbeat_task_body( thin_prompt_command: str, reward_memory_rule: str = REWARD_MEMORY_OUTCOME_COMPACT_RULE, captured_envelope: bool = False, + antigravity_app: bool = False, ) -> str: policy_tail = _render_compact_policy_tail( material_queue_rule=material_queue_rule, @@ -676,7 +698,20 @@ def render_thin_heartbeat_task_body( if pr_review_pre_quota_command else "" ) + scheduler_rule = ( + ANTIGRAVITY_SCHEDULER_HINT_THIN_RULE + if antigravity_app + else SCHEDULER_HINT_THIN_RULE + ) if captured_envelope: + envelope_scheduler_rule = ( + ANTIGRAVITY_SCHEDULER_HINT_THIN_RULE + if antigravity_app + else ( + "Apply `scheduler` as projected using inline ACK argv. Read saved scheduler detail\n" + "only for a needed missing/truncated/referenced command; failure argv only after host update failure." + ) + ) return f"""Advance `{goal_id}` from {active_state}. {HOST_LOOP_SAFETY_RULE} @@ -700,8 +735,7 @@ def render_thin_heartbeat_task_body( ``` {SCOPE_BOUNDED_WORK_RULE} Observed capabilities -> --available-capability, never a user gate. -Apply `scheduler` as projected using inline ACK argv. Read saved scheduler detail -only for a needed missing/truncated/referenced command; failure argv only after host update failure. +{envelope_scheduler_rule} Exact monitor settlement=no refresh/spend; auxiliary poll continues work. Validate work; execute `writeback.settlement_plan` and `writeback.next_cli_actions` with their exact identity. Do not guess commands from abbreviated previews. @@ -731,7 +765,7 @@ def render_thin_heartbeat_task_body( {HEARTBEAT_NOTIFICATION_RULE_SHORT} {SCOPE_BOUNDED_WORK_RULE} {RUNTIME_CAPABILITY_PROJECTION_THIN_RULE} -{SCHEDULER_HINT_THIN_RULE} +{scheduler_rule} {HEARTBEAT_VISION_WRITEBACK_RULE_SHORT} {HOST_LOOP_TODO_CLOSEOUT_COMPACT_RULE} `agent_read_required`: drain/read/triage before work; settle/ACK. diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index 7426fbd82a..a4da8ae0d0 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -199,7 +199,7 @@ def _command_prompt_specs(*, cli_bin: str, include_legacy_aliases: bool) -> list "argument_hint": "[--fine-grained] [--new-peer] [--capability-route issue-fix] [task text]", "instructions": [ "Visible command arguments: `$ARGUMENTS`.", - "Identify the exact current host surface (codex-app, trae_app, codex-app-ssh, codex-ide-plugin, codex-cli-tui, opencode, opencode2, traex-cli, pi, gemini-cli, cursor-agent, zcode, agy, kiro-cli, deepseek-harness, or ark-managed-agent).", + "Identify the exact current host surface (codex-app, trae_app, codex-app-ssh, codex-ide-plugin, codex-cli-tui, opencode, opencode2, traex-cli, pi, gemini-cli, cursor-agent, zcode, antigravity-app, agy, kiro-cli, deepseek-harness, or ark-managed-agent).", _loopx_start_goal_arguments_instruction( cli_bin=cli_bin, host_surface=None, @@ -208,6 +208,7 @@ def _command_prompt_specs(*, cli_bin: str, include_legacy_aliases: bool) -> list "During first planning, follow the shared goal_requirements_guidance: reuse existing owner-approved requirements and declare only missing source-grounded overall requirements through the existing outcome owner, link actual Todos and read back the canonical declaration. Preserve existing requirements on resume; maximum timeout is not a minimum work commitment and independent executable checks stay optional.", "When the host explicitly supplies a `loopx_task_planning_v0` packet from `loopx todo plan` for a registered Goal/Agent, execute that bounded planning checkpoint instead of starting another Goal. Follow its shared planner, requirement declaration/readback and Todo delta in the same invocation, then return actual Todo ids for readback. Its caller-owned execution_handoff retains host activation and quota; do not create a planning Todo, execute task work, or claim delivery during the checkpoint.", "For a Codex App heartbeat, run the returned activation command, require ok=true, and save its `LoopX managed heartbeat bootstrap v2` task_body through automation_update. The saved loader fetches the current thin contract on every wake; do not persist a raw thin/compact/full execution body. Preserve the current goal, registered agent, task binding and existing schedule; read back the automation through the same App.", + f"For an Antigravity App fixed resident session (`antigravity-app` / `agy`), read `` `Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`), bind it once via `{cli_bin} bind-agent-thread --goal-id --thread-id --host-surface agy --agent-id --with-agy-hooks --execute` and `{cli_bin} sync-global` (updating `~/.gemini/config/hooks.json` `Stop` recovery with the active `{cli_bin}` path and `--conversation-id`; do not create a `new-conversation` `sidecar.json` for a fixed session). On every wake, run `{cli_bin} --format json heartbeat-prompt --thin --runtime-profile antigravity_app --goal-id --agent-id `, follow `task_body` only when `ok=true`, perform peer code/doc edits and `quota should-run` inside an isolated `.worktrees/` git worktree (keeping the main checkout clean for `workspace_guard`), and before ending every turn (settled, `waiting_external`, or idle) unless stopped, call `schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), TimerCondition=\"any\", Prompt=...)` (`180`s floor; `3 -> 6 -> 10`m backoff) without shell `sleep`.", "If the packet exposes a goal-selection gate, rerun one exact choice before any mutation.", "When authoring task Todos, treat `--action-kind` as the documented extensible public-safe token: choose a short task-relevant value such as `implement`, `test`, or `review`; do not search the LoopX source for an allowlist.", "Consume the turn-start quota JSON packet exactly once: read the complete output directly or save it and query it with `jq`; never pipe it through `head` or `tail`, and never rerun the turn-start call to recover hidden fields. A host whose runtime mints Turn identity uses `--begin-turn`; every other host passes its own `--turn-instance-id`. When selection is required, choose the Todo and use `interaction_contract.cli_channel.selection_command` with the returned Turn identity before mutation.", @@ -919,6 +920,12 @@ def _merge_managed_hooks_json( cli_bin: str, uninstall: bool, execute: bool, + goal_id: str | None = None, + agent_id: str | None = None, + runtime_root: str | None = None, + conversation_id: str | None = None, + registry: str | None = None, + resolve_local_executable: bool = True, ) -> str: """Add or remove the managed ``loopx`` Stop recovery hook in Antigravity ``hooks.json``.""" marker_path = config_path.parent / ANTIGRAVITY_HOOKS_MARKER_NAME @@ -970,7 +977,15 @@ def _merge_managed_hooks_json( if existing is not None and not loopx_owned: return "skipped_user_owned_hooks_entry" - entry = build_antigravity_hooks_template(cli_bin=cli_bin)[MANAGED_MCP_KEY] + entry = build_antigravity_hooks_template( + cli_bin=cli_bin, + goal_id=goal_id, + agent_id=agent_id, + runtime_root=runtime_root, + conversation_id=conversation_id, + registry=registry, + resolve_local_executable=resolve_local_executable, + )[MANAGED_MCP_KEY] if not execute: return "unchanged" if existing == entry and not legacy_owned else "would_write" if existing == entry and not legacy_owned: @@ -991,6 +1006,36 @@ def _merge_managed_hooks_json( return "written" +def sync_antigravity_hooks( + *, + cli_bin: str = "loopx", + agy_home: str | None = None, + uninstall: bool = False, + execute: bool, + goal_id: str | None = None, + agent_id: str | None = None, + runtime_root: str | None = None, + conversation_id: str | None = None, + registry: str | None = None, + resolve_local_executable: bool = True, +) -> dict[str, str]: + """Preview or update Antigravity ``hooks.json`` with the managed Stop recovery hook.""" + config_path = _antigravity_config_home(agy_home) / ANTIGRAVITY_HOOKS_CONFIG_FILENAME + status = _merge_managed_hooks_json( + config_path=config_path, + cli_bin=cli_bin, + uninstall=uninstall, + execute=execute, + goal_id=goal_id, + agent_id=agent_id, + runtime_root=runtime_root, + conversation_id=conversation_id, + registry=registry, + resolve_local_executable=resolve_local_executable, + ) + return {"path": str(config_path), "status": status} + + def install_slash_commands( *, execute: bool, @@ -1009,6 +1054,11 @@ def install_slash_commands( zcode_home: str | None = None, zcode_agents_home: str | None = None, agy_home: str | None = None, + agy_goal_id: str | None = None, + agy_agent_id: str | None = None, + agy_conversation_id: str | None = None, + agy_runtime_root: str | None = None, + agy_registry: str | None = None, kiro_home: str | None = None, pi_project: str | None = None, pi_scope: str = "project", @@ -1309,6 +1359,11 @@ def install_slash_commands( cli_bin=cli_bin, uninstall=uninstall, execute=execute, + goal_id=agy_goal_id, + agent_id=agy_agent_id, + runtime_root=agy_runtime_root, + conversation_id=agy_conversation_id, + registry=agy_registry, ) installed.append( { diff --git a/loopx/thread_agent_binding.py b/loopx/thread_agent_binding.py index 8c02b189b7..a9490403b4 100644 --- a/loopx/thread_agent_binding.py +++ b/loopx/thread_agent_binding.py @@ -25,6 +25,7 @@ "codex-cli-tui", } ) +ANTIGRAVITY_THREAD_HOST_SURFACES = frozenset({"agy", "antigravity-app"}) _CODEX_THREAD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") AGENT_BINDING_ROUTE_SCHEMA_VERSION = "loopx_agent_binding_route_v0" @@ -173,6 +174,7 @@ def resolve_thread_agent_binding( *, host_surface: str, thread_id: str | None, + exact_surface: bool = False, ) -> dict[str, Any]: """Resolve a thread binding without guessing from registry order.""" @@ -188,10 +190,15 @@ def resolve_thread_agent_binding( } if not normalized_thread_id: return base + allowed_surfaces = ( + ANTIGRAVITY_THREAD_HOST_SURFACES + if not exact_surface and normalized_surface in ANTIGRAVITY_THREAD_HOST_SURFACES + else frozenset({normalized_surface}) + ) matches = [ item for item in _bindings_for_goal(goal or {}) - if item["host_surface"] == normalized_surface + if item["host_surface"] in allowed_surfaces and item["thread_id"] == normalized_thread_id ] base["matches"] = matches @@ -312,7 +319,9 @@ def _registry_thread_binding_request( if normalized_thread_id is None: raise ValueError("thread_id is required") candidate_surfaces = ( - (normalized_surface,) + tuple(sorted(ANTIGRAVITY_THREAD_HOST_SURFACES)) + if normalized_surface in ANTIGRAVITY_THREAD_HOST_SURFACES + else (normalized_surface,) if normalized_surface is not None else tuple(sorted(CODEX_THREAD_HOST_SURFACES)) ) @@ -343,6 +352,7 @@ def _goal_registry_binding_matches( goal, host_surface=candidate_surface, thread_id=thread_id, + exact_surface=True, ) if binding["status"] == "conflict": agent_ids = [item["agent_id"] for item in binding["matches"]] @@ -480,6 +490,7 @@ def _binding_context( host_surface: str, thread_id: str, agent_id: str, + exact_surface: bool = False, ) -> tuple[dict[str, Any], list[dict[str, str]], dict[str, Any]]: goal = find_registry_goal(payload, goal_id) if goal is None: @@ -500,6 +511,7 @@ def _binding_context( goal, host_surface=host_surface, thread_id=thread_id, + exact_surface=exact_surface, ) return goal, current, existing @@ -583,6 +595,7 @@ def _prepare_unbinding( host_surface=host_surface, thread_id=thread_id, agent_id=agent_id, + exact_surface=True, ) result: dict[str, Any] = { "ok": True, diff --git a/skills/loopx-project/references/heartbeat-hosts.md b/skills/loopx-project/references/heartbeat-hosts.md index ab678a601b..1a64b4c4f6 100644 --- a/skills/loopx-project/references/heartbeat-hosts.md +++ b/skills/loopx-project/references/heartbeat-hosts.md @@ -10,30 +10,47 @@ Select `antigravity-app` explicitly; `agy` remains the legacy CLI. Install its skill facade with `slash-commands --install --surface antigravity-app` and workflow skills with `workflow-skills --install --host-surface antigravity-app`. Use the activation packet for the already registered Goal/Agent. Bind its native -conversation id from the current host's `ANTIGRAVITY_CONVERSATION_ID`, never -another chat's title or the only registered lane. - -Write only `sidecar_template.sidecar_json` to its `sidecar_config_path` under -`~/.gemini/config/sidecars//sidecar.json`. Native `builtin: schedule` -requires an `args` array beginning with the cron expression. `config.cron`, a -top-level `sidecar` wrapper and LoopX's template metadata are not native config. -Preserve an existing sidecar's id, enable choice and scoped permissions. New -sidecars retain the host's user enable step; configuration does not prove a live +conversation id from the current host's `ANTIGRAVITY_CONVERSATION_ID` (or the +`` `Conversation ID`), never another chat's title or the only +registered lane: run `bind-agent-thread --goal-id --thread-id +--host-surface agy --agent-id --with-agy-hooks --execute` and `sync-global` +so `~/.gemini/config/hooks.json` points to the active `loopx` CLI and `--conversation-id`. + +For a fixed resident in-session patrol (default when bound in an active +Antigravity App conversation), do not create a `sidecar.json` (`agentapi new-conversation`). +On every wake, run `loopx --format json --runtime-root --registry +heartbeat-prompt --thin --runtime-profile antigravity_app --goal-id --agent-id `, +follow `task_body` only when `ok=true`, and perform all repository edits and +`quota should-run` admission/settlement inside an isolated `.worktrees/` git worktree +(keeping the main checkout clean so `workspace_guard` passes). Before ending every +patrol turn — after settlement, on `waiting_external` / CI / PR review waits, or when +idle/no-op — unless `scheduler_hint.action=stop_until_explicit_resume`, arm the native +in-session wake with `schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), +TimerCondition="any", Prompt=...)` (minimum `180` seconds / 3 minutes; unchanged-wait +backoff `3 -> 6 -> 10` minutes) and end the turn; never use shell `sleep` polling loops. +When `scheduler_hint.action=stop_until_explicit_resume`, cancel any active schedule via +`manage_task` without re-arming. + +Only when explicitly configuring detached background new-conversation ticks instead +of a fixed resident session, write `sidecar_template.sidecar_json` to its +`sidecar_config_path` under `~/.gemini/config/sidecars//sidecar.json`. +Native `builtin: schedule` requires an `args` array beginning with the cron expression. +`config.cron`, a top-level `sidecar` wrapper and LoopX's template metadata are not +native config. Preserve an existing sidecar's id, enable choice and scoped permissions. +New sidecars retain the host's user enable step; configuration does not prove a live loop. Inspect native startup/tick results after any change. -The native schedule starts a fresh conversation with the stable bootstrap. -That conversation must load fresh Core admission before work, preserving its -registered Goal/Agent and current settlement identity. A fresh native context -is not a new Goal or authority to replay the failed task. A successful schedule -or conversation-start receipt does not establish completed work; inspect the -resulting admission and settlement. Native timer dispatch still starts a model -conversation when Core later selects a quiet no-op; no lower model cost is claimed. +A detached native sidecar schedule starts a fresh conversation with the stable +bootstrap, which must still load fresh Core admission before work and preserve its +registered Goal/Agent and current settlement identity. `hooks_template` is a native top-level named `loopx` group containing `Stop` handlers, not `hooks.loopx` or a `before_continuation` event. Global -`--with-agy-hooks` installation is disabled until a concrete Goal, Agent and -native conversation are bound. Bound recovery handles only the native `ERROR` -event with a recognized Google model transport failure and fresh admission. +`--with-agy-hooks` installation stays disabled until a concrete Goal, Agent and +native conversation are bound (pass `--goal-id`, `--agent-id`, `--conversation-id` +to `slash-commands --with-agy-hooks`, or use `bind-agent-thread --with-agy-hooks`). +Bound recovery handles only the native `ERROR` event with a recognized Google model +transport failure and fresh admission. The latest native input must match before and after admission; its index and creation time distinguish repeated identical messages. Missing native readback does not admit a continuation; @@ -45,13 +62,15 @@ unrelated inherited `PYTHONPATH`. This provider recovery is not a generic pre-invocation enforcement gate and does not repair an upstream network connection. Uninstall removes only an unchanged, recorded managed entry. -Follow fresh `scheduler_hint.app_automation` for cadence and terminal actions. -Update the existing native schedule or the same sidecar's `args[0]`, inspect host -readback, then execute the current `ack_hint.cli_args`; on failure execute the -current failure hint without ACK. A terminal stop requires no scheduler ACK. -Never copy a Codex automation's identity or claim cadence applied from the -template alone. In-session one-shot timers use `DurationSeconds`; recurring -timers use `CronExpression`, without combining both forms. +Follow fresh `scheduler_hint.app_automation` for cadence and terminal actions: +in fixed-session mode, use `max(180, recommended_interval_minutes * 60)` in +in-session `schedule(...)` (`3 -> 6 -> 10`m backoff) and execute projected +`ack_hint.cli_args` / `failure_hint.cli_args` when applicable; in detached +sidecar mode, update the sidecar's `args[0]`, inspect host readback, then +execute `ack_hint.cli_args` (or `failure_hint` on failure). A terminal stop +requires no scheduler ACK. Never copy a Codex automation's identity or assume +`automation_update` exists on Antigravity. In-session one-shot timers use +`DurationSeconds`; recurring timers use `CronExpression`, without combining both forms. When the exact host is Codex App connected to a remote workspace over SSH and `automation_update` is unavailable because of that host boundary, use the diff --git a/skills/loopx-project/references/start-and-connect.md b/skills/loopx-project/references/start-and-connect.md index 957255f89a..e3b704c7fe 100644 --- a/skills/loopx-project/references/start-and-connect.md +++ b/skills/loopx-project/references/start-and-connect.md @@ -42,11 +42,16 @@ explicit route switch. Include `--goal-id ` when known. Codex App automatically reads the stable ambient `CODEX_THREAD_ID`, while Trae App reads -`TRAECLI_THREAD_ID`. TraeX CLI also reads `TRAECLI_THREAD_ID`, with its own +`TRAECLI_THREAD_ID`, and Antigravity (`antigravity-app` / `agy`) reads +`ANTIGRAVITY_CONVERSATION_ID` (or the `` `Conversation ID`; +both `agy` and `antigravity-app` resolve bindings across the same Antigravity +session). TraeX CLI also reads `TRAECLI_THREAD_ID`, with its own `traex-cli` binding scope; it never reuses a `trae_app` binding merely because the opaque thread id matches. Other hosts that expose a stable opaque thread id should pass it as `--thread-id ` on every `/loopx` -invocation. If that thread is already bound, reuse the returned +invocation (and Antigravity fixed sessions may pass `--with-agy-hooks` on +`bind-agent-thread` to sync bound `Stop` recovery in `~/.gemini/config/hooks.json`). +If that thread is already bound, reuse the returned `--agent-id ` on start, heartbeat, quota, refresh-state, and Todo commands. Include `--agent-id ` only when the current session already owns that identity, the thread binding resolves to it, diff --git a/tests/conftest.py b/tests/conftest.py index e60e366b8b..39704dd389 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -91,6 +91,9 @@ def _isolated_default_runtime_routes(tmp_path_factory, monkeypatch): monkeypatch.setenv("HOME", str(home)) monkeypatch.setenv("USERPROFILE", str(home)) monkeypatch.delenv("CODEX_HOME", raising=False) + # Prevent an active Antigravity host conversation from leaking ambient + # thread identity into hermetic start-goal / hook template tests. + monkeypatch.delenv("ANTIGRAVITY_CONVERSATION_ID", raising=False) # Tests opt into provider selection; isolate the operator's Chat route. monkeypatch.delenv("LOOPX_CHAT_CODEX_MODEL_PROVIDER", raising=False) for module_name, attribute, parts in _DEFAULT_ROUTE_REFERENCES: diff --git a/tests/control_plane/test_heartbeat_prompt_support.py b/tests/control_plane/test_heartbeat_prompt_support.py index 6e9b22b710..b18c041fb4 100644 --- a/tests/control_plane/test_heartbeat_prompt_support.py +++ b/tests/control_plane/test_heartbeat_prompt_support.py @@ -568,3 +568,53 @@ def test_exact_heartbeat_requires_agent_and_receipt_producing_profile() -> None: runtime_profile="codex_cli", turn_instance_id="turn-exact", ) + + +def test_antigravity_app_heartbeat_prompt_guides_inplace_schedule_patrol_within_budget() -> None: + for mode in ("full", "compact", "brief", "thin"): + for scope_chars in (0, 320): + for explicit_route in (False, True): + for reward_memory_enabled in (False, True): + profile = {"scope_summary": "x" * scope_chars} if scope_chars else None + route = ( + {"registry_path": "/fixture/registry.json", "runtime_root": "/fixture/runtime"} + if explicit_route + else {} + ) + payload = build_heartbeat_prompt( + goal_id="reward-memory-budget-fixture", + agent_id="worker-a", + registered_agents=["worker-a"], + agent_profile=profile, + runtime_profile="antigravity_app", + reward_memory_enabled=reward_memory_enabled, + **route, + **{mode: True}, + ) + body = str(payload["task_body"]) + assert payload["interface_budget"]["within_budget"] is True, ( + mode, + scope_chars, + explicit_route, + reward_memory_enabled, + ) + assert "automation_update" not in body, mode + assert "DurationSeconds=max(180, interval*60)" in body, mode + assert 'TimerCondition="any"' in body, mode + assert "3->6->10" in body, mode + assert ".worktrees/" in body, mode + assert "manage_task" in body, mode + assert "do not re-arm" in body, mode + assert "pause_or_delete_current_heartbeat" in body, mode + + codex_payload = build_heartbeat_prompt( + goal_id="loopx-meta", + agent_id="codex-side-bypass", + registered_agents=["codex-side-bypass"], + runtime_profile="codex_app_heartbeat", + thin=True, + ) + codex_body = str(codex_payload["task_body"]) + assert "automation_update" in codex_body + assert 'TimerCondition="any"' not in codex_body + assert "DurationSeconds=max(180, interval*60)" not in codex_body diff --git a/tests/test_agy_host_surface.py b/tests/test_agy_host_surface.py index e7e2a1e44a..f5df02e32d 100644 --- a/tests/test_agy_host_surface.py +++ b/tests/test_agy_host_surface.py @@ -689,3 +689,164 @@ def test_antigravity_app_real_cli_ack_and_stateful_backoff_identity( ) is None ) + + +def test_antigravity_ambient_conversation_id_facade_and_bound_hooks_sync( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Antigravity fixed sessions resolve ANTIGRAVITY_CONVERSATION_ID, bind hooks.json + atomically, and receive in-place schedule(DurationSeconds>=180) + .worktrees/ guidance.""" + project = connected_project(tmp_path / "proj", goal_id="resident-goal") + registry_path = project / ".loopx" / "registry.json" + runtime_root = tmp_path / "runtime" + state_path = project / ".loopx" / "goals" / "resident-goal" / "ACTIVE_GOAL_STATE.md" + state_path.parent.mkdir(parents=True) + state_path.write_text("# Goal\n\n## Agent Todo\n", encoding="utf-8") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + registry["common_runtime_root"] = str(runtime_root) + registry["goals"][0].update( + state_file=".loopx/goals/resident-goal/ACTIVE_GOAL_STATE.md", + coordination={"registered_agents": ["antigravity"], "agent_model": "peer_v1"}, + ) + registry_path.write_text(json.dumps(registry), encoding="utf-8") + from loopx.global_registry import sync_project_registry_to_global + from tests.control_plane.canonical_authority_fixture import ( + initialize_canonical_source_fixture, + ) + + initialize_canonical_source_fixture( + runtime_root, + "resident-goal", + state_path=state_path, + ) + sync_project_registry_to_global( + registry_path=registry_path, + runtime_root_override=str(runtime_root), + goal_id="resident-goal", + dry_run=False, + ) + + custom_agy_home = tmp_path / "agy-cfg" + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("AGY_HOME", str(custom_agy_home)) + monkeypatch.delenv("ANTIGRAVITY_CONVERSATION_ID", raising=False) + + # Preview and execute bind-agent-thread --with-agy-hooks + conv_id = "conv-fixed-1234" + preview = run_cli( + "--registry", str(registry_path), + "--runtime-root", str(runtime_root), + "bind-agent-thread", + "--goal-id", "resident-goal", + "--thread-id", conv_id, + "--host-surface", "agy", + "--agent-id", "antigravity", + "--with-agy-hooks", + "--agy-home", str(custom_agy_home), + cwd=project, + ) + assert preview.returncode == 0, preview.stderr + preview_payload = json.loads(preview.stdout) + assert preview_payload["antigravity_hooks"]["status"] == "would_write" + assert not (custom_agy_home / "hooks.json").exists() + + bound_res = run_cli( + "--registry", str(registry_path), + "--runtime-root", str(runtime_root), + "bind-agent-thread", + "--goal-id", "resident-goal", + "--thread-id", conv_id, + "--host-surface", "agy", + "--agent-id", "antigravity", + "--with-agy-hooks", + "--agy-home", str(custom_agy_home), + "--execute", + cwd=project, + ) + assert bound_res.returncode == 0, bound_res.stderr + bound_payload = json.loads(bound_res.stdout) + assert bound_payload["ok"] is True + assert bound_payload["antigravity_hooks"]["status"] == "written" + hooks_data = json.loads((custom_agy_home / "hooks.json").read_text(encoding="utf-8")) + assert hooks_data["loopx"]["enabled"] is True + stop_cmd = hooks_data["loopx"]["Stop"][0]["command"] + assert f"--conversation-id {conv_id}" in stop_cmd + assert "--goal-id resident-goal" in stop_cmd + assert "--agent-id antigravity" in stop_cmd + + # Non-Antigravity host surfaces reject --with-agy-hooks cleanly + bad_surface = run_cli( + "--registry", str(registry_path), + "--runtime-root", str(runtime_root), + "bind-agent-thread", + "--goal-id", "resident-goal", + "--thread-id", "codex-t", + "--host-surface", "codex-app", + "--agent-id", "antigravity", + "--with-agy-hooks", + cwd=project, + ) + assert bad_surface.returncode == 1 + assert "--with-agy-hooks requires" in json.loads(bad_surface.stdout)["error"] + + # Ambient ANTIGRAVITY_CONVERSATION_ID resolves the agy binding when invoking antigravity-app + env = {**os.environ, "ANTIGRAVITY_CONVERSATION_ID": conv_id, "LOOPX_RUNTIME_ROOT": str(runtime_root)} + for surface in ("agy", "antigravity-app"): + start_res = run_cli( + "--registry", str(registry_path), + "--runtime-root", str(runtime_root), + "start-goal", "--guided", + "--project", str(project), + "--goal-id", "resident-goal", + "--host-surface", surface, + "--goal-text", "继续原地巡检", + cwd=project, + env=env, + ) + assert start_res.returncode == 0, start_res.stderr + start_payload = json.loads(start_res.stdout) + assert start_payload["thread_id"] == conv_id + assert start_payload["agent_id"] == "antigravity" + assert start_payload["thread_agent_binding"]["status"] == "bound" + + # slash-commands --install --surface antigravity-app --with-agy-hooks supports bound flags & /loopx guidance + sc_dir = tmp_path / "sc-agy" + sc_res = run_cli( + "--registry", str(registry_path), + "--runtime-root", str(runtime_root), + "slash-commands", "--install", + "--surface", "antigravity-app", + "--agy-home", str(sc_dir), + "--with-agy-hooks", + "--goal-id", "resident-goal", + "--agent-id", "antigravity", + "--conversation-id", conv_id, + cwd=project, + ) + assert sc_res.returncode == 0, sc_res.stderr + sc_hooks = json.loads((sc_dir / "hooks.json").read_text(encoding="utf-8")) + assert sc_hooks["loopx"]["enabled"] is True + assert f"--conversation-id {conv_id}" in sc_hooks["loopx"]["Stop"][0]["command"] + loopx_skill = (sc_dir / "skills" / "loopx" / "SKILL.md").read_text(encoding="utf-8") + for phrase in ( + "antigravity-app", + "Conversation ID", + "ANTIGRAVITY_CONVERSATION_ID", + "--with-agy-hooks", + ".worktrees/", + "DurationSeconds", + "3 -> 6 -> 10", + ): + assert phrase in loopx_skill, phrase + + activation = build_host_loop_activation_packet( + agent_type=ANTIGRAVITY_APP_AGENT_TYPE, + goal_id="resident-goal", + agent_id="antigravity", + registered_agents=["antigravity"], + ) + patrol_contract = activation["host_mutation"]["fixed_session_patrol_contract"] + assert patrol_contract["min_duration_seconds"] == 180 + assert patrol_contract["backoff_progression_minutes"] == [3, 6, 10] + assert patrol_contract["detached_sidecar_required"] is False diff --git a/tests/test_antigravity_host_runtime.py b/tests/test_antigravity_host_runtime.py index 97f5fa336a..5d577a532a 100644 --- a/tests/test_antigravity_host_runtime.py +++ b/tests/test_antigravity_host_runtime.py @@ -89,6 +89,7 @@ def test_native_retry_requires_fresh_admission_and_is_bounded_per_input( if response: assert "heartbeat-prompt --thin" in response["reason"] assert "--agent-id worker" in response["reason"] + assert "schedule(DurationSeconds>=180" in response["reason"] clock[0] += 61 assert ( runtime.stop_hook(args, event(lastUserInput="A new authorized request"))[ diff --git a/tests/test_thread_agent_binding.py b/tests/test_thread_agent_binding.py index a4b31730a6..aa4aeb8f79 100644 --- a/tests/test_thread_agent_binding.py +++ b/tests/test_thread_agent_binding.py @@ -997,3 +997,68 @@ def test_list_attached_session_bindings_is_a_read_only_row_per_binding(): "agent_id": "codex", } ] + + +def test_antigravity_thread_bindings_bridge_agy_and_antigravity_app_with_conflict_fence( + tmp_path: Path, +) -> None: + path = _registry(tmp_path, ["agent-a", "agent-b"]) + assert ( + bind_thread_agent_in_registry( + registry_path=path, + goal_id="goal", + host_surface="agy", + thread_id="conv-1", + agent_id="agent-a", + execute=True, + )["ok"] + is True + ) + resolved = resolve_registry_thread_agent_binding( + registry_path=path, + host_surface="antigravity-app", + thread_id="conv-1", + ) + assert resolved["status"] == "bound" + assert resolved["agent_id"] == "agent-a" + assert resolved["matches"] == [{"goal_id": "goal", "agent_id": "agent-a"}] + + conflict = bind_thread_agent_in_registry( + registry_path=path, + goal_id="goal", + host_surface="antigravity-app", + thread_id="conv-1", + agent_id="agent-b", + execute=True, + ) + assert conflict["ok"] is False + assert conflict["error_kind"] == "thread_agent_binding_conflict" + + same_agent = bind_thread_agent_in_registry( + registry_path=path, + goal_id="goal", + host_surface="antigravity-app", + thread_id="conv-1", + agent_id="agent-a", + execute=True, + ) + assert same_agent["ok"] is True + + # Unbinding stays exact-surface so removing antigravity-app preserves agy unless removed too + unb = unbind_thread_agent_in_registry( + registry_path=path, + goal_id="goal", + host_surface="antigravity-app", + thread_id="conv-1", + agent_id="agent-a", + execute=True, + ) + assert unb["ok"] is True and unb["written"] is True + assert ( + resolve_registry_thread_agent_binding( + registry_path=path, + host_surface="antigravity-app", + thread_id="conv-1", + )["agent_id"] + == "agent-a" + ) From 34cc5ebd3e192404bc93f396eb872306a0e29e69 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:42:47 +0800 Subject: [PATCH 2/2] fix(antigravity): fix exact-surface unbind readback, default registry hooks, and skill isolation Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli.py | 1 + loopx/cli_commands/registry_admin.py | 2 + loopx/cli_commands/slash_commands.py | 21 +++++++- loopx/cli_runtime.py | 12 ++++- loopx/doctor.py | 7 ++- loopx/slash_command_install.py | 79 ++++++++++++++++++++-------- tests/test_agy_host_surface.py | 78 +++++++++++++++++++++++++++ tests/test_slash_command_install.py | 22 ++++++++ 8 files changed, 193 insertions(+), 29 deletions(-) diff --git a/loopx/cli.py b/loopx/cli.py index c5173eef78..9f039398bb 100644 --- a/loopx/cli.py +++ b/loopx/cli.py @@ -365,6 +365,7 @@ def _main(argv: list[str] | None = None) -> int: args, registry_path=registry_path, allow_missing_registry=not user_supplied_registry(raw_argv), + registry_was_configured=registry_was_configured, ) if common_command_result is not None: return common_command_result diff --git a/loopx/cli_commands/registry_admin.py b/loopx/cli_commands/registry_admin.py index a75a8c52af..32c1e56dcb 100644 --- a/loopx/cli_commands/registry_admin.py +++ b/loopx/cli_commands/registry_admin.py @@ -712,11 +712,13 @@ def handle_registry_admin_command( _registry_goal(source_path, args.goal_id), host_surface=args.host_surface, thread_id=args.thread_id, + exact_surface=True, ) global_binding = resolve_thread_agent_binding( _registry_goal(global_path, args.goal_id), host_surface=args.host_surface, thread_id=args.thread_id, + exact_surface=True, ) if args.command == "bind-agent-thread": readback_verified = all( diff --git a/loopx/cli_commands/slash_commands.py b/loopx/cli_commands/slash_commands.py index 93e5af025f..60da0abbad 100644 --- a/loopx/cli_commands/slash_commands.py +++ b/loopx/cli_commands/slash_commands.py @@ -2,6 +2,7 @@ import argparse from collections.abc import Callable +import os from pathlib import Path from ..pi_goal_mode.installation import inspect_pi_installations, render_pi_installation_markdown @@ -174,6 +175,8 @@ def handle_slash_commands_command( *, output_format: FormatSelector, print_payload: PrintPayload, + registry_path: Path | None = None, + registry_was_configured: bool | None = None, ) -> int | None: if args.command != "slash-commands": return None @@ -192,9 +195,23 @@ def handle_slash_commands_command( else (getattr(args, "control_cli_bin", None) or args.cli_bin) ) agy_goal_id = getattr(args, "goal_id", None) + if registry_was_configured is None: + from ..paths import default_registry_path + + raw_reg = getattr(args, "registry", None) + configured_registry = bool(os.environ.get("LOOPX_REGISTRY")) or ( + bool(raw_reg) and str(raw_reg) != str(default_registry_path()) + ) + else: + configured_registry = registry_was_configured + resolved_registry = ( + registry_path + if registry_path is not None + else (Path(args.registry).expanduser() if getattr(args, "registry", None) else None) + ) agy_registry = ( - str(Path(args.registry).expanduser().resolve()) - if agy_goal_id and getattr(args, "registry", None) + str(resolved_registry.resolve()) + if agy_goal_id and configured_registry and resolved_registry is not None else None ) agy_runtime_root = ( diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index ba7e8b1b90..bc674449aa 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -560,6 +560,7 @@ def _dispatch_common_command( *, registry_path: Path, allow_missing_registry: bool, + registry_was_configured: bool | None = None, ) -> int | None: if args.command == "start-goal": from .cli_commands.start_goal import handle_start_goal_command @@ -706,7 +707,11 @@ def _dispatch_common_command( from .cli_commands.slash_commands import handle_slash_commands_command return handle_slash_commands_command( - args, output_format=output_format, print_payload=print_payload, + args, + output_format=output_format, + print_payload=print_payload, + registry_path=registry_path, + registry_was_configured=registry_was_configured, ) if args.command == "doctor": from .cli_commands.doctor import handle_doctor_command @@ -864,6 +869,7 @@ def dispatch_common_command( *, registry_path: Path, allow_missing_registry: bool, + registry_was_configured: bool | None = None, ) -> int | None: from .control_plane.effect_runtime import effect_runtime_request_scope @@ -872,6 +878,7 @@ def dispatch_common_command( args, registry_path=registry_path, allow_missing_registry=allow_missing_registry, + registry_was_configured=registry_was_configured, ) @@ -882,7 +889,7 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: guard_result = enforce_native_controller_guard(args) if guard_result is not None: return guard_result - registry_path, _registry_was_configured = resolve_cli_registry(args, raw_argv) + registry_path, registry_was_configured = resolve_cli_registry(args, raw_argv) if args.command in _REGISTRY_INSPECTION_COMMANDS: from .registry import ( inspect_registry, inspect_registry_boundary, @@ -930,6 +937,7 @@ def _dispatch_selected(args: argparse.Namespace, raw_argv: list[str]) -> int: args, registry_path=registry_path, allow_missing_registry=not user_supplied_registry(raw_argv), + registry_was_configured=registry_was_configured, ) if result is None: # pragma: no cover - caller guards the private interface raise AssertionError(f"selected command was not dispatched: {args.command}") diff --git a/loopx/doctor.py b/loopx/doctor.py index 405a5342fe..9cfe865986 100644 --- a/loopx/doctor.py +++ b/loopx/doctor.py @@ -803,7 +803,7 @@ def collect_doctor( project_skill = skills["loopx-project"] elif (agy_cfg_skills / "loopx" / "SKILL.md").exists(): skill_roots = (agy_cfg_skills,) - skills = inspect_skill_facades(agy_cfg_skills) + skills = inspect_skill_facades(agy_cfg_skills, host_surface="antigravity-app") project_skill = skills["loopx"] else: skill_roots = (agy_cfg_skills, *codex_skill_roots()) @@ -1303,7 +1303,10 @@ def collect_doctor( required_skill_ids=ARK_MANAGED_AGENT_REQUIRED_SKILL_IDS, source_root=repo_root, ) - agy_facades = inspect_skill_facades(agy_cfg_home / "skills") + agy_facades = inspect_skill_facades( + agy_cfg_home / "skills", + host_surface="antigravity-app", + ) workflow_skill_ids = set( agy_workflow_readback.get("materialized_skill_ids") or () ) diff --git a/loopx/slash_command_install.py b/loopx/slash_command_install.py index a4da8ae0d0..7b290a4d32 100644 --- a/loopx/slash_command_install.py +++ b/loopx/slash_command_install.py @@ -190,7 +190,22 @@ def _dsh_native_loopx_instructions(*, cli_bin: str) -> list[str]: ] -def _command_prompt_specs(*, cli_bin: str, include_legacy_aliases: bool) -> list[CommandFacadeSpec]: +def _command_prompt_specs( + *, + cli_bin: str, + include_legacy_aliases: bool, + host_surface: str | None = None, +) -> list[CommandFacadeSpec]: + codex_heartbeat_instruction = ( + "For a Codex App heartbeat, run the returned activation command, require ok=true, and save its `LoopX managed heartbeat bootstrap v2` task_body through automation_update. The saved loader fetches the current thin contract on every wake; do not persist a raw thin/compact/full execution body. Preserve the current goal, registered agent, task binding and existing schedule; read back the automation through the same App." + if host_surface in {None, "codex", "codex-cli", "codex-ide-plugin", "codex-app", "codex-app-ssh"} + else None + ) + antigravity_resident_instruction = ( + f"For an Antigravity App fixed resident session (`antigravity-app` / `agy`), read `` `Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`), bind it once via `{cli_bin} bind-agent-thread --goal-id --thread-id --host-surface agy --agent-id --with-agy-hooks --execute` and `{cli_bin} sync-global` (updating `~/.gemini/config/hooks.json` `Stop` recovery with the active `{cli_bin}` path and `--conversation-id`; do not create a `new-conversation` `sidecar.json` for a fixed session). On every wake, run `{cli_bin} --format json heartbeat-prompt --thin --runtime-profile antigravity_app --goal-id --agent-id `, follow `task_body` only when `ok=true`, perform peer code/doc edits and `quota should-run` inside an isolated `.worktrees/` git worktree (keeping the main checkout clean for `workspace_guard`), and before ending every turn (settled, `waiting_external`, or idle) unless stopped, call `schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), TimerCondition=\"any\", Prompt=...)` (`180`s floor; `3 -> 6 -> 10`m backoff) without shell `sleep`." + if host_surface in {"agy", "antigravity-app"} + else None + ) specs: list[CommandFacadeSpec] = [ { "command": "/loopx", @@ -198,23 +213,27 @@ def _command_prompt_specs(*, cli_bin: str, include_legacy_aliases: bool) -> list "description": "Inspect LoopX state, or start concrete project work when arguments are provided.", "argument_hint": "[--fine-grained] [--new-peer] [--capability-route issue-fix] [task text]", "instructions": [ - "Visible command arguments: `$ARGUMENTS`.", - "Identify the exact current host surface (codex-app, trae_app, codex-app-ssh, codex-ide-plugin, codex-cli-tui, opencode, opencode2, traex-cli, pi, gemini-cli, cursor-agent, zcode, antigravity-app, agy, kiro-cli, deepseek-harness, or ark-managed-agent).", - _loopx_start_goal_arguments_instruction( - cli_bin=cli_bin, - host_surface=None, - ), - "Treat the returned `ordered_steps` and `goal_start_contract` as authoritative. Follow their identity, capability-route, Todo, writeback, host-loop, quota, and stop/gate rules before substantive work; do not reconstruct those rules from skill memory.", - "During first planning, follow the shared goal_requirements_guidance: reuse existing owner-approved requirements and declare only missing source-grounded overall requirements through the existing outcome owner, link actual Todos and read back the canonical declaration. Preserve existing requirements on resume; maximum timeout is not a minimum work commitment and independent executable checks stay optional.", - "When the host explicitly supplies a `loopx_task_planning_v0` packet from `loopx todo plan` for a registered Goal/Agent, execute that bounded planning checkpoint instead of starting another Goal. Follow its shared planner, requirement declaration/readback and Todo delta in the same invocation, then return actual Todo ids for readback. Its caller-owned execution_handoff retains host activation and quota; do not create a planning Todo, execute task work, or claim delivery during the checkpoint.", - "For a Codex App heartbeat, run the returned activation command, require ok=true, and save its `LoopX managed heartbeat bootstrap v2` task_body through automation_update. The saved loader fetches the current thin contract on every wake; do not persist a raw thin/compact/full execution body. Preserve the current goal, registered agent, task binding and existing schedule; read back the automation through the same App.", - f"For an Antigravity App fixed resident session (`antigravity-app` / `agy`), read `` `Conversation ID` (or `$ANTIGRAVITY_CONVERSATION_ID`), bind it once via `{cli_bin} bind-agent-thread --goal-id --thread-id --host-surface agy --agent-id --with-agy-hooks --execute` and `{cli_bin} sync-global` (updating `~/.gemini/config/hooks.json` `Stop` recovery with the active `{cli_bin}` path and `--conversation-id`; do not create a `new-conversation` `sidecar.json` for a fixed session). On every wake, run `{cli_bin} --format json heartbeat-prompt --thin --runtime-profile antigravity_app --goal-id --agent-id `, follow `task_body` only when `ok=true`, perform peer code/doc edits and `quota should-run` inside an isolated `.worktrees/` git worktree (keeping the main checkout clean for `workspace_guard`), and before ending every turn (settled, `waiting_external`, or idle) unless stopped, call `schedule(DurationSeconds=max(180, recommended_interval_minutes * 60), TimerCondition=\"any\", Prompt=...)` (`180`s floor; `3 -> 6 -> 10`m backoff) without shell `sleep`.", - "If the packet exposes a goal-selection gate, rerun one exact choice before any mutation.", - "When authoring task Todos, treat `--action-kind` as the documented extensible public-safe token: choose a short task-relevant value such as `implement`, `test`, or `review`; do not search the LoopX source for an allowlist.", - "Consume the turn-start quota JSON packet exactly once: read the complete output directly or save it and query it with `jq`; never pipe it through `head` or `tail`, and never rerun the turn-start call to recover hidden fields. A host whose runtime mints Turn identity uses `--begin-turn`; every other host passes its own `--turn-instance-id`. When selection is required, choose the Todo and use `interaction_contract.cli_channel.selection_command` with the returned Turn identity before mutation.", - "Runtime capability flags are host observations, not task requirements or grants; registered Agents reuse supported ones via `loopx agent-capabilities`. Before initial quota, include capabilities already established by this host context or successful task-facing use. Read capability_gate.repair_missing even when should_run is true: when runtime_capability_reentry is projected, verify its real callsite and follow the returned same-Turn command before choosing fallback work. Never infer credentials or production access from network availability, and do not claim a missing declaration proves a missing tool.", - f"If arguments are empty and the host already identifies an active LoopX goal, follow its exact CLI `interaction_contract` or quota command first; otherwise inspect `{cli_bin} status` and `{cli_bin} bootstrap-command-pack --project .` before changing files.", - "If this session cannot mutate the host loop surface, surface the exact pasteable gate instead of claiming autonomous setup.", + line + for line in [ + "Visible command arguments: `$ARGUMENTS`.", + "Identify the exact current host surface (codex-app, trae_app, codex-app-ssh, codex-ide-plugin, codex-cli-tui, opencode, opencode2, traex-cli, pi, gemini-cli, cursor-agent, zcode, antigravity-app, agy, kiro-cli, deepseek-harness, or ark-managed-agent).", + _loopx_start_goal_arguments_instruction( + cli_bin=cli_bin, + host_surface=None, + ), + "Treat the returned `ordered_steps` and `goal_start_contract` as authoritative. Follow their identity, capability-route, Todo, writeback, host-loop, quota, and stop/gate rules before substantive work; do not reconstruct those rules from skill memory.", + "During first planning, follow the shared goal_requirements_guidance: reuse existing owner-approved requirements and declare only missing source-grounded overall requirements through the existing outcome owner, link actual Todos and read back the canonical declaration. Preserve existing requirements on resume; maximum timeout is not a minimum work commitment and independent executable checks stay optional.", + "When the host explicitly supplies a `loopx_task_planning_v0` packet from `loopx todo plan` for a registered Goal/Agent, execute that bounded planning checkpoint instead of starting another Goal. Follow its shared planner, requirement declaration/readback and Todo delta in the same invocation, then return actual Todo ids for readback. Its caller-owned execution_handoff retains host activation and quota; do not create a planning Todo, execute task work, or claim delivery during the checkpoint.", + codex_heartbeat_instruction, + antigravity_resident_instruction, + "If the packet exposes a goal-selection gate, rerun one exact choice before any mutation.", + "When authoring task Todos, treat `--action-kind` as the documented extensible public-safe token: choose a short task-relevant value such as `implement`, `test`, or `review`; do not search the LoopX source for an allowlist.", + "Consume the turn-start quota JSON packet exactly once: read the complete output directly or save it and query it with `jq`; never pipe it through `head` or `tail`, and never rerun the turn-start call to recover hidden fields. A host whose runtime mints Turn identity uses `--begin-turn`; every other host passes its own `--turn-instance-id`. When selection is required, choose the Todo and use `interaction_contract.cli_channel.selection_command` with the returned Turn identity before mutation.", + "Runtime capability flags are host observations, not task requirements or grants; registered Agents reuse supported ones via `loopx agent-capabilities`. Before initial quota, include capabilities already established by this host context or successful task-facing use. Read capability_gate.repair_missing even when should_run is true: when runtime_capability_reentry is projected, verify its real callsite and follow the returned same-Turn command before choosing fallback work. Never infer credentials or production access from network availability, and do not claim a missing declaration proves a missing tool.", + f"If arguments are empty and the host already identifies an active LoopX goal, follow its exact CLI `interaction_contract` or quota command first; otherwise inspect `{cli_bin} status` and `{cli_bin} bootstrap-command-pack --project .` before changing files.", + "If this session cannot mutate the host loop surface, surface the exact pasteable gate instead of claiming autonomous setup.", + ] + if line is not None ], }, { @@ -343,7 +362,11 @@ class SkillFacadeReadbackStatus(str, Enum): _MAX_SKILL_FACADE_READ_BYTES = 1024 * 1024 -def inspect_skill_facades(skills_dir: Path) -> dict[str, dict[str, Any]]: +def inspect_skill_facades( + skills_dir: Path, + *, + host_surface: str | None = None, +) -> dict[str, dict[str, Any]]: """Read the canonical facades without changing files or running a host. Compare the installer's current rendering, allowing its existing cli_bin @@ -351,7 +374,11 @@ def inspect_skill_facades(skills_dir: Path) -> dict[str, dict[str, Any]]: """ cli_placeholder = "__LOOPX_FACADE_CLI_PARAMETER__" summaries: dict[str, dict[str, Any]] = {} - for spec in _command_prompt_specs(cli_bin=cli_placeholder, include_legacy_aliases=False): + for spec in _command_prompt_specs( + cli_bin=cli_placeholder, + include_legacy_aliases=False, + host_surface=host_surface, + ): name = str(spec["name"]) path = skills_dir / name / "SKILL.md" status = SkillFacadeReadbackStatus.MISSING @@ -440,6 +467,7 @@ def materialize_loopx_entry_skill( for item in _command_prompt_specs( cli_bin=cli_bin, include_legacy_aliases=False, + host_surface=host_surface, ) if item["name"] == "loopx" ) @@ -1065,6 +1093,11 @@ def install_slash_commands( pi_user_home: str | None = None, ) -> dict[str, Any]: facade_specs = _command_prompt_specs(cli_bin=cli_bin, include_legacy_aliases=True) + agy_facade_specs = _command_prompt_specs( + cli_bin=cli_bin, + include_legacy_aliases=True, + host_surface="antigravity-app", + ) canonical_specs = [spec for spec in facade_specs if "alias_for" not in spec] legacy_alias_specs = [spec for spec in facade_specs if "alias_for" in spec] specs = facade_specs if include_legacy_aliases else canonical_specs @@ -1294,7 +1327,7 @@ def install_slash_commands( # ~/.gemini/config/skills//SKILL.md root so both Antigravity App # and legacy CLI work out of the box. _install_skill_facade( - specs=facade_specs, + specs=agy_facade_specs, installed=installed, skills_dir=agy_root / "skills", surface="agy", @@ -1306,7 +1339,7 @@ def install_slash_commands( ) if agy_home is None and "antigravity-app" not in effective_surfaces: _install_skill_facade( - specs=facade_specs, + specs=agy_facade_specs, installed=installed, skills_dir=agy_config_root / "skills", surface="antigravity-app", @@ -1319,7 +1352,7 @@ def install_slash_commands( if "antigravity-app" in effective_surfaces: _install_skill_facade( - specs=facade_specs, + specs=agy_facade_specs, installed=installed, skills_dir=agy_config_root / "skills", surface="antigravity-app", diff --git a/tests/test_agy_host_surface.py b/tests/test_agy_host_surface.py index f5df02e32d..3a6680a8c8 100644 --- a/tests/test_agy_host_surface.py +++ b/tests/test_agy_host_surface.py @@ -850,3 +850,81 @@ def test_antigravity_ambient_conversation_id_facade_and_bound_hooks_sync( assert patrol_contract["min_duration_seconds"] == 180 assert patrol_contract["backoff_progression_minutes"] == [3, 6, 10] assert patrol_contract["detached_sidecar_required"] is False + + # CLI unbind-agent-thread reads back with exact_surface=True even when a sibling surface shares (thread_id, agent_id) + bind_app = run_cli( + "--registry", str(registry_path), + "--runtime-root", str(runtime_root), + "bind-agent-thread", + "--goal-id", "resident-goal", + "--thread-id", conv_id, + "--host-surface", "antigravity-app", + "--agent-id", "antigravity", + "--execute", + cwd=project, + ) + assert bind_app.returncode == 0, bind_app.stderr + assert json.loads(bind_app.stdout)["ok"] is True + + unbind_app = run_cli( + "--registry", str(registry_path), + "--runtime-root", str(runtime_root), + "unbind-agent-thread", + "--goal-id", "resident-goal", + "--thread-id", conv_id, + "--host-surface", "antigravity-app", + "--agent-id", "antigravity", + "--execute", + cwd=project, + ) + assert unbind_app.returncode == 0, unbind_app.stderr + unbind_payload = json.loads(unbind_app.stdout) + assert unbind_payload["ok"] is True + assert unbind_payload["registration_readback"] == {"verified": True} + + # Sibling agy binding remains intact after unbinding antigravity-app + resolve_agy = run_cli( + "--registry", str(registry_path), + "--runtime-root", str(runtime_root), + "resolve-agent-thread", + "--thread-id", conv_id, + "--host-surface", "agy", + cwd=project, + ) + assert resolve_agy.returncode == 0, resolve_agy.stderr + assert json.loads(resolve_agy.stdout)["status"] == "bound" + + # slash-commands --with-agy-hooks run from an empty directory without --registry omits nonexistent CWD .loopx/registry.json + empty_cwd = tmp_path / "empty-cwd" + empty_cwd.mkdir() + sc_no_reg_dir = tmp_path / "sc-agy-no-reg" + env_no_reg = {k: v for k, v in os.environ.items() if k != "LOOPX_REGISTRY"} + sc_no_reg = run_cli( + "--runtime-root", str(runtime_root), + "slash-commands", "--install", + "--surface", "antigravity-app", + "--agy-home", str(sc_no_reg_dir), + "--with-agy-hooks", + "--goal-id", "resident-goal", + "--agent-id", "antigravity", + "--conversation-id", conv_id, + cwd=empty_cwd, + env=env_no_reg, + ) + assert sc_no_reg.returncode == 0, sc_no_reg.stderr + no_reg_hooks = json.loads((sc_no_reg_dir / "hooks.json").read_text(encoding="utf-8")) + no_reg_stop = no_reg_hooks["loopx"]["Stop"][0]["command"] + assert f"--conversation-id {conv_id}" in no_reg_stop + assert "--registry" not in no_reg_stop + assert str(empty_cwd) not in no_reg_stop + + # Antigravity installed skill facades match doctor readback when scoped to antigravity-app + from loopx.slash_command_install import inspect_skill_facades + + agy_facades = inspect_skill_facades( + sc_no_reg_dir / "skills", + host_surface="antigravity-app", + ) + assert agy_facades["loopx"]["readback_status"] == "ready" + monkeypatch.setenv("AGY_HOME", str(sc_no_reg_dir)) + assert collect_doctor(agent_type="antigravity-app")["antigravity"]["command_facades_ready"] is True diff --git a/tests/test_slash_command_install.py b/tests/test_slash_command_install.py index 102f91f910..6523d5c8b0 100644 --- a/tests/test_slash_command_install.py +++ b/tests/test_slash_command_install.py @@ -1366,3 +1366,25 @@ def test_marker_retires_after_user_edits_the_entry_and_dry_run_writes_nothing( ) assert _row(payload, "cursor_mcp_server")["status"] == "skipped_user_owned_mcp_entry" assert json.loads(config.read_text(encoding="utf-8"))["mcpServers"]["loopx"] == entry + + +def test_antigravity_resident_guidance_is_isolated_to_antigravity_surfaces(tmp_path: Path) -> None: + ark_skills = tmp_path / "ark-skills" + materialize_loopx_entry_skill( + skills_dir=ark_skills, + execute=True, + host_surface="ark-managed-agent", + ) + ark_text = (ark_skills / "loopx" / "SKILL.md").read_text(encoding="utf-8") + assert "Antigravity App fixed resident session" not in ark_text + assert "--with-agy-hooks" not in ark_text + + codex_home = tmp_path / "codex" + install_slash_commands( + execute=True, + surfaces=["codex"], + codex_home=str(codex_home), + ) + codex_text = (codex_home / "skills" / "loopx" / "SKILL.md").read_text(encoding="utf-8") + assert "Antigravity App fixed resident session" not in codex_text + assert "--with-agy-hooks" not in codex_text