Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/system-specs/modules/crew-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,13 @@ create. Every create path takes these steps: the dashboard, the CLI, the first
mate and an app's `ensure_team`. Crews created before this rule keep the
binding they have; deleting a crew leaves its workspace, like its memory store,
on disk and in `workspaces`. The workspace is the crew's own data directory; it
does not become the `project` of the crew's sessions.
does not become the `project` of the crew's sessions. Its pinned thread's
`session_map.json` entries do not stay: the dashboard delete destroys
`dashboard:member-<slug>` and each `dashboard:member-<slug>.memory-<store>` entry
through the session manager (`member_thread_teardown.destroy_member_thread_sessions`),
which also ends a live process for the thread, unless another live crew still
derives the slug. `kirocrew agent delete` leaves them, since only the gateway's
own map may rewrite that file.
A template has no workspace of its own, so a worker template a crew opens with
`session_create` (`agent="kirocrew-worker"`) inherits the crew's workspace along
with its store; naming another crew bound elsewhere stays refused
Expand Down
33 changes: 27 additions & 6 deletions src/kiro_crew/dashboard/agent_admin/crew_removal.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,22 +316,29 @@ def _prune_private_copy_outcome(crew: str, bound_template: str) -> str:


async def _remove_member_leftovers(
name: str, cfg: KiroCrewConfig, bound_template: str, crons: Any, actor: str
name: str,
cfg: KiroCrewConfig,
bound_template: str,
crons: Any,
actor: str,
sessions: Any = None,
) -> list[tuple[str, str, str]]:
"""Remove what a deleted crewmate leaves outside its config record. Never raises.

The one teardown both deletes run once the record is gone --
``DELETE /api/agents/{name}`` and ``kirocrew agent delete``: the avatar, the
goal check-in schedules (skipped when *crons* is ``None``), the git worktrees
its workers ran in, and its private template copy. *cfg* is the config
goal check-in schedules (skipped when *crons* is ``None``), its pinned
thread's sessions (skipped when *sessions*, the gateway's session manager,
is ``None``: only the process that owns the map may rewrite it), the git
worktrees its workers ran in, and its private template copy. *cfg* is the config
captured while the record was still in it and *bound_template* the binding
read inside the delete's critical section, as each step documents.

Every step runs whatever the one before it did. Returns one
``(outcome, kind, detail)`` per thing touched: *outcome* is ``"removed"``,
``"kept"`` (a worktree :func:`remove_crewmate_worktrees` keeps on purpose) or
``"failed"``; *kind* is ``"avatar"``, ``"goal check-in"``, ``"worktree"`` or
``"private template copy"``; *detail* names the item, empty for a failure.
``"failed"``; *kind* is ``"avatar"``, ``"goal check-in"``, ``"thread session"``,
``"worktree"`` or ``"private template copy"``; *detail* names the item, empty for a failure.
"""
report: list[tuple[str, str, str]] = []

Expand All @@ -354,6 +361,15 @@ def present() -> bool:
if jobs is None:
report.append(("failed", "goal check-in", ""))
report.extend(("removed", "goal check-in", job) for job in jobs or ())
if sessions is not None and getattr(sessions, "_session_map", None) is not None:
from kiro_crew.dashboard.member_thread_teardown import destroy_member_thread_sessions

keys = await destroy_member_thread_sessions(
sessions, name, cfg, claimed=_member_slug_is_claimed
)
if keys is None:
report.append(("failed", "thread session", ""))
report.extend(("removed", "thread session", key) for key in keys or ())
# One with uncommitted changes is kept; its branches and the repositories'
# own checkouts are never touched.
from kiro_crew.crewmate_worktree import remove_for_member
Expand Down Expand Up @@ -544,7 +560,12 @@ def _drop_from_team() -> None:
# Best-effort: no step blocks the crew's removal.
state = request.app.get("state")
leftovers = await _remove_member_leftovers(
name, cfg, bound_template, getattr(state, "crons", None), "dashboard"
name,
cfg,
bound_template,
getattr(state, "crons", None),
"dashboard",
getattr(state, "sessions", None),
)
if ("removed", "private template copy", bound_template) in leftovers:
clear_list_agents_cache()
Expand Down
61 changes: 61 additions & 0 deletions src/kiro_crew/dashboard/member_thread_teardown.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Destroying a deleted crewmate's pinned-thread sessions, one step of the crew delete."""

