Skip to content
Merged
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
17 changes: 15 additions & 2 deletions src/kiro_crew/connections/ownership.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ class DisconnectScope:
# a surviving artifact. Restricting the re-stat to attempts is what makes a
# survivor unambiguously a FAILED unlink.
attempted_urls: tuple[str, ...]
# Whether the agent-spec rebuild after the purge confirmed a write. False when it
# declined (this instance may not write the shared agent home) or raised: new
# sessions may still load the entry this Disconnect removed from the config.
agent_spec_rewritten: bool


def _json_spec_names(spec_dir: Path) -> list[str] | None:
Expand Down Expand Up @@ -719,11 +723,19 @@ def _collect_owned(url: object, holder: str) -> None:
# ``~/.kiro/agents/kirocrew.lock`` (apps/bridges._mcp_lock), so they are
# different flocks and reentrancy never arises.
try:
from kiro_crew.agent import rebuild_agent_config
from kiro_crew.agent import rebuild_agent_config_reporting

await _offload_config_write(rebuild_agent_config)
_spec_path, spec_rewritten = await _offload_config_write(rebuild_agent_config_reporting)
except Exception: # noqa: BLE001 — the config write already landed
logger.warning("agent config rebuild failed after disconnect", exc_info=True)
spec_rewritten = False
else:
if not spec_rewritten:
logger.warning(
"agent spec was not rewritten after disconnect of %s: this instance may "
"not write the shared agent home",
slug,
)

# OUTSIDE the lock and awaited by nobody. This provider is warmable again precisely
# because its stored grant is gone, and the pool only premints ahead of need -- so
Expand All @@ -748,4 +760,5 @@ def _collect_owned(url: object, holder: str) -> None:
census_incomplete=census_gap,
census_unreadable=tuple(_census_source_name(label) for label in unreadable),
attempted_urls=tuple(attempted),
agent_spec_rewritten=spec_rewritten,
)
38 changes: 38 additions & 0 deletions src/kiro_crew/dashboard/handlers/_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -3948,3 +3948,41 @@ async def vector_memory_for_store(state: DashboardState, store: str):
from kiro_crew.context import ContextBuilder

return await ContextBuilder.ensure_store(store)


# The response text for a saved change whose agent-spec rebuild did not confirm a write.
AGENT_SPEC_NOT_REWRITTEN = (
"saved, but the agent spec may not have been rewritten, so new sessions may keep "
"the previous servers; see the gateway log"
)


def rebuild_agent_spec(context: str) -> bool:
"""Rebuild the agent spec after a dashboard config write; True only on a confirmed rewrite.

Blocking: call it through ``asyncio.to_thread``. A handler puts the answer in
its response as ``agent_spec_rewritten`` so the dashboard can say the change
was saved but may not have reached the agent spec. ``False`` covers both
unconfirmed outcomes: the rebuild declined to write (this instance may not own
the shared agent home), or it raised, possibly after part of the spec set was
already written. The config write itself already landed, so neither is an
error response.

The import stays function-local: ``kiro_crew.agent`` imports the dashboard
handlers, and resolving the name at call time is what lets a test that
substitutes ``kiro_crew.agent.rebuild_agent_config`` reach this call.
"""
try:
from kiro_crew.agent import rebuild_agent_config_reporting

