agents(conversation-done): delete conversation after successful cleanup (#4567)

Finished agent conversations remained behind after `/conversation-done`
reclaimed their worktrees, branches, and Bazel output bases.

Once all workspace cleanup steps succeed, prefix the active
conversation title with `"done "` and delete the conversation via
`DeleteCascadeTrajectory` on the validated loopback Language Server
endpoint with HTTP redirects disabled and sanitized log output.
diff --git a/.agents/skills/conversation-done/SKILL.md b/.agents/skills/conversation-done/SKILL.md
index 4edfd6e..8c46574 100644
--- a/.agents/skills/conversation-done/SKILL.md
+++ b/.agents/skills/conversation-done/SKILL.md
@@ -1,19 +1,18 @@
 ---
 name: conversation-done
 description: >-
-  Clean up files and resources that aren't part of the agent conversation
-  (e.g. Bazel output base, Git worktree, local/remote branches)
+  Clean up workspace resources (Bazel output base, Git worktree, local/remote
+  branches) and delete the agent conversation after successful cleanup
 ---
 
 # Conversation Done Skill
 
-Cleans up external workspace resources created during agent workflows while
-preserving agent conversation data, chat history, and brain transcripts.
+Cleans up workspace resources created during agent workflows and deletes the
+active agent conversation once all cleanup steps succeed.
 
 ## Overview
 
-When agents work on tasks, several external resources outside the agent
-conversation directory (`~/.gemini/jetski/brain/`) are created:
+When working on tasks, agents create several workspace and session resources:
 
 1. **Bazel Output Base(s)**: Intermediate build artifacts, execroot trees,
    and running Bazel server and persistent worker processes (consuming tens of
@@ -21,15 +20,13 @@
 2. **Remote Git Branch**: The feature branch pushed to the user's fork
    (e.g., `origin`).
 3. **Local Git Branch**: The feature branch associated with the worktree.
-4. **Git Worktree**: The checked-out directory on disk (removed last, and only
-   if all other cleanup steps succeed).
-5. **Conversation Name**: Once cleanup completes without errors, the active
-   conversation title is prefixed with `"done "` (without duplicating an
-   existing `"done "` prefix, capped at 70 characters).
-
-This skill safely shuts down active build processes, reclaims these external
-resources, and marks the conversation title as `"done "` without removing the
-conversation transcript or chat history.
+4. **Git Worktree**: The checked-out directory on disk (removed after build
+   and branch cleanup steps succeed).
+5. **Agent Conversation**: Once all workspace cleanup steps succeed, the script
+   prefixes the active conversation (`ANTIGRAVITY_CONVERSATION_ID`) title with
+   `"done "` (without duplicating an existing `"done "` prefix, capped at 70
+   characters) and permanently deletes the conversation via the local Language
+   Server.
 
 ## Script Location
 
@@ -98,20 +95,28 @@
 * **Upstream Remote Protection**: Never deletes branches on `upstream`.
 * **No Expunge Rule**: Never runs `bazel clean --expunge`; shuts down servers
   gracefully and deletes the specific output base directory directly.
-* **Worktree Deleted Last**: Removes the Git worktree only after all other
-  cleanup steps succeed, keeping the working directory intact on failure.
+* **Worktree Deleted After Branch & Build Cleanup**: Removes the Git worktree
+  only after Bazel and Git branch cleanup steps succeed, keeping the working
+  directory intact on failure.
+* **Conversation Deleted Last on Success**: Prefixes the conversation title
+  with `"done "` and permanently deletes the active conversation only after all
+  workspace cleanup steps succeed, preserving the conversation and transcripts
+  if any cleanup step fails.
 
 ## Reporting Results
 
-After running the cleanup script, always report to the user what resources were
-deleted (or would be deleted in `--dry-run` mode), including:
+Deleting the active conversation immediately terminates and removes the
+session. When running live cleanup from inside an active conversation, state
+which resources you will clean up beforehand (or run `--dry-run` first to
+preview). In `--dry-run` mode or external invocations without an active
+conversation ID, report the deleted (or previewed) resources:
 
 * **Bazel Output Base(s)**: Paths and reclaimed disk space sizes.
 * **Remote Git Branch**: Deleted remote branch (`<remote>/<branch>`).
 * **Local Git Branch**: Deleted local branch name.
 * **Git Worktree**: Removed worktree directory path.
-* **Conversation Name**: Updated conversation title (prefixed with `"done "`
-  after successful cleanup).
+* **Agent Conversation**: Updated `"done "` conversation title and deleted (or
+  previewed) conversation ID.
 
 If any resources were skipped, left intact via `--leave-*` flags, or not found,
 note that briefly in the summary.
diff --git a/.agents/skills/conversation-done/scripts/cleanup.py b/.agents/skills/conversation-done/scripts/cleanup.py
index 974bc2a..2cf77fb 100755
--- a/.agents/skills/conversation-done/scripts/cleanup.py
+++ b/.agents/skills/conversation-done/scripts/cleanup.py
@@ -1,10 +1,10 @@
 #!/usr/bin/env python3
-"""Cleans up workspace resources created for an agent conversation.
+"""Cleans up workspace resources, prefixes 'done ', and deletes the conversation.
 
-This script cleans up files and resources that are external to the agent
-conversation itself (such as Bazel output bases, Git worktrees, and local or
-remote Git branches), while leaving the conversation history, transcripts,
-and brain state intact.
+This script cleans up workspace resources created for an agent task (such as
+Bazel output bases, Git worktrees, and local or remote Git branches) and, once
+all cleanup steps succeed, prefixes the active conversation title with "done "
+and deletes the conversation via the local Language Server.
 
 Usage examples:
   # Clean up current worktree and its associated resources:
@@ -34,15 +34,27 @@
 import glob
 import json
 import os
+import re
 import shutil
 import signal
 import stat
 import subprocess
 import sys
-import urllib.error
+import traceback
+import urllib.parse
 import urllib.request
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
+from http.client import HTTPMessage
 
+_LOOPBACK_HOSTS = frozenset(
+    {
+        # keep-sorted start
+        "127.0.0.1",
+        "::1",
+        "localhost",
+        # keep-sorted end
+    }
+)
 _PROTECTED_BRANCHES = frozenset(
     {
         # keep-sorted start
@@ -62,7 +74,7 @@
 # Maximum conversation title length displayed by the UI.
 _CONVERSATION_TITLE_MAX_LENGTH = 70
 _DONE_TITLE_PREFIX = "done "
-# Bound urllib.request.urlopen (which has no default timeout) on local loopback RPCs.
+# Bound urllib.request (which has no default timeout) on local loopback RPCs.
 _LS_RPC_TIMEOUT_SECONDS = 5
 # Cap git ls-remote so unreachable remotes do not stall cleanup.
 _GIT_LS_REMOTE_TIMEOUT_SECONDS = 10
@@ -80,12 +92,26 @@
 _UPDATE_ANNOTATIONS_METHOD = (
     "exa.language_server_pb.LanguageServerService/UpdateConversationAnnotations"
 )
+_DELETE_TRAJECTORY_METHOD = (
+    "exa.language_server_pb.LanguageServerService/DeleteCascadeTrajectory"
+)
+_ANSI_ESCAPE_RE = re.compile(
+    r"(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]"
+    r"|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)"
+    r"|\x1b[@-_]"
+)
+_CONTROL_WHITESPACE_RE = re.compile(r"[\t\n\r]+")
+_CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]+")
 
 
 def parse_args(argv: Sequence[str]) -> argparse.Namespace:
     """Parses command-line arguments."""
     parser = argparse.ArgumentParser(
-        description="Clean up agent workspace resources (Bazel output base, worktree, branches)."
+        description=(
+            "Clean up agent workspace resources (Bazel output base, worktree, "
+            "branches), prefix 'done ' on the conversation title, and delete "
+            "the conversation."
+        )
     )
     parser.add_argument(
         "--worktree",
@@ -145,6 +171,13 @@
     return parser.parse_args(argv)
 
 
+def _sanitize_log_text(value: object) -> str:
+    """Strips ANSI escape sequences, CR/LF, and control characters for logging."""
+    without_ansi = _ANSI_ESCAPE_RE.sub("", str(value))
+    single_line = _CONTROL_WHITESPACE_RE.sub(" ", without_ansi)
+    return _CONTROL_CHARS_RE.sub("", single_line)
+
+
 def log(msg: str) -> None:
     """Prints an informational message."""
     print(msg, flush=True)
@@ -816,9 +849,45 @@
     return deleted, succeeded
 
 
+def _parse_loopback_ls_base_url(raw_address: str) -> str | None:
+    """Validates a loopback Language Server endpoint and formats its base URL.
+
+    Args:
+        raw_address: `host:port` or `http(s)://host:port` endpoint string.
+
+    Returns:
+        Normalized `http(s)://host:port` base URL when loopback and valid, or
+        None when malformed or non-loopback.
+    """
+    addr = raw_address.strip()
+    if not addr:
+        return None
+    for ch in addr:
+        if ord(ch) <= 0x20 or ch in "@\\?#":
+            return None
+    candidate = addr if "://" in addr else f"http://{addr}"
+    try:
+        parsed = urllib.parse.urlsplit(candidate)
+        port = parsed.port
+    except ValueError:
+        return None
+    scheme = parsed.scheme.lower()
+    if scheme not in ("http", "https"):
+        return None
+    if parsed.path or parsed.query or parsed.fragment:
+        return None
+    if port is None or not (1 <= port <= 65535):
+        return None
+    host = (parsed.hostname or "").strip("[]").lower()
+    if host not in _LOOPBACK_HOSTS:
+        return None
+    netloc = f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
+    return f"{scheme}://{netloc}"
+
+
 def format_done_title(current_title: str) -> str:
     """Prepends 'done ' to a conversation title and truncates to max length."""
-    cleaned = " ".join(current_title.splitlines()).strip()
+    cleaned = _sanitize_log_text(current_title).strip()
     if not cleaned:
         return _DONE_TITLE_PREFIX.strip()
 
@@ -830,34 +899,84 @@
     return prefixed[:_CONVERSATION_TITLE_MAX_LENGTH].rstrip()
 
 
+def _post_ls_json(
+    base_url: str,
+    method: str,
+    body: Mapping[str, object],
+    csrf_header_value: str,
+) -> dict[str, object]:
+    """Sends a JSON POST RPC to a validated loopback Language Server endpoint.
+
+    Args:
+        base_url: Validated `http(s)://host:port` loopback base URL.
+        method: Connect RPC path under the Language Server.
+        body: JSON-serializable request payload.
+        csrf_header_value: Scoped CSRF header value.
+
+    Returns:
+        Decoded JSON response object, or an empty dict for blank responses.
+    """
+    url = f"{base_url}/{method}"
+    raw_body = json.dumps(body).encode("utf-8")
+    headers = {
+        "Content-Type": "application/json",
+        "Connect-Protocol-Version": "1",
+        "x-codeium-csrf-token": csrf_header_value,
+    }
+    req = urllib.request.Request(
+        url,
+        data=raw_body,
+        headers=headers,
+        method="POST",
+    )
+    opener = urllib.request.build_opener(_NoRedirectHandler())
+    with opener.open(req, timeout=_LS_RPC_TIMEOUT_SECONDS) as resp:
+        resp_bytes = resp.read()
+    if not resp_bytes:
+        return {}
+    parsed = json.loads(resp_bytes.decode("utf-8"))
+    return parsed if isinstance(parsed, dict) else {}
+
+
 def prefix_conversation_title(
     conversation_id: str,
-    ls_address: str,
+    base_url: str,
     csrf_header_value: str,
     dry_run: bool,
 ) -> None:
-    """Prepends 'done ' to the active conversation title via the Language Server."""
-    headers = {
-        "Content-Type": "application/json",
-        "x-codeium-csrf-token": csrf_header_value,
-    }
-    list_url = f"http://{ls_address}/{_GET_TRAJECTORIES_METHOD}"
-    list_req = urllib.request.Request(
-        list_url,
-        data=b"{}",
-        headers=headers,
-    )
+    """Prepends 'done ' to the active conversation title via the Language Server.
+
+    Args:
+        conversation_id: Identifier of the active conversation.
+        base_url: Validated `http(s)://host:port` loopback Language Server URL.
+        csrf_header_value: Scoped CSRF token for Language Server RPCs.
+        dry_run: If True, logs preview message without updating annotations.
+    """
     try:
-        with urllib.request.urlopen(list_req, timeout=_LS_RPC_TIMEOUT_SECONDS) as resp:
-            payload = json.loads(resp.read().decode("utf-8"))
-    except (urllib.error.URLError, json.JSONDecodeError, OSError) as exc:
-        log_warn(f"Failed to query conversation title: {exc}")
+        payload = _post_ls_json(
+            base_url, _GET_TRAJECTORIES_METHOD, {}, csrf_header_value
+        )
+    except (CleanupError, json.JSONDecodeError, OSError) as exc:
+        log_warn(f"Failed to query conversation title: {_sanitize_log_text(exc)}")
         return
 
-    summaries = payload.get("trajectorySummaries") or {}
-    entry = summaries.get(conversation_id) or {}
-    annotations = entry.get("annotations") or {}
-    current_title = annotations.get("title") or entry.get("summary") or ""
+    summaries = payload.get("trajectorySummaries")
+    if not isinstance(summaries, dict):
+        return
+    entry = summaries.get(conversation_id)
+    if not isinstance(entry, dict):
+        return
+
+    current_title = ""
+    annotations = entry.get("annotations")
+    if isinstance(annotations, dict):
+        raw_title = annotations.get("title")
+        if raw_title:
+            current_title = str(raw_title)
+    if not current_title:
+        raw_summary = entry.get("summary")
+        if raw_summary:
+            current_title = str(raw_summary)
     if not current_title:
         return
 
@@ -865,31 +984,63 @@
     if new_title == current_title:
         return
 
+    safe_title = _sanitize_log_text(new_title)
     if dry_run:
-        log(f"  [Dry Run] Would rename conversation to: {new_title}")
+        log(f"  [Dry Run] Would rename conversation to: {safe_title}")
         return
 
-    update_url = f"http://{ls_address}/{_UPDATE_ANNOTATIONS_METHOD}"
-    update_body = json.dumps(
-        {
-            "cascadeId": conversation_id,
-            "annotations": {"title": new_title},
-            "mergeAnnotations": True,
-        }
-    ).encode("utf-8")
-    update_req = urllib.request.Request(
-        update_url,
-        data=update_body,
-        headers=headers,
-    )
     try:
-        with urllib.request.urlopen(
-            update_req, timeout=_LS_RPC_TIMEOUT_SECONDS
-        ) as resp:
-            resp.read()
-        log(f"Renamed conversation to: {new_title}")
-    except (urllib.error.URLError, OSError) as exc:
-        log_warn(f"Failed to rename conversation: {exc}")
+        _post_ls_json(
+            base_url,
+            _UPDATE_ANNOTATIONS_METHOD,
+            {
+                "cascadeId": conversation_id,
+                "annotations": {"title": new_title},
+                "mergeAnnotations": True,
+            },
+            csrf_header_value,
+        )
+        log(f"Renamed conversation to: {safe_title}")
+    except (CleanupError, json.JSONDecodeError, OSError) as exc:
+        log_warn(f"Failed to rename conversation: {_sanitize_log_text(exc)}")
+
+
+def delete_conversation(
+    conversation_id: str,
+    base_url: str,
+    csrf_header_value: str,
+    dry_run: bool,
+) -> None:
+    """Deletes the active conversation via the local Language Server.
+
+    Args:
+        conversation_id: Identifier of the conversation to delete.
+        base_url: Validated `http(s)://host:port` loopback Language Server URL.
+        csrf_header_value: Scoped CSRF token for Language Server RPCs.
+        dry_run: If True, logs preview message without deleting.
+
+    Raises:
+        CleanupError: If the Language Server rejects or redirects the RPC.
+        json.JSONDecodeError: If the Language Server returns malformed JSON.
+        OSError: If the Language Server RPC fails due to network or HTTP errors.
+    """
+    safe_id = _sanitize_log_text(conversation_id)
+    if dry_run:
+        log(f"  [Dry Run] Would delete conversation: {safe_id}")
+        return
+
+    try:
+        _post_ls_json(
+            base_url,
+            _DELETE_TRAJECTORY_METHOD,
+            {"cascadeId": conversation_id},
+            csrf_header_value,
+        )
+    except (CleanupError, json.JSONDecodeError, OSError) as exc:
+        exc.add_note(f"Failed to delete conversation {safe_id}")
+        raise
+
+    log(f"Deleted conversation: {safe_id}")
 
 
 async def list_resources(main_repo: str) -> None:
@@ -913,6 +1064,21 @@
     """Raised when workspace or Git discovery fails."""
 
 
+class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
+    """Rejects HTTP redirects so CSRF credentials are never forwarded off-host."""
+
+    def redirect_request(
+        self,
+        req: urllib.request.Request,
+        fp: object,
+        code: int,
+        msg: str,
+        headers: HTTPMessage,
+        newurl: str,
+    ) -> urllib.request.Request | None:
+        raise CleanupError(f"HTTP redirect ({code}) rejected for Language Server RPC.")
+
+
 @dataclasses.dataclass
 class WorktreeInfo:
     """Information about a Git worktree."""
@@ -1017,6 +1183,11 @@
         log_error("No valid targets identified for cleanup.")
         sys.exit(1)
 
+    conversation_id = os.environ.get("ANTIGRAVITY_CONVERSATION_ID", "").strip()
+    ls_address = os.environ.get("ANTIGRAVITY_LS_ADDRESS", "").strip()
+    csrf_header_value = os.environ.get("ANTIGRAVITY_CSRF_TOKEN", "").strip()
+    has_conversation_rpc = bool(conversation_id and ls_address and csrf_header_value)
+
     # Show preview
     for target in targets:
         log("\nIdentified resources for cleanup:")
@@ -1032,6 +1203,8 @@
             log(f"  Remote branch:      {target.remote}/{target.branch}")
         if target.branch:
             log(f"  Local branch:       {target.branch}")
+    if has_conversation_rpc:
+        log(f"  Conversation:       {_sanitize_log_text(conversation_id)}")
 
     if not args.force and not args.dry_run and sys.stdin.isatty():
         confirm = input("\nProceed with cleanup? [y/N]: ").strip()
@@ -1071,16 +1244,36 @@
         log_error("Cleanup finished with errors.")
         sys.exit(1)
 
-    conversation_id = os.environ.get("ANTIGRAVITY_CONVERSATION_ID", "").strip()
-    ls_address = os.environ.get("ANTIGRAVITY_LS_ADDRESS", "").strip()
-    csrf_header_value = os.environ.get("ANTIGRAVITY_CSRF_TOKEN", "").strip()
-    if conversation_id and ls_address and csrf_header_value:
+    if has_conversation_rpc:
+        base_url = _parse_loopback_ls_base_url(ls_address)
+        if base_url is None:
+            log_error(
+                "Refusing Language Server RPC to invalid or non-loopback address: "
+                f"{_sanitize_log_text(ls_address)}"
+            )
+            log_error("Cleanup finished with errors.")
+            sys.exit(1)
+
         prefix_conversation_title(
             conversation_id=conversation_id,
-            ls_address=ls_address,
+            base_url=base_url,
             csrf_header_value=csrf_header_value,
             dry_run=args.dry_run,
         )
+        try:
+            delete_conversation(
+                conversation_id=conversation_id,
+                base_url=base_url,
+                csrf_header_value=csrf_header_value,
+                dry_run=args.dry_run,
+            )
+        except (CleanupError, json.JSONDecodeError, OSError) as exc:
+            for entry in traceback.format_exception_only(exc):
+                cleaned_entry = _sanitize_log_text(entry).strip()
+                if cleaned_entry:
+                    log_error(cleaned_entry)
+            log_error("Cleanup finished with errors.")
+            sys.exit(1)
 
     log("\nCleanup completed.")
 
@@ -1090,7 +1283,7 @@
     try:
         asyncio.run(async_main(sys.argv[1:]))
     except CleanupError as exc:
-        log_error(str(exc))
+        log_error(_sanitize_log_text(exc))
         sys.exit(1)
 
 
diff --git a/.agents/skills/conversation-done/scripts/cleanup_test.py b/.agents/skills/conversation-done/scripts/cleanup_test.py
index a17edfe..6bdfb5d 100644
--- a/.agents/skills/conversation-done/scripts/cleanup_test.py
+++ b/.agents/skills/conversation-done/scripts/cleanup_test.py
@@ -3,10 +3,14 @@
 from __future__ import annotations
 
 import asyncio
+import http.server
+import io
+import json
 import os
 import stat
 import subprocess
 import tempfile
+import threading
 import unittest
 from pathlib import Path
 from unittest import mock
@@ -371,21 +375,31 @@
                 self.assertNotIn("Git worktree: /repo/worktrees/feat1", deleted)
 
     async def test_exits_nonzero_when_cleanup_fails(self) -> None:
-        """Verifies async_main exits with code 1 and skips renaming on failure."""
+        """Verifies async_main exits 1 and skips renaming/deleting on failure."""
         target = cleanup.CleanupTarget(
             worktree_path="/repo/worktrees/feat1",
             branch="feat1",
         )
-        with mock.patch("cleanup.get_main_repo", return_value="/repo/main"), mock.patch(
-            "cleanup.get_worktrees", return_value=[]
-        ), mock.patch("cleanup.build_cleanup_target", return_value=target), mock.patch(
+        env = {
+            "ANTIGRAVITY_CONVERSATION_ID": "conv-fail-1",
+            "ANTIGRAVITY_LS_ADDRESS": "127.0.0.1:5387",
+            "ANTIGRAVITY_CSRF_TOKEN": "mock_token_val",
+        }
+        with mock.patch.dict(os.environ, env, clear=False), mock.patch(
+            "cleanup.get_main_repo", return_value="/repo/main"
+        ), mock.patch("cleanup.get_worktrees", return_value=[]), mock.patch(
+            "cleanup.build_cleanup_target", return_value=target
+        ), mock.patch(
             "cleanup.execute_cleanup_target", return_value=([], False)
-        ), mock.patch("cleanup.prefix_conversation_title") as mock_rename:
+        ), mock.patch("cleanup.prefix_conversation_title") as mock_rename, mock.patch(
+            "cleanup.delete_conversation"
+        ) as mock_delete_conv:
             with self.assertRaises(SystemExit) as cm:
                 await cleanup.async_main(["--branches", "feat1", "--force"])
 
         self.assertEqual(cm.exception.code, 1)
         mock_rename.assert_not_called()
+        mock_delete_conv.assert_not_called()
 
     async def test_remove_readonly_output_base_entries(self) -> None:
         """Verifies read-only files/dirs are removed without mutating symlink targets."""
@@ -566,12 +580,259 @@
             cleanup.format_done_title("DONE   Fix flaky upload test"),
             "done Fix flaky upload test",
         )
+        self.assertEqual(
+            cleanup.format_done_title("Fix\n\x1b[31mflaky\x1b[0m\x07\x9b2J test"),
+            "done Fix flaky test",
+        )
         self.assertEqual(cleanup.format_done_title("   "), "done")
         long_title = "a" * 80
         formatted = cleanup.format_done_title(long_title)
         self.assertEqual(len(formatted), 70)
         self.assertTrue(formatted.startswith("done "))
 
+    def test_parse_loopback_ls_base_url(self) -> None:
+        """Verifies loopback Language Server endpoint validation."""
+        self.assertEqual(
+            cleanup._parse_loopback_ls_base_url("127.0.0.1:5387"),
+            "http://127.0.0.1:5387",
+        )
+        self.assertEqual(
+            cleanup._parse_loopback_ls_base_url("localhost:5387"),
+            "http://localhost:5387",
+        )
+        self.assertEqual(
+            cleanup._parse_loopback_ls_base_url("[::1]:5387"),
+            "http://[::1]:5387",
+        )
+        self.assertEqual(
+            cleanup._parse_loopback_ls_base_url("https://localhost:5387"),
+            "https://localhost:5387",
+        )
+        for invalid in (
+            "",
+            "evil.example.com:5387",
+            "192.168.1.10:5387",
+            "http://evil.example.com@127.0.0.1:5387",
+            "http://127.0.0.1:5387/extra",
+            "http://127.0.0.1:5387?q=1",
+            "ftp://127.0.0.1:5387",
+            "127.0.0.1",
+            "127.0.0.1:0",
+            "127.0.0.1:99999",
+        ):
+            self.assertIsNone(cleanup._parse_loopback_ls_base_url(invalid))
+
+    def test_prefix_and_delete_conversation_loopback_rpc_and_redirect_guard(
+        self,
+    ) -> None:
+        """Verifies rename + DeleteCascadeTrajectory RPCs and redirect guards."""
+        recorded: list[tuple[str, str, dict[str, str], dict[str, object]]] = []
+        mode = {"status": 200}
+        redirect_target = {"url": ""}
+
+        class FakeLsHandler(http.server.BaseHTTPRequestHandler):
+            def do_GET(self) -> None:
+                hdrs = {k.lower(): v for k, v in self.headers.items()}
+                recorded.append(("GET", self.path, hdrs, {}))
+                self.send_response(200)
+                self.send_header("Content-Type", "application/json")
+                self.end_headers()
+                self.wfile.write(b"{}")
+
+            def do_POST(self) -> None:
+                length = int(self.headers.get("Content-Length", "0"))
+                raw = self.rfile.read(length).decode("utf-8")
+                hdrs = {k.lower(): v for k, v in self.headers.items()}
+                recorded.append(("POST", self.path, hdrs, json.loads(raw)))
+                if mode["status"] == 302:
+                    self.send_response(302)
+                    self.send_header("Location", redirect_target["url"])
+                    self.end_headers()
+                    return
+                self.send_response(mode["status"])
+                self.send_header("Content-Type", "application/json")
+                self.end_headers()
+                if self.path.endswith("/GetAllCascadeTrajectories"):
+                    resp_payload = {
+                        "trajectorySummaries": {
+                            "conv-123": {"summary": "Clean up feature branch"}
+                        }
+                    }
+                    self.wfile.write(json.dumps(resp_payload).encode("utf-8"))
+                    return
+                self.wfile.write(b"{}")
+
+            def log_message(self, format: str, *args: object) -> None:
+                del format, args
+
+        mock_token = "csrf-test-123"
+        httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), FakeLsHandler)
+        port = httpd.server_address[1]
+        base_url = f"http://127.0.0.1:{port}"
+        redirect_target["url"] = f"{base_url}/redirected"
+        thread = threading.Thread(target=httpd.serve_forever, daemon=True)
+        thread.start()
+        try:
+            cleanup.prefix_conversation_title(
+                "conv-123", base_url, mock_token, dry_run=True
+            )
+            cleanup.delete_conversation("conv-123", base_url, mock_token, dry_run=True)
+            self.assertEqual(len(recorded), 1)
+            self.assertEqual(recorded[0][0], "POST")
+            self.assertTrue(recorded[0][1].endswith("/GetAllCascadeTrajectories"))
+            recorded.clear()
+
+            cleanup.prefix_conversation_title(
+                "conv-123", base_url, mock_token, dry_run=False
+            )
+            cleanup.delete_conversation("conv-123", base_url, mock_token, dry_run=False)
+            self.assertEqual(len(recorded), 3)
+            self.assertEqual(
+                recorded[0][1],
+                "/exa.language_server_pb.LanguageServerService/GetAllCascadeTrajectories",
+            )
+            self.assertEqual(
+                recorded[1][1],
+                "/exa.language_server_pb.LanguageServerService/UpdateConversationAnnotations",
+            )
+            self.assertEqual(
+                recorded[1][3],
+                {
+                    "cascadeId": "conv-123",
+                    "annotations": {"title": "done Clean up feature branch"},
+                    "mergeAnnotations": True,
+                },
+            )
+            method, path, hdrs, payload = recorded[2]
+            self.assertEqual(method, "POST")
+            self.assertEqual(
+                path,
+                "/exa.language_server_pb.LanguageServerService/DeleteCascadeTrajectory",
+            )
+            self.assertEqual(hdrs.get("x-codeium-csrf-token"), mock_token)
+            self.assertEqual(hdrs.get("connect-protocol-version"), "1")
+            self.assertEqual(payload, {"cascadeId": "conv-123"})
+
+            recorded.clear()
+            mode["status"] = 302
+            with self.assertRaisesRegex(
+                cleanup.CleanupError, r"HTTP redirect \(302\) rejected"
+            ) as redirect_cm:
+                cleanup.delete_conversation(
+                    "conv-123\x1b[31m\x07", base_url, mock_token, dry_run=False
+                )
+            self.assertIn(
+                "Failed to delete conversation conv-123",
+                redirect_cm.exception.__notes__,
+            )
+            self.assertEqual(len(recorded), 1)
+            self.assertEqual(recorded[0][0], "POST")
+            self.assertEqual(
+                recorded[0][1],
+                "/exa.language_server_pb.LanguageServerService/DeleteCascadeTrajectory",
+            )
+        finally:
+            httpd.shutdown()
+            httpd.server_close()
+            thread.join()
+
+    async def test_prefixes_and_deletes_conversation_on_success(self) -> None:
+        """Verifies async_main prefixes 'done ' before deleting the conversation."""
+        target = cleanup.CleanupTarget(
+            worktree_path="/repo/worktrees/feat1",
+            branch="feat1",
+        )
+        mock_token = "csrf-ok-456"
+        env = {
+            "ANTIGRAVITY_CONVERSATION_ID": "conv-done-9",
+            "ANTIGRAVITY_LS_ADDRESS": "127.0.0.1:5387",
+            "ANTIGRAVITY_CSRF_TOKEN": mock_token,
+        }
+        order: list[str] = []
+
+        def record_prefix(**_kwargs: object) -> None:
+            order.append("prefix")
+
+        def record_delete(**_kwargs: object) -> None:
+            order.append("delete")
+
+        with mock.patch.dict(os.environ, env, clear=False), mock.patch(
+            "cleanup.get_main_repo", return_value="/repo/main"
+        ), mock.patch("cleanup.get_worktrees", return_value=[]), mock.patch(
+            "cleanup.build_cleanup_target", return_value=target
+        ), mock.patch(
+            "cleanup.execute_cleanup_target",
+            return_value=(["Git worktree: /repo/worktrees/feat1"], True),
+        ), mock.patch(
+            "cleanup.prefix_conversation_title", side_effect=record_prefix
+        ) as mock_prefix, mock.patch(
+            "cleanup.delete_conversation", side_effect=record_delete
+        ) as mock_delete_conv:
+            await cleanup.async_main(["--branches", "feat1", "--force"])
+
+        self.assertEqual(order, ["prefix", "delete"])
+        mock_prefix.assert_called_once_with(
+            conversation_id="conv-done-9",
+            base_url="http://127.0.0.1:5387",
+            csrf_header_value=mock_token,
+            dry_run=False,
+        )
+        mock_delete_conv.assert_called_once_with(
+            conversation_id="conv-done-9",
+            base_url="http://127.0.0.1:5387",
+            csrf_header_value=mock_token,
+            dry_run=False,
+        )
+
+        err_buf = io.StringIO()
+        with mock.patch.dict(os.environ, env, clear=False), mock.patch(
+            "sys.stderr", err_buf
+        ), mock.patch("cleanup.get_main_repo", return_value="/repo/main"), mock.patch(
+            "cleanup.get_worktrees", return_value=[]
+        ), mock.patch("cleanup.build_cleanup_target", return_value=target), mock.patch(
+            "cleanup.execute_cleanup_target",
+            return_value=(["Git worktree: /repo/worktrees/feat1"], True),
+        ), mock.patch("cleanup.prefix_conversation_title"), mock.patch(
+            "cleanup.delete_conversation",
+            side_effect=OSError("connection refused\x1b[31m\r\ninjected"),
+        ):
+            with self.assertRaises(SystemExit) as cm:
+                await cleanup.async_main(["--branches", "feat1", "--force"])
+        self.assertEqual(cm.exception.code, 1)
+        stderr_out = err_buf.getvalue()
+        self.assertIn("connection refused injected", stderr_out)
+        self.assertNotIn("\x1b", stderr_out)
+        self.assertNotIn("\r", stderr_out)
+
+        bad_env = dict(env)
+        bad_env["ANTIGRAVITY_LS_ADDRESS"] = "evil.example.com:5387\r\n\x1b[31mFAKE"
+        bad_err_buf = io.StringIO()
+        with mock.patch.dict(os.environ, bad_env, clear=False), mock.patch(
+            "sys.stderr", bad_err_buf
+        ), mock.patch("cleanup.get_main_repo", return_value="/repo/main"), mock.patch(
+            "cleanup.get_worktrees", return_value=[]
+        ), mock.patch("cleanup.build_cleanup_target", return_value=target), mock.patch(
+            "cleanup.execute_cleanup_target",
+            return_value=(["Git worktree: /repo/worktrees/feat1"], True),
+        ), mock.patch(
+            "cleanup.prefix_conversation_title"
+        ) as mock_bad_prefix, mock.patch(
+            "cleanup.delete_conversation"
+        ) as mock_bad_delete:
+            with self.assertRaises(SystemExit) as bad_cm:
+                await cleanup.async_main(["--branches", "feat1", "--force"])
+        self.assertEqual(bad_cm.exception.code, 1)
+        mock_bad_prefix.assert_not_called()
+        mock_bad_delete.assert_not_called()
+        bad_stderr = bad_err_buf.getvalue()
+        self.assertEqual(
+            bad_stderr.count("Refusing Language Server RPC"),
+            1,
+        )
+        self.assertIn("evil.example.com:5387 FAKE", bad_stderr)
+        self.assertNotIn("\x1b", bad_stderr)
+        self.assertNotIn("\r", bad_stderr)
+
 
 if __name__ == "__main__":
     unittest.main()