from __future__ import annotations

import asyncio
import logging
from typing import Any, Callable

logger = logging.getLogger(__name__)


async def destroy_member_thread_sessions(
sessions: Any, name: str, cfg: Any, *, claimed: Callable[[str], bool]
) -> list[str] | None:
"""Destroy a deleted crewmate's pinned-thread sessions. Never raises.

The thread is keyed ``dashboard:member-<slug>`` or, on a private store,
``dashboard:member-<slug>.memory-<store>`` in ``session_map.json``. Nothing
else clears that entry: a Fresh start keeps the key, a restart restores it,
and member threads are not listed where a session can be deleted.

Each key goes through ``sessions.destroy``, which ends a live process for the
thread and deletes its map entry in one step. The slug is resolved from
*cfg*, the config captured while the record still existed, and nothing is
destroyed while *claimed* answers that a live crew still derives it. The V1
key and the current store's key are named outright, so an entry a Fresh
start left without a session ID is reached; earlier generations are found
by the exact ``.memory-`` boundary, which keeps a sibling whose slug only
shares a prefix out.

Returns the keys destroyed, or ``None`` when a step failed.
"""
try:
from kiro_crew.members import (
MEMORY_STORE_SLOT_SUFFIX,
member_slug,
member_thread_session_alias,
)

slug = member_slug(name, cfg)
if await asyncio.to_thread(claimed, slug):
return []
smap = sessions._session_map
exact = member_thread_session_alias(slug)
keys = [exact]
store = getattr(cfg.agents.get(name), "memory_store", "")
if isinstance(store, str) and store and store != "default":
keys.append(member_thread_session_alias(slug, store))
prefix = exact + MEMORY_STORE_SLOT_SUFFIX
keys += sorted(
key for key in smap.mapped_sids_by_key() if key.startswith(prefix) and key not in keys
)
held = [key for key in keys if smap.has_hint(key)]
for key in held:
await sessions.destroy(key)
return held
except Exception:
logger.warning(
"crew delete: could not remove the thread sessions of %r", name, exc_info=True
)
return None
159 changes: 159 additions & 0 deletions test/test_crew_delete_forgets_member_thread_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
"""Deleting a crewmate destroys its pinned thread's session-map entries.

A crewmate's standing thread is keyed ``dashboard:member-<slug>`` (V1) or
``dashboard:member-<slug>.memory-<store>`` (a private store), in
``session_map.json``, and nothing else clears that entry. ``DELETE
/api/agents/{name}`` destroys it through the live session manager, so a running
process for the thread goes with it.

Pinned beside the removal: a sibling whose slug only shares a prefix, an
unrelated chat, a slug another live crew still derives, and a delete with no
dashboard state (``kirocrew agent delete``), which touches no session.
"""

from __future__ import annotations

import json
from types import SimpleNamespace
from unittest.mock import MagicMock

import pytest
from aiohttp import web

from kiro_crew.config.loader import KiroCrewAgentConfig, KiroCrewConfig
from kiro_crew.dashboard.handlers import agents as agents_mod
from kiro_crew.dashboard.handlers.agents import api_kirocrew_agent_delete
from kiro_crew.session_map import SESSION_MAP_FILENAME, SessionMap

GONE_V2 = "dashboard:member-mate.memory-member-mate-2b2eef2a151f4deba9af8ecae7da93e8"
GONE_V1 = "dashboard:member-mate"
SIBLING = "dashboard:member-mate-0a2620b15f41.memory-member-mate-0a2620b15f41-5805c68c"
UNRELATED = "dashboard:chat-1-1790000000"


@pytest.fixture(autouse=True)
def _owner_caller(_floor_monkeypatch):
_floor_monkeypatch.setattr(
"kiro_crew.dashboard.handlers.source_providers.is_owner_dashboard_request",
lambda request: True,
)