_spec_path, wrote = rebuild_agent_config_reporting()
except Exception:
logger.warning("agent spec rebuild failed after %s", context, exc_info=True)
return False
if not wrote:
logger.warning(
"agent spec was not rewritten after %s: this instance may not write the shared "
"agent home, so new sessions may keep the previous spec",
context,
)
return wrote
31 changes: 16 additions & 15 deletions src/kiro_crew/dashboard/handlers/computer_use.py
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,8 @@ async def api_computer_use_config_save(request: web.Request) -> web.Response:
# are read per call and need no restart, and re-saving the same value must not
# tear down the user's session.
sessions_reset = 0
# None when the enable did not change, so no rebuild ran to report on.
spec_rewritten: bool | None = None
if STATE_KEY_ENABLED in state_patch and state_patch[STATE_KEY_ENABLED] != enabled_before:
# REBUILD THE AGENT SPEC FIRST. The enable is also a spec-emission gate
# (``agent._computer_use_spec_gate``): while it is off the server is not in
Expand All @@ -787,24 +789,21 @@ async def api_computer_use_config_save(request: web.Request) -> web.Response:
# its own acquisition, and ``rebuild_agent_config`` never takes this lock,
# so this cannot self-deadlock.
#
# A rebuild failure must not fail the SAVE: the write already landed and
# was audited. The fallback is the un-rebuilt spec — the tool surface
# appears on the next gateway start.
# A rebuild that fails or declines to write must not fail the SAVE: the
# write already landed and was audited. The response says the spec was
# not rewritten; the tool surface then appears on the next gateway start.
#
# The import is function-local and must STAY function-local, which is not
# a style choice: it makes the name resolve at CALL time, so
# ``kiro_crew.agent`` is the single place a test can substitute the
# rebuild. Hoisting it to module scope binds the name here at import time,
# and the test guard that keeps the suite from rewriting the operator's
# real ``~/.kiro/agents`` would silently stop reaching this call site.
# ``rebuild_agent_spec`` resolves ``kiro_crew.agent`` at CALL time, so that
# module is the single place a test can substitute the rebuild, and the
# test guard that keeps the suite from rewriting the operator's real
# ``~/.kiro/agents`` reaches this call site.
# Pinned by ``test_patching_the_agent_module_REACHES_the_handler``.
try:
from kiro_crew.agent import rebuild_agent_config
from kiro_crew.dashboard.handlers._shared import rebuild_agent_spec

async with _get_config_lock():
await asyncio.to_thread(rebuild_agent_config)
except Exception:
logger.exception("computer-use enable saved, but agent config rebuild failed")
async with _get_config_lock():
spec_rewritten = await asyncio.to_thread(
rebuild_agent_spec, "computer-use enable change"
)

from kiro_crew.dashboard.handlers.sessions import _reset_all_sessions

Expand All @@ -818,6 +817,8 @@ async def api_computer_use_config_save(request: web.Request) -> web.Response:

payload = await _full_payload()
payload["sessions_reset"] = sessions_reset
if spec_rewritten is not None:
payload["agent_spec_rewritten"] = spec_rewritten
return web.json_response(payload)


Expand Down
41 changes: 33 additions & 8 deletions src/kiro_crew/dashboard/handlers/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,7 @@ async def api_connections_disconnect(request: web.Request) -> web.Response:
"grantSharedWith": list(scope.grant_shared_with),
"grantCensusIncomplete": scope.census_incomplete,
"grantCensusUnreadable": list(scope.census_unreadable),
"agentSpecRewritten": scope.agent_spec_rewritten,
}
)

Expand Down Expand Up @@ -1005,7 +1006,7 @@ def _oauth_client_configured(provider: Provider) -> bool:
return bool(oauth_client_view(provider, config=config, vault_names=names).get("configured"))


async def _refresh_client_projections(slug: str) -> bool:
async def _refresh_client_projections(slug: str) -> bool | None:
"""Bring every runtime projection of ``slug``'s client in line with the record.

The vault and config.json are the source of truth; the emitted agent spec and
Expand All @@ -1017,7 +1018,12 @@ async def _refresh_client_projections(slug: str) -> bool:
would otherwise merge straight back; (2) rebuild the agent spec so the next
session reads the new client (or none).

Returns False when the scope scrub or the spec rebuild failed. The caller reports that as an
Returns True when every projection is refreshed, and None when the record and
scopes are clean but the rebuild declined to write the spec (this instance may
not write the shared agent home): the caller answers success, audits it, and
says ``agent_spec_rewritten: false``, because that decline repeats on every
call and a 500 would never clear. Returns False when the scope scrub or the
spec rebuild failed. The caller reports that as an
error rather than success: the RECORD is committed (and stays committed --
reverting the source to match a stale projection would keep the retired
credential authoritative, the opposite of what the operator asked), but a
Expand Down Expand Up @@ -1052,12 +1058,19 @@ async def _refresh_client_projections(slug: str) -> bool:
)
return False
try:
from kiro_crew.agent import rebuild_agent_config # circular at module scope
from kiro_crew.agent import rebuild_agent_config_reporting # circular at module scope

await asyncio.to_thread(rebuild_agent_config)
_spec_path, wrote = await asyncio.to_thread(rebuild_agent_config_reporting)
except Exception: # noqa: BLE001 -- reported to the caller, see docstring
logger.warning("rebuild_agent_config failed after an OAuth client change", exc_info=True)
return False
if not wrote:
logger.warning(
"agent spec was not rewritten after an OAuth client change for %s: this instance "
"may not write the shared agent home",
slug,
)
return None
return True


Expand Down Expand Up @@ -1250,14 +1263,18 @@ async def api_connections_oauth_client_put(request: web.Request) -> web.Response

slug = str(provider["slug"])

spec_rewritten = [True]

async def _mutate() -> web.Response | None:
async with _OAUTH_CLIENT_MUTATION:
failure = await _write_oauth_client(
slug, client_id=client_id, secret=secret, clear=clear
)
if failure is not None:
return failure
if not await _refresh_client_projections(slug):
refreshed = await _refresh_client_projections(slug)
spec_rewritten[0] = refreshed is True
if refreshed is False:
views_now = await asyncio.to_thread(_oauth_client_views)
return _projection_stale_response(
slug, next((v for v in views_now if v.get("slug") == slug), None)
Expand Down Expand Up @@ -1290,7 +1307,9 @@ async def _mutate() -> web.Response | None:
)
views = await asyncio.to_thread(_oauth_client_views)
current = next((v for v in views if v.get("slug") == slug), None)
return web.json_response({"ok": True, "client": current})
return web.json_response(
{"ok": True, "client": current, "agent_spec_rewritten": spec_rewritten[0]}
)


async def api_connections_oauth_client_delete(request: web.Request) -> web.Response:
Expand Down Expand Up @@ -1328,6 +1347,8 @@ def _drop_client(cfg: dict) -> dict | None:
del clients[slug]
return cfg

spec_rewritten = [True]

async def _mutate() -> web.Response | None:
async with _OAUTH_CLIENT_MUTATION:
# Same order and the same rollback as the PUT: the vault half goes
Expand All @@ -1350,7 +1371,9 @@ async def _mutate() -> web.Response | None:
{"error": "could not write config.json", "code": "config_write_failed"},
status=500,
)
if not await _refresh_client_projections(slug):
refreshed = await _refresh_client_projections(slug)
spec_rewritten[0] = refreshed is True
if refreshed is False:
views_now = await asyncio.to_thread(_oauth_client_views)
return _projection_stale_response(
slug, next((v for v in views_now if v.get("slug") == slug), None)
Expand All @@ -1370,4 +1393,6 @@ async def _mutate() -> web.Response | None:
)
views = await asyncio.to_thread(_oauth_client_views)
current = next((v for v in views if v.get("slug") == slug), None)
return web.json_response({"ok": True, "client": current})
return web.json_response(
{"ok": True, "client": current, "agent_spec_rewritten": spec_rewritten[0]}
)
12 changes: 8 additions & 4 deletions src/kiro_crew/dashboard/handlers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
_atomic_json_write,
_declined_foreign_spec_write,
kiro_agents_dir_path,
rebuild_agent_config,
rebuild_agent_config_reporting,
)
from kiro_crew.agent_discovery import _read_agent_spec
from kiro_crew.agent_spec_format import iter_agent_spec_files
Expand All @@ -36,7 +36,7 @@
)
from kiro_crew.config.paths import data_home, kiro_agents_dir
from kiro_crew.dashboard.chat_utils import run_to_completion
from kiro_crew.dashboard.handlers._shared import read_bounded_json
from kiro_crew.dashboard.handlers._shared import AGENT_SPEC_NOT_REWRITTEN, read_bounded_json
from kiro_crew.dashboard.state import DashboardState
from kiro_crew.env import emit_env
from kiro_crew.loop_lock import LoopBoundLock
Expand Down Expand Up @@ -3656,8 +3656,12 @@ async def _run_one_uninstall(uname: str) -> None:
rebuild_ok = False
rebuild_error: str | None = None
try:
await asyncio.to_thread(rebuild_agent_config)
rebuild_ok = True
_spec_path, rebuild_ok = await asyncio.to_thread(rebuild_agent_config_reporting)
if not rebuild_ok:
# Declined, not failed: this instance may not write the shared agent
# home, so the saved change does not reach new sessions.
rebuild_error = AGENT_SPEC_NOT_REWRITTEN
logger.warning("agent spec was not rewritten after apply: %s", rebuild_error)
except Exception as exc:
# Rebuild failures can surface file paths, env var contents, or
# credential fragments (e.g. JSON decode errors that echo file
Expand Down
25 changes: 13 additions & 12 deletions src/kiro_crew/dashboard/handlers/mcp_custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from aiohttp import web

from kiro_crew.dashboard.handlers import mcp as _mcp
from kiro_crew.dashboard.handlers._shared import rebuild_agent_spec
from kiro_crew.dashboard.handlers.mcp import (
_find_server_spec_anywhere,
_get_kirocrew_entry,
Expand Down Expand Up @@ -358,15 +359,13 @@ async def _record_owner_servers(entries: dict[str, dict]) -> None:
logger.warning("could not record owner MCP servers %s", sorted(entries), exc_info=True)


async def _rebuild_agent_config() -> None:
"""Best-effort agent-config rebuild so changes load on the next session."""
try:
# circular import: kiro_crew.agent imports dashboard handlers.
from kiro_crew.agent import rebuild_agent_config
async def _rebuild_agent_config() -> bool:
"""Rebuild the agent spec so the change loads on the next session.

await asyncio.to_thread(rebuild_agent_config)
except Exception:
logger.warning("rebuild_agent_config failed after MCP custom write", exc_info=True)
True only when the spec was rewritten; the caller reports a False to the
dashboard instead of claiming the change is live.
"""
return await asyncio.to_thread(rebuild_agent_spec, "MCP custom write")


async def api_mcp_custom_add(request: web.Request) -> web.Response:
Expand Down Expand Up @@ -459,7 +458,7 @@ async def api_mcp_custom_add(request: web.Request) -> web.Response:
await _mcp._offload_config_write(_mcp._atomic_write, _mcp._kirocrew_mcp_json(), data)

await _record_owner_servers(cleaned)
await _rebuild_agent_config()
spec_rewritten = await _rebuild_agent_config()

added = sorted(cleaned)
sel().log_api_access(
Expand All @@ -469,7 +468,9 @@ async def api_mcp_custom_add(request: web.Request) -> web.Response:
source="dashboard",
resources=f"custom:{','.join(added)} enabled={enable}",
)
return web.json_response({"ok": True, "added": added, "enabled": enable})
return web.json_response(
{"ok": True, "added": added, "enabled": enable, "agent_spec_rewritten": spec_rewritten}
)


async def api_mcp_custom_get(request: web.Request) -> web.Response:
Expand Down Expand Up @@ -628,7 +629,7 @@ async def api_mcp_custom_update(request: web.Request) -> web.Response:
return web.json_response({"error": f"server '{name}' not found"}, status=404)

await _record_owner_servers({name: spec})
await _rebuild_agent_config()
spec_rewritten = await _rebuild_agent_config()

sel().log_api_access(
caller="dashboard",
Expand All @@ -637,4 +638,4 @@ async def api_mcp_custom_update(request: web.Request) -> web.Response:
source="dashboard",
resources=f"custom:{name}",
)
return web.json_response({"ok": True, "name": name})
return web.json_response({"ok": True, "name": name, "agent_spec_rewritten": spec_rewritten})
14 changes: 5 additions & 9 deletions src/kiro_crew/dashboard/handlers/mcp_discover.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from aiohttp import web

from kiro_crew.agent import SharedAgentHomeRefused
from kiro_crew.dashboard.handlers._shared import rebuild_agent_spec
from kiro_crew.dashboard.handlers.mcp import (
_find_server_spec_anywhere,
_get_mcp_lock,
Expand Down Expand Up @@ -379,15 +380,9 @@ async def _install_from_official(request: web.Request, server_id: str) -> web.Re
enable_now = not mcp_entry_is_muted(existing)

# Rebuild the rendered agent configs so the new server loads on the next
# session, mirroring api_mcp_apply. Best-effort: the config write above
# already succeeded and survives a failed rebuild.
try:
# circular import: kiro_crew.agent imports dashboard handlers.
from kiro_crew.agent import rebuild_agent_config

await asyncio.to_thread(rebuild_agent_config)
except Exception:
logger.warning("rebuild_agent_config failed after MCP install", exc_info=True)
# session, mirroring api_mcp_apply. The config write above already landed
# and survives a skipped rebuild; the response says whether the spec moved.
spec_rewritten = await asyncio.to_thread(rebuild_agent_spec, "MCP install")

sel().log_api_access(
caller="dashboard",
Expand All @@ -403,6 +398,7 @@ async def _install_from_official(request: web.Request, server_id: str) -> web.Re
"required_env": required_env,
"method": method,
"enabled": enable_now,
"agent_spec_rewritten": spec_rewritten,
}
)

Expand Down
Loading
Loading