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
64 changes: 49 additions & 15 deletions docs/system-specs/modules/app-kit-platform.md
Original file line number Diff line number Diff line change
Expand Up @@ -1195,24 +1195,38 @@ The prior file is snapshotted BEFORE the replace (the write path unlinks a legac
symlink first, so reading afterwards would find nothing). An unreadable prior file
means "nothing to preserve", never "abort the refresh".

**An update carries the edits across its own deregister.** Both branches of
`POST /api/apps/{name}/update` deregister the app before re-registering it, and
**An update carries the edits across its own deregister.** The local-source branch
of `POST /api/apps/{name}/update` deregisters the app before re-registering it, and
deregistering deletes the agent files, so the re-registration would find no prior
file. The route therefore snapshots the app's agent files first
file. That branch therefore snapshots the app's agent files first
(`snapshot_app_agent_configs`, regular files only, keyed by file name) and hands
the snapshot to `register_app(name, prior_agent_configs)`; an agent with no file
on disk takes its prior config from it. The failed-update restore uses the same
snapshot. This is what keeps a user's `model` or `description` across a registry
update, a pin-follow of an adopted former built-in, or a local update. An agent
the new version renames or drops gets nothing from the snapshot. Disable and
re-enable still start from the template: a disabled app keeps no agent file and no
snapshot, so the same is true when an update newly asks for `sessionApproval` and
suspends the app.
snapshot. An agent the new version renames or drops gets nothing from the snapshot.

**A registry update keeps the agent files instead.** The update route's registry
branch and a registry install over an installed app deregister with
`deregister_app(name, keep_agents=True)` (§17), so registration rewrites each file in
place and reads the edits from it. A file it does not rewrite keeps its last good
copy, as on the boot reconcile: a full disk, a data home that does not own a shared
agents directory (registration declines to write there, and a deleted file would
never come back), or an agent the new version ships unreadable. After the take-down
`_reinstall_from_registry` prunes the files the installed manifest no longer
declares (`_prune_stale_app_resources`), and an app the update left unable to run
loses them all: suspended on success, deregistered on a failure. Pinned by
`test_a_registry_update_keeps_an_agent_file_it_cannot_rewrite` and
`test_a_registry_update_that_needs_consent_leaves_no_agent_file`.

Both keep a user's `model` or `description` across a registry update, a pin-follow of
an adopted former built-in, or a local update. Disable and re-enable still start from
the template: a disabled app keeps no agent file and no snapshot, so the same is true
when an update newly asks for `sessionApproval` and suspends the app.

Writer: `apps/bridges_agents.py::_register_agents`, `_preserve_user_agent_edits`,
`_read_agent_config`, `snapshot_app_agent_configs`; the update route
`apps/routes_install.py::handle_update_app` with
`apps/routes_lifecycle.py::_snapshot_agent_configs_off_loop`.
`apps/routes_lifecycle.py::_snapshot_agent_configs_off_loop` and
`_reinstall_from_registry`.

## 4. A generated prompt is pinned through the app's policy

Expand Down Expand Up @@ -4382,10 +4396,29 @@ state that is no longer on disk, so nothing retries. **The scrub also re-materia
the tracking record, and that pop is what ends the watch's authority to reconcile MCP for
the app — so it has to happen BEFORE `deregister_app`. Scrubbing first leaves a window in
which a backend that recovers re-registers the OLD manifest's servers, and entries the
update removed survive it. Uninstall, the disable rollback and the two update paths in `kiro_crew.apps.routes` all
order it this way, and
update removed survive it. Uninstall, the disable rollback, the two update paths in
`kiro_crew.apps.routes` and a registry install over an installed app all order it
this way, and
`test_update_stops_the_backend_before_deregistering_resources` pins it.

**A registry update takes the app down only to replace it.** The update route's
registry branch and both registry install routes, over an installed app, go through
`routes_lifecycle._reinstall_from_registry`, which hands `install_from_registry` the
stop and a deregister that keeps the agent files (§3) as `before_replace`. The
install awaits it right before `update_app` copies a managed app's new files in: once
every gate, the clone, the build, `setup.onInstall` and the startup-hook recheck have
passed. A refusal before that point leaves the app running, and a failure after the
take-down restores it (`_restore_app_after_failed_update`). The backend stops first
because on Windows the copy fails while it holds a file open under the tree. A
self-managed app (`resources: "app"`) is never taken down: it replaces no installed
file, and it owns the registrations a deregister would delete. A gateway-managed app
whose registry entry declares `resources: "app"` takes that path too: once the install has
written its record self-managed, even if a later step fails, its backend is stopped and
`deregister_app` runs in full, since from then on it registers its own. Pinned by
`test_an_update_takes_the_app_down_only_to_copy_its_files`,
`test_reinstall_over_an_installed_app_takes_it_down_to_replace_its_files` and
`test_registry_update_to_self_managed_cleans_up_only_gateway_owned_resources`.

`backend_status.running` on `/api/apps` is likewise read off the record
(`AppProcess.is_running`) rather than asserted from the record merely existing.
For an adopted backend, where we hold no handle to poll, "we still track it"
Expand Down Expand Up @@ -5783,7 +5816,7 @@ records which module owns which part, so a change lands in its owner.
| Module under `src/kiro_crew/apps/` | Owns |
|---|---|
| `routes.py` | The facade: the only import path and patch surface, installing `kiro_crew._facade_mirror` over the owners below, and the route table (`register_app_routes`) |
| `routes_lifecycle.py` | The steps the install, update, uninstall, enable and disable handlers share: `_check_min_version`, the dual-pass warning redactor `_redact_warning`, `_register_app_off_loop` / `_deregister_app_off_loop`, `_start_backend_after_install`, `_stop_backend_and_observe`, `_app_may_run_after_install`, `_restore_app_after_failed_update`, `_suspend_app_for_session_approval_reconsent`, `_refuse_while_startup_hook_runs` and `_unregister_notification_channels` |
| `routes_lifecycle.py` | The steps the install, update, uninstall, enable and disable handlers share: `_check_min_version`, the dual-pass warning redactor `_redact_warning`, `_register_app_off_loop` / `_deregister_app_off_loop`, `_start_backend_after_install`, `_stop_backend_and_observe`, `_app_may_run_after_install`, `_restore_app_after_failed_update`, `_reinstall_from_registry`, `_suspend_app_for_session_approval_reconsent`, `_refuse_while_startup_hook_runs` and `_unregister_notification_channels` |
| `routes_proxy.py` | The reverse proxy from an app's dashboard UI to its own backend (`handle_app_api_proxy`): `_resolve_app_backend_url`, the per-app secret cache it signs with (`_get_app_secret`, `invalidate_app_secret_cache`), the principal claim (`_proxy_principal`), the headers and the `token` query credential it strips (`_forwarded_query`) and the event-stream relay |
| `routes_static.py` | An installed app's UI bundle (`handle_app_ui_file`, `_open_ui_file` and the stream bounds), the content types the UI and art routes answer with, and `handle_app_dev_mode` |
| `routes_art.py` | The installed-art route (`handle_app_art_file`) over an app's manifest-declared art (`_declared_art_paths`, `_read_declared_art`), and the git blob proxy (`handle_blob_proxy`, `_fetch_git_blob`) with the repository and ref validators (`_is_safe_repo_identifier`, `_SAFE_REF_RE`), the fetch timeout and concurrency bound, and the blob-cache touch. Both art paths screen on one extension set |
Expand Down Expand Up @@ -6307,8 +6340,9 @@ over the same data. `install_clone._downgrade_refusal` compares the cloned
manifest's `version` with the installed record's after the admission gate and
before the build or `onInstall` runs. An older one is refused with code
`would_downgrade` and a sentence naming both versions, the checkout is put back the
way an admission refusal puts it back, and the update route restores the stopped
app, so the installed version keeps its tree, record and commit. The comparison is
way an admission refusal puts it back, and the app keeps running (the refusal comes
before the copy step where an update takes it down), so the installed version keeps
its tree, record and commit. The comparison is
`catalog._version_newer`, the one the store's `updateAvailable` uses: a pre-release
of the installed release is older, a re-sync of the same version passes, and a
version either side cannot read is never refused. A fresh install has no record
Expand Down
30 changes: 17 additions & 13 deletions src/kiro_crew/apps/bridges_register.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,13 +225,12 @@ def register_app(
return result

# NOTE: pruning of resources a manifest UPGRADE removed is NOT done here.
# The enable/update route handlers all deregister_app() first, so nothing
# stale survives for them to prune — a prune here (a directory walk over
# every agent file + lock acquisition, scaling with agent count) would run
# redundantly on every one of those deregister-first calls. The one path
# that re-registers WITHOUT a preceding deregister — the boot reconcile —
# does the prune itself, off the loop, in
# reconcile_enabled_app_resources(). See that function.
# Every path either deregisters first, so nothing stale survives for it to
# prune — a prune here (a directory walk over every agent file + lock
# acquisition, scaling with agent count) would run redundantly on each of
# those calls — or re-registers over kept agent specs and prunes itself, off
# the loop: the boot reconcile (reconcile_enabled_app_resources) and a
# registry update (routes_lifecycle._reinstall_from_registry).

# MCP servers BEFORE agents: _register_agents copies the app's own registered
# server specs into each agent config, so registering them afterwards leaves
Expand Down Expand Up @@ -558,21 +557,26 @@ def discard_app_session_pointers(app_name: str) -> SessionPointerCleanup:
return SessionPointerCleanup(dropped=cleared)


def deregister_app(app_name: str) -> RegistrationResult:
def deregister_app(app_name: str, *, keep_agents: bool = False) -> RegistrationResult:
"""Deregister all resources for an app.

Removes symlinks and cron manifests. Does not remove the app directory.

``keep_agents`` leaves the agent specs for a registry update that registers the
app again: registration rewrites each in place, so one it cannot rewrite keeps
its last good copy and the user's edits (app-kit-platform §3).

Does NOT touch session resume pointers — see
:func:`discard_app_session_pointers` for why that belongs to uninstall alone.
"""
result = RegistrationResult()

try:
n = _deregister_agents(app_name)
result.agents = [f"removed {n} agent(s)"]
except Exception as exc:
result.errors.append(f"agent deregistration failed: {exc}")
if not keep_agents:
try:
n = _deregister_agents(app_name)
result.agents = [f"removed {n} agent(s)"]
except Exception as exc:
result.errors.append(f"agent deregistration failed: {exc}")

try:
_deregister_skills(app_name)
Expand Down
2 changes: 2 additions & 0 deletions src/kiro_crew/apps/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,8 @@ def _holders(name: str) -> tuple[str, ...]:
_SCRIPT_TIMEOUT,
NATIVE_WINDOWS_HOOK_REFUSAL,
RESERVED_APP_NAME_CODE,
Awaitable,
Callable,
StreamingLogLines,
_adoption_pending,
_install_script_platform_refusal,
Expand Down
7 changes: 7 additions & 0 deletions src/kiro_crew/apps/registry_pipeline/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import logging
import os
import sys
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import Any

Expand Down Expand Up @@ -254,6 +255,7 @@ async def install_from_registry(
*,
resolved_entry: dict[str, Any] | None = None,
start_disabled: bool = False,
before_replace: Callable[[], Awaitable[None]] | None = None,
) -> dict[str, Any]:
"""Clone an app from its git repo and install it.

Expand Down Expand Up @@ -284,6 +286,9 @@ async def install_from_registry(
start_disabled: Create new self-managed records disabled for a caller
that performs the guarded enable separately. Managed installs already
start disabled. Existing records keep their enabled state.
before_replace: Awaited right before a managed app's files are copied in,
once every gate, the build and ``onInstall`` have passed. An update takes
the app down here; a self-managed app replaces no installed file.

Steps:
1. Validate the app exists in the trusted registry JSON
Expand Down Expand Up @@ -1483,6 +1488,8 @@ async def _roll_back_refused() -> None:
# the whole transaction (clone/build → copy → register → backend
# start); asyncio.Lock is not reentrant, so no acquisition here.
existing = get_app(name)
if before_replace is not None:
await before_replace()
# Off-loop: install_app/update_app do a blocking filesystem copy
# that can take minutes on large source trees — on the loop it
# would trip the loop-stall watchdog and kill the gateway.
Expand Down
5 changes: 5 additions & 0 deletions src/kiro_crew/apps/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,10 @@ async def _close_proxy_session(app: web.Application) -> None:
__all__ = sorted(n for n in set(globals()) | set(_EXPORTS) if not n.startswith("_"))

if TYPE_CHECKING: # every owner-defined name in _EXPORTS, for type checkers and IDEs
from kiro_crew.apps.bridges import ( # noqa: F401
_prune_stale_app_resources,
_registration_source,
)
from kiro_crew.apps.point_grants import ( # noqa: F401
point_grant_families,
)
Expand Down Expand Up @@ -345,6 +349,7 @@ async def _close_proxy_session(app: web.Application) -> None:
_redact_warning,
_refuse_while_startup_hook_runs,
_register_app_off_loop,
_reinstall_from_registry,
_restore_app_after_failed_update,
_snapshot_agent_configs_off_loop,
_start_backend_after_install,
Expand Down
41 changes: 11 additions & 30 deletions src/kiro_crew/apps/routes_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
)
from kiro_crew.apps.registry import (
git_unavailable_refusal,
install_from_registry,
is_registry_source,
registry_name_from_source,
)
Expand All @@ -42,6 +41,7 @@
_deregister_app_off_loop,
_refuse_while_startup_hook_runs,
_register_app_off_loop,
_reinstall_from_registry,
_restore_app_after_failed_update,
_snapshot_agent_configs_off_loop,
_start_backend_after_install,
Expand Down Expand Up @@ -90,25 +90,16 @@ async def handle_update_app(request: web.Request) -> web.Response:
source = body.get("source", info.get("source", ""))

# Registry-installed apps: re-clone from registry.
# Same order as the local-source branch below: stop the backend and scrub
# its resources BEFORE the files are replaced. For an already-installed
# app ``install_from_registry`` reaches ``update_app``, which renames the
# live tree aside and copies the new one in -- on Windows that fails with a
# sharing violation (WinError 32) while the backend still holds a file open
# under the tree. A failed install must not leave the app broken either:
# the failure path restores what was there (``_restore_app_after_failed_update``),
# exactly as the local-source branch does.
if is_registry_source(source):
registry_name = registry_name_from_source(source)
async with app_lifecycle_lock(name):
# Preflight BEFORE the stop so a retryable refusal leaves app state
# untouched (app-kit-platform: refusal "without mutating app state").
# Preflight so a retryable refusal is the local branch's 409, leaving app
# state untouched (app-kit-platform: refusal "without mutating app state").
# ``install_from_registry`` re-checks at its own replacement boundary.
startup_refusal = await _refuse_while_startup_hook_runs(name, action="update")
if startup_refusal is not None:
return startup_refusal
# ``install_from_registry`` asks this too, but only after the stop below
# has taken the app down; a host without git must keep the app running.
# A host without git keeps the app running and reads the missing tool.
git_refusal = git_unavailable_refusal(name)
if git_refusal is not None:
return web.json_response(
Expand All @@ -121,22 +112,8 @@ async def handle_update_app(request: web.Request) -> web.Response:
status=400,
)

# Stop the backend, then deregister old resources -- same order as
# uninstall and the disable rollback. Stopping pops the tracking record,
# so the health watch cannot re-register the OLD manifest's MCP servers
# after the scrub (see app-kit-platform §17).
await asyncio.get_running_loop().run_in_executor(
subprocess_executor(), stop_app_backend, name
)
# Deregistering deletes the agent configs that hold the user's edits.
prior_agents = await _snapshot_agent_configs_off_loop(name)
await _deregister_app_off_loop(name)

reg_install = await install_from_registry(registry_name)
reg_install = await _reinstall_from_registry(name, registry_name)
if not reg_install.get("ok"):
restore_refused = await _restore_app_after_failed_update(name, prior_agents)
if restore_refused:
reg_install["backend_refused"] = restore_refused
sel().log_api_access(
caller="dashboard",
operation="app_update",
Expand All @@ -149,8 +126,12 @@ async def handle_update_app(request: web.Request) -> web.Response:
# ``enabled`` when the new version adds ``permissions.sessionApproval``,
# and a backend started here would run an app the UI shows as disabled.
still_enabled = await _app_may_run_after_install(name)
if still_enabled:
reg_result = await _register_app_off_loop(name, prior_agents)
if not still_enabled:
# The take-down kept the agent specs for the re-registration; an app
# that may not run gets none (as on the registry install routes).
await _suspend_app_for_session_approval_reconsent(name)
else:
reg_result = await _register_app_off_loop(name)
# Same promotion as the local-source branch: the re-install
# rewrote app-crons.json, and only this call carries a changed
# cron field into the RUNNING scheduler before the next start.
Expand Down
Loading
Loading