class _Sessions:
"""The two session-manager calls the delete route makes, over a real map."""

def __init__(self) -> None:
self._session_map = SessionMap()
self.destroyed: list[str] = []

async def destroy(self, key: str) -> None:
self.destroyed.append(key)
self._session_map.delete(key)

async def refresh_defaults(self) -> None:
return None


def _seed(*, extra_agents: dict | None = None) -> None:
from kiro_crew.config import config_dir

cfg = KiroCrewConfig()
cfg.agents = {
"kirocrew": KiroCrewAgentConfig(kiro_agent="kirocrew"),
"mate": KiroCrewAgentConfig(kiro_agent="kirocrew", member_id="mate"),
"mate2": KiroCrewAgentConfig(kiro_agent="kirocrew", member_id="mate-0a2620b15f41"),
**(extra_agents or {}),
}
cfg.default_agent = "kirocrew"
cfg.save()
keys = (GONE_V1, GONE_V2, SIBLING, UNRELATED)
entries = {key: {"sid": f"sid-{n}"} for n, key in enumerate(keys)}
path = config_dir() / SESSION_MAP_FILENAME
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(entries), encoding="utf-8")


def _delete_request(name: str, state: object):
request = MagicMock(spec=web.Request)
request.method = "DELETE"
request.match_info = {"name": name}
request.app = {"state": state}
return request


@pytest.mark.asyncio
async def test_delete_destroys_the_departed_crewmates_thread_entries():
_seed()
sessions = _Sessions()
state = SimpleNamespace(sessions=sessions, crons=None)

resp = await api_kirocrew_agent_delete(_delete_request("mate", state))

assert resp.status == 200
assert sorted(sessions.destroyed) == sorted([GONE_V1, GONE_V2])
left = set(sessions._session_map._data)
assert left == {SIBLING, UNRELATED}


@pytest.mark.asyncio
async def test_an_entry_a_fresh_start_left_without_a_sid_goes_too():
"""Fresh start clears the sid and keeps the key: the shape the issue reports."""
_seed()
sessions = _Sessions()
sessions._session_map.clear_sid(GONE_V1)
assert sessions._session_map.has_hint(GONE_V1)
assert GONE_V1 not in sessions._session_map.mapped_sids_by_key()
state = SimpleNamespace(sessions=sessions, crons=None)

resp = await api_kirocrew_agent_delete(_delete_request("mate", state))

assert resp.status == 200
assert GONE_V1 in sessions.destroyed
assert not sessions._session_map.has_hint(GONE_V1)


@pytest.mark.asyncio
async def test_a_slug_another_live_crew_still_derives_keeps_its_entries(monkeypatch):
_seed()
monkeypatch.setattr(agents_mod, "_member_slug_is_claimed", lambda slug: True)
sessions = _Sessions()
state = SimpleNamespace(sessions=sessions, crons=None)

resp = await api_kirocrew_agent_delete(_delete_request("mate", state))

assert resp.status == 200
assert sessions.destroyed == []
assert set(sessions._session_map._data) == {GONE_V1, GONE_V2, SIBLING, UNRELATED}


@pytest.mark.asyncio
async def test_a_failed_destroy_does_not_fail_the_committed_delete():
_seed()

class _Failing(_Sessions):
async def destroy(self, key: str) -> None:
raise RuntimeError("boom")

sessions = _Failing()
state = SimpleNamespace(sessions=sessions, crons=None)

resp = await api_kirocrew_agent_delete(_delete_request("mate", state))

assert resp.status == 200
assert "mate" not in KiroCrewConfig.load().agents


@pytest.mark.asyncio
async def test_leftovers_without_a_session_manager_touch_no_session():
"""The CLI delete passes no manager: the map file is left as it was."""
from kiro_crew.config import config_dir

_seed()
path = config_dir() / SESSION_MAP_FILENAME
before = path.read_bytes()
cfg = KiroCrewConfig.load()

report = await agents_mod._remove_member_leftovers("mate", cfg, "", None, "cli")

assert not [row for row in report if row[1] == "thread session"]
assert path.read_bytes() == before
Loading