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
41 changes: 39 additions & 2 deletions docs/system-specs/modules/app-kit-platform.md
Original file line number Diff line number Diff line change
Expand Up @@ -641,8 +641,9 @@ copy of the core file-read endpoint's binary-extension set in its own `tests/`.
Every backend app gate runs the same scanner, `test/core_app_independence.py`:
`core_app_imports` finds a core import of the app's package in any spelling, and
`core_name_strings` finds a core string naming it, minus the reasoned rows the gate
allows. The aws-control and Files gates call it with their own package and names,
and the next app to leave adds a gate that does the same, never another scanner.
allows. The aws-control, Files and Design Critique gates call it with their own
package and names, and the next app to leave adds a gate that does the same, never
another scanner.

## 0. Three-axis classification: origin, resources, lifecycle

Expand Down Expand Up @@ -4788,6 +4789,40 @@ slot another create path made first (ChatEmbed's own POST) carries neither.

Writers: `apps/worker_slots.py`. Tests: `test/test_apps_worker_slots.py`.

## 23a. A built-in's worker slot mode is a seam the built-in fills

A slot's `mode` is fixed at creation, and the chat sidebar lists only `""` slots, so an
app whose throwaway worker slots must stay off the sidebar creates them under a mode of
its own. `POST /api/chat/slots` and the auto-create on `POST /api/chat` accept only
`chat_handlers._CREATABLE_MODES`, which is `""` followed by `seams.worker_slot_modes()`
(section 30); the core spells no app's mode.

- **Registration.** A builtin's `seams.py` calls `seams.register_worker_slot_mode(app_id)`
with its own id when it is imported. A non-`str` id is refused with `ValueError`; the
loader logs that module and skips it, like any broken provider.
- **Built-ins only, in practice.** `chat_handlers` reads the seam once, at import, and
that first lookup is what loads the builtin seams modules. An installed app's
`on_startup` runs later, so it reaches no create path, and no manifest field is read.
With no builtin registering one, the create paths accept `""` alone. The mode-switch
(`chat_folders._VALID_MODES`) and fork-override allowlists stay narrower on purpose.
- **Light package.** The lookup imports the app's package `__init__`, so Design
Critique serves `register_routes` from a module `__getattr__` that imports its route
module on first access. That access is the boot route loop's guarded lookup, so an
unreadable route file is skipped like any unreadable app, not fatal.

Design Critique is held to it by `test/test_core_design_critique_decoupling.py`, which
runs the shared `test/core_app_independence.py` scans: no module under `src/kiro_crew`
outside `apps/builtins/`, and no `scripts/` file, imports the app's package or names
`design_critique` / `design-critique` in a non-docstring string. Its UI is held the
same way by `website/src/apps/design-critique/designCritiqueBoundary.test.ts`: outside that
directory only the `/design-critique` row of `apps/builtinRegistry.ts` imports from it,
and the app's backend and frontend tests live in its own directories.

Writers: `apps/seams.py`, `apps/builtins/design_critique/seams.py`.
Tests: `test/test_app_seams.py`,
`apps/builtins/design_critique/tests/test_worker_slot_mode.py`,
`apps/builtins/design_critique/tests/test_unreadable_routes_skipped.py`.

## 24. A backend's principal claim is opt-in and bound to one request

`X-KiroCrew-Proxy` proves only that the gateway forwarded a request. An app whose
Expand Down Expand Up @@ -5151,6 +5186,7 @@ this repository without core changing.
| `aws_account_policy` | `AwsAccountPolicy`: `resolve_consent_target()`, `configured_region(p)`, `is_sso_profile(p)` | `dashboard/handlers/aws_consent.py` (`s3` / `ce` cards), `dashboard/handlers/aws_project_profile.py` (the project pill) | the consent card names the CLI default chain; the pill probes in the default region and reports a failed probe as `unavailable` |
| `transfer_staging` | `TransferStaging`: `pinned_staging(prefix)` | `cloud/microvm/api.py` `staging_dir` | `RuntimeError`, never the shared temp directory |
| `stopped_loop_tombstone` | `StoppedLoopTombstone`: `keeps_stopped_loop(slot_key, app_id)` | `dashboard/session_directive_apply_monitor.py` `_keeps_stopped_loop` (the stop of a legacy autonudge loop) | the loop row is removed, as for every other legacy loop (see `knowledge.md`, "Repository boundary") |
| worker slot modes | `register_worker_slot_mode(app_id)`, one per app | `dashboard/chat_handlers.py` `_CREATABLE_MODES` (section 23a) | the chat create paths accept `""` alone |

A builtin app registers from a `seams.py` at its package root. The first lookup of any
seam imports every such module once, for each name in `BUILTIN_NAMES`, found by file so
Expand All @@ -5164,6 +5200,7 @@ an installed app's `on_startup` hook, calls `seams.register` itself.
A provider answers whether or not its app is enabled, because the core features above
worked with aws-control switched off (its default). One app holds a seam: a second app
registering it is refused with `ValueError`, so the answer cannot depend on import order.
Worker slot modes are the exception: each app registers its own id.
A broken provider module is logged and skipped. The one-time load holds its own lock,
never the registry's, so a provider module registering from another thread cannot
deadlock it; a seams module therefore only registers while it is imported, and never
Expand Down
33 changes: 30 additions & 3 deletions src/kiro_crew/apps/builtins/design_critique/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,35 @@
"""Design Critique — builtin app package marker.

The startup route loop in ``dashboard/routes/system.py`` imports this package and
checks ``hasattr(module, "register_routes")`` on the package object, so the
handler must be re-exported here.
reads ``register_routes`` off the package object, inside the guard that skips an
app whose files cannot be read.

The core's ``apps.seams`` imports this package to reach ``seams.py`` while
``dashboard.chat_handlers`` is itself being imported, so the route module (which
imports the dashboard) is not imported here. ``register_routes`` is served by the
module ``__getattr__`` below instead, which imports the route module on first access:
that access is the route loop's guarded lookup, so an unreadable route file is
skipped there like any other unreadable app.
"""

from .backend.routes import register_routes # noqa: F401
from __future__ import annotations

import importlib
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from kiro_crew.apps.builtins.design_critique.backend.routes import ( # noqa: F401
register_routes,
)

#: Each lazily served name and its owner's dotted name.
_LAZY_OWNERS: dict[str, str] = {
"register_routes": "kiro_crew.apps.builtins.design_critique.backend.routes",
}


def __getattr__(name: str) -> Any:
owner = _LAZY_OWNERS.get(name)
if owner is None:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
return getattr(importlib.import_module(owner), name)
18 changes: 18 additions & 0 deletions src/kiro_crew/apps/builtins/design_critique/seams.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Design Critique's registrations in the core's :mod:`kiro_crew.apps.seams`.

The core imports this module on its first seam lookup, which ``dashboard.chat_handlers``
makes while it is itself being imported, so it imports nothing of the app. The page's
``openSlot()`` creates its throwaway ``dc-*`` worker slots under the app's own mode, and
repeats it on every send so a slot recreated after a gateway restart keeps it. A
non-``""`` mode is what keeps those slots off the chat sidebar, which lists only plain
``""`` slots.
"""

from __future__ import annotations

from kiro_crew.apps import seams

#: The manifest name, which is also the worker slot mode.
APP_ID = "design-critique"

seams.register_worker_slot_mode(APP_ID)
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
script imports cleanly as a module (its entry point runs only when it is the
program), so the test calls the shipped function directly under ``node``.

It lives in ``test/`` rather than the app's own ``tests/``: running ``node`` is a
subprocess spawn, and ``test_spawn_audit`` holds every spawn under
``src/kiro_crew`` to the sandbox chokepoint or its allowlist.
Running ``node`` is a subprocess spawn, and ``test_spawn_audit`` holds every spawn
under ``src/kiro_crew`` to the sandbox chokepoint or its allowlist, so ``_rules`` is a
row of ``test/spawn_audit_app_spawns.py``.
"""

from __future__ import annotations
Expand All @@ -21,14 +21,9 @@

import pytest

# test/<this file> -> parents[1] is the repo root.
# tests/<this file> -> parents[1] is the app's own directory.
CAPTURE_SITE = (
Path(__file__).resolve().parents[1]
/ "src"
/ "kiro_crew"
/ "apps"
/ "builtins"
/ "design_critique"
/ "skills"
/ "design-critique"
/ "scripts"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""The local-target guard screens against the core's ONE credential dot-dir denylist.

``_DENIED_ROOT_PARTS`` must be :data:`kiro_crew.security.DENIED_ROOT_PARTS` itself —
identity, not equality — so a credential directory the core adds for any app is
denied here too. ``test/test_denied_root_parts_shared.py`` pins the owner's own shape.
"""

from __future__ import annotations

from kiro_crew.apps.builtins.design_critique.backend import routes
from kiro_crew.security import DENIED_ROOT_PARTS


def test_the_local_target_guard_consumes_the_shared_object() -> None:
# `is`, not `==`: a byte-identical local copy would pass equality while
# re-creating exactly the drift the shared owner removes.
assert routes._DENIED_ROOT_PARTS is DENIED_ROOT_PARTS
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@

import pytest

REPO_ROOT = Path(__file__).resolve().parents[1]
SCRIPTS = REPO_ROOT / "src/kiro_crew/apps/builtins/design_critique/skills/design-critique/scripts"
# tests/<this file> -> parents[1] is the app's own directory.
APP_ROOT = Path(__file__).resolve().parents[1]
SCRIPTS = APP_ROOT / "skills/design-critique/scripts"
SSRF_GUARD = SCRIPTS / "ssrf-guard.mjs"
ENSURE_PW = SCRIPTS / "ensure-playwright.mjs"

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""An unreadable Design Critique route module is skipped at boot, not fatal.

The package keeps its route module out of its ``__init__`` and serves
``register_routes`` from a module ``__getattr__``. That lookup is what the startup
route loop in ``dashboard/routes/system.py`` guards against ``OSError``, so a route
file an endpoint security agent denies is logged and skipped there, and the other
built-ins still register.
"""

from __future__ import annotations

import importlib
import logging
from types import SimpleNamespace

import pytest
from aiohttp import web

from kiro_crew.dashboard.routes import system

ROUTES = "kiro_crew.apps.builtins.design_critique.backend.routes"


def _app() -> web.Application:
app = web.Application()
app["state"] = SimpleNamespace(owner_id="owner", broadcast_ws=lambda *a, **k: None)
return app


def test_the_route_module_is_read_by_the_lookup_not_the_call(
monkeypatch: pytest.MonkeyPatch,
) -> None:
package = importlib.import_module("kiro_crew.apps.builtins.design_critique")
real_import = importlib.import_module

def _import(name: str, *args, **kwargs):
if name == ROUTES:
raise PermissionError(13, "Permission denied", "backend/routes.py")
return real_import(name, *args, **kwargs)

monkeypatch.setattr(importlib, "import_module", _import)
with pytest.raises(PermissionError):
getattr(package, "register_routes")


def test_an_unreadable_route_module_does_not_abort_route_setup(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
real_import = importlib.import_module

def _import(name: str, *args, **kwargs):
if name == ROUTES:
raise PermissionError(13, "Permission denied", "backend/routes.py")
return real_import(name, *args, **kwargs)

monkeypatch.setattr(importlib, "import_module", _import)
app = _app()
with caplog.at_level(logging.WARNING, logger=system.__name__):
system.register(app) # must not raise

warned = [r.getMessage() for r in caplog.records if "design_critique" in r.getMessage()]
assert warned and "PermissionError" in warned[0], warned
paths = {getattr(r.resource, "canonical", "") for r in app.router.routes()}
assert not any(p.startswith("/api/apps/design-critique/") for p in paths)
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""Design Critique's ``dc-*`` worker slots are created under the app's own mode.

The page's ``openSlot()`` posts ``mode: "design-critique"`` and repeats it on every
send. The core accepts it only because this app registers it from its ``seams.py``
(through ``kiro_crew.apps.seams``); a slot created without it would be a plain ``""``
chat and land in the user's chat sidebar.
"""

from __future__ import annotations

from kiro_crew.apps import seams
from kiro_crew.dashboard import chat_handlers


def test_the_app_registers_its_own_name_as_its_worker_mode() -> None:
assert "design-critique" in seams.worker_slot_modes()


def test_the_chat_create_paths_accept_it() -> None:
assert "design-critique" in chat_handlers._CREATABLE_MODES
assert chat_handlers._CREATABLE_MODES[0] == ""
40 changes: 35 additions & 5 deletions src/kiro_crew/apps/seams.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
paid-service consent cards and the composer's project pill resolve an AWS profile
through that app's account policy. The MicroVM control calls stage a secret under
the app's sandbox-masked transfer root. A stop of a legacy autonudge loop asks whether
an app reads the stopped row back. Core names each such need as a SEAM here and asks
for its provider when it runs. The app registers the provider,
and core never imports the app, so the app can leave this repository without core
changing.
an app reads the stopped row back. The chat create paths accept the slot mode an app's
throwaway worker slots are born with. Core names each such need as a SEAM here and asks
for its provider when it runs. The app registers the provider, and core never imports
the app, so the app can leave this repository without core changing.

Empty by default. A seam that no app filled answers ``None``. Each core caller's own
docstring says what it does then: degrade to a fixed answer, or refuse.
Expand All @@ -29,7 +29,9 @@
what they do.

One provider per seam. A second app that registers a seam another app already holds
is refused, because otherwise the answer would depend on import order.
is refused, because otherwise the answer would depend on import order. Worker slot
modes are the one seam every app may fill: each app registers its own, under its own
id, through :func:`register_worker_slot_mode`.
"""

from __future__ import annotations
Expand Down Expand Up @@ -118,6 +120,8 @@ def keeps_stopped_loop(self, slot_key: str, app_id: str) -> bool:
_lock = threading.Lock()
#: seam -> (app id, provider).
_providers: dict[str, tuple[str, object]] = {}
#: app id -> the worker slot mode it registered, in registration order.
_worker_slot_modes: dict[str, str] = {}
#: Serializes the one-time import of the builtin seams modules. :func:`register`
#: never takes it, so a provider module can register while it is held. A seams
#: module must therefore only register while it is imported, never look a seam up.
Expand Down Expand Up @@ -171,6 +175,32 @@ def stopped_loop_tombstone() -> StoppedLoopTombstone | None:
return cast("StoppedLoopTombstone | None", provider(SEAM_STOPPED_LOOP_TOMBSTONE))


def register_worker_slot_mode(app_id: str) -> None:
"""Let the chat create paths accept *app_id* as the mode of that app's worker slots.

A slot's ``mode`` is fixed when it is created, and the chat sidebar lists only
``""`` slots, so an app whose throwaway worker slots must stay off the sidebar
creates them under a mode of its own. Each builtin passes its own id as that mode.
Registering again is a no-op.
"""
if not isinstance(app_id, str):
raise ValueError(f"a worker slot mode must be a str, not {type(app_id).__name__}")
with _lock:
_worker_slot_modes[app_id] = app_id


def worker_slot_modes() -> tuple[str, ...]:
"""Every registered worker slot mode, builtins in ``BUILTIN_NAMES`` order.

``dashboard.chat_handlers`` reads it once, at import, so only a builtin's seams
module reaches the create paths: it is loaded by the first lookup, before any
installed app runs. Empty when no app registered one.
"""
_load_builtin_seams()
with _lock:
return tuple(_worker_slot_modes.values())


def _load_builtin_seams() -> None:
"""Import each shipped builtin's ``seams`` module, once per process.

Expand Down
14 changes: 7 additions & 7 deletions src/kiro_crew/dashboard/chat_api/chat_send.py
Original file line number Diff line number Diff line change
Expand Up @@ -672,13 +672,13 @@ async def _api_chat_send(request: web.Request) -> web.StreamResponse:
requested_memory_mode = None

# Honor mode from the body when auto-creating a slot, mirroring memory_mode
# above: an app whose worker slot lives only in gateway memory (e.g. Design
# Critique) repeats mode on send(), so a slot recreated here after a
# gateway restart keeps its non-"" surface and stays out of the chat
# sidebar's surface allowlist. Only creation-allowlisted values pass;
# anything else is dropped so get_or_create_slot uses its default. Unlike
# memory_mode there is no mismatch error: get_or_create_slot ignores mode
# for an already-existing slot.
# above: an app whose worker slot lives only in gateway memory repeats mode
# on send(), so a slot recreated here after a gateway restart keeps its
# non-"" surface and stays out of the chat sidebar's surface allowlist.
# Only creation-allowlisted values pass; anything else is dropped so
# get_or_create_slot uses its default. Unlike memory_mode there is no
# mismatch error: get_or_create_slot ignores mode for an already-existing
# slot.
requested_mode = body.get("mode")
if not isinstance(requested_mode, str) or requested_mode not in _CREATABLE_MODES:
requested_mode = ""
Expand Down
16 changes: 9 additions & 7 deletions src/kiro_crew/dashboard/chat_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from kiro_crew.agent_sdk.capabilities import MODEL_NAMESPACE_ACP, capabilities_of # noqa: F401
from kiro_crew.agent_sdk.provider_identity import is_claude_code # noqa: F401
from kiro_crew.agent_switch_command import switch_announcement # noqa: F401
from kiro_crew.apps import seams as _app_seams
from kiro_crew.atomic_write import atomic_write, read_bytes_with_retry # noqa: F401
from kiro_crew.config.loader import ( # noqa: F401
AUTOCOMPACT_PCT_MAX,
Expand Down Expand Up @@ -664,13 +665,14 @@

# Modes a slot may be CREATED with. A deliberate superset of the mode-SWITCH
# allowlist (chat_folders._VALID_MODES) and the fork override allowlist
# (chat_fork): "design-critique" is an app-worker mode assigned at birth by the
# Design Critique app's openSlot() — the custom mode keeps its throwaway dc-*
# slots off the chat sidebar, which renders only plain "" slots
# (chat/page/pageEnvironment.ts filteredSlots). Switching an existing session INTO an
# app-worker mode, or forking one with it as an override, is not a real flow, so those two
# allowlists deliberately stay narrower — do not "sync" them to this one.
_CREATABLE_MODES = ("", "design-critique")
# (chat_fork): beyond "", each entry is an app-worker mode a shipped built-in app
# registers for itself (apps/seams.py worker_slot_modes) and assigns at birth to the
# throwaway worker slots it opens — the custom mode keeps them off the chat sidebar,
# which renders only plain "" slots (chat/page/pageEnvironment.ts filteredSlots).
# Switching an existing session INTO an app-worker mode, or forking one with it as an
# override, is not a real flow, so those two allowlists deliberately stay narrower — do
# not "sync" them to this one.
_CREATABLE_MODES = ("", *_app_seams.worker_slot_modes())

# Deferral is an optimization, so a request shape added later must stay on the
# synchronous path until its publication ordering has been reviewed explicitly.
Expand Down
Loading
Loading