diff --git a/AGENTS.md b/AGENTS.md index f897c8a975b2..d915f04151d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,7 +80,7 @@ in the **same commit** when you change what it documents. | the pipeline conductor agent or its skill | [pipeline-conductor](docs/system-specs/modules/pipeline-conductor.md) | | task runner | [task](docs/system-specs/modules/task.md) + [taskrunner](docs/system-specs/modules/taskrunner.md) | | `workflows/` (the dynamic-workflow engine) | [workflows](docs/system-specs/modules/workflows.md) | -| `kas_workflows/`, `acp/workflow_sink.py` (Kiro Agent's own workflow engine) | [kas-workflows](docs/system-specs/modules/kas-workflows.md) | +| `kas_workflows/`, `acp/workflow_sink.py`, `dashboard/handlers/kas_workflows.py` (Kiro Agent's own workflow engine) | [kas-workflows](docs/system-specs/modules/kas-workflows.md) | | themes | [themes](docs/system-specs/modules/themes.md) + [theming-contract](website/docs/theming-contract.md) | | anything under `website/` | [`website/AGENTS.md`](website/AGENTS.md) | | user-facing strings, dates, numbers, sort order | [i18n-catalog](website/docs/i18n-catalog.md) (authoring) + [i18n-gates](docs/ci/i18n-gates.md) (CI) | diff --git a/config-baseline.json b/config-baseline.json index 4548c9376dee..81c2adc3bc51 100644 --- a/config-baseline.json +++ b/config-baseline.json @@ -2025,7 +2025,7 @@ "sensitive": false, "tags": [], "label": "Kiro Workflows on Kiro Agent", - "help": "Developer opt-in to Kiro Agent's (KAS) own workflow engine, off by default. This build has no surface that reads it yet, so setting it changes nothing. No effect unless the backend is Kiro Agent.", + "help": "Developer opt-in to Kiro Agent's (KAS) own workflow engine, off by default. When on, a dashboard chat's model can start Kiro Agent workflow runs, the dashboard can start, follow and answer them, and the gateway reconnects a chat's interrupted runs when it starts. No effect unless the backend is Kiro Agent.", "hasChildren": false, "enumValues": null, "defaultValue": false diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index 562e4cd12527..4c2bb37a9316 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -295,6 +295,7 @@ and the Apps group's unpinned set, to a fresh browser profile. | Steering | Always-injected steering documents | `?tab=steering` | `pages/overview/SteeringTab.tsx` | `handlers/steering.py` | `GET,POST /api/steering`, `PUT,DELETE /api/steering/{key}` | | Hooks | Event-triggered agent runs | `?tab=hooks` | `pages/HooksPage.tsx`, `pages/hookEventWireValues.ts` (internal split of HooksPage — the event names the picker offers and the rows show, no new user-facing destination), `pages/HookLaneMatcherHelp.tsx` (internal split of HooksPage — the `SessionLaneChanged` matcher grammar and its Insert a lane menu, no new user-facing destination) | `handlers/hooks.py` | `GET,POST /api/hooks`, `PUT,DELETE /api/hooks/{hook_id}`, `GET /api/kiro-hooks`, `POST /api/kiro-hooks/rescan`, `GET /api/chat/tags` | | Workflows | Saved dynamic-workflow definitions and their runs. **Remove** takes a saved workflow out of the library after a confirmation; it is a tombstone, so past runs and workflows adapted from it keep their lineage. A run's detail reads in two modes: the phase **Tree** (what happened, newest work last) and a **Graph** that draws the run's PLANNED phase graph (read off the run's own captured script source) and colours each node from the live run state (planned / running / ran ok / ran failed), marks a phase the plan could not promise runs at all, marks work that ran without being predicted, and says when the plan is partial because the preview hit its ceiling. The plan rides the run-detail snapshot and is requested only while Graph mode is open. In the Tree, a script step's row opens that step's transcript read-only beneath it (reasoning, tool calls with their status, the reply), kept in the gateway's memory only | `?tab=workflows` | `pages/overview/WorkflowLibraryTab.tsx`, `components/workflows/WorkflowsRuns.tsx` (Tree / Graph switch), `components/workflows/WorkflowStepTranscript.tsx` (a step's read-only transcript), `components/workflows/WorkflowRunGraph.tsx` (the drawing), `components/workflows/planModel.ts` (pure model: pair the plan with what ran), `pages/chat/workflowRunsPoll.ts` (internal helper: the chat side panel's runs-list poll cadence; no new user-facing feature) | `handlers/workflows.py`, `workflows/preview.py` (read the planned graph off a script's source), `workflows/step_transcripts.py` (a step's in-memory transcript), `workflows/update_from_run.py` (append a finished run as a saved workflow's next revision) | `POST /api/workflows/run`, `GET,POST /api/workflows/definitions`, `DELETE /api/workflows/definitions/{ref}`, `POST /api/workflows/author`, `GET /api/workflows/runs/{id}` (carries `plan` when `plan=1`), `GET /api/workflows/runs/{id}/agents/{agent_id}/transcript` (one step's kept transcript), `GET,POST /api/workflows/runs/{id}/update-definition` (append a finished run to a saved workflow; no dashboard control yet) | +| Kiro Workflows (Kiro Agent) | Kiro Agent's own workflow engine, behind the developer opt-in `agent.kas_workflows`: recipes, runs mirrored from Kiro Agent's notifications, step approvals and questions held for a person, run controls, and reconnect on boot and when a run's Kiro Agent process crashes. Run changes reach the dashboard as `kas_workflow_revision` frames on `/api/ws`. Off, or on another backend, every route refuses | API only in this change; the dashboard surfaces arrive with the frontend | — | `handlers/kas_workflows.py` | `GET /api/workflows/kas/state`, `GET,POST,DELETE /api/workflows/kas/recipes`, `GET /api/workflows/kas/recipes/detail`, `GET,POST /api/workflows/kas/runs`, `GET /api/workflows/kas/runs/{workflow_id}`, `POST /api/workflows/kas/runs/{workflow_id}/{action}`, `GET /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/transcript`, `POST /api/workflows/kas/approvals/{key}`, `POST /api/workflows/kas/questions/{key}`, `GET /api/workflows/kas/slots/{slot}/runs` | | Bot abilities | A Bot that owns its file shows **Comes with** (read-only: what the worker base provides) and **Added to** (what its own file adds, each stored row with **Remove**); **Add abilities** unions another agent's connections, skills, resources and auto-approvals into the file, skipping anything already present. The exception is **behavior directions**: the agent's prompt, minus any opening text the worker base already carries, replaces the file's single directions slot; an agent without directions leaves it alone, and **Remove** clears it. The worker appends the slot after its built-in instructions, and the slot records no source agent. Picking an agent previews at once (bound to the file and the agent as previewed, so an apply after either changed shows a fresh preview), listing the auto-approvals it writes | `/capabilities?tab=crews` → Bot → **Abilities** (also from the Bots page's editor; General's **View abilities**) | `components/crew/WorkerKitPane.tsx`, `components/crew/CrewEditorNextDialog.tsx` | `handlers/member_worker_kit.py` (`kiro_crew/mate_worker_kit.py`) | `GET,PUT /api/agents/{name}/worker-kit`, `POST /api/agents/{name}/worker-kit/preview` (each also as `/api/agents/b64/{name_b64}/...` for a name that needs encoding) | | Bot abilities load error | When a Bot's abilities read fails, the Abilities section shows a notice instead of the bands: a read past the 20 s gateway limit (`reason: timed_out`) or the 30 s dashboard limit names the likely causes (many added abilities, a slow or unreachable drive) and points at the gateway log, which names the Bot and how long the read took; a Bot file that no longer parses says to fix or restore that file. **Try again** reads again; **Ask the agent** hands the error to a chat through the editor's leave guard, so unsaved edits ask first. The `get_member_capabilities` guide tool reads the same view under the same limit and answers a sentence the agent can relay | `/capabilities?tab=crews` → Bot → **Abilities** when the read fails | `components/crew/CrewEditorNextDialog.tsx`, `components/crew/workerKitErrors.ts` | `handlers/_bounded_read.py` (used by `handlers/agent_capabilities.py`, `handlers/member_worker_kit.py`, `handlers/change_cards.py`) | `GET /api/agents/{name}/capabilities`, `GET /api/agents/{name}/worker-kit`, `GET /api/cards/agent/capabilities` | diff --git a/docs/system-specs/modules/README.md b/docs/system-specs/modules/README.md index 2b53b746fe5f..4cc03721f565 100644 --- a/docs/system-specs/modules/README.md +++ b/docs/system-specs/modules/README.md @@ -63,7 +63,7 @@ agent loads only the one it needs. | [task.md](task.md) | Task models and state. | | [taskrunner.md](taskrunner.md) | The execution engine that runs a task spec to completion. | | [workflows.md](workflows.md) | The dynamic-workflow engine: the frozen `ctx` contract, the event stream, budgets, and the named conformance gates with the test pinning each. | -| [kas-workflows.md](kas-workflows.md) | Kiro Workflows on Kiro Agent's own engine: the `agent.kas_workflows` gate, the run mirror, the runtime sink, which chats get the surface, the router's launch, observe and reconnect turns, step approvals and questions, which chat a run belongs to and boot recovery from Kiro Agent's run lists. | +| [kas-workflows.md](kas-workflows.md) | Kiro Workflows on Kiro Agent's own engine: the `agent.kas_workflows` gate, the run mirror, the runtime sink, which chats get the surface, the router's launch, observe and reconnect turns, step approvals and questions, which chat a run belongs to, boot recovery from Kiro Agent's run lists and the dashboard's `/api/workflows/kas/*` routes. | | [decisions.md](decisions.md) | The Jev decision seam: `decisions.enabled` as the only opt-in, session-key sampling through `decisions.bucket`, the scrub-before-send refusal, `skills.select` as the one integration that consumes an answer (with the word-overlap result as its fallback), and the basic call-metadata log. | | [crew-mode.md](crew-mode.md) | Crews: the config record, `select_crew` roster and binding, model and workspace resolution, the Crews UI, and the record of the retired `"crew"` slot mode (the old Crew Mode). | | [pipeline-conductor.md](pipeline-conductor.md) | The `kirocrew-pipeline-conductor` agent and its skill: the generated spec's permission narrowing, the three deterministic scripts, the patrol cycle, and what the RFC leaves unbuilt. | diff --git a/docs/system-specs/modules/cli.md b/docs/system-specs/modules/cli.md index 1f88839a5db4..5aab3282bb19 100644 --- a/docs/system-specs/modules/cli.md +++ b/docs/system-specs/modules/cli.md @@ -4666,6 +4666,7 @@ scope or `yolo_max_seconds` bounds it, and it is refused when an `approval_modes policy denies `yolo`. The grant is the dashboard's only (`SafetyOverride.is_cli_launch`): Slack's `is_yolo_mode` ignores it, and so does a dashboard turn a channel message started or steered, or one in a channel-linked slot (`DashboardState.yolo_reaches`), +and so does a Kiro Workflows step of such a chat (`chat_turn/kas_step_mode._kas_step_mode_reader`), and so do dashboard channel agents. Those keep asking exactly as without the flag. Other channels already auto-approve under the flag itself. That policy, and picking another mode in the dashboard, diff --git a/docs/system-specs/modules/kas-workflows.md b/docs/system-specs/modules/kas-workflows.md index 15032b71350a..e570d8e809c4 100644 --- a/docs/system-specs/modules/kas-workflows.md +++ b/docs/system-specs/modules/kas-workflows.md @@ -25,15 +25,16 @@ plus the seams in the ACP layer named below. Kiro Crew's own engine, which runs Without the turn starter nothing could answer a run's steps or read its end, so the switch turns nothing on. -The router's dashboard entry points (`router.launch_from_turn`, +The dashboard calls the router's entry points (`router.launch_from_turn`, `router.observe_from_turn`, `KasWorkflowRouter.recover_on_boot`, `router.install_turn_starter` and `router.install_dashboard_hooks`) and the chat helpers `chat.rewind_refusal`, `chat.has_kas_workflows` and `chat.AUTHOR_REDIRECT` -are the dashboard's to call, and nothing in the gateway calls them yet. So no -session starts with the workflow surface on and no step request is claimed. What -runs is the runtime sink, which folds run notifications into the mirror instead of -fanning them out to every session on the process, and the reader loop's -fail-closed answer to a step request nobody claimed. +("The dashboard", below). Its workflow startup installs the turn starter and the +dashboard hooks on every gateway, so the switch alone decides whether a dashboard +chat gets the workflow surface. With the switch off, what runs is the runtime sink, +which folds run notifications into the mirror instead of fanning them out to every +session on the process, and the reader loop's fail-closed answer to a step request +nobody claimed. ## Modules @@ -153,7 +154,8 @@ drives each run and each step session, which chat each parent ACP session belong to, each chat's approval-mode reader and session binding (both from `note_chat_session`), the held approvals and questions, and two counters every surface reads as its change key: `revision` (moved on every change a surface would -render) and `recipes_revision` (moved on `recipes_changed`). +render; each move calls `DashboardHooks.changed`, which must return at once) and +`recipes_revision` (moved on `recipes_changed`). Every run has a visible parent, the chat it belongs to: @@ -429,8 +431,11 @@ A run is undriven when the mirror holds it, it is not finished, it belongs to a A run lives in its chat's Kiro Agent process, and the idle sweep counts only the chat's own turns. The session manager's idle hold (`SessionManager.set_idle_hold`, [session.md](session.md)) is where the dashboard keeps the process of a chat whose -run is running or paused on an ask for a person; nothing installs a hold yet, so -such a chat's process still expires on `session.timeout_secs`. +run is running or paused on an ask for a person: the workflow triggers install +`kas_workflow_triggers.idle_held_sessions`, which names the chat of each run a live +process here drives that is running, or paused with an ask waiting for a person. +Such a chat's process does not expire on `session.timeout_secs`; a run paused for +any other reason, a finished one and one with no live process hold nothing. - `reattach(slot, runtime, session_id)` loads each of the chat's undriven runs on the chat's live process. A run KAS reconciled to paused with @@ -456,7 +461,8 @@ such a chat's process still expires on `session.timeout_secs`. and reconnects only the chats that crash left with no process, since a reconnect of any other chat could start a process whose stale-run sweep claims the crashed chat's run first. A teardown the gateway chose, an idle expiry included, sends no - reconnect. Nothing in this tree calls `due_reconnects` or `slots_driven_by` yet. + reconnect. The dashboard's crash listener is their caller ("The dashboard", + below). - `recover_on_boot(chat_exists, reconnect, *, folders=())` is run once at startup, after its caller waits `OWNER_ABANDON_SECS` (135 s, KAS's default stale window) plus `BOOT_RECOVERY_SLACK_SECS` (15 s). It sends the query process one @@ -479,6 +485,95 @@ such a chat's process still expires on `session.timeout_secs`. window, KAS refuses another process's resume of the run, the chat's reconnect included. +## The dashboard + +`src/kiro_crew/dashboard/handlers/kas_workflows.py` serves `/api/workflows/kas/*` +(the feature map's Kiro Workflows row lists every route) and is the router's caller; +turn admission (`src/kiro_crew/dashboard/chat_turn/turn_admission.py`) wires a +chat's turns to it. + +- Every route is the dashboard owner's, and an app token is refused (403). Unless + the gate holds, every route answers 409 `engine_not_kas`, with one exception: on a + Kiro Agent backend whose router still holds a run, the reads (the state, a run, a + project's runs, a chat's runs, a step transcript) and Stop stay open, so a run the + switch went off under can still be watched and stopped. A project directory a + request names is confined first ("Reads and controls"), off the event loop like a + recipe directory's check, a launch runs in its + chat's own project, every answer passes the dashboard's recursive redaction, and + the module is a registered redaction sink. +- A launch (`POST /api/workflows/kas/runs`) names an open chat. The route registers + the pending launch (`prepare_launch`), queues the launch marker as that chat's next + turn and answers 202; the run starts on the chat's own session when that turn runs. + Before it queues, it loads the chat's transcript window off the loop + (`load_window_off_loop`) and answers 400 `invalid_slot` if the chat closed + meanwhile. The observe starter loads it the same way: for a chat restored at + gateway start the observe turn is queued once the window is loaded, after the + same closed and busy checks, and its token is dropped when it does not start. + Turn admission knows a launch, reconnect or observe marker only as the whole + prompt, so a marker queued behind a busy turn drains alone (`DRAINS_ALONE_META`), + never merged with another queued message, whatever + `dashboard.merge_queued_messages` says. +- Turn admission names each Kiro Agent chat turn's session to the router + (`note_chat_session`, with the chat's approval-mode reader) before the turn can + start a run, so a launched run and one the model starts both find their chat. The + launch and reconnect markers are answered by `launch_from_turn` and the observe + marker by `observe_from_turn`, with no model prompt; an ordinary turn schedules + `schedule_reattach` while the switch is on. In a chat's own turn a KAS plan handoff waits on the person's + card in every approval mode, for the person window rather than the approval + window, and a steer sent during an observe turn is queued as the chat's next turn. +- `GET .../runs/{workflow_id}/steps/{node_id}/transcript` serves `step_transcript` + ("Step transcript", above): the router's kept copy of the step's conversation, + `?path=` naming one iteration of a loop's step. The route reads no file; a step + that has not started answers 404 `step_unknown`. Its answer carries the step's + model reading (`model`, `effort`, `defaultEffort`, `modelOptions`, + `effortOptions`), which the step composer's model picker shows and offers. +- `POST .../runs/{workflow_id}/steps/{node_id}/model` (`{model?, effort?, path?}`) + serves `set_step_model` ("Reads and controls", above) and answers the model and + effort now in force. A body with neither field, or with a field that is not a + string of at most 200 characters (a blank model included), answers 400 + `invalid_model`; an empty effort picks the model's default level. A step that has + not started answers 404 `step_unknown`, a refusal 409 `kas_workflow_error`. It is + a control, so with the switch off it is refused even while a run is held. +- `GET .../slots/{slot}/runs` serves `chat_runs`, which asks Kiro Agent on a live + process, spawning the query process when none is up ("Reads and controls", + above). `GET .../state` serves the mirror's rows, the held approvals and questions + and both revisions, starting no process. + The dashboard's `changed` hook pushes each move of `revision` to the owner's + sockets as a coalesced `kas_workflow_revision` frame on `/api/ws`, so a client + reads the routes again on the frame (`dashboard/kas_workflow_triggers.py`, + [learn-cron-dashboard.md](learn-cron-dashboard.md)). + No read sends a turn or decides a held approval. `POST .../slots/{slot}/reconnect` + sends a chat its reconnect turn at once and resets its automatic tries. Every + reconnect turn (this route, the crash pass, boot recovery) goes through + `_send_reconnect`, which loads a chat's transcript window off the loop first + (`load_window_off_loop`), since a chat restored at gateway start has not read it. + The crash pass and boot recovery load it before they check whether the chat is + busy or the gateway is stopping, so a turn the person starts during the read is + seen and gets no reconnect turn queued behind it. +- When a Kiro Agent process crashes (`runtime_death.subscribe`, a death whose + `expected` is False), the dashboard waits `EXIT_RECONNECT_WAIT_SECS` (45 s: KAS's + 30 s claim on the dead process's runs plus 15 s) and sends a reconnect turn to + each chat whose runs that process drove (`slots_driven_by`) and that + `due_reconnects(only=...)` names (`kas_workflow_triggers.reconnect_after_process_exit`), + after waiting up to `BOOT_RECOVERY_TURN_SECS` for a chat's running turn; a chat + still busy is left to its next ordinary turn. A crash inside the wait moves the one + pass to the same delay after it. A teardown the gateway chose, an idle expiry + included, sends nothing, nor does anything while the gateway stops or with the + switch off. +- A chat's approval-mode change (`POST /api/chat/mode`, and the approval card's + Trust, Trust reads and YOLO presses) re-decides the held step approvals under the + new mode (`recheck_pending`, through `kas_workflow_triggers.recheck_step_approvals`) + before the route answers. +- At startup the dashboard starts `start_kas_boot_recovery` once per process. + `recover_runs_on_boot` reads the gate, waits `OWNER_ABANDON_SECS` plus + `BOOT_RECOVERY_SLACK_SECS`, reads the gate again, and calls `recover_on_boot` with + an open chat as *chat_exists* and the open chats' project folders as *folders*. A + chat busy with a turn gets no extra one: that turn reattaches its runs. +- The rewind, edit-resend and regenerate routes refuse with the rewind guard's 409 + (below) before they change anything, and Kiro Crew's own workflow authoring routes + refuse a chat whose model holds KAS's `run_workflow` (409 `kas_workflows_in_chat`, + `chat.AUTHOR_REDIRECT`). + ## Rewind guard `chat.rewind_refusal(slot, message_ts)` answers the 409 body @@ -523,5 +618,10 @@ The `test/test_kas_workflows_*.py` files pin this module, with `test/kas_workflow_helpers.py` as their shared harness; `test/test_acp_observe_turn.py` and `test/test_acp_session_provider_observe.py` pin the observed turn, and `test/test_kas_workflow_markers.py` the channel echo lines. +`test/test_chat_runner_kas_observe.py` and `test/test_kas_slot_needs_person.py` pin +the dashboard's chat-turn wiring and its sidebar flag. `test/test_kas_workflows_live_capture.py` folds the recorded run `test/fixtures/acp_frames/kas/workflow-run-live.jsonl` through the mirror. +`scripts/capture_kas_workflow.py` records a fresh capture from the engine the +installed `kiro-cli acp --agent-engine v3` runs, and writes that engine's version into +the capture's header. diff --git a/docs/system-specs/modules/learn-cron-dashboard.md b/docs/system-specs/modules/learn-cron-dashboard.md index 3daf09d96855..1eff8d02eccd 100644 --- a/docs/system-specs/modules/learn-cron-dashboard.md +++ b/docs/system-specs/modules/learn-cron-dashboard.md @@ -2869,7 +2869,8 @@ specified compatibility change. colour; - `session_relaunch` — reload (`reload_slot_session`), workspace and project; - `slot_approval` — the approval-mode change (`api_chat_mode` and its core - `apply_approval_mode`), the approve route, and the caller gates both run; + `apply_approval_mode`, which re-decides held Kiro Workflows step approvals + after a successful change), the approve route, and the caller gates both run; - `followup_card` — the follow-up card route; - `project_lists` — the recent and favourite project lists; - `pending_context` — the pending-context route, with the validators and the @@ -2938,6 +2939,7 @@ specified compatibility change. appended to the `compose(...)` call at the end of the file; the contract test's `_OWNER_MODULES` finds it by scanning `chat_api/`. - `ws.py` — WebSocket endpoint at `/api/ws`. Single multiplexed connection for all real-time events. Pushes dashboard status every 5s, current slots on connect, log ring buffer replay on subscribe. The connect snapshot comes from `slot_list_pass.shared_slot_list`, which `GET /api/chat/slots` uses too, coalesced per audience (`include_check_status`, `dashboard_user`, and whether the caller's redaction stands down, `redaction_switch.bypassed_in`, so the owner's list with redaction off is never handed to another reader; a pass for any other audience runs its credential passes in full, since a trailing pass runs in its first caller's context) on a leading and a trailing edge: a caller that finds no pass of its audience within the window after the last one serializes at once, and a caller inside that window joins the trailing pass, which runs once a window has gone by with no caller joining it and at most `PASS_WINDOW_MAX_S` (2s) after its first caller. The window is `PASS_WINDOW_PASSES` (3) times the last pass's duration, within `PASS_WINDOW_MIN_S` (20ms) and `PASS_WINDOW_MAX_S`, so a cheap list makes no caller wait noticeably. A browser holds one WebSocket per host in its opening handshake at a time, so a reconnect storm's tabs arrive one handshake apart; the loop answers those handshakes while the trailing pass waits, so the storm's connects and GETs cost a few `serialize_slots` passes instead of one each, and no caller receives a list taken before it asked. A state the pass table cannot key (no weak reference to it, or no hash) shares no pass: each caller serializes at once. The socket registers right after its handshake, before it awaits the pass, because the tab sends its catch-up reads (notifications, approvals, questions, workflow runs, the open transcript) as soon as the socket opens, and a change made after one of them is answered reaches the tab only as a frame. Until the snapshot is queued, the hub holds every frame for that socket (`ws_snapshot_hold`, read by `_spawn_ws_send` and the owner sends, binary included), and the connect starts their sends in order right behind the snapshot's, so the snapshot stays the first frame; a connect whose snapshot failed still gets them. What a socket holds counts against `WS_HARD_MAX_BUFFERED_BYTES` and `WS_HELD_MAX_FRAMES`, and each released frame passes the hub's stall check right before it is written, so a socket that would pass the ceiling while held, or passes it at the release, is dropped (the slow-client rule above). A held slot list or patch (`slots`, `slots_diff`, `slot_patch`, told by the frame's `{"type": "slots", `, `{"type": "slots_diff", ` or `{"type": "slot_patch", ` start) is older than the snapshot's whole list, and sent behind it would remove a row the snapshot added from the tab, whose slot-storage sweep then deletes that row's shared panel and scroll state for good; a held removal patch for a session closed and resumed while the connect waited would likewise remove the live session and evict its background chat state. `ws_snapshot_hold.drop_superseded_slot_frames` therefore discards them before the release (an awaited owner send of one is handed a finished send, so it counts as superseded, not as a hang); the connect then resets the socket's `SLOT_DIFF_SEQ_KEY`, so a delta never names a base the tab did not receive, and calls `push_slots_update()`, whose coalesced list settles the socket on the current rows in case a dropped frame was newer than the pass. Every other held frame is a change and follows the snapshot in order. An awaited owner send (`deliver_ws_owners`, `deliver_ws_owners_bytes`) waits for the send the release starts for its held frame and counts only once that send completes, so a tab that drops before its snapshot is not a delivery: `WS_OWNER_SEND_MAX_S` bounds the whole wait, held time included, and the `WS_OWNER_SEND_TIMEOUT_S` stall window starts only at the release, since nothing reaches the buffer while the frame is held. A socket removed from the registry while still held (a connect cancelled during the shared pass) discards its held frames and ends those waits as sends to a closed socket (`ws_snapshot_hold.drop_held`, called by `_remove_ws`). The hold ends before the snapshot drains, so a tab that stops reading still fills the buffer the stall check reads and is dropped as before. A trailing pass's list and rows are shared, so a reader copies before it changes them. A pass is a `SlotPass`: its rows plus the hold flags (`slotsPartial`, `slotsHeldKeys`, `slotsHoldChannels`) read in the same synchronous section that took them, and the connect snapshot sends those captured values, never the state's flags after the await, because a restore that finished while the connect waited would otherwise label rows taken mid-restore as complete and the client would drain every session they omit (`shared_slot_pass`; `shared_slot_list` returns only the rows, for `GET /api/chat/slots`). An app socket's scopes are resolved at connect, but the snapshot is filtered and its envelope extras (`yolo`) built with `effective_allowed_events` applied AFTER the pass wait, so an app disabled during the wait gets neither another session's metadata nor the security posture; `ws["_allowed_events"]` stays the connect-time set the hub intersects live. The socket is a `ws_heartbeat.LagTolerantWebSocketResponse` with a 30s heartbeat: when aiohttp's PONG timeout runs more than `PONG_LATE_TOLERANCE_S` (1s) past its deadline, or after data arrived whose heartbeat reset is still queued, it starts the 15s window again instead of closing, because a loop stall past the deadline would otherwise close (1006) a peer whose PONG was already in the kernel; a peer that sends nothing is still closed when a window ends on time. Each socket's open and close write one INFO line through `ws_close_log`, written while the `kiro_crew` level gate is at WARNING (the `agent.log_level` default) or below, so a default gateway log carries it: the socket's id, its client (`dashboard` or the app's name), the close code (the one the gateway sent when it closed the socket itself, 1006 when no close frame was exchanged, as for a hub drop), the side that ended it (`peer`, `heartbeat`, `server` for a hub drop or a revoked person's socket, `shutdown`, or `exception `), its age and the sockets still open, never the token or the query string. Open and close lines share `LINES_PER_MINUTE` (20) a minute; the next is one summary line and the rest of that minute writes nothing. The browser half is the `[pane] ws-close` line `handleClose` writes (code, reason, `wasClean`, the classified kind, the socket's age), which the desktop app copies into gateway-launch.log. Tests: `test/test_slot_list_pass.py`, `test/test_ws_snapshot_hold.py`, `test/test_ws_snapshot_hold_ceiling.py`, `test/test_ws_heartbeat_loop_lag.py`, `test/test_ws_app_scope_after_shared_pass.py`, `test/test_ws_snapshot_hold_flags_with_shared_pass.py`, `test/test_dashboard_ws_close_log.py`, `website/src/test/useWebSocket.closeLog.test.ts`. The lesson/cron counts in the status snapshot refresh only every 30s (`_WS_COUNTS_CACHE_TTL`) through ONE gateway-wide cache in `status_counts.py` (`_refresh_status_counts`, single-flight — one store touch per TTL no matter how many sockets are open) and are computed OFF the event loop by `_load_status_counts` (`asyncio.to_thread` for both `DashboardState._count_lessons` — the JSONL half plus a vector-store SQL `COUNT(*)`, the same total `/api/status`/SSE report, fixing the JSONL-only false zero of #7204 — and `CronService.count_enabled_from_disk`), so slow/large/NFS home-dir latency cannot stall the loop and starve every other WebSocket/coroutine. The `background_turns` field leaves the loop the same way: until the first unattended turn sizes the cap's semaphore, its cap is a `config.json` read (`effective_max_background_turns`), so the shared `cached_status_snapshot` funnel that all three status emitters use takes `background_turn_stats` in a worker and hands it to `status_snapshot`. Each count is guarded independently: a component that has never refreshed successfully is published as `null` (= unknown, rendered as a loading skeleton), never an authoritative 0; failures retry on the next ~5s tick until 6 consecutive, then back off to the TTL cadence with one rate-limited operator-visible warning. It deliberately uses `count_enabled_from_disk` (a pure read) rather than `list_jobs`, whose off-thread `_arm_timer` would raise `RuntimeError` and silently cancel all cron timers (see cron spec § Enabled Predicate & Off-Thread Count). Server→Client: `{"type": "dashboard|slots|slots_diff|slot_title|slot_patch|notification|refresh|chat_message|chat_chunk|chat_done|chat_phase|tool_status|chunk_watch_ack|log|refine|sessions_restarting|slot_clear|slot_agent_switch|slot_read|session_projection|slot_projection", "data": {...}}`. A new owner socket also gets a one-shot `slot_projection/subscribed` `{"revisions": {slot: {fold: revision}}}` floor on connect, when a crew-log publisher has pushed anything (see [crew-log-projection.md](crew-log-projection.md)). **Slot patches**: a dashboard-user socket that connects with `?caps=slot_patch` (`SLOT_PATCH_CAPABILITY`, recorded as `SLOT_PATCH_WS_FLAG` on the socket) receives `slot_patch` `{"slots": [{"key", : ...}], "removed": [key]?}` for a pin, rename, single-session folder move or close, or a sub-agent count change, instead of the full `slots` list. `DashboardState.push_slot_patch(key, fields)` projects the named fields from the dashboard-user view of that one slot, and `push_slot_removed(key)` announces a close and re-states the `parent` of every row the close MOVED -- a row whose key went null, and a row re-parented onto an open ancestor, which carries `ancestor: true` and a live key, so the test is not "key is null". `slot_patch` also carries the debounced sub-agent counts: `DashboardState.push_subagent_patch()` (scheduled on lifecycle events such as spawn/done/`subagent_queued`, never idle ticks) is stateless: every flush re-states `subagents_running`/`subagents_queued` for every live slot not under construction in one patch, and requests the `legacy_only` full list when a legacy/SSE audience exists. Repeated counts are idempotent and self-healing: the next lifecycle flush corrects intermediate connect snapshots and retries lists dropped by full SSE queues, without assuming a broadcast reached every consumer. The client reconciles the queued count from every such patch row (`reconcileSubagentQueuedFromSlots`). `slot_patch` also carries session-tree changes: on each `TreeAdvanced` event, coalesced by `CrewLogPublisher`, `DashboardState.push_lineage_patch()` sends `parent` and `lineage_pending` for the rows whose values moved, and sends nothing when none did. Every other consumer (SSE readers, app tokens, sockets that did not declare the capability, such as a tab whose bundle predates the frame) receives the full list through `push_slots_update(legacy_only=True)`, which skips capable sockets and serializes nothing when no such consumer is connected; an ordinary `push_slots_update()` coalesced into the same window widens the broadcast back to every socket. Filing into a folder that changes the folder tree still sends the full list. **Slot list deltas**: a dashboard-user socket that also declares `slot_diff.1` (`SLOT_DIFF_CAPABILITY`, recorded as `SLOT_DIFF_WS_FLAG`, set only when `SLOT_PATCH_WS_FLAG` is) receives each coalesced list from `state_parts/slots_diff.py` instead of the generic and owner fan-outs. Each audience view (owner, other dashboard user) keeps one base, the list it was last sent, numbered from one per-process counter. A socket that holds the view's current base gets `slots_diff` `{"base", "rows": [{"key", "row"}], "removed": [key], "envelope": {field: value}, "seq"}`: the whole changed rows, the rows that left and the envelope fields whose value moved. Any other socket, and every socket when the list gained or reordered a row, an envelope field appeared or went away, or the delta would be over half the full frame, gets the full `slots` frame plus `slotsSeq`. A list with no change is still sent as an empty delta. The client rebuilds the list from the one it holds and hands it to the full-frame handler; a delta whose `base` it does not hold sends `slots_resync` once and ignores deltas until a numbered list arrives. `slots_resync` from a diff socket is answered with the view's held base, as one sequenced full frame to that socket alone; only when no base exists does it fall back to `push_slots_update()`. A resync from any other socket is ignored. While a diff socket is open, each slots pass serializes a row once and builds every frame it sends (generic, owner, diff) from those texts; without one it dumps whole lists as before. The pass runs on the serving loop: an off-loop caller hops there, so sequence numbers are loop-only. User-view diff sends pass `_ws_client_allowed`, which records the grant. `FULL_FRAME_REASONS` counts the full frames sent to diff sockets by reason (`no_base`, `rows_added_or_moved`, `envelope_keys`, `over_share`). `KIROCREW_WS_DISABLED_CAPS` (comma-separated, read per connect) makes the gateway ignore the named capabilities, the rollback lever for `slot_diff.1`. This is the snapshot-versus-delta question [rfc-fold-delta-push.md](../../request-for-change/rfc-fold-delta-push.md) sections 2.1 and 4 answered for folds. **Stream scoping**: a dashboard-user socket that connects with `?caps=chunk_scope.1` (`ws_chunk_scope.CHUNK_SCOPE_CAPABILITY`) receives the four stream frames, `chat_chunk`, `chat_thinking`, `tool_call` and `tool_result`, only for the slots its tab names in `{"type": "chunk_watch", "slots": [...]}`. Each `chunk_watch` replaces the socket's set; the gateway keeps at most 64 printable keys of at most 256 characters. A capable socket gets every frame until its first `chunk_watch`, so nothing is held back before the tab names what it shows. For a slot it does not watch, `ws_chunk_scope.UnwatchedFrames` sends one `chat_phase` `{"slot", "phase": "streaming"|"thinking"}` per phase change instead of each chunk; one `tool_status` per tool call with the status-line fields and a shrunk `input_preview`; one `tool_status` `{"slot", "tool_call_id", "returned": true}` per final result, carrying `output` only for a spawn launch or an answered question; and the slot's reasoning, which is never persisted, held back and sent as one `chat_thinking` frame before that slot's next frame, past 16 KB, or when the slot joins the set. A refinement of a call whose result already went out is dropped until `chat_done`. Each coarse frame is encoded once per fan-out, and its grant is audited under the delivered type. Every other frame (`slots`, `slot_patch`, `chat_message`, `chat_status`, `chat_done`, ...) reaches every socket. The gateway answers each `chunk_watch` with `chunk_watch_ack` `{"slots", "catchup"}`; `catchup` names the newly watched slots whose turn is live (`running` or `linked_turn_running`), and the new set takes effect before the ack is queued, so a transcript re-read started on the ack overlaps every chunk that follows. App-token sockets, cap-less sockets and older bundles get every frame as before, and `KIROCREW_WS_DISABLED_CAPS=chunk_scope.1` makes the gateway treat the capability as undeclared. **Partial slot lists**: the dashboard-user `slots` frame (`_slots_ws_frame`) and the connect snapshot carry up to three hold fields, set by `DashboardState` from `state_parts/slot_list_hold.py`, that tell a client which absent rows it must not treat as deleted. `slotsPartial` (boolean) is `true` while a restart is still discovering the slot set: `begin_slot_list_rebuild` sets it before the boot restore, and it clears only once no hold cause remains (an unreadable open-tab registry, a dropped tab or a deferred crewmate thread still absent, channel sessions not yet safe to drain, or no complete channel pass) or `_SLOT_LIST_PARTIAL_DEADLINE_S` (600s) after the rebuild began, with a logged warning; a suspended push never clears it. While it is `true` the client drains no unread entry, evicts no per-slot chat state and counts no absent row in a badge. `slotsHeldKeys` (string array) names known absent keys that stay held even after the label clears: dropped tabs the restore reported and that are still absent or under construction, and the crewmate threads it deferred that are still in the reopen seed (minus those deleted from History since, `release_deleted_slot_keys`), plus the incomplete channel sessions of the latest channel pass. `slotsHoldChannels` (boolean) holds every channel-origin key until the first channel discovery pass returns, and after any pass that cannot name all channel sessions. Per-key holds have no expiry. An app-token `slots` broadcast carries none of them; the connect snapshot sends `slotsPartial` to every socket, app tokens and `false` included, and the other two only to the dashboard user. A false or empty field may be omitted (`_slots_ws_frame` sends each only when set), and an absent field reads as false or empty, so a frame from an older gateway is complete with nothing held. The client reads all three through one helper, `slotListHoldTest` in `website/src/utils/slotListHold.ts`. Client→Server: `{"type": "subscribe_logs|unsubscribe_logs|slot_focused|slot_read|slots_resync"}`. `slot_read` (`{"type": "slot_read", "slot": "", "read_ts": ""?}`) is the unread-badge read report: an owner window sends it when the user reads a slot there, and the gateway stores it and rebroadcasts it to owner-authorized sockets only (`_handle_slot_read` — owner-gated like `slot_focused`, non-owner frames ignored — denies leave SEL records, grants deliberately do not, because the owner gate admits only the dashboard user's own sockets and a grant is never a cross-boundary decision; slot key validated as a non-empty ≤512-char string with deliberately NO liveness check, so a just-deleted slot still clears stale badges; `read_ts` is the ≤64-char watermark: the newest row time the reader had shown. `slot_read_state` keeps the newest parseable one per slot in `chat_read_state.json` in the fenced `pinned-order` directory (`{"epoch", "reads"}`, one coalesced atomic owner-only write per second, read after the listener is up beside the session orders; writes run one at a time, each taking its snapshot when it starts, so an older snapshot never lands over a newer one; a read that lands while a write runs gets another write, and a failed write stays pending for the next read) and the broadcast carries the stored time only once the disk holds it, so the echo is the sender's acknowledgement that the read survives a restart and an older or resent read never moves it back; a frame with no usable `read_ts` relays at once; receivers keep badges lit by newer messages). Every slot row carries it as `last_read_ts` and the store's `epoch` (when the file was first created) as `read_epoch`, both person-only like the order fields (`PIN_ORDER_FIELDS`). `last_read_ts` is the slot's written read or `null`, never the epoch; `read_epoch` is the written epoch, and `null` until the file has been read and its epoch is on disk; a load whose first write failed publishes no epoch and retries that write when it runs again. After each slot list the dashboard (`hooks/websocket/serverReads.ts`) clears a badge a real read covers (`last_read_ts`, a kept read, or a row this window showed, or a read another device relayed before its write landed; never `read_epoch`, which proves nothing was read) and badges a slot not on screen whose candidate time is newer than both that read and `read_epoch`. The candidate is the row's `unread_ts`: a crewmate thread's assistant reply, or its prompt while it waits on the user; a terminal failure (`unread_failed`) badges even a muted session once the app mutes are known, and a muted session badges nothing else; under unread-on-attention a running turn that is not waiting badges nothing, and an idle chat badges on its turn's last agent row (`last_agent_ts`) or its terminal failure, so a message that arrived while no window was open, or a read made on another device, is right from the first list, and an upgrade marks nothing older unread without clearing a badge a window restored. A `slot_patch` runs no read pass, because its rows keep an older list's read and agent times. A read the gateway has not confirmed stays in the browser's `mc-read-outbox` (`lib/readOutbox.ts`, survives a reload), counts as read there, and is sent again once on each new socket (`resendKeptReads`), until a `slot_read` echo or a row's `last_read_ts` covers it. A manual mark-as-unread is deliberately tab-lifetime: the sentinel lives in that window's sessionStorage, never in shared state — a shared copy would surface one window's private reminder in every sibling — so it does not survive tab close and no other window's read can clear it. `slot_focused` (`{"type": "slot_focused", "slot": ""|null}`) is the resume-prefetch intent signal: focusing a slot whose session is persisted but not live schedules a speculative `session/load` (`schedule_eager_spawn(allow_resume=True, focus_resume=True)` → `get_or_create(speculative=True, speculative_resume=True, focus_resume=True)`; `focus_resume` changes no queue and marks the load as one the owner is about to wait on, so it does not wait for the user's MCP servers: [acp-client](acp-client.md) § Which servers the first prompt waits for), overlapping the multi-second transcript replay with the user reading that history; `slot: null` means blur (tab hidden). An owner's frame naming a slot also starts a due re-walk of that slot's skill scope ahead of its next session-start prompt build (`dashboard/skill_read_ahead.read_ahead`, on a worker thread; the rule and its bounds are in [memory-skills-hooks](memory-skills-hooks.md)). Before anything spawns, `_eager_spawn` asks the shared `resume_takes_tool_search_replay` (`agent_sdk/tool_search.py`; providers.md → Native-resume compatibility) with the backend the factory selects for the key and no channel identity: a direct dashboard kiro-cli slot with Tool Search on would have its load replaced by a fresh session plus replay, so the speculative load could only come back `resumed=False` and be refused after a full runtime spawn and teardown — that slot is left to its first turn with the log reason `left to first turn (tool-search replay)`, and the first turn takes the fresh-session path it always takes. The handler tracks the prefetch task per connection and cancels it on every focus change, blur, and disconnect — rapid tab flipping settles into at most one pending prefetch per socket, and only the task this path armed is ever cancelled, never one from the slot-create/project-set signals, and a reload's respawn pending for the slot (a resume start armed with `on_ended`, `_eager_spawn_reported_resume`) is kept rather than re-armed: re-arming would cancel that load and restart it at the debounce, dropping the priority it was armed at and the row its reload posts when it ends. Another window's pending focus prefetch is re-armed as before, so the window now focused tracks it and the other window's blur cannot cancel it. A prefetched session no real turn claims is torn down by a TTL (`_RESUME_PREFETCH_TTL_SECS`, 600s) via `SessionManager.remove_if_unclaimed`, releasing kiro-cli's native per-session lock instead of waiting out the idle sweep. Live-but-unclaimed speculative sessions — fresh and resumed alike — are additionally capped by a HOST-DERIVED allowance, `resource_status.prewarm_allowance()`: the fixed ceiling `PREWARM_MAX_LIVE` (3) on an ample host, one session in the tight band (available memory at or under `_DEFAULT_PRESSURE_GB`), none in the critical band (at or under `_DEFAULT_CRITICAL_GB`), and the fixed ceiling again when the probe cannot read memory (never worse than before); and, at ADMISSION only, none while the subagent gate's macOS kernel memory-pressure hold applies (`chat_turn.eager_spawn._pressure_hold_blocks_prewarm` → `SubagentManager.memory_pressure_hold_active()`: the floor on, the kernel at WARN or worse and a dedicated subagent of this gateway running), because a speculative runtime must not take the memory held starts wait for; the idle pre-warms already live are not evicted for it, and the re-probe after registration does not read the hold. The allowance is applied as ADMISSION before the spawn (`_admit_prefetch`: a zero allowance skips the spawn outright and the first message cold-starts; otherwise the oldest still-unclaimed sessions are evicted first so the population never overshoots during the handshake; the probe runs via `asyncio.to_thread` because it reads procfs; eviction is bounded by the arm generation current when the admitting slot signal arrived, so an admission delayed past a CONCURRENT signal's registration — the worker-thread probe can be held that long under Windows scheduling — refuses instead of evicting the session that signal spawned moments ago and spawning a second one, while a genuinely later signal still outranks and evicts older registrations) and again as EVICTION after registration (`_cap_armed_prefetches(cap=allowance)`) for an allowance that shrank while the handshake ran. Every eviction is the conditional `remove_if_unclaimed`; a claimed session is never touched, so sequential slot signals cannot stack one idle agent process per tab. `sessions_restarting` event pushed by `_reset_all_sessions()` with `{"status": "restarting"|"ready"}` so the frontend knows when sessions are being recycled. Each provider shutdown is bounded by `_SHUTDOWN_TIMEOUT_SECS` (10s) via `asyncio.wait_for`; on timeout, `_sync_kill_provider` force-kills the process tree to prevent leaks (see `docs/architecture/resource-protection.md`). `slot_clear` pushed on `/clear` (frontend clears messages for active slot). `slot_agent_switch` pushed on `/agent` switch (frontend re-fetches slots for updated agent label). Uses `asyncio.ensure_future(ws.send_str())` because aiohttp 3.13's `send_str()` is a coroutine. **Security**: `origin.check_ws_origin()` validates the `Origin` header before accepting the upgrade — rejects missing or cross-origin requests (allowed: `127.0.0.1`, `localhost`, `kirocrew.localhost`). A dashboard session that is neither the owner nor an admitted teammate is then refused 403 `owner_only` before the upgrade (`require_owner_for_dashboard_caller`), so it gets no snapshot and no frames; an app token keeps its manifest scope. +- `kas_workflow_triggers.py` — what the dashboard does for Kiro Workflows (`agent.kas_workflows`) without a request. The router's `revision` is a property whose every move calls the dashboard's `changed` hook (`kas_workflows/router_base.DashboardHooks`), and `revision_publisher` pushes it to owner sockets only (`broadcast_ws_owners`) as `kas_workflow_revision` `{"revision": }`, coalesced on a leading and a trailing edge over `REVISION_PUSH_WINDOW_SECS` (250 ms): a move after a quiet window is sent at once, later moves inside the window become one trailing frame with the latest value. The frame is classified in `ws_event_scope._OWNER_ONLY_EVENTS`, so an app token's denial is audited as `owner_only`. A client re-reads `GET /api/workflows/kas/state` on it; the frame carries no run data. `install_kas_workflow_triggers` (from `server_runtime/workflow_startup._kick_workflow_initialization`) gives the router these hooks with the bell notes and marker rows of `router.dashboard_hooks`, and `uninstall_kas_workflow_triggers` (from `_workflow_shutdown`) removes them. `recheck_step_approvals` re-decides the step approvals the router holds under their chats' current mode (`KasWorkflowRouter.recheck_pending`, which skips every approval whose chat's mode did not change); `slot_approval.apply_approval_mode` awaits it after a successful mode change, the approve route after a card's Trust or YOLO press, and the waiting turn (`chat_turn/permission_prompt`) after a Trust-reads press. It decides nothing while `agent.kas_workflows` is off (`kas_workflows.chat.chat_workflows_enabled`), reads no config when nothing is held, and never raises. A Kiro Agent process crash reconnects interrupted runs: the triggers subscribe to `runtime_death` (`subscribe`), and each announced death with `expected` False of a process that drove a run arms one `reconnect_after_process_exit` pass `EXIT_RECONNECT_WAIT_SECS` (45 s) later for the chats of the runs that process drove (`KasWorkflowRouter.slots_driven_by`, read at the death), because KAS refuses to load a dead process's run while its `run.claim` holds (one beat interval, 30 s on the pinned engine) and the wait adds the boot pass's 15 s slack. Only those chats are reconnected: a process started for another chat's reconnect in the same project would claim their runs in KAS's stale-run sweep, and KAS would then refuse their own chat's reconnect while that process holds them. A crash inside the wait moves the pass to the same delay after it, with the chats of both crashes, so one pass serves every chat the crashes left without a process, and the uninstall drops a pass not yet started. A teardown the gateway chose itself (`expected` True: an idle expiry, a reset, a recycle) sends no reconnect, so a chat holding a paused run does not get a reconnect turn and a new process at every idle expiry; its next ordinary turn reattaches what the teardown stopped. The pass sends nothing while the gateway is stopping, with no router, or with `agent.kas_workflows` off; otherwise it sends the reconnect turn (`handlers/kas_workflows._send_reconnect`) to each of the pass's chats that `due_reconnects(only=...)` names, which keeps the router's interval and try bounds and marks no other chat tried. A chat whose turn is running is waited for, up to `BOOT_RECOVERY_TURN_SECS`, because that turn most likely ran on the process that died; one still busy after that is left to its own next ordinary turn (`schedule_reattach`, which turn admission runs only while `agent.kas_workflows` is on). The boot pass (`start_kas_boot_recovery`), the crash pass and each chat's ordinary turn are the only ways a run reconnects; none repeats on a clock, and the routes start none. `GET /api/workflows/kas/state` and `GET /api/workflows/kas/runs` send no turn and decide nothing. `install_kas_workflow_triggers` also makes `idle_held_sessions` the session manager's idle hold (`SessionManager.set_idle_hold`, session.md), and the uninstall removes it: a run lives in its chat's Kiro Agent process and only the chat's own turns move the idle clock, so the hold keeps the idle sweep from stopping a step still working `session.timeout_secs` after the chat's last turn. It names the session key (`effective_session_key`) of each open chat with a run that a live process of this gateway drives (the row's `driven`) and that is `running`, or `paused` with an `attention` entry, an ask waiting for a person. A run paused for another reason, a finished one and one with no live process hold nothing, so such a chat expires on the usual clock; the cost is one Kiro Agent process kept per chat with a working or waiting run. Router rows that cannot be read hold nothing for that sweep. Tests: `test/test_kas_workflow_triggers.py`, `test/test_session_idle_hold.py`, `test/test_kas_workflow_mode_recheck.py`, `test/test_kas_workflows_round4.py::test_every_revision_bump_reaches_the_changed_hook`, `test/test_ws_event_scoping_frames.py::TestKasWorkflowRevisionFrameIsOwnerOnly`. - `handlers/` package (`handlers/core.py`, `handlers/messaging.py` and siblings) — status, system (live CPU/memory/network), memory CRUD, cron CRUD, lesson CRUD, skills, agent config (save + auto-restart sessions), logs SSE with persistent ring buffer (1000 entries, replays on connect) + queue-based handler (also pushes to WS log subscribers via `ensure_future`), log level control, session delete, refine status push via `broadcast_ws` with throttled chunks (~4/sec). `start_time` included in SSE/WS dashboard status payload. MCP management: probe cache (`_bg_mcp_probe()` at startup, 10-min TTL, merges enabled/disabledTools from global mcp.json), server/tool toggle writes to `~/.kiro/settings/mcp.json` + syncs to kirocrew.json, bulk toggle-all, `_sync_mcp_to_agent()` helper. - `handlers/browser_harness_status.py`, `handlers/browser_ops.py` and `handlers/browser_live.py` — the agent browser's three route families (see @@ -3415,7 +3417,8 @@ surface. The modules of | `turn_context` | memory-mode fold into the execution context, pending context drain and detach, folder steering gate, the unavailable-agent message, the DM member binding check, the session memory assignment and the skills context restored after a compaction (`_restore_skills_context_after_compaction`) | | `prompt_assembly` | cold-start replay history, egress scrub of the dashboard prefix, checklist resync, prompt and skill mentions (`_resolve_prompt_mention`, `_expand_prompt_mention` and its off-loop form `_expand_prompt_mention_off_loop`, `_expand_dollar_skills`) and the prompt chip, the early embed and memory reads of a cold start's first message (`_prewarm_startup_query`), and the prompt the turn sends (`_turn_build_prompt`): a slash command's own prompt, the context build (the raw message kept for Slack, the theme persona gate, the ContextBuilder's `build_message` and the first-turn history it assembles) or the bare message, and the settle of what the turn owed its prompts once it ends (`_turn_settle_debts`): the replay, the re-injection flag, the skill bodies and the first-turn history debt | | `model_fallback` | session model default and settle, served-model sync, fallback chain, swap and restore probe, refusal fallback hop, the canonical-model backfill and the pinned-model verdict, and the model-access fallback arm of the turn's `except AcpError` chain (`_on_acp_model_access`) | -| `tool_approval` | PreToolUse block reasons, spec-hook notices, credential hints, trust and auto-approve policy, name-grant refusals, and the permission arm's own answers (`_on_permission_request`): the hooks, the trust reads, the grants and auto-approve | +| `tool_approval` | PreToolUse block reasons, spec-hook notices, trust and auto-approve policy, name-grant refusals, and the permission arm's own answers (`_on_permission_request`): the hooks, the trust reads, the grants and auto-approve | +| `kas_step_mode` | how a Kiro Workflows step of the chat reads the chat's approval mode when it asks (`_kas_step_mode_reader`): the flags and precedence `tool_approval` reads for the chat's own tool calls, read at request time | | `permission_prompt` | a permission request put to the user (`_on_permission_prompt`): the batch-rejection cascade's auto-reject, the approval card, the wait and what the answer does | | `elicitation_prompt` | an MCP server's own question put to the user (`_on_elicitation_request`): the elicitation card row, the wait in the slot's approval registry, and the answer sent back (`read_elicitation_answer` maps a Stop or the generic approve onto an elicitation action); no trust tier answers it | | `mcp_session` | session MCP report, the session-start notice for Kiro Crew's own servers a session lacks (`_notice_unresolved_control_plane`: the `CONTROL_PLANE_SERVERS` its report lists as unresolved, `_unresolved_control_plane`, and the row's text, `_unresolved_control_plane_notice`; `turn_admission` calls it on a new session, and it posts nothing when the seed-declined notice already names the withheld servers), the session-init OAuth drain and the MCP OAuth banner lifecycle (`_emit_mcp_oauth_request`, its supersede, its expiry when a sign-in attempt ends, and completion) and the scrub of the ACP strings it shows, the stream's MCP arms (`_on_mcp_oauth_request`, `_on_mcp_server_initialized`, `_on_mcp_server_init_failure`), and the KAS consent link that reaches a chat between turns (`_watch_mcp_consent_between_turns`, installed by `turn_admission`; it and the mid-turn arm draw through `_show_mcp_oauth_request`) | @@ -3437,7 +3440,7 @@ surface. The modules of | `stream_chunks` | the stream's text and thinking arms, which hold the live-stream and thinking-stream sinks `security_posture` names: a chunk of the reply's text (`_on_text_chunk`): the segment cut after a tool group, with the tool rows it marks done and the crew log's next model-call step, the drop of text after an applied terminal directive, the per-delta redaction and the segment's raw copy, the turn-emit flag and the consumption report, and the `chat_chunk` frame the live-stream redactor releases, a plain sentence end included (`release_sentence_end`); and a chunk of thinking (`_on_thinking_chunk`) and the `chat_thinking` frame the thinking-stream redactor releases | | `tool_rows` | what a turn's tool rows persist and broadcast: row meta, the WS payload, the refinement rewrite, the tool-call identity key and the rows-only save, and the stream's tool-call and tool-update arms (`_on_tool_call`, `_on_tool_call_update`) | | `tool_results` | what a tool's result does to the turn (`_on_tool_result`): its row, its file changes, the session directive it carries (decode, apply, strip), the MCP-app render it claims and the follow-ups it arms | -| `deny_chokepoints` | answering a permission request with a rejection: redacted deny rows, the security-event audit before the wire (`_reject_attributed`), the bounded in-band steer of the reason | +| `deny_chokepoints` | answering a permission request with a rejection: redacted deny rows, the security-event audit before the wire (`_reject_attributed`), the bounded in-band steer of the reason and the credential hint it carries (`_credential_tool_hint_for`) | | `turn_spec_hooks` | the session agent spec's hooks and the agent notices: the turn's dispatch of every hook event (`_fire`), the welcome row, the run-nowhere and withheld-hooks notices, and the Stop hook with the continuations it and a tool refusal queue, and the reply's linked-Slack mirror and channel-neutral leg (`_turn_stop_hook`) | | `crew_log_attribution` | what a session's crew log records about it: the predecessor store, the served model, lineage, the seeded tree, the inherited parent, the workspace and the memory/app/channel class, and the close of a turn's crew log and its streak's activity once it ends (`_turn_close_crew_log`), and every new crew-log record helper (the turn's `latch_crew_log_previous` call is in `turn_admission`, the eager spawn's in `eager_spawn`, and the model-call step a text chunk after a tool group opens in `stream_chunks`) | | `native_cards` | harness-native sub-agent Activity cards (kiro-cli's, KAS's and Claude Code's; `_native_subagent_sync`) and the native AskUserQuestion card (`_post_native_question_card`), and the stream's native sub-agent arms (`_on_subagent_list`, `_on_subagent_activity`) | diff --git a/docs/system-specs/modules/runtime-ownership.md b/docs/system-specs/modules/runtime-ownership.md index b47453729c89..31b9e9e6e09e 100644 --- a/docs/system-specs/modules/runtime-ownership.md +++ b/docs/system-specs/modules/runtime-ownership.md @@ -512,9 +512,16 @@ nothing to recover and re-acquires on its next turn, which drops a dead runtime the way past. A sub-agent run parked on a wait cannot: nothing restarts an `AcpRuntime` under it, so the sub-agent reaper asks that run's own handle each sweep and ends the run ([subagent.md](subagent.md), *Transient Retry (mid-stream 5xx) and dependency waits*). -There is deliberately no observer registry: a notification channel -with no subscriber is a mechanism whose first real consumer would have to redesign -it. + +One layer is pushed the death: `runtime_death.subscribe(listener)` calls the +listener with `(runtime, death)` after each `announce`, once the record is stored. +Its one consumer is the dashboard's Kiro Workflows reconnect +(`dashboard/kas_workflow_triggers`), which acts on a crash (`expected` False) +only, because a workflow run lives in its chat's process and can lose it while +no turn is in flight on it, so no tenant's poisoned queue would report it. A +listener runs inside the death path: it schedules its +work and returns, and never awaits there. One that raises is logged and skipped, +and the record stays readable. `subscribe` returns the unsubscribe. A shared death still has to bound recovery, so it is counted per session (`note_shared_death` / `clear_shared_deaths`) as the substitute ceiling for the @@ -547,7 +554,10 @@ Pinned by `test_runtime_death_is_a_process_event.py` — `test_a_shared_runtimes_death_is_nobodys_single_failure`, `test_co_tenancy_is_read_before_the_dead_flag_flips`, `test_the_death_is_announced_exactly_once`, -`test_a_tenant_asks_by_handle_never_by_pid`. +`test_a_tenant_asks_by_handle_never_by_pid`; the subscriber by +`test_runtime_death_subscribe.py` — `test_a_subscriber_hears_each_death_once`, +`test_a_failing_subscriber_breaks_nothing`, +`test_an_unsubscribed_listener_hears_nothing`. ## Reconciliation: the kernel against the registry diff --git a/docs/system-specs/modules/security.md b/docs/system-specs/modules/security.md index fbf25f77ee5e..c6ea6a65a033 100644 --- a/docs/system-specs/modules/security.md +++ b/docs/system-specs/modules/security.md @@ -7361,7 +7361,7 @@ After expiry, re-authorization is required. A 5-minute grace window allows `!yol **An app's unattended pooled task (App Kit level 44).** An app that declares `permissions.unattended` (a staged grant shown at install) may run a pooled task with `unattended=True` (`apps/agent_turn_unattended.py`). The task holds a `SafetyOverride` scoped grant of its own (`worker_auto_approve.hold_turn_grant`, `app::turn::autoapprove`: refused under an `approval_modes` deny of `yolo`, audited fail-closed, 24h cap, ended by every app teardown through `revoke_app`, and never started once a stop of the app has begun: activation and registration are one step under the lock `revoke_app` holds, checked against the app's stop fence), and every permission request is asked first of the task's floor (`_resolve_permission`'s `turn_floor`): the grant still live, the tool on the task's allowlist (by the host-read identity, never the title), and every path the call names inside the task's work dir under the app's data directory, resolved through every link (an MCP tool, whose server decides what it touches, a shell call, a web fetch or search, an unknown built-in, `code`, a `glob` or `grep` pattern that starts a new root or climbs out of the named one, a work dir that no longer resolves to itself, a pathless file call, a variable or a cut-short scan cannot be told and is refused). Then a critical `approval_pending` row is written, and the hook gate judges the call with no approver: a `POLICY ∩ PROFILE` deny, a held call and a headless git read are refused, the rest approved, unless the grant ended meanwhile: both approval branches read the task's `turn_withdrawal` right before the approval is sent and hand it to the transport as `withdraw_if`, read again under the write lock. Nothing is ever asked, and nothing runs unasked: the agent of an unattended task may declare only built-ins its harness raises a permission request for on every call, and no MCP tool (`unasked_tools_refusal`; on kiro-cli that excludes its in-folder reads and searches). A task with an allowlist, or unattended, whose agent spec approves calls itself (`allowedTools`, a server `autoApprove`, a `permissions` allow, any `toolsSettings` key that does not only narrow, an `includeMcpJson`, `useLegacyMcpJson` or `includePowers` that is not `false`) is refused before its session opens. App Kit spec §32a. -**The grant is process-global; approval modes are per-slot.** `POST /api/chat/mode` sets `normal` / `trust_reads` / `trust` against the slot named in `slot` (or every slot when it is omitted), while `yolo` is the global grant and ignores `slot`. Because the grant covers every slot, a **slot-scoped** `trust`/`trust_reads` does NOT revoke it: that request asks for auto-approval on one slot and cannot be answered by withdrawing authority from slots it never named (the shape that let a programmatic per-slot `trust` end an operator's live grant). Every other mode change still revokes, so `normal` remains the off-switch at any scope. A grant DECLARED in owner-only config is exempt from the narrowing — it has no TTL, and selecting another approval mode is the one action documented to end it. That exemption keys on the grant's **source** (`SafetyOverride.is_declared`), never its permanence: an `until_shutdown` ad-hoc pick is equally permanent and keeps the scope protection, while a declared grant the governance ceiling refused to make permanent is timed and still counts as declared. A caller that presents an attested `cron:` session key, which is what `ScriptContext.set_session_mode` does, is held to the slot-scoped `trust` and `trust_reads` on a session that same cron created: `yolo`, `normal` and any other mode answer 403 `mode_not_allowed` before the governance read or the override is consulted, an unnamed slot answers 400 `slot_required`, and a slot another creator made answers 403 `not_creator`. A cron caller's admitted `trust`/`trust_reads` never deactivates the global grant, declared or not: like an app token, a scheduled run asking for auto-approval on the one session it opened is not the operator selecting another mode, so the declared-grant exemption above does not reach it (`and not cron_creator` in `api_chat_mode`). The rules and their audit are in [session-control](session-control.md) and [learn-cron-dashboard](learn-cron-dashboard.md). +**The grant is process-global; approval modes are per-slot.** `POST /api/chat/mode` sets `normal` / `trust_reads` / `trust` against the slot named in `slot` (or every slot when it is omitted), while `yolo` is the global grant and ignores `slot`. Because the grant covers every slot, a **slot-scoped** `trust`/`trust_reads` does NOT revoke it: that request asks for auto-approval on one slot and cannot be answered by withdrawing authority from slots it never named (the shape that let a programmatic per-slot `trust` end an operator's live grant). Every other mode change still revokes, so `normal` remains the off-switch at any scope. A grant DECLARED in owner-only config is exempt from the narrowing — it has no TTL, and selecting another approval mode is the one action documented to end it. That exemption keys on the grant's **source** (`SafetyOverride.is_declared`), never its permanence: an `until_shutdown` ad-hoc pick is equally permanent and keeps the scope protection, while a declared grant the governance ceiling refused to make permanent is timed and still counts as declared. A caller that presents an attested `cron:` session key, which is what `ScriptContext.set_session_mode` does, is held to the slot-scoped `trust` and `trust_reads` on a session that same cron created: `yolo`, `normal` and any other mode answer 403 `mode_not_allowed` before the governance read or the override is consulted, an unnamed slot answers 400 `slot_required`, and a slot another creator made answers 403 `not_creator`. A cron caller's admitted `trust`/`trust_reads` never deactivates the global grant, declared or not: like an app token, a scheduled run asking for auto-approval on the one session it opened is not the operator selecting another mode, so the declared-grant exemption above does not reach it (`and not cron_creator` in `api_chat_mode`). A successful change also re-decides the Kiro Workflows step approvals held under a chat's previous mode (`kas_workflow_triggers.recheck_step_approvals`, only while `agent.kas_workflows` is on); the approval card's Trust, Trust-reads and YOLO presses run the same re-check. The rules and their audit are in [session-control](session-control.md) and [learn-cron-dashboard](learn-cron-dashboard.md). SEL audit events are emitted on every lifecycle transition: - `safety_override:activate` — override enabled diff --git a/docs/system-specs/modules/session.md b/docs/system-specs/modules/session.md index c8a4f4a137c8..6c5f2a3a01b0 100644 --- a/docs/system-specs/modules/session.md +++ b/docs/system-specs/modules/session.md @@ -2434,9 +2434,8 @@ against sweep completeness, and are torn down at `close_all`. just before each idle reset, so a key the hold starts naming while the sweep waits on its probes is kept. A held key is exempt on the idle axis only, as a listed one is. A source that raises stops that sweep, which then expires - nothing. The hold is for the dashboard's chats whose Kiro Workflows run is - working or waiting on a person, and no code installs one yet - ([kas-workflows.md](kas-workflows.md)). + nothing. The one installer is the dashboard's Kiro Workflows triggers + (`kas_workflow_triggers.idle_held_sessions`, in learn-cron-dashboard.md). Tests: `test/test_session_idle_hold.py`. A listed key that no slot ever claimed, such as a cron job that runs without a tab, is reaped on neither axis, even after its job is deleted. The RSS recycle, when enabled, or diff --git a/scripts/capture_kas_workflow.py b/scripts/capture_kas_workflow.py new file mode 100644 index 000000000000..a75671ae67d3 --- /dev/null +++ b/scripts/capture_kas_workflow.py @@ -0,0 +1,619 @@ +#!/usr/bin/env python3 +"""Drive Kiro Agent (KAS) through one small native workflow run and record the frames. + +``ACP_BACKENDS_NATIVE_WORKFLOWS`` in ``src/kiro_crew/agent_sdk/backends_routing.py`` +admits a harness whose OWN workflow engine Crew drives over the ``_kiro/workflow/*`` +extension methods (:mod:`kiro_crew.kas_workflows`). The harness-parity X-capture rule +(``docs/ci/harness-parity-gate.md``) holds that set to a LIVE capture of KAS itself, +so this script is that capture, as one command: + + python3 scripts/capture_kas_workflow.py + python3 scripts/capture_kas_workflow.py --out build/kas-workflow-live.jsonl + +It spawns KAS the way Crew's production relay does (``kiro-cli acp --agent-engine v3 +--auth-method cli``), declares the client capabilities Crew declares while the Kiro +Workflows switch is on, and then, in a scratch project: + +1. ``session/new`` with ``_meta.kiro.settings.workflows.enabled: true`` + (:func:`kiro_crew.kas_workflows.chat.workflow_settings`); +2. writes a two-step workspace recipe and reads it back with + ``_kiro/workflow/listRecipes``; +3. ``_kiro/workflow/new`` + ``_kiro/workflow/invoke`` with the params + :func:`kiro_crew.kas_workflows.wire.new_run_params` builds; +4. answers every request the run sends: a step's ``_kiro/userInput`` question with + its first option, a ``session/request_permission`` with its allow-once option; +5. waits for the run's terminal ``_kiro/workflow/run_complete``, then reads it with + ``_kiro/workflow/load``, ``inspect`` and ``list``, and waits for the parent turn + KAS starts on its own when a run ends (``session_info_update`` ``turn_start`` / + ``turn_end``, :func:`kiro_crew.acp.kas_wire.turn_boundary`). + +The step prompts ask the first step to send its parent a note (``send_message`` -> +``_kiro/session/notify``) and the second to ask one structured question +(``user_input`` -> ``_kiro/userInput``), so the capture holds every non-standard +frame class the workflow router reads. + +What it writes +-------------- +Agent-to-client lines only, verbatim and in order, in the corpus's fixture shape +(``test/fixtures/acp_frames/README.md``), with these reductions, each named in the +header's note: + +* host inventory frames are omitted (MCP status, tool tags, powers, steering, + progressive context, the session list, governance, config options, the command + list, context-usage ``session_info_update``s) -- they describe the recording HOST, + and ``scripts/check_acp_frame_host_data.py`` refuses them; +* model prose (``agent_thought_chunk``, ``agent_message_chunk``) and the step + prompts KAS echoes (``user_message_chunk``) are omitted, which keeps the capture + under the corpus's frame cap; +* the scratch project reads as ``/work`` and the home directory as ``~``; +* every uuid, session id and workflow id is replaced with a fixed synthetic value, + consistently, so the frames still cross-reference each other. + +It does not authenticate anything: kiro-cli resolves its own sign-in. It does not +write into the committed corpus: the default output is under ``build/`` (git-ignored), +because a stray ``.jsonl`` in ``test/fixtures/acp_frames/`` is collected by +``test/test_acp_frame_replay.py`` and fails for want of a snapshot. Moving a reviewed +capture in is a separate step. + +Exit codes: ``0`` captured and commit-ready · ``2`` usage or environment error (kiro-cli +missing, no KAS package) · ``3`` KAS refused (initialize unanswered, auth error, a +request error) · ``4`` the run never ended inside ``--timeout`` · ``5`` written, but a +recording-host marker survived the sweep. +""" + +from __future__ import annotations + +import argparse +import datetime as _datetime +import importlib.util +import json +import os +import queue +import re +import shutil +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path +from typing import Any + +REPO_ROOT = Path(__file__).resolve().parents[1] + +# Importing ``kiro_crew`` builds the metrics provider; a script is not pytest, so pin +# telemetry off before the import (``update_acp_frame_snapshots.py`` does the same). +os.environ["KIROCREW_TELEMETRY"] = "0" +sys.path.insert(0, str(REPO_ROOT / "src")) + +from kiro_crew.acp.types import KAS_CLIENT_CAPABILITIES # noqa: E402 +from kiro_crew.agent_sdk.tool_search import with_client_meta_settings # noqa: E402 +from kiro_crew.kas_workflows import wire # noqa: E402 +from kiro_crew.kas_workflows.chat import workflow_settings # noqa: E402 + +EXIT_OK = 0 +EXIT_USAGE = 2 +EXIT_REFUSED = 3 +EXIT_TIMEOUT = 4 +EXIT_MARKERS = 5 + +#: The production relay spawn (``acp.kas_transport``): kiro-cli's v3 engine, with +#: kiro-cli owning authentication. +RELAY_ARGV = ("acp", "--agent-engine", "v3", "--auth-method", "cli") + +#: How many times the drive answers a step that parked for input before it gives up +#: and lets ``--timeout`` end the drive. +MAX_REPLIES = 2 + +RECIPE_NAME = "kirocrew-capture" +RECIPE: dict[str, Any] = { + "name": RECIPE_NAME, + "description": "Two tiny steps: a note to the parent, then a question for the user.", + "steps": [ + { + "type": "step", + "id": "note", + "agent": "wf-coder", + "prompt": ( + "Do not read, write or run anything. Send your parent one message with " + "the send_message tool, severity info, text 'capture note'. Then finish " + "the step by reporting success with the single word ok." + ), + }, + { + "type": "step", + "id": "ask", + "agent": "wf-coder", + "prompt": ( + "Do not read, write or run anything. Ask the user 'Pick a colour' with " + "exactly two options, Red and Blue, using the user_input tool if you have " + "it. Once you have the answer, finish the step by reporting success with " + "the colour." + ), + }, + ], +} + +#: Notification methods that are inventories of the recording host, not product shape. +DROPPED_METHODS = frozenset( + { + "_kiro/mcp/status", + "_kiro/tools/didChange", + "_kiro/powers/items_changed", + "_kiro/steering/documents_changed", + "_kiro/progressive_context/items_changed", + "_kiro/sessions/changed", + "_kiro/governance/state", + } +) +#: Also dropped: the model's prose (thinking, message chunks) and the step prompts +#: KAS echoes as ``user_message_chunk``. No workflow parser reads them, and they are +#: most of a run's lines: kept, the capture passes the corpus's frame cap +#: (``test_acp_frame_replay.py`` ``_MAX_FRAMES``). +DROPPED_UPDATES = frozenset( + { + "available_commands_update", + "config_option_update", + "agent_thought_chunk", + "agent_message_chunk", + "user_message_chunk", + } +) +#: Keys of the session/new answer that list what the signed-in account can use. +SESSION_INVENTORY = frozenset({"models", "configOptions", "modes"}) +#: ``session_info_update`` kinds that are product shape (the engine's own turn +#: boundaries). Every other ``session_info_update`` is a context-usage breakdown that +#: names the host's files, and is dropped. +KEPT_INFO_KINDS = frozenset({"turn_start", "turn_end"}) + +_UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") +_WORKFLOW_ID = re.compile(r"\bwf_[0-9a-f]{16}\b") + + +class Refused(Exception): + """KAS would not do what the drive needs.""" + + +class Driver: + """One KAS process over stdio: send requests, answer its requests, log its lines.""" + + def __init__(self, argv: list[str], cwd: Path, frame_timeout: float) -> None: + self.proc = subprocess.Popen( + argv, + cwd=str(cwd), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + bufsize=1, + ) + self.frame_timeout = frame_timeout + self.frames: list[dict[str, Any]] = [] + self.inbox: queue.Queue[dict[str, Any]] = queue.Queue() + self.next_id = 1 + self.questions = 0 + self.permissions = 0 + threading.Thread(target=self._read, daemon=True).start() + + def _read(self) -> None: + assert self.proc.stdout is not None + for line in self.proc.stdout: + try: + msg = json.loads(line) + except ValueError: + continue + if isinstance(msg, dict): + self.frames.append(msg) + self.inbox.put(msg) + + def _write(self, obj: dict[str, Any]) -> None: + assert self.proc.stdin is not None + self.proc.stdin.write(json.dumps(obj) + "\n") + self.proc.stdin.flush() + + def send(self, method: str, params: dict[str, Any]) -> int: + """Send a request without waiting for its answer (it is read like any line).""" + rid = self.next_id + self.next_id += 1 + self._write({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}) + print(f"[{time.strftime('%H:%M:%S')}] -> {method}", file=sys.stderr, flush=True) + return rid + + def call(self, method: str, params: dict[str, Any], timeout: float | None = None) -> Any: + rid = self.send(method, params) + deadline = time.monotonic() + (timeout or self.frame_timeout) + while True: + msg = self.pump(deadline) + if msg is None: + raise Refused(f"{method} was not answered") + if msg.get("id") == rid and "method" not in msg: + if "error" in msg: + raise Refused(f"{method} answered an error: {msg['error']}") + return msg.get("result") + + def pump(self, deadline: float) -> dict[str, Any] | None: + """The next agent line before *deadline*, answering it first when it is a request.""" + remaining = deadline - time.monotonic() + if remaining <= 0: + return None + try: + msg = self.inbox.get(timeout=remaining) + except queue.Empty: + return None + method = msg.get("method") + if isinstance(method, str) and method.startswith(("_kiro/workflow/", "_kiro/session/")): + print(f"[{time.strftime('%H:%M:%S')}] <- {method}", file=sys.stderr, flush=True) + if "method" in msg and "id" in msg: + print(f"[{time.strftime('%H:%M:%S')}] <- request {method}", file=sys.stderr, flush=True) + self._answer(msg) + return msg + + def _answer(self, msg: dict[str, Any]) -> None: + method, params = msg.get("method"), msg.get("params") or {} + if method == "_kiro/userInput": + self.questions += 1 + options = params.get("options") or [] + first = options[0].get("title") if options and isinstance(options[0], dict) else "ok" + result: dict[str, Any] = {"action": "answered", "answer": first or "ok"} + elif method == "session/request_permission": + self.permissions += 1 + options = params.get("options") or [] + allow = next( + (o.get("optionId") for o in options if o.get("kind") == "allow_once"), + options[0].get("optionId") if options else None, + ) + result = {"outcome": {"outcome": "selected", "optionId": allow}} + else: + self._write( + { + "jsonrpc": "2.0", + "id": msg["id"], + "error": {"code": -32601, "message": f"{method} is not served"}, + } + ) + return + self._write({"jsonrpc": "2.0", "id": msg["id"], "result": result}) + + def close(self) -> None: + try: + self.proc.kill() + finally: + self.proc.wait(timeout=10) + + +def _run_complete(msg: dict[str, Any], workflow_id: str) -> bool: + params = msg.get("params") or {} + return ( + msg.get("method") == wire.NOTIFY_RUN_COMPLETE + and params.get("workflowId") == workflow_id + and params.get("status") in wire.TERMINAL_RUN_STATUSES + ) + + +def _parked_step(final_state: Any) -> dict[str, Any] | None: + """The step node a paused run's ``finalState`` holds parked, or None.""" + stack = [final_state.get("root")] if isinstance(final_state, dict) else [] + while stack: + node = stack.pop() + if not isinstance(node, dict): + continue + if node.get("type", wire.NODE_TYPE_STEP) == wire.NODE_TYPE_STEP and ( + node.get("status") == wire.STATUS_PAUSED and not node.get("children") + ): + return node + stack.extend(node.get("children") or []) + return None + + +def _parent_woke(frames: list[dict[str, Any]], parent: str) -> bool: + """Whether *parent* has had a whole engine-started turn (``turn_start`` .. ``turn_end``).""" + started = False + for msg in frames: + if (msg.get("params") or {}).get("sessionId") != parent: + continue + kind = _info_kind(msg) + if kind == "turn_start": + started = True + elif kind == "turn_end" and started: + return True + return False + + +def _info_kind(msg: dict[str, Any]) -> str | None: + update = (msg.get("params") or {}).get("update") or {} + if update.get("sessionUpdate") != "session_info_update": + return None + kiro = (update.get("_meta") or {}).get("kiro") or {} + return kiro.get("kind") if isinstance(kiro, dict) else None + + +def drive(driver: Driver, work: Path, run_timeout: float) -> dict[str, Any]: + """The whole drive; returns facts for the header note.""" + init = driver.call( + "initialize", + { + "clientInfo": {"name": "kirocrew", "version": "capture"}, + "protocolVersion": 1, + "clientCapabilities": KAS_CLIENT_CAPABILITIES, + }, + timeout=120, + ) + methods = wire.extension_methods((init or {}).get("agentCapabilities")) + if methods is not None and wire.METHOD_NEW not in methods: + raise Refused("this KAS does not advertise _kiro/workflow/new") + params: dict[str, Any] = {"cwd": str(work), "mcpServers": []} + params = with_client_meta_settings(params, workflow_settings(True)) + session = driver.call("session/new", params, timeout=120) + parent = (session or {}).get("sessionId") + if not parent: + raise Refused("session/new returned no sessionId") + + recipe_dir = work / ".kiro" / "workflows" + recipe_dir.mkdir(parents=True, exist_ok=True) + recipe_path = recipe_dir / f"{RECIPE_NAME}.workflow.json" + recipe_path.write_text(json.dumps(RECIPE, indent=2), encoding="utf-8") + driver.call(wire.METHOD_LIST_RECIPES, {"workspacePaths": [str(work)]}) + + created = driver.call( + wire.METHOD_NEW, + wire.new_run_params( + source=str(recipe_path), + parent_session_id=parent, + inputs={}, + run_label="capture", + ), + ) + workflow_id = wire.as_str((created or {}).get("workflowId")) + if workflow_id is None: + raise Refused("_kiro/workflow/new created no run") + driver.call(wire.METHOD_INVOKE, {"workflowId": workflow_id}) + + deadline = time.monotonic() + run_timeout + status = None + step_sessions: dict[str, str] = {} + replies = 0 + while True: + msg = driver.pump(deadline) + if msg is None: + raise TimeoutError(f"run {workflow_id} did not end within {run_timeout:g}s") + params = msg.get("params") or {} + started_node = wire.as_str(params.get("nodeId")) + started_session = wire.as_str(params.get("sessionId")) + if msg.get("method") == wire.NOTIFY_NODE_START and started_node and started_session: + step_sessions[started_node] = started_session + if _run_complete(msg, workflow_id): + status = params["status"] + break + if ( + msg.get("method") == wire.NOTIFY_RUN_COMPLETE + and params.get("workflowId") == workflow_id + and params.get("status") == wire.STATUS_PAUSED + and replies < MAX_REPLIES + ): + # A step parked for input. Crew's reply to a parked step is a plain + # session/prompt on the STEP's session (wire.NODE_ACTION_REPLY), which + # KAS reroutes into the run. + parked = _parked_step(params.get("finalState")) or {} + parked_node = wire.as_str(parked.get("nodeId")) + session_id = (step_sessions.get(parked_node) if parked_node else None) or ( + wire.as_str(parked.get("sessionId")) + ) + if session_id: + replies += 1 + driver.send( + wire.METHOD_SESSION_PROMPT, + {"sessionId": session_id, "prompt": [{"type": "text", "text": "Blue"}]}, + ) + + driver.call(wire.METHOD_LOAD, {"workflowId": workflow_id}) + driver.call(wire.METHOD_INSPECT, {"workflowId": workflow_id}) + # The scoped list Crew's router sends (``KasWorkflowRouter`` lists by project). + driver.call(wire.METHOD_LIST, {"workspacePaths": [str(work)]}) + + # The parent turn KAS starts on its own (a waking note, or the run's end). It + # may already have started during the run; waited for, not required, because + # a busy or gated parent gets the nudge buffered instead. + wake_deadline = time.monotonic() + min(run_timeout, 180.0) + while not _parent_woke(driver.frames, parent): + if driver.pump(wake_deadline) is None: + break + woke = _parent_woke(driver.frames, parent) + return { + "status": status, + "replies": replies, + "woke": woke, + "questions": driver.questions, + "permissions": driver.permissions, + } + + +def reduce_frames(frames: list[dict[str, Any]]) -> list[dict[str, Any]]: + """The slice the corpus keeps: product shape, not host inventory or thinking.""" + out = [] + for msg in frames: + method = msg.get("method") + if method in DROPPED_METHODS: + continue + update = (msg.get("params") or {}).get("update") + if method == "session/update" and isinstance(update, dict): + kind = update.get("sessionUpdate") + if kind in DROPPED_UPDATES: + continue + if kind == "session_info_update" and _info_kind(msg) not in KEPT_INFO_KINDS: + continue + result = msg.get("result") + if isinstance(result, dict) and "sessionId" in result: + # session/new's answer: its model catalog, config options and mode list + # (which names the host's own agents) are the account's and host's + # inventory. The session id and the ``_meta`` that echoes + # ``workflowsEnabled`` are kept. + msg = {**msg, "result": {k: v for k, v in result.items() if k not in SESSION_INVENTORY}} + out.append(msg) + return out + + +def scrub(frames: list[dict[str, Any]], work: Path, home: Path) -> str: + """Render *frames* as JSONL with host paths and minted ids replaced, consistently.""" + text = "\n".join(json.dumps(f, ensure_ascii=False) for f in frames) + for real, alias in ((str(work.resolve()), "/work"), (str(work), "/work")): + text = text.replace(real, alias) + for real in {str(home.resolve()), str(home)}: + text = text.replace(real, "~") + sessions: dict[str, str] = {} + + def _session(match: re.Match[str]) -> str: + return sessions.setdefault(match.group(0), f"kas-wf-session-{len(sessions) + 1}") + + text = re.sub(r"sess_" + _UUID.pattern, _session, text) + ids: dict[str, str] = {} + + def _uuid(match: re.Match[str]) -> str: + return ids.setdefault(match.group(0), f"kas-wf-id-{len(ids) + 1}") + + text = _UUID.sub(_uuid, text) + runs: dict[str, str] = {} + + def _run(match: re.Match[str]) -> str: + return runs.setdefault(match.group(0), f"wf_{len(runs) + 1:016x}") + + return _WORKFLOW_ID.sub(_run, text) + "\n" + + +def host_markers(text: str) -> list[tuple[str, str]]: + """Markers ``scripts/check_acp_frame_host_data.py`` would refuse, as ``(match, why)``.""" + gate = REPO_ROOT / "scripts" / "check_acp_frame_host_data.py" + spec = importlib.util.spec_from_file_location("acp_frame_host_data_gate", gate) + if spec is None or spec.loader is None: + raise RuntimeError(f"cannot load {gate}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + found = [] + for pattern, why in module.PATTERNS: + match = re.search(pattern, text) + if match: + found.append((match.group(0), why)) + return found + + +def versions(kiro_cli: str, home: Path) -> tuple[str, str]: + """``(kiro_cli_version, agent_version)``: the engine version is the ``@kiro/agent`` + package.json kiro-cli installed for ITS version, not kiro-cli's own.""" + out = subprocess.run( + [kiro_cli, "--version"], capture_output=True, text=True, encoding="utf-8", timeout=30 + ) + match = re.search(r"(\d+\.\d+\.\d+)", out.stdout) + if not match: + raise RuntimeError(f"cannot read the kiro-cli version from {out.stdout!r}") + cli = match.group(1) + kas_root = home / ".local" / "share" / "kiro-cli" / "kas" + for pkg in sorted(kas_root.glob(f"{cli}-*/node_modules/@kiro/agent/package.json")): + version = json.loads(pkg.read_text(encoding="utf-8")).get("version") + if version: + return cli, str(version) + raise RuntimeError(f"no @kiro/agent package.json for kiro-cli {cli} under {kas_root}") + + +def _question_path(facts: dict[str, Any]) -> str: + """How the question step asked, which depends on the step agent's tools.""" + if facts.get("questions"): + return "The question step asked through a _kiro/userInput request." + return ( + "The question step's agent had no user_input tool, so it asked by parking " + "(send_message warning -> node_paused, paused, run_complete status paused)." + ) + + +def meta_header(cli: str, agent: str, facts: dict[str, Any]) -> dict[str, Any]: + return { + "_meta": { + "backend": "kas", + "recorded": "live", + "date": _datetime.date.today().isoformat(), + "agent_version": agent, + "kiro_cli_version": cli, + "note": ( + f"KAS {agent} (the @kiro/agent package.json kiro-cli {cli} installs) reached " + "through `kiro-cli acp --agent-engine v3 --auth-method cli`, the production " + "relay spawn, driven over stdio by scripts/capture_kas_workflow.py: " + "session/new with _meta.kiro.settings.workflows.enabled, a two-step " + "workspace recipe (a parent note, then a question for the user) listed, " + "created and invoked, the run's end, then load/inspect/list and the parent " + f"turn KAS starts itself. {_question_path(facts)} A step that parks for " + "input is answered with a session/prompt on its own session, Crew's reply " + "path. Run ended " + f"{facts['status']}; parked-step replies {facts['replies']}; questions answered " + f"{facts['questions']}; permissions answered {facts['permissions']}; parent " + f"woke {facts['woke']}. Agent-to-client lines verbatim and in order, except: " + "host inventory frames are omitted (_kiro/mcp/status, _kiro/tools/didChange, " + "_kiro/powers/items_changed, _kiro/steering/documents_changed, " + "_kiro/progressive_context/items_changed, _kiro/sessions/changed, " + "_kiro/governance/state, available_commands_update, config_option_update, " + "context-usage session_info_update, and the models/configOptions/modes " + "inventory of the session/new answer), model prose and echoed step " + "prompts (agent_thought_chunk, agent_message_chunk, user_message_chunk) " + "are omitted, the scratch " + "project reads as /work and the home directory as ~, and every uuid, " + "session id and workflow id is a fixed synthetic value." + ), + } + } + + +def parse_args(argv: list[str]) -> argparse.Namespace: + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--out", type=Path, default=REPO_ROOT / "build" / "kas-workflow-live.jsonl") + p.add_argument("--kiro-cli", default=shutil.which("kiro-cli") or "kiro-cli") + p.add_argument("--timeout", type=float, default=600.0, help="seconds for the run to end") + p.add_argument("--frame-timeout", type=float, default=90.0, help="seconds per request") + return p.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(sys.argv[1:] if argv is None else argv) + home = Path.home() + if shutil.which(args.kiro_cli) is None: + print(f"error: kiro-cli not found: {args.kiro_cli}", file=sys.stderr) + return EXIT_USAGE + work = Path(tempfile.mkdtemp(prefix="kas-wf-capture-")) + driver = Driver([args.kiro_cli, *RELAY_ARGV], work, args.frame_timeout) + code = EXIT_OK + facts: dict[str, Any] = {} + try: + facts = drive(driver, work, args.timeout) + except Refused as exc: + print(f"KAS refused: {exc}", file=sys.stderr) + code = EXIT_REFUSED + except TimeoutError as exc: + print(f"timeout: {exc}", file=sys.stderr) + code = EXIT_TIMEOUT + finally: + driver.close() + # Read after the drive: kiro-cli extracts its engine on the first ``acp`` spawn, + # so a fresh HOME has no @kiro/agent package.json before it. + cli = agent = "" + if code == EXIT_OK: + try: + cli, agent = versions(args.kiro_cli, home) + except (OSError, RuntimeError, subprocess.SubprocessError) as exc: + print(f"error: {exc}", file=sys.stderr) + code = EXIT_USAGE + if code != EXIT_OK: + raw = args.out.with_suffix(".raw.jsonl") + raw.parent.mkdir(parents=True, exist_ok=True) + raw.write_text("\n".join(json.dumps(f) for f in driver.frames) + "\n", encoding="utf-8") + print(f"unreduced frames (host data, do not commit): {raw}", file=sys.stderr) + return code + body = scrub(reduce_frames(driver.frames), work, home) + text = json.dumps(meta_header(cli, agent, facts), ensure_ascii=False) + "\n" + body + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(text, encoding="utf-8") + print(f"wrote {args.out} ({body.count(chr(10))} frames); {facts}") + markers = host_markers(text) + for match, why in markers: + print(f"host marker survived: {match!r} ({why})", file=sys.stderr) + return EXIT_MARKERS if markers else EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/kiro_crew/change_card_catalog_kinds.py b/src/kiro_crew/change_card_catalog_kinds.py index c7b99ccfa741..39085f0de833 100644 --- a/src/kiro_crew/change_card_catalog_kinds.py +++ b/src/kiro_crew/change_card_catalog_kinds.py @@ -251,6 +251,9 @@ "session.max_per_creator": tuple(range(MAX_PER_CREATOR_MIN, MAX_PER_CREATOR_MAX + 1)), # On, a new KAS session reuses a stored remote MCP sign-in without asking. "agent.kas_persist_mcp_sign_in": (False, True), + # On, a Kiro Agent chat's model can start multi-step Kiro Workflows runs + # (kiro_crew.kas_workflows), so turning it on reads as a widen. + "agent.kas_workflows": (False, True), } #: Card-editable config paths (``_EDITABLE_CONFIG``) that no value can widen diff --git a/src/kiro_crew/config/sections_agent.py b/src/kiro_crew/config/sections_agent.py index 9926e86d08dc..28abdafd44ef 100644 --- a/src/kiro_crew/config/sections_agent.py +++ b/src/kiro_crew/config/sections_agent.py @@ -1488,9 +1488,10 @@ class AgentConfig: default=False, metadata=_meta( "Kiro Workflows on Kiro Agent", - "Developer opt-in to Kiro Agent's (KAS) own workflow engine, off by " - "default. This build has no surface that reads it yet, so setting it " - "changes nothing. No effect unless the backend is Kiro Agent.", + "Developer opt-in to Kiro Agent's (KAS) own workflow engine, off by default. When " + "on, a dashboard chat's model can start Kiro Agent workflow runs, the dashboard can " + "start, follow and answer them, and the gateway reconnects a chat's interrupted runs " + "when it starts. No effect unless the backend is Kiro Agent.", ), ) subagent_mem_buffer_pct: int = field( diff --git a/src/kiro_crew/dashboard/chat_api/slot_approval.py b/src/kiro_crew/dashboard/chat_api/slot_approval.py index 9e45e0869767..b480d8f98345 100644 --- a/src/kiro_crew/dashboard/chat_api/slot_approval.py +++ b/src/kiro_crew/dashboard/chat_api/slot_approval.py @@ -822,6 +822,11 @@ async def apply_approval_mode( state.notify( "safety", "An approval-mode change may not be saved to disk", kept_grants.NOT_SAVED ) + # A Kiro Workflows step that asked under a chat's previous mode follows the + # new one, as its next step would. + from kiro_crew.dashboard.kas_workflow_triggers import recheck_step_approvals + + await recheck_step_approvals() state.push_slots_update() return web.json_response({"ok": True, "mode": mode}) @@ -871,6 +876,10 @@ def _sweep_pending_approvals( # and the card stays open. continue if not fut.done(): + # A KAS plan handoff waits for the person under every mode + # (chat_runner marks the card ``person_only``). + if _get_pattern_from_pending(slot, aid, "person_only") == "1": + continue # Read while still pending: names the row the frame settles. _mid = slot.approval_instance(aid) or "" fut.set_result("approved") @@ -1665,6 +1674,12 @@ def audit_caller() -> str: if resolution is not None and resolution.decision is not None: shared_decisions.broadcast_decision(state, resolution.decision) state.push_slots_update() + if original_action in ("trust", "yolo"): + # A Kiro Workflows step that asked under this chat's previous mode + # follows the new one, as its next step would. + from kiro_crew.dashboard.kas_workflow_triggers import recheck_step_approvals + + await recheck_step_approvals() # SEL audit (best-effort — must not block the UI-unblocking path above) try: sel().log_api_access( diff --git a/src/kiro_crew/dashboard/chat_delivery.py b/src/kiro_crew/dashboard/chat_delivery.py index 2c732e4bbc47..5d4c5a525c5d 100644 --- a/src/kiro_crew/dashboard/chat_delivery.py +++ b/src/kiro_crew/dashboard/chat_delivery.py @@ -630,6 +630,12 @@ async def steer_into_running_turn( client = getattr(slot, "_acp_client", None) if client is None or not getattr(client, "supports_steer", False): return STEER_UNAVAILABLE + if getattr(slot, "_kas_observing", False) is True: + # The running turn is a KAS observe turn (kas_workflows.router): it sent + # nothing and reads the turn Kiro Agent started on its own, so a steer + # would be folded into THAT turn. The message is the chat's next + # ordinary turn instead: the caller queues it. + return STEER_UNAVAILABLE loss_prone = getattr(client, "steer_needs_loss_recovery", False) is True if not user_origin and not held_peer and loss_prone: # The requeue keeps a steer this harness drops but may run it twice; peers opt in. diff --git a/src/kiro_crew/dashboard/chat_regenerate.py b/src/kiro_crew/dashboard/chat_regenerate.py index b171e35a3fab..1bf2935ddaab 100644 --- a/src/kiro_crew/dashboard/chat_regenerate.py +++ b/src/kiro_crew/dashboard/chat_regenerate.py @@ -43,6 +43,7 @@ from kiro_crew.dashboard.state import TURN_OPENING_INJECT_KINDS, DashboardState, _ChatSlot from kiro_crew.dashboard.system_notices import is_system_notice from kiro_crew.history_schema import HUMAN_TURN_META_KEY +from kiro_crew.kas_workflows import chat as kas_chat from kiro_crew.messaging.alternation_echo import is_stored_echo_row from kiro_crew.security import redact_credentials, redact_exfiltration_urls from kiro_crew.sel import sel @@ -738,6 +739,21 @@ async def api_chat_slot_edit_resend(request: web.Request) -> web.Response: {"error": "index or ts required", "code": "index_or_ts_required"}, status=400 ) + # The rewind route's Kiro Workflows guard, on this sibling door: this + # edit discards the same native conversation (``discard_conversation`` + # below), so a live run launched from this message on is refused here + # too, before any mutation. + kas_refusal = kas_chat.rewind_refusal(slot.key, msgs[index].get("ts")) + if kas_refusal is not None: + return web.json_response( + { + "error": kas_refusal["error"], + "code": kas_chat.REWIND_REFUSED_CODE, + "runs": kas_refusal["runs"], + }, + status=409, + ) + # A hold a restart restored into this idle slot is owed to this turn, above # its user row. Flushed on the LIVE slot, not the scratch copy below: the # copy shares the hold and its note dicts, so a flush there would retire diff --git a/src/kiro_crew/dashboard/chat_rewind.py b/src/kiro_crew/dashboard/chat_rewind.py index 0cdd0bb57a35..521d89737eea 100644 --- a/src/kiro_crew/dashboard/chat_rewind.py +++ b/src/kiro_crew/dashboard/chat_rewind.py @@ -55,6 +55,7 @@ from kiro_crew.dashboard.slot_registry import SlotRegistry from kiro_crew.dashboard.state import _TRANSIENT_ROLES, DashboardState from kiro_crew.dashboard.system_notices import is_system_notice +from kiro_crew.kas_workflows import chat as kas_chat from kiro_crew.sel import sel from kiro_crew.session_map import _kiro_sessions_dir @@ -316,6 +317,22 @@ async def api_chat_slot_rewind(request: web.Request) -> web.Response: else: index = raw_index - disk_older + # A Kiro Workflows run launched from this message or after it may be + # driven by the very conversation this rewind discards: refused while + # one is still live (paused included), like the Kiro IDE's checkpoint + # guard. Before any mutation, so a refusal changes nothing. The same + # guard runs on edit-resend and regenerate (``kas_chat.rewind_refusal``). + kas_refusal = kas_chat.rewind_refusal(slot.key, msgs[index].get("ts")) + if kas_refusal is not None: + return web.json_response( + { + "error": kas_refusal["error"], + "code": kas_chat.REWIND_REFUSED_CODE, + "runs": kas_refusal["runs"], + }, + status=409, + ) + # Capture orphan info before any mutation, so we can clean up the # kiro-cli session file even if the swap path errors out partway. session_key = effective_session_key(slot) diff --git a/src/kiro_crew/dashboard/chat_runner.py b/src/kiro_crew/dashboard/chat_runner.py index 6b5cc372d7f4..fb8103cc35ec 100644 --- a/src/kiro_crew/dashboard/chat_runner.py +++ b/src/kiro_crew/dashboard/chat_runner.py @@ -462,6 +462,7 @@ validate_file_path, ) from kiro_crew.image_artifacts import register_images_off_loop +from kiro_crew.kas_workflows.engine import kas_workflows_enabled # noqa: F401 from kiro_crew.llm_helpers import ( # noqa: F401 TRANSIENT_RETRIES, PromptBusyExhaustedError, @@ -1221,6 +1222,7 @@ async def _run_chat( full_message = turn.full_message if ( not is_slash + and not turn._kas_observe and _message_is_typed and not turn._text_injected and turn._directive_user_origin @@ -1252,6 +1254,9 @@ async def _run_chat( # re-apply build_message's provenance so only the user's text is upgraded. if _agent_started: event_stream = turn._agent_turn_stream = client.stream_unsolicited() + elif turn._kas_observe: + # Reads the turn KAS started on this session itself; sends nothing. + event_stream = client.stream_observe() elif is_slash: if turn.first_word == "/compact": _begin_compact_command(turn) diff --git a/src/kiro_crew/dashboard/chat_turn/deny_chokepoints.py b/src/kiro_crew/dashboard/chat_turn/deny_chokepoints.py index a438d1b55115..d436adc77014 100644 --- a/src/kiro_crew/dashboard/chat_turn/deny_chokepoints.py +++ b/src/kiro_crew/dashboard/chat_turn/deny_chokepoints.py @@ -14,6 +14,12 @@ REFUSAL_INBAND_RECOVERY_PREFIX, build_refusal_steer_notice, ) +from kiro_crew.deny_guidance import ( + DENY_CLASS_AWS_CREDENTIAL, + DENY_CLASS_SSO_CREDENTIAL, + classify_deny, + resolve_credential_tool_hint, +) from kiro_crew.tool_row_prefix import tool_row if TYPE_CHECKING: @@ -23,10 +29,7 @@ redact_exfiltration_urls, sel, ) - from kiro_crew.dashboard.chat_turn.tool_approval import ( - _credential_tool_hint_for, - _pre_tool_block_reason, - ) + from kiro_crew.dashboard.chat_turn.tool_approval import _pre_tool_block_reason from kiro_crew.dashboard.chat_turn.tool_rows import _tool_meta @@ -79,6 +82,28 @@ async def _steer_repeat_loop_notice(client: Any, notice: str) -> bool: return sent is not False +#: Deny classes a credential-vending MCP server can actually resolve. Only these +#: justify the capability-manager lookup: the hint is appended for them alone, so +#: probing on any other refusal would spend a subprocess to produce a string +#: nothing reads. +_CREDENTIAL_HINT_CLASSES = frozenset({DENY_CLASS_AWS_CREDENTIAL, DENY_CLASS_SSO_CREDENTIAL}) + + +async def _credential_tool_hint_for(reason: str, cause: str, subject: str = "") -> str: + """The host's credential-vendor hint, when *reason* is a refusal it can answer. + + Gated on the class rather than resolved unconditionally because the lookup + shells out to the edition's package manager. A refusal is already a bad moment + to add latency to, and for every non-credential class the result would be + discarded by :func:`build_refusal_steer_notice` anyway. + """ + if cause != DENY_CAUSE_POLICY: + return "" + if classify_deny(reason, subject) not in _CREDENTIAL_HINT_CLASSES: + return "" + return await resolve_credential_tool_hint() + + async def _steer_policy_notice( client: Any, title: str, diff --git a/src/kiro_crew/dashboard/chat_turn/kas_step_mode.py b/src/kiro_crew/dashboard/chat_turn/kas_step_mode.py new file mode 100644 index 000000000000..76483c24fae1 --- /dev/null +++ b/src/kiro_crew/dashboard/chat_turn/kas_step_mode.py @@ -0,0 +1,35 @@ +"""How a Kiro Workflows step reads its parent chat's approval mode (``_kas_step_mode_reader``).""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Callable + + from kiro_crew.dashboard.chat_turn.tool_approval import ( + _auto_approve_reason, + _slot_is_trusted, + ) + + +def _kas_step_mode_reader(state: Any, slot: Any) -> Callable[[], tuple[str, str]]: + """How a KAS workflow step reads its parent chat's approval mode, when it asks. + + The same flags this chat's own tool calls consult, in the same precedence + (:func:`_auto_approve_reason`), with the same channel scoping of the CLI + launch grant (``yolo_reaches``): the process-wide override where it reaches + this chat, or this chat's trust (session or scoped), is ``trust``; + ``_trust_reads`` alone is ``trust_reads``; anything else is ``normal``. Read + at request time, not captured, so the picker's change reaches the next step. + """ + + def read() -> tuple[str, str]: + yolo = bool(state.is_yolo_active() and state.yolo_reaches(slot)) + if yolo or _slot_is_trusted(slot): + return "trust", _auto_approve_reason(slot, yolo) + if getattr(slot, "_trust_reads", False): + return "trust_reads", "trust_reads" + return "normal", "" + + return read diff --git a/src/kiro_crew/dashboard/chat_turn/permission_prompt.py b/src/kiro_crew/dashboard/chat_turn/permission_prompt.py index 6fb0d3171d8d..56b363bd3102 100644 --- a/src/kiro_crew/dashboard/chat_turn/permission_prompt.py +++ b/src/kiro_crew/dashboard/chat_turn/permission_prompt.py @@ -35,6 +35,7 @@ format_approval_expired_note, format_approval_no_budget_card, format_approval_timeout_card, + person_wait_window_secs, ) from kiro_crew.hooks import HOOK_EVENT_PRE_TOOL_USE, hook_tool_input from kiro_crew.safety_override import yolo_policy_permits @@ -112,6 +113,7 @@ async def _on_permission_prompt( _declined_grant_notices = turn._declined_grant_notices _refusal_notices = turn._refusal_notices _refusal_reasons = turn._refusal_reasons + _kas_person_only = turn._kas_person_only client = turn.client session_key = turn.session_key slot = turn.slot @@ -230,6 +232,11 @@ async def _on_permission_prompt( "request_id": str(event.request_id), "tool_call_id": event.tool_call_id or "", } + if _kas_person_only: + # Read by the Trust/YOLO mode-switch sweep + # (chat_handlers.api_chat_mode), which approves every other + # pending card and must leave this one for the person. + perm_meta["person_only"] = "1" if event.tool_purpose: perm_meta["tool_purpose"] = _redact_tool_field(event.tool_purpose, limit=_MAX_TOOL_PURPOSE) if event.tool_input: @@ -687,7 +694,15 @@ def _shown(text: str) -> str: tool_call_id=event.tool_call_id or "", since=_trace_asked, ) - _approval_window = min(state.approval_timeout_for(slot), tool_approval_timeout_secs()) + _approval_window = ( + # A KAS plan handoff waits for the person, not + # for the approval window (gap 4): bounded only by what is + # left of this turn's own ceiling. An unattended slot keeps + # its deny-fast window: no person is there to wait for. + person_wait_window_secs() + if _kas_person_only and not slot.unattended + else min(state.approval_timeout_for(slot), tool_approval_timeout_secs()) + ) # Whether turning YOLO on would have answered this prompt, for the timeout # card's advice. Read before the wait from what is already in scope. Not when # YOLO is already active, since the prompt still reached a person (the grant @@ -695,13 +710,15 @@ def _shown(text: str) -> str: # permit YOLO, which then cannot be turned on; not for a deny-rules # override card, which only the owner's own click approves (deny_override); # not when no auto-approve answers this request (a card's turn, a held Bot - # limit or an organisation's web ``ask``: ``_no_auto_approve``); not for a child - # call the YOLO rung never takes (``child_unconditional_grant_eligible``). + # limit or an organisation's web ``ask``: ``_no_auto_approve``); not for a KAS + # plan handoff, which waits for a person in every mode; not for a child call + # the YOLO rung never takes (``child_unconditional_grant_eligible``). _yolo_covers = not ( state.is_yolo_active() or not yolo_policy_permits() or _override_offer is not None or turn._no_auto_approve + or _kas_person_only or not event.child_unconditional_grant_eligible ) _unattended_wait = slot.unattended @@ -1013,6 +1030,11 @@ def _shown(text: str) -> str: slot._trust_reads = True # A person chose this slot's mode: its creator's changes stop reaching it. slot._posture_inherited = False + # A Kiro Workflows step that asked under this chat's previous mode + # follows the new one, as its next step would. + from kiro_crew.dashboard.kas_workflow_triggers import recheck_step_approvals + + await recheck_step_approvals() outcome = "approved" if outcome == "approved" and _override_offer is not None: # The click lets the named rule step aside, not the whole gate: judge the diff --git a/src/kiro_crew/dashboard/chat_turn/prompt_assembly.py b/src/kiro_crew/dashboard/chat_turn/prompt_assembly.py index 7f87dd7eea92..cd9ea16269a9 100644 --- a/src/kiro_crew/dashboard/chat_turn/prompt_assembly.py +++ b/src/kiro_crew/dashboard/chat_turn/prompt_assembly.py @@ -673,6 +673,12 @@ async def _turn_build_prompt(turn: _ChatTurn) -> None: outcome="bypass", metadata={"command": first_word, "slot": slot.key}, ) + elif turn._kas_observe: + # Nothing is sent on an observe turn, so nothing is built for it: a + # context build here would spend this turn's re-injection and + # replay debts on a prompt that never goes out. + full_message = message + turn.full_message = full_message elif state.context_builder: # Length of the message as the user's text stands NOW (after any diff --git a/src/kiro_crew/dashboard/chat_turn/recipient.py b/src/kiro_crew/dashboard/chat_turn/recipient.py index 0fd6004749be..746f49d4b31d 100644 --- a/src/kiro_crew/dashboard/chat_turn/recipient.py +++ b/src/kiro_crew/dashboard/chat_turn/recipient.py @@ -33,6 +33,7 @@ ) from kiro_crew.messaging.renderer import MIRROR_ECHO_LABEL, split_options_trailer from kiro_crew.messaging.upload_gate import uploads_restricted +from kiro_crew.messaging.workflow_markers import mirror_text from kiro_crew.mirror_admission import admission_required, verify_mirror_admission from kiro_crew.platform import redact_via_context from kiro_crew.span_rewrite import rewrite_spans @@ -1185,7 +1186,11 @@ def _prepare_mirror_msg(raw_user_message: str) -> str: chokepoint: this echo goes to a channel without passing a renderer, and a credential the user typed with markdown between its halves is whole once the client renders the markup away. + + A workflow marker row (launch / reconnect / observe, each carrying a turn + token) is echoed as its one short human line instead, never with the token. """ + raw_user_message = mirror_text(raw_user_message or "") safe, _ = redact_for_display(raw_user_message or "", redact_via_context) if len(safe) <= _MIRROR_ECHO_LIMIT: return safe diff --git a/src/kiro_crew/dashboard/chat_turn/segment_flush.py b/src/kiro_crew/dashboard/chat_turn/segment_flush.py index 3f8636d48ee2..2e13c3d30ea4 100644 --- a/src/kiro_crew/dashboard/chat_turn/segment_flush.py +++ b/src/kiro_crew/dashboard/chat_turn/segment_flush.py @@ -1354,6 +1354,26 @@ async def _turn_settle_answer(turn: _ChatTurn) -> None: ) _recovering_compaction = True turn._recovering_compaction = _recovering_compaction + elif ( + turn._kas_observe + and _stop_reason != STOP_REASON_CANCELLED + and not turn._produced_visible_output + and not turn._terminal_directive_applied + and not _refusal_reasons + ): + # An observe turn sent nothing, so an empty one is not a model that + # failed to answer: KAS ran no turn here (its nudge went to a busy + # session's next turn, or there was none) or its turn only ran tools. + # Neither retry rung applies -- replaying the observe message reads + # nothing again, and a continuation would be a REAL prompt nobody + # asked for. Say so once when nothing at all happened. + if _turn_tool_calls == 0: + slot.append( + "notice", + "ℹ️ Kiro Agent did not reply to the workflow in this chat.", + "msg msg-info", + meta={"kind": EMPTY_TURN_NOTICE_KIND}, + ) elif ( _stop_reason != STOP_REASON_CANCELLED # A turn cut at the request cap gets its own card in diff --git a/src/kiro_crew/dashboard/chat_turn/tool_approval.py b/src/kiro_crew/dashboard/chat_turn/tool_approval.py index 58d6a8f08d4d..1462343d7453 100644 --- a/src/kiro_crew/dashboard/chat_turn/tool_approval.py +++ b/src/kiro_crew/dashboard/chat_turn/tool_approval.py @@ -20,13 +20,6 @@ override_offer_key, slot_deny_waivers, ) -from kiro_crew.dashboard.state import DENY_CAUSE_POLICY -from kiro_crew.deny_guidance import ( - DENY_CLASS_AWS_CREDENTIAL, - DENY_CLASS_SSO_CREDENTIAL, - classify_deny, - resolve_credential_tool_hint, -) from kiro_crew.deny_notice import REFUSED_TURN_RESUME_MAX from kiro_crew.executors import run_in_tool_gate_pool from kiro_crew.hooks import ( @@ -40,6 +33,7 @@ identity_grant_covers_child, unattended_turn, ) +from kiro_crew.kas_workflows.chat import needs_a_person as kas_needs_a_person from kiro_crew.name_grant import log_decline, shell_command_for_event, should_log_decline # Kept on the runner facade's surface (its base-name contract); the refusal label @@ -209,28 +203,6 @@ def _project_hook_files_notice() -> str: ) -#: Deny classes a credential-vending MCP server can actually resolve. Only these -#: justify the capability-manager lookup: the hint is appended for them alone, so -#: probing on any other refusal would spend a subprocess to produce a string -#: nothing reads. -_CREDENTIAL_HINT_CLASSES = frozenset({DENY_CLASS_AWS_CREDENTIAL, DENY_CLASS_SSO_CREDENTIAL}) - - -async def _credential_tool_hint_for(reason: str, cause: str, subject: str = "") -> str: - """The host's credential-vendor hint, when *reason* is a refusal it can answer. - - Gated on the class rather than resolved unconditionally because the lookup - shells out to the edition's package manager. A refusal is already a bad moment - to add latency to, and for every non-credential class the result would be - discarded by :func:`build_refusal_steer_notice` anyway. - """ - if cause != DENY_CAUSE_POLICY: - return "" - if classify_deny(reason, subject) not in _CREDENTIAL_HINT_CLASSES: - return "" - return await resolve_credential_tool_hint() - - def _slot_is_trusted(slot: Any) -> bool: """True when this slot's tool calls are auto-approved. TWO representations. @@ -846,6 +818,14 @@ async def _decide_permission_request(turn: _ChatTurn, event) -> Literal[_Flow.CO # paths may honor it (unconditional grants: trust-all / YOLO / # native crew) and which must not (content-matching paths). _child_grant_eligible = event.child_unconditional_grant_eligible + # KAS's workflow plan handoff is always the person's call: it passes no grant rung + # (session trust, YOLO, native crew, trusted patterns, trust-reads, a hook + # auto-approve) and reaches the permission request, which the mode-switch sweep + # also leaves pending (``person_only``). + _kas_person_only = kas_needs_a_person(event) + turn._kas_person_only = _kas_person_only + if _kas_person_only: + _child_grant_eligible = False if _child_low_fidelity: # Diagnostic for a path that is otherwise invisible in # logs: without it a trust-all session watching its @@ -1062,6 +1042,8 @@ async def _decide_permission_request(turn: _ChatTurn, event) -> Literal[_Flow.CO web_term=_web_ask, ) tool_result = ToolHookResult(action=TOOL_ALLOW) + if _kas_person_only and tool_result.action == TOOL_AUTO_APPROVE: + tool_result = ToolHookResult(action=TOOL_ALLOW) if tool_result.action == TOOL_AUTO_APPROVE: # The hook layer granted this by NAME (its # `auto_approve_tools` globs, or the read-only allowlist). @@ -1641,6 +1623,7 @@ async def _decide_permission_request(turn: _ChatTurn, event) -> Literal[_Flow.CO and cmd and not _child_low_fidelity and not _card_turn + and not _kas_person_only ): # Trust-reads never auto-approves git: git reads # ``.git/config`` on every invocation and ``core.fsmonitor`` diff --git a/src/kiro_crew/dashboard/chat_turn/turn_admission.py b/src/kiro_crew/dashboard/chat_turn/turn_admission.py index f789071baf99..16c00235fa8b 100644 --- a/src/kiro_crew/dashboard/chat_turn/turn_admission.py +++ b/src/kiro_crew/dashboard/chat_turn/turn_admission.py @@ -30,6 +30,11 @@ ) from kiro_crew.dashboard.slot_queue_repository import UNREADABLE_SOURCE_CHANNEL from kiro_crew.dashboard.state import durable_row_count +from kiro_crew.kas_workflows.router import KasWorkflowRouter +from kiro_crew.kas_workflows.router import get_router as get_kas_workflow_router +from kiro_crew.kas_workflows.router import is_observe_turn as is_kas_observe_turn +from kiro_crew.kas_workflows.router import launch_from_turn as launch_kas_workflow_from_turn +from kiro_crew.kas_workflows.router import observe_from_turn as observe_kas_workflow_from_turn from kiro_crew.llm_helpers import _billing_stats from kiro_crew.members import DM_SLOT_MODE, is_dispatchable_member_name, member_lifecycle from kiro_crew.platform import redact_log_via_context @@ -49,6 +54,7 @@ effective_session_key, expire_slack_options, invalidate_stale_kas_session, + kas_workflows_enabled, logger, publish_turn_identity, read_beside_claim, @@ -89,6 +95,7 @@ _slot_predecessor_store, ) from kiro_crew.dashboard.chat_turn.eager_spawn import _clear_eager_spawn_failures + from kiro_crew.dashboard.chat_turn.kas_step_mode import _kas_step_mode_reader from kiro_crew.dashboard.chat_turn.mcp_session import ( _drain_session_init_oauth_requests, _notice_crew_left_out_mcp, @@ -1373,7 +1380,17 @@ async def _claim_session(wait_if_busy: bool) -> tuple[Any, bool, bool]: if _refused_native_todos: _deferred_options_expiry = False turn._deferred_options_expiry = _deferred_options_expiry - if _refused_native_todos and is_new and not resumed: + # A KAS workflow launch message (kiro_crew.kas_workflows.router) is the + # other post-claim turn that dispatches no prompt: it needs the claimed + # session itself, as the new run's parent, so it is answered only here. + _kas_launch = not is_slash and KasWorkflowRouter.is_turn_action(message) + # An observe turn (the same module) dispatches no prompt either, but it + # streams: it reads the turn KAS started on this session by itself. On a + # session this claim just created there is no such turn to read, and the + # turn is answered without a stream like a launch. + turn._kas_observe = not is_slash and is_kas_observe_turn(message) + _dispatchless = _refused_native_todos or _kas_launch or (turn._kas_observe and is_new) + if _dispatchless and is_new and not resumed: # ``get_or_create`` has consumed the session's one-shot FRESH # observation, but this refusal dispatches no prompt. The native # session holds no history, so re-use the replay lease: the next @@ -1381,7 +1398,7 @@ async def _claim_session(wait_if_busy: bool) -> tuple[Any, bool, bool]: # plus member rules). A warm refusal has no observation to restore # and must not manufacture a duplicate. state.sessions.mark_provider_switch_replay(session_key) - elif _refused_native_todos and is_new and resumed: + elif _dispatchless and is_new and resumed: # A speculative resume also arms is_new. Its native transcript # survives (``resumed`` must stay True so the next turn does not # replay history the session already holds -- the invariant that a @@ -1541,6 +1558,36 @@ async def _claim_session(wait_if_busy: bool) -> tuple[Any, bool, bool]: if _refused_native_todos: _refuse_blocked_slash(turn) return _Flow.END + # Tells the router which chat this KAS session is and how to read the + # chat's approval mode, so a run's steps follow it (a launch's steps too). + try: + get_kas_workflow_router().note_chat_session( + slot.key, + client, + _kas_step_mode_reader(state, slot), + ) + except Exception: # noqa: BLE001 -- never costs the turn + logger.debug("KAS workflow chat not noted", exc_info=True) + if _kas_launch: + _launch_reply = await launch_kas_workflow_from_turn(slot.key, message, client) + slot.append("assistant", _launch_reply or "", "msg msg-a") + state.push_slots_update() + return _Flow.END + if turn._kas_observe: + _observe_refusal = observe_kas_workflow_from_turn(slot.key, message, client, is_new=is_new) + if _observe_refusal is not None: + slot.append("assistant", _observe_refusal, "msg msg-a") + state.push_slots_update() + return _Flow.END + # An ordinary turn on a chat whose workflow run lost its Kiro Agent process + # (a restart) re-attaches the run in the background; a no-op otherwise. + # With the switch off an interrupted run stays parked, as the routes refuse + # to resume it. + if kas_workflows_enabled(loaded_cfg): + try: + get_kas_workflow_router().schedule_reattach(slot.key, client) + except Exception: # noqa: BLE001 -- never costs the turn + logger.debug("KAS workflow reattach not scheduled", exc_info=True) if _deferred_options_expiry: _deferred_options_expiry = False turn._deferred_options_expiry = _deferred_options_expiry @@ -1553,6 +1600,10 @@ async def _claim_session(wait_if_busy: bool) -> tuple[Any, bool, bool]: # this slot (chat_turn/agent_started.py); set again by every turn, so the # agent.agent_started_turns switch applies from the next one. _watch_agent_turns(state, slot, client, loaded_cfg) + # An observe turn sent no prompt: its session's live turn is the one KAS + # started itself, so a steer would land inside Kiro Agent's own turn. + # The steer path reads this and queues the message as the next turn. + slot._kas_observing = turn._kas_observe # Billing stats as they stand BEFORE this turn's prompt is sent. The # runtime installs a fresh per-turn stats object only inside the dispatch # in _run_chat; a turn that dies before that (expired credential, broken pipe) diff --git a/src/kiro_crew/dashboard/chat_turn/turn_dispatch_gates.py b/src/kiro_crew/dashboard/chat_turn/turn_dispatch_gates.py index f5d3cc6ae1fe..526f193b0d12 100644 --- a/src/kiro_crew/dashboard/chat_turn/turn_dispatch_gates.py +++ b/src/kiro_crew/dashboard/chat_turn/turn_dispatch_gates.py @@ -357,7 +357,8 @@ async def _turn_dispatch_gates(turn: _ChatTurn) -> _Flow | None: _replays_prompt = ( _synthetic_recovery_turn and not turn._synthetic_payload and _prompt_hooks_ran(turn) ) - if _sends_prompt: + # An observe turn is not a prompt the person submitted (see _turn_build_prompt). + if _sends_prompt and not turn._kas_observe: injected = await _fire(turn, HOOK_EVENT_USER_PROMPT_SUBMIT, message, replay=_replays_prompt) turn._prompt_hooks_fired = True else: @@ -413,7 +414,7 @@ async def _turn_dispatch_gates(turn: _ChatTurn) -> _Flow | None: # which is how a click reaches a live agent instead of being reverted by # its next full snapshot. A harness that keeps its checklist itself gets # neither (see _checklist_resync). - if _sends_prompt and not is_slash: + if _sends_prompt and not is_slash and not turn._kas_observe: full_message, _todo_sync_rendered, _todo_recovery_carried = await _checklist_resync( slot, full_message, @@ -497,6 +498,7 @@ async def _turn_dispatch_gates(turn: _ChatTurn) -> _Flow | None: and not _turn_provenance_restored and not _is_synthetic and not is_slash + and not turn._kas_observe and message not in _SYNTHETIC_RECOVERY_MSGS and not _synthetic_recovery_turn ): diff --git a/src/kiro_crew/dashboard/chat_turn/turn_entry.py b/src/kiro_crew/dashboard/chat_turn/turn_entry.py index 877abe9becb0..332edf4ddd97 100644 --- a/src/kiro_crew/dashboard/chat_turn/turn_entry.py +++ b/src/kiro_crew/dashboard/chat_turn/turn_entry.py @@ -517,6 +517,9 @@ async def _turn_open(turn: _ChatTurn) -> _Flow | None: # object must hold it before the cut is published on the slot. Nothing touches it # between here and the flag block. turn._produced_visible_output = False + # Set after the session claim when this turn reads a turn KAS started on its + # own (kiro_crew.kas_workflows.router.observe_from_turn); read after the stream. + turn._kas_observe = False # Continues the slot's counter rather than starting at 0: seqs are ordered # across turns so a client floor from an earlier turn sits below every # chunk of this one (see _ChatSlot._chunk_seq). @@ -1154,6 +1157,7 @@ async def _turn_release_handles(turn: _ChatTurn) -> None: # flush into a finished turn's (already-flushed) locals. slot._steer_segment_cut = None slot._compact_command_turn = False + slot._kas_observing = False # Same lifecycle for the child-fidelity opt-in latched at turn start: # it is THIS consumer's promise to render the low-fidelity downgrade # card. Leaving it set would let a later, fidelity-UNAWARE consumer of diff --git a/src/kiro_crew/dashboard/chat_turn/turn_locals.py b/src/kiro_crew/dashboard/chat_turn/turn_locals.py index 0784ece3d3bd..7656d5f4e2f9 100644 --- a/src/kiro_crew/dashboard/chat_turn/turn_locals.py +++ b/src/kiro_crew/dashboard/chat_turn/turn_locals.py @@ -208,6 +208,8 @@ class _ChatTurn: _is_refusal_retry_turn: "bool" _is_synthetic: "bool" _jev_route_text: "str" + _kas_observe: "bool" + _kas_person_only: "bool" _l1_escalated: "bool" _l1_interrupted: "bool" _leak_card_posted: "bool" diff --git a/src/kiro_crew/dashboard/chat_turn/turn_spec_hooks.py b/src/kiro_crew/dashboard/chat_turn/turn_spec_hooks.py index 8cd6879606cd..5b18dfcae3df 100644 --- a/src/kiro_crew/dashboard/chat_turn/turn_spec_hooks.py +++ b/src/kiro_crew/dashboard/chat_turn/turn_spec_hooks.py @@ -96,7 +96,10 @@ redact_exfiltration_urls, ) from kiro_crew.dashboard.chat_turn.builtin_tools_notice import _notice_unapplied_builtin_tools - from kiro_crew.dashboard.chat_turn.deny_chokepoints import _redact_display_text + from kiro_crew.dashboard.chat_turn.deny_chokepoints import ( + _credential_tool_hint_for, + _redact_display_text, + ) from kiro_crew.dashboard.chat_turn.mcp_oauth_notice import _notice_dropped_mcp_oauth from kiro_crew.dashboard.chat_turn.mirror_stream_renewal import _stop_mirror_stream_renewal from kiro_crew.dashboard.chat_turn.recipient import ( @@ -111,7 +114,6 @@ ) from kiro_crew.dashboard.chat_turn.tool_approval import ( _SPEC_HOOKS_UNREADABLE_BLOCK, - _credential_tool_hint_for, _owed_refusal_reasons, _project_hook_files_notice, _spec_confirm_hooks_notice, diff --git a/src/kiro_crew/dashboard/chat_utils_injected_rows.py b/src/kiro_crew/dashboard/chat_utils_injected_rows.py index 952d3a2df972..04f9ade03443 100644 --- a/src/kiro_crew/dashboard/chat_utils_injected_rows.py +++ b/src/kiro_crew/dashboard/chat_utils_injected_rows.py @@ -659,6 +659,12 @@ def is_system_injection_item(item: dict) -> bool: #: card as the person's own words. AUTOMATION_STEER_WIRE_KEY = "automationSteer" +#: Queue-entry meta key: the entry is a turn the chat answers from its whole text +#: (a Kiro Agent workflow launch, reconnect or observe marker, +#: ``dashboard/handlers/kas_workflows.py``), so it drains alone. Merged with another +#: message it would be part of the prompt, and the turn would go to the model as text. +DRAINS_ALONE_META = "drains_alone" + def releases_past_subagent_hold(item: dict) -> bool: """Whether the sub-agent hold lets *item* drain while children still run. @@ -737,7 +743,8 @@ def _dequeue_next_message(slot, merge_enabled: bool) -> tuple: A merge run stops at a system injection, at an attachment-bearing entry (see :func:`carries_attachments`), at a possibly-delivered steer (``STEER_POSSIBLY_DELIVERED_META``), at a requeued automation steer - (:data:`AUTOMATION_STEER_META`), at an entry a decision steered + (:data:`AUTOMATION_STEER_META`), at a turn read from its whole text + (:data:`DRAINS_ALONE_META`), at an entry a decision steered (``meta.decisions_strip``) and where the stamped turn actor changes, so an app's queued send never folds into the user's own words, and where the stamped source channels change, so a turn admission refuses for one @@ -765,6 +772,8 @@ def _dequeue_next_message(slot, merge_enabled: bool) -> tuple: or (item.get("meta") or {}).get(STEER_POSSIBLY_DELIVERED_META) # Automation text, never folded into a person's row. or (item.get("meta") or {}).get(AUTOMATION_STEER_META) + # A marker the chat's turn matches whole; merged, no run starts. + or (item.get("meta") or {}).get(DRAINS_ALONE_META) is True # A decision's receipt names one message; a merged row has one meta. or (item.get("meta") or {}).get("decisions_strip") ): diff --git a/src/kiro_crew/dashboard/handlers/core_config_schema.py b/src/kiro_crew/dashboard/handlers/core_config_schema.py index 7be3ae077f92..2536ee64db49 100644 --- a/src/kiro_crew/dashboard/handlers/core_config_schema.py +++ b/src/kiro_crew/dashboard/handlers/core_config_schema.py @@ -282,6 +282,8 @@ def _acp_backend_patch_values() -> list[str]: # Settings > Developer > Feature Previews > Session control. Read on every # session-control call, so no restart. "agent.session_control": {"type": "bool"}, + # KAS's own workflows, the single gateway opt-in (kiro_crew.kas_workflows). + "agent.kas_workflows": {"type": "bool"}, "agent.completion_keep": {"type": "enum", "values": ["head", "tail", "both"]}, "agent.completion_keep_chars": { "type": "int", diff --git a/src/kiro_crew/dashboard/handlers/kas_workflows.py b/src/kiro_crew/dashboard/handlers/kas_workflows.py new file mode 100644 index 000000000000..fd85ec24a6ee --- /dev/null +++ b/src/kiro_crew/dashboard/handlers/kas_workflows.py @@ -0,0 +1,1170 @@ +"""Dashboard routes for KAS's own workflow engine (``/api/workflows/kas/*``). + +Served only while the configured agent backend brings its own engine AND the +operator turned on ``agent.kas_workflows`` (the single opt-in, +:func:`kiro_crew.kas_workflows.engine.kas_workflows_enabled`); otherwise every +route answers 409 ``engine_not_kas`` and Crew's own ``/api/workflows/*`` routes +apply. + +A run's parent is a visible chat. The client opens that chat the normal way +(``POST /api/chat/slots`` with the run's title, folder and project), then posts +here naming it; this route registers the launch and sends the chat its launch +message, and the chat's own turn starts the run on its own Kiro Agent session +(:func:`kiro_crew.kas_workflows.router.launch_from_turn`). + +Every route is the dashboard OWNER's: these start runs that execute tools, and +answer the permission prompts those tools raise. App tokens are refused. +""" + +from __future__ import annotations + +import asyncio +import logging +import os +import re +from typing import Any, Awaitable, Callable + +from aiohttp import web + +from kiro_crew.dashboard.chat_utils_injected_rows import DRAINS_ALONE_META +from kiro_crew.dashboard.handlers.workflows import ( + _audit_authorization, + _error, + _json_response_off_loop, + _redact_obj, +) + +logger = logging.getLogger(__name__) + +#: Most inputs one launch may carry, and the longest value. +_MAX_INPUTS = 64 +_MAX_INPUT_CHARS = 16 * 1024 + + +#: Operations that only READ a run the router already holds. When the switch is +#: off these stay available (together with Stop) so a run still in flight can be +#: viewed and halted, while launching and controlling it are refused (gap 5). +_READ_ONLY_WHEN_HELD = frozenset( + { + "workflow.kas.state", + "workflow.kas.run", + "workflow.kas.slot_runs", + "workflow.kas.step_transcript", + "workflow.kas.runs", + } +) + + +async def _refusal(request: web.Request, operation: str) -> web.Response | None: + """Owner-only, and only while KAS owns workflows AND the operator opted in. + + When the switch is off we are normally exactly origin/main: every route + answers 409 ``engine_not_kas``. The one exception (gap 5): on a Kiro Agent + backend where the router still holds a run the operator turned the feature + off under, the run's READS and its Stop stay open so it can be viewed and + halted; launch/resume/retry/grant/answers are still refused. With no held + run — or on any other backend — nothing is open, so OFF is origin/main. + """ + from kiro_crew.config import KiroCrewConfig + from kiro_crew.dashboard.handlers._shared import require_owner_dashboard_request + from kiro_crew.kas_workflows.engine import backend_brings_kas_workflows, kas_workflows_enabled + + if request.get("app"): + return _error("dashboard user required", "dashboard_user_required", 403) + denied = await require_owner_dashboard_request(request, operation) + if denied is not None: + return denied + config = await asyncio.to_thread(KiroCrewConfig.load) + if kas_workflows_enabled(config): + return None + # Switch off. Read-only-held-run mode only on a Kiro Agent backend that still + # holds at least one run; otherwise refuse everything (origin/main shape). + if backend_brings_kas_workflows(getattr(config.agent, "acp_backend", "")): + from kiro_crew.kas_workflows.router import get_router + + if get_router().rows(): + if operation in _READ_ONLY_WHEN_HELD: + return None + if operation == "workflow.kas.control" and request.match_info.get("action") == "cancel": + return None + return _error( + "Kiro Workflows is turned off, so this run can be viewed but not controlled", + "engine_not_kas", + 409, + ) + return _error( + "Kiro Agent is not the selected agent, so its workflows are unavailable", + "engine_not_kas", + 409, + ) + + +_INVALID_CWD = ( + "cwd must be an existing project directory inside your home directory, " + "the gateway's project directory or a recent project" +) + + +def _project_dir(raw: Any, *, server_held: str = "") -> str | None: + """*raw* as an existing, non-sensitive project directory under an allowed root, or None. + + The roots are server-held (home, the gateway's project directory, the + recent-projects list); *server_held* adds one more, for a value the gateway + itself holds (a chat's own project), never one taken from the request. + Blocking: it reads the recent-projects file and resolves every root, so a + route runs it with ``asyncio.to_thread``, as it does :func:`_recipe_dir_allowed`. + """ + from kiro_crew.kas_workflows.project_root import allowed_project_roots, confine_project_dir + + extra = [server_held] if server_held else [] + return confine_project_dir(raw, allowed_project_roots(extra)) + + +def _router_error(exc: Exception) -> web.Response: + from kiro_crew.kas_workflows.router import KasWorkflowError + + if isinstance(exc, KasWorkflowError): + return _error(str(_redact_obj(str(exc))), "kas_workflow_error", 409) + logger.warning("KAS workflow route failed", exc_info=True) + return _error("Kiro Workflows request failed", "kas_workflow_failed", 500) + + +async def _body(request: web.Request) -> dict[str, Any] | None: + try: + body = await request.json() + except Exception: # noqa: BLE001 + return None + return body if isinstance(body, dict) else None + + +def _marker_queue_meta() -> dict[str, Any]: + """Queue meta for a launch, reconnect or observe marker: it drains alone. + + Turn admission knows each marker only when it is the whole prompt, so a + queued marker never merges with another queued message, whatever + ``dashboard.merge_queued_messages`` says. + """ + return {DRAINS_ALONE_META: True} + + +async def _send_reconnect(state: Any, router: Any, slot_key: str) -> bool: + """Send *slot_key*'s chat a reconnect turn; False when the chat is gone. + + A chat restored at gateway start has not read its transcript window yet, and + queuing a turn reads it; the window is loaded off the loop first + (``load_window_off_loop``), as every reader of a live chat does. A caller + that decides on the chat's state first (busy, the gateway stopping) loads + the window before that check, so this load returns without suspending and + nothing runs between the check and the queued turn. + """ + from kiro_crew.dashboard.chat import _run_chat + from kiro_crew.dashboard.state import load_window_off_loop + + slot = state.get_slot(slot_key) if state is not None else None + if slot is None: + return False + await load_window_off_loop(slot) + slot = state.get_slot(slot_key) + if slot is None: + return False + slot.enqueue_or_run_prompt( + router.prepare_reconnect(slot_key), _run_chat, state, extra_meta=_marker_queue_meta() + ) + state.push_slots_update() + return True + + +def boot_recovery_enabled(config: Any) -> bool: + """Boot recovery runs only on KAS, and only with the KAS workflows switch on. + + One gateway setting now, ``agent.kas_workflows``, read through the shared + :func:`kiro_crew.kas_workflows.engine.kas_workflows_enabled` gate (there is no + longer a per-device preview flag to miss). + """ + from kiro_crew.kas_workflows.engine import kas_workflows_enabled + + return kas_workflows_enabled(config) + + +async def recover_runs_on_boot( + state: Any, + *, + sleep: Callable[[float], Awaitable[Any]] = asyncio.sleep, + load_config: Callable[[], Any] | None = None, +) -> list[tuple[str, str, str]]: + """At gateway start, reattach the chats of this gateway's interrupted runs. + + Waits out KAS's owner-abandonment window first, so the previous gateway's + runs read stale to KAS. Then re-reads the gate (the operator may have + changed it meanwhile) and hands the router the open chats' project folders + to list first, and this gateway's chats: one reconnect turn per chat, + awaited, so the router's concurrency bound holds. Never calls ``resumeAll`` + (see :meth:`KasWorkflowRouter.recover_on_boot`). + """ + from kiro_crew.config import KiroCrewConfig + from kiro_crew.kas_workflows import router as router_mod + + reader = load_config or KiroCrewConfig.load + if not boot_recovery_enabled(await asyncio.to_thread(reader)): + return [] + await sleep(router_mod.OWNER_ABANDON_SECS + router_mod.BOOT_RECOVERY_SLACK_SECS) + if not boot_recovery_enabled(await asyncio.to_thread(reader)): + return [] + router = router_mod.get_router() + + def chat_exists(slot_key: str) -> bool: + return state is not None and state.get_slot(slot_key) is not None + + async def reconnect(slot_key: str) -> bool: + from kiro_crew.dashboard.state import load_window_off_loop + + slot = state.get_slot(slot_key) if state is not None else None + if slot is None: + return False + await load_window_off_loop(slot) # before the busy check (_send_reconnect) + slot = state.get_slot(slot_key) + if slot is None: + return False + if getattr(slot, "running", False): + # Its own turn reattaches it (KasWorkflowRouter.schedule_reattach). + return False + if not await _send_reconnect(state, router, slot_key): + return False + task = getattr(slot, "task", None) + if isinstance(task, asyncio.Future): + try: + await asyncio.wait_for( + asyncio.shield(task), timeout=router_mod.BOOT_RECOVERY_TURN_SECS + ) + except Exception: # noqa: BLE001 -- a timeout or a failed turn reports itself + logger.debug("boot reconnect turn for %s did not settle", slot_key) + return True + + return await router.recover_on_boot(chat_exists, reconnect, folders=_open_chat_folders(state)) + + +def _open_chat_folders(state: Any) -> list[str]: + """The project folder of each open chat that has one, for boot recovery to list.""" + slots = getattr(state, "_slots", None) + if not isinstance(slots, dict): + return [] + return [str(slot.project) for slot in list(slots.values()) if getattr(slot, "project", "")] + + +#: The one boot-recovery task this process started (cancelled at shutdown). +_BOOT_RECOVERY: list[asyncio.Task] = [] + + +def start_kas_boot_recovery(state: Any) -> None: + """Start :func:`recover_runs_on_boot` once per process, off the boot path. + + It waits out KAS's owner window before doing anything, and a failure only + leaves interrupted runs for their chats' next turn or the next Kiro Agent + process crash to reconnect. + """ + if _BOOT_RECOVERY: + return + + async def _go() -> None: + try: + await recover_runs_on_boot(state) + except asyncio.CancelledError: + raise + except Exception: # noqa: BLE001 -- best effort; reconnect-on-turn still works + logger.info("KAS workflow boot recovery failed", exc_info=True) + + task = asyncio.create_task(_go(), name="kas-workflow-boot-recovery") + _BOOT_RECOVERY.append(task) + tasks = getattr(state, "_background_tasks", None) + if isinstance(tasks, set): + tasks.add(task) + task.add_done_callback(tasks.discard) + + +def cancel_kas_boot_recovery() -> None: + for task in _BOOT_RECOVERY: + if not task.done(): + task.cancel() + + +def observe_turn_starter(state: Any) -> Any: + """How the KAS router sends a chat the observe turn for a run's end. + + KAS wakes a run's parent with a model turn only when that session is idle; + a chat mid-turn has KAS's nudge folded into the turn it is running, so there + is no separate engine turn to read and the chat is skipped (an observe + queued behind that turn would only read nothing and say so). A closed chat + is skipped too. + + A chat restored at gateway start has not read its transcript window, and + queuing a turn reads it. For such a chat the window is read off the loop + first (``load_window_off_loop``), then the same checks run and the turn is + queued; when it is not started then, the router's observe token is dropped + (``take_observe``), as the router drops it for a start refused at once. + """ + + def enqueue(slot: Any, message: str) -> bool: + from kiro_crew.dashboard.chat import _run_chat + + started = bool( + slot.enqueue_or_run_prompt(message, _run_chat, state, extra_meta=_marker_queue_meta()) + ) + state.push_slots_update() + return started + + async def start_after_window(slot_key: str, message: str) -> None: + from kiro_crew.dashboard.state import load_window_off_loop + from kiro_crew.kas_workflows import router as router_mod + + started = False + try: + slot = state.get_slot(slot_key) + if slot is not None: + await load_window_off_loop(slot) + slot = state.get_slot(slot_key) + if slot is not None and not getattr(slot, "running", False): + started = enqueue(slot, message) + except Exception: # noqa: BLE001 -- a chat that cannot take it loses only the view + logger.warning("KAS workflow observe turn not started for %s", slot_key, exc_info=True) + router = getattr(router_mod, "_ROUTER", None) + token = router.observe_token(message) if router is not None else None + if not started and router is not None and token: + router.take_observe(slot_key, token) + + def start(slot_key: str, message: str) -> bool: + slot = state.get_slot(slot_key) + if slot is None or getattr(slot, "running", False): + return False + if getattr(slot, "window_pending", False) is not True: + return enqueue(slot, message) + task = asyncio.get_running_loop().create_task(start_after_window(slot_key, message)) + tasks = getattr(state, "_background_tasks", None) + if isinstance(tasks, set): + tasks.add(task) + task.add_done_callback(tasks.discard) + return True + + return start + + +#: A model id or effort level a launch may name: KAS treats an unknown model as a +#: warning and an unsupported effort as the model's default, so only the shape +#: is checked here. +_OPTION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$") + + +def _launch_options(body: dict[str, Any]) -> dict[str, str] | web.Response: + """``model`` / ``effort`` from a launch body, or a 400.""" + out: dict[str, str] = {} + for key in ("model", "effort"): + raw = body.get(key) + if raw is None or raw == "" or raw == "auto": + continue + if not isinstance(raw, str) or not _OPTION_RE.fullmatch(raw): + return _error(f"{key} must be a model or effort id", f"invalid_{key}", 400) + out[key] = raw + return out + + +#: KAS's own run-label rules (acp-type-covenant ``WorkflowRunLabelSchema``): +#: at most 100 characters, no control characters, line/paragraph separators or +#: double quotes. KAS REJECTS a label that breaks them, and the launch only +#: reaches KAS on the chat's turn, after this route has answered 202, so the +#: person's display name is made to fit here instead (the same rewrite KAS's +#: ``sanitizeRunLabelForDisplay`` applies to labels it composes itself). +_RUN_LABEL_MAX_CHARS = 100 +_RUN_LABEL_FORBIDDEN_RE = re.compile("[\u0000-\u001f\u007f-\u009f\u2028\u2029]") + + +def _run_label(raw: Any) -> str | None: + """A launch's ``runLabel`` made to pass KAS's rules, or None when blank.""" + if not isinstance(raw, str): + return None + cleaned = _RUN_LABEL_FORBIDDEN_RE.sub(" ", raw).replace('"', "'").strip() + return cleaned[:_RUN_LABEL_MAX_CHARS].strip() or None + + +def _inputs(raw: Any) -> dict[str, str] | None: + raw = raw or {} + if not isinstance(raw, dict) or len(raw) > _MAX_INPUTS: + return None + out: dict[str, str] = {} + for key, value in raw.items(): + if not isinstance(key, str) or not isinstance(value, str) or len(value) > _MAX_INPUT_CHARS: + return None + out[key] = value + return out + + +#: A recipe's file lives under ``/.kiro/workflows``. A new recipe's name +#: is also its file stem, so it must be a safe basename: a leading alphanumeric +#: then letters, digits, dots, dashes and underscores (no ``/``, no ``..`` — the +#: leading-alnum rule rejects a name that starts with a dot). Mirrors the +#: extension's ``RECIPE_NAME_PATTERN`` (``workflow-recipe-create.ts``). +_RECIPE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$") +_RECIPE_FILE_SUFFIX = ".workflow.json" +_WORKFLOWS_DIR = (".kiro", "workflows") + + +def _recipe_name(raw: Any) -> str | None: + """A recipe name that is a safe file stem, or None.""" + if not isinstance(raw, str): + return None + name = raw.strip() + return name if _RECIPE_NAME_RE.fullmatch(name) else None + + +def _workflows_dir(scope: Any, cwd: str) -> str | None: + """The ``.kiro/workflows`` directory a new recipe of *scope* is written to. + + ``workspace`` is under the project *cwd*; ``global`` is under the user's + home. The path is composed from fixed segments and an already-validated + name, never from client text, so nothing can escape the workflows dir. + """ + if scope == "workspace": + return os.path.join(cwd, *_WORKFLOWS_DIR) + if scope == "global": + return os.path.join(os.path.expanduser("~"), *_WORKFLOWS_DIR) + return None + + +def _global_workflows_root() -> str: + """The real ``~/.kiro/workflows`` a global recipe must sit under. Blocking: it resolves home.""" + return os.path.join(os.path.realpath(os.path.expanduser("~")), *_WORKFLOWS_DIR) + + +def _under(path: str, root: str) -> bool: + return path == root or path.startswith(root + os.sep) + + +def _recipe_dir_allowed(resolved_dir: str, cwd: str, scope: str | None = None) -> bool: + """Whether the REAL directory *resolved_dir* may hold a recipe Crew writes or removes. + + ``os.makedirs``/``open``/``os.remove`` follow symlinks, so a symlinked + ``.kiro`` or ``workflows`` could lead them out of the project (workspace) or + the user's workflows dir (global). *cwd* is already realpath'd by + :func:`_project_dir`. With no *scope*, either root is allowed (a delete, + where the recipe's own listing says which it is). + """ + roots = { + "workspace": [cwd], + "global": [_global_workflows_root()], + None: [cwd, _global_workflows_root()], + }.get(scope, []) + return any(_under(resolved_dir, root) for root in roots) + + +def _recipe_scaffold(name: str) -> str: + """A minimal recipe that passes KAS validation: one coder step over a prompt. + + The same shape the extension writes (``recipeScaffold``), so a created + recipe is immediately launchable and editable. + """ + import json + + recipe = { + "name": name, + "description": "Describe what this workflow does.", + "inputs": {"task": "prompt"}, + "steps": [{"type": "step", "id": "main", "agent": "wf-coder", "prompt": "{{task}}"}], + } + return json.dumps(recipe, indent=2) + "\n" + + +async def api_kas_recipe_detail(request: web.Request) -> web.Response: + """GET /api/workflows/kas/recipes/detail?cwd=&source= — one recipe with its steps. + + ``source`` must be a recipe KAS lists for ``cwd`` right now (the router + checks), so no caller can name an arbitrary file to read. A ``.workflow.json`` + recipe answers its steps' agent and prompt text; a bundled or YAML recipe + answers ``definitionAvailable: false`` with no steps (gap 27). + """ + refusal = await _refusal(request, "workflow.kas.recipe_detail") + if refusal is not None: + return refusal + cwd = await asyncio.to_thread(_project_dir, request.query.get("cwd")) + if cwd is None: + return _error(_INVALID_CWD, "invalid_cwd", 400) + source = request.query.get("source") + if not isinstance(source, str) or not source.strip(): + return _error("source is required", "invalid_source", 400) + from kiro_crew.kas_workflows.router import get_router + + try: + detail = await get_router().recipe_detail(cwd, source.strip()) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + return web.json_response(_redact_obj(detail)) + + +async def api_kas_recipe_create(request: web.Request) -> web.Response: + """POST /api/workflows/kas/recipes — {cwd, name, scope: workspace|global}. + + Writes ``/.kiro/workflows/.workflow.json`` with a minimal valid + scaffold, WITHOUT overwriting an existing file (create-exclusive). ``name`` + must be a safe basename; the directory is composed from fixed segments, so + the path cannot escape the workflows directory (gap 18). + """ + refusal = await _refusal(request, "workflow.kas.recipe_create") + if refusal is not None: + return refusal + body = await _body(request) + if body is None: + return _error("a JSON object body is required", "invalid_body", 400) + cwd = await asyncio.to_thread(_project_dir, body.get("cwd")) + if cwd is None: + return _error(_INVALID_CWD, "invalid_cwd", 400) + name = _recipe_name(body.get("name")) + if name is None: + return _error( + "name must start with a letter or digit and use only letters, digits, dots, " + "dashes and underscores", + "invalid_name", + 400, + ) + scope = body.get("scope") + directory = _workflows_dir(scope, cwd) + if directory is None: + return _error("scope must be 'workspace' or 'global'", "invalid_scope", 400) + # Confine the REAL target. ``os.makedirs`` + ``open('x')`` follow symlinks, + # so a symlinked ``.kiro`` or ``workflows`` could lead the write out of the + # project (workspace) or the user's workflows dir (global). Resolve the + # directory and refuse unless it still sits under the allowed root (``cwd`` + # is already realpath'd by ``_project_dir``). + resolved_dir = await asyncio.to_thread(os.path.realpath, directory) + if not await asyncio.to_thread(_recipe_dir_allowed, resolved_dir, cwd, scope): + return _error( + "the recipe directory resolves outside the allowed location", + "recipe_path_escape", + 400, + ) + path = os.path.join(resolved_dir, name + _RECIPE_FILE_SUFFIX) + + def _write() -> str | None: + os.makedirs(resolved_dir, exist_ok=True) + try: + # Exclusive create: never clobber an existing recipe. + with open(path, "x", encoding="utf-8") as handle: + handle.write(_recipe_scaffold(name)) + except FileExistsError: + return None + return path + + try: + written = await asyncio.to_thread(_write) + except OSError: + logger.warning("KAS recipe create failed", exc_info=True) + return _error("The recipe file could not be written", "recipe_write_failed", 500) + if written is None: + return _error("A recipe with that name already exists", "recipe_exists", 409) + _audit_authorization(request, "workflow.kas.recipe_create", f"allowed:{name}") + return web.json_response({"name": name, "source": written}, status=201) + + +async def api_kas_recipe_delete(request: web.Request) -> web.Response: + """DELETE /api/workflows/kas/recipes?cwd=&source= — remove a recipe file. + + ``source`` must be a recipe KAS lists for ``cwd`` right now and NOT read-only + (built-in / bundled recipes have no file to remove), so only a real, + editable recipe file is deleted — no caller can name an arbitrary path + (gap 18). + """ + refusal = await _refusal(request, "workflow.kas.recipe_delete") + if refusal is not None: + return refusal + cwd = await asyncio.to_thread(_project_dir, request.query.get("cwd")) + if cwd is None: + return _error(_INVALID_CWD, "invalid_cwd", 400) + source = request.query.get("source") + if not isinstance(source, str) or not source.strip(): + return _error("source is required", "invalid_source", 400) + source = source.strip() + from kiro_crew.kas_workflows.router import get_router + + try: + recipes = await get_router().recipes(cwd) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + match = next((r for r in recipes if r.get("source") == source), None) + if match is None: + return _error("That recipe is not listed for this project", "recipe_unknown", 404) + if match.get("readOnly"): + return _error("A built-in recipe cannot be deleted", "recipe_read_only", 409) + if not ( + isinstance(source, str) and os.path.isabs(source) and source.endswith(_RECIPE_FILE_SUFFIX) + ): + return _error("That recipe has no file to delete", "recipe_no_file", 409) + # KAS lists what it finds under ``.kiro/workflows``, symlinks followed, so a + # listed file is not yet proof it lives where Crew may remove files: confine + # the file's REAL directory exactly as create confines its write. Removing + # a symlinked recipe removes the link, never its target. + source_dir = await asyncio.to_thread(os.path.realpath, os.path.dirname(source)) + if not await asyncio.to_thread(_recipe_dir_allowed, source_dir, cwd): + return _error( + "the recipe file resolves outside the allowed location", + "recipe_path_escape", + 400, + ) + + def _remove() -> bool: + try: + os.remove(source) + except FileNotFoundError: + return True + except OSError: + return False + return True + + if not await asyncio.to_thread(_remove): + logger.warning("KAS recipe delete failed", exc_info=True) + return _error("The recipe file could not be removed", "recipe_delete_failed", 500) + _audit_authorization(request, "workflow.kas.recipe_delete", "allowed") + return web.json_response({"deleted": True}) + + +async def api_kas_recipes(request: web.Request) -> web.Response: + """GET /api/workflows/kas/recipes?cwd= — the recipes KAS offers for a project.""" + refusal = await _refusal(request, "workflow.kas.recipes") + if refusal is not None: + return refusal + cwd = await asyncio.to_thread(_project_dir, request.query.get("cwd")) + if cwd is None: + return _error(_INVALID_CWD, "invalid_cwd", 400) + from kiro_crew.kas_workflows.router import get_router + + try: + recipes = await get_router().recipes(cwd) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + return web.json_response(_redact_obj({"recipes": recipes})) + + +async def api_kas_runs(request: web.Request) -> web.Response: + """GET /api/workflows/kas/runs?cwd= — a project's runs, from disk.""" + refusal = await _refusal(request, "workflow.kas.runs") + if refusal is not None: + return refusal + cwd = await asyncio.to_thread(_project_dir, request.query.get("cwd")) + if cwd is None: + return _error(_INVALID_CWD, "invalid_cwd", 400) + from kiro_crew.kas_workflows.router import get_router + + router = get_router() + try: + runs = await router.runs(cwd) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + return web.json_response( + _redact_obj( + { + "runs": runs, + "approvals": router.approvals(), + "questions": router.questions(), + "revision": router.revision, + } + ) + ) + + +async def api_kas_state(request: web.Request) -> web.Response: + """GET /api/workflows/kas/state — revision, known runs, approvals, questions. + + Reads only what the router already holds: it starts no process, sends no + turn and decides no held approval. A chat's mode change re-decides held + approvals and a process crash reconnects interrupted runs + (``kas_workflow_triggers``); a client learns of either from the + ``kas_workflow_revision`` frame on ``/api/ws``. + """ + refusal = await _refusal(request, "workflow.kas.state") + if refusal is not None: + return refusal + from kiro_crew.kas_workflows.router import get_router + + router = get_router() + return web.json_response( + _redact_obj( + { + "revision": router.revision, + "runs": router.rows(), + "approvals": router.approvals(), + "questions": router.questions(), + # The recipe list's own change key: bumped on every KAS + # ``recipes_changed`` push, so a client invalidates its cached + # recipe list the moment the set on disk changes (gap 16). + "recipesRevision": router.recipes_revision, + } + ) + ) + + +async def api_kas_run_start(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs — {slot, source, inputs?, runLabel?, name?}. + + ``slot`` is the chat that will parent the run; its project is the run's + project. Answers 202: the run starts when that chat's launch turn runs. + """ + refusal = await _refusal(request, "workflow.kas.start") + if refusal is not None: + return refusal + body = await _body(request) + if body is None: + return _error("a JSON object body is required", "invalid_body", 400) + slot_key = body.get("slot") + state = request.app.get("state") + slot = state.get_slot(slot_key) if state is not None and isinstance(slot_key, str) else None + if slot is None: + return _error("slot must name an open chat", "invalid_slot", 400) + slot_project = getattr(slot, "project", "") or "" + cwd = await asyncio.to_thread(_project_dir, slot_project, server_held=slot_project) + if cwd is None: + return _error("the chat must have a project directory", "invalid_cwd", 400) + source = body.get("source") + if not isinstance(source, str) or not source.strip(): + return _error("source is required", "invalid_source", 400) + inputs = _inputs(body.get("inputs")) + if inputs is None: + return _error("inputs must be an object of strings", "invalid_inputs", 400) + run_label = _run_label(body.get("runLabel")) + name = body.get("name") if isinstance(body.get("name"), str) else "" + options = _launch_options(body) + if isinstance(options, web.Response): + return options + from kiro_crew.dashboard.chat import _run_chat + from kiro_crew.dashboard.state import load_window_off_loop + from kiro_crew.kas_workflows.router import get_router + + # Queuing the launch reads the chat's transcript window, which a chat + # restored at gateway start has not read yet: off the loop first, as + # _send_reconnect does. The chat must still be open after these awaits. + await load_window_off_loop(slot) + if state.get_slot(slot_key) is not slot: + return _error("slot must name an open chat", "invalid_slot", 400) + try: + launch = get_router().prepare_launch( + slot.key, + cwd, + source.strip(), + inputs, + run_label=run_label, + model=options.get("model"), + effort=options.get("effort"), + ) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + started = slot.enqueue_or_run_prompt( + launch.message(run_label or name or source.strip()), + _run_chat, + state, + extra_meta=_marker_queue_meta(), + ) + state.push_slots_update() + _audit_authorization(request, "workflow.kas.start", "allowed") + return web.json_response({"slot": slot.key, "queued": not started}, status=202) + + +async def api_kas_run_get(request: web.Request) -> web.Response: + """GET /api/workflows/kas/runs/{workflow_id} — one run with its approvals.""" + refusal = await _refusal(request, "workflow.kas.run") + if refusal is not None: + return refusal + from kiro_crew.kas_workflows.router import get_router + + try: + row = get_router().run(request.match_info["workflow_id"]) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + return web.json_response(_redact_obj(row)) + + +async def api_kas_slot_runs(request: web.Request) -> web.Response: + """GET /api/workflows/kas/slots/{slot}/runs — one chat's runs, reloaded after a restart.""" + refusal = await _refusal(request, "workflow.kas.slot_runs") + if refusal is not None: + return refusal + from kiro_crew.kas_workflows.router import get_router + + router = get_router() + try: + runs = await router.chat_runs(request.match_info["slot"]) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + return web.json_response( + _redact_obj( + { + "runs": runs, + "approvals": router.approvals(), + "questions": router.questions(), + "revision": router.revision, + } + ) + ) + + +async def api_kas_step_transcript(request: web.Request) -> web.Response: + """GET /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/transcript — a step's chat. + + Serves the router's kept copy of the step's conversation + (:meth:`KasWorkflowRouter.step_transcript`, folded from the frames the step's + Kiro Agent process sends); no session file is read. ``?path=`` (the node's + runtime path) picks one iteration of a loop's step. + """ + refusal = await _refusal(request, "workflow.kas.step_transcript") + if refusal is not None: + return refusal + from kiro_crew.kas_workflows.router import StepNotStarted, get_router + + path = (request.query.get("path") or "")[:2000] or None + try: + body = await get_router().step_transcript( + request.match_info["workflow_id"], request.match_info["node_id"], path + ) + except StepNotStarted as exc: + return _error(str(_redact_obj(str(exc))), "step_unknown", 404) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + # Like every other KAS read: the transcript builder redacts its text fields, + # but names, kinds and session metadata ride through raw, so the whole body + # takes the same recursive key-and-value pass (off the loop: it can be big). + return await _json_response_off_loop(body) + + +async def api_kas_run_control(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs/{workflow_id}/{action} — pause|resume|cancel|delete.""" + refusal = await _refusal(request, "workflow.kas.control") + if refusal is not None: + return refusal + from kiro_crew.kas_workflows.router import CONTROL_METHODS, get_router + + action = request.match_info["action"] + if action not in CONTROL_METHODS: + return _error("unknown action", "invalid_action", 400) + body = await _body(request) or {} + reason = body.get("reason") if isinstance(body.get("reason"), str) else None + workflow_id = request.match_info["workflow_id"] + router = get_router() + try: + await router.control(workflow_id, action, reason) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, f"workflow.kas.{action}", "allowed") + return web.json_response( + _redact_obj({"workflowId": workflow_id, "row": router.run_row(workflow_id)}) + ) + + +async def api_kas_step_reply(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/reply — {text, path?}. + + Sends the person's reply to a step parked for their next message. + """ + refusal = await _refusal(request, "workflow.kas.step_reply") + if refusal is not None: + return refusal + body = await _body(request) or {} + text = body.get("text") + if not isinstance(text, str): + return _error("text is required", "invalid_reply", 400) + raw_path = body.get("path") + path = raw_path[:2000] if isinstance(raw_path, str) and raw_path else None + from kiro_crew.kas_workflows.router import StepNotStarted, get_router + + workflow_id = request.match_info["workflow_id"] + try: + await get_router().reply_to_step(workflow_id, request.match_info["node_id"], path, text) + except StepNotStarted as exc: + return _error(str(_redact_obj(str(exc))), "step_unknown", 404) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.step_reply", "allowed") + return web.json_response({"sent": True}) + + +#: The longest model id or effort level the model route takes; Kiro Agent's are short. +_MAX_MODEL_FIELD_CHARS = 200 + + +async def api_kas_step_model(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/model — {model?, effort?, path?}. + + Changes the model or the effort level a running or parked step's next turn + runs on (:meth:`KasWorkflowRouter.set_step_model`); an empty ``effort`` picks + the model's own default level. Answers the values now in force. + """ + refusal = await _refusal(request, "workflow.kas.step_model") + if refusal is not None: + return refusal + body = await _body(request) or {} + model = body.get("model") + effort = body.get("effort") + if model is not None and (not isinstance(model, str) or not model.strip()): + return _error("model must be a model id", "invalid_model", 400) + if effort is not None and not isinstance(effort, str): + return _error("effort must be an effort level", "invalid_model", 400) + if model is None and effort is None: + return _error("model or effort is required", "invalid_model", 400) + if len(model or "") > _MAX_MODEL_FIELD_CHARS or len(effort or "") > _MAX_MODEL_FIELD_CHARS: + return _error("model or effort is too long", "invalid_model", 400) + raw_path = body.get("path") + path = raw_path[:2000] if isinstance(raw_path, str) and raw_path else None + from kiro_crew.kas_workflows.router import StepNotStarted, get_router + + workflow_id = request.match_info["workflow_id"] + try: + answer = await get_router().set_step_model( + workflow_id, + request.match_info["node_id"], + path, + model=model.strip() if model is not None else None, + effort=effort.strip() if effort is not None else None, + ) + except StepNotStarted as exc: + return _error(str(_redact_obj(str(exc))), "step_unknown", 404) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.step_model", "allowed") + return web.json_response(_redact_obj(answer)) + + +async def api_kas_approval_answer(request: web.Request) -> web.Response: + """POST /api/workflows/kas/approvals/{key} — {optionId}: answer a step's prompt.""" + refusal = await _refusal(request, "workflow.kas.approve") + if refusal is not None: + return refusal + body = await _body(request) + option_id = body.get("optionId") if body else None + if not isinstance(option_id, str) or not option_id: + return _error("optionId is required", "invalid_option", 400) + from kiro_crew.kas_workflows.router import get_router + + try: + await get_router().answer(request.match_info["key"], option_id) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.approve", f"answered:{option_id[:64]}") + return web.json_response({"answered": True}) + + +async def api_kas_slot_reconnect(request: web.Request) -> web.Response: + """POST /api/workflows/kas/slots/{slot}/reconnect — re-attach a chat's runs now. + + Sends the chat a reconnect turn, which loads its unfinished runs on the + chat's live Kiro Agent process and resumes any a restart interrupted. + Resets the automatic-reconnect try count for that chat. + """ + refusal = await _refusal(request, "workflow.kas.reconnect") + if refusal is not None: + return refusal + from kiro_crew.kas_workflows.router import get_router + + router = get_router() + slot_key = request.match_info["slot"] + router.reset_reconnect_tries(slot_key) + if not await _send_reconnect(request.app.get("state"), router, slot_key): + return _error("slot must name an open chat", "invalid_slot", 400) + _audit_authorization(request, "workflow.kas.reconnect", "allowed") + return web.json_response({"slot": slot_key}, status=202) + + +def _body_path(body: dict[str, Any]) -> str | None: + raw = body.get("path") + if not isinstance(raw, str): + return None + return raw.strip("/")[:2000] or None + + +def _body_reason(body: dict[str, Any]) -> str | None: + raw = body.get("reason") + return raw if isinstance(raw, str) and raw.strip() else None + + +def _row_response(router: Any, workflow_id: str, **extra: Any) -> web.Response: + return web.json_response( + _redact_obj({"workflowId": workflow_id, "row": router.run_row(workflow_id), **extra}) + ) + + +async def api_kas_run_retry(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs/{workflow_id}/retry — {nodeId?, path?}. + + Retries every failed/aborted step of a finished run, or the one named + (KAS ``_kiro/workflow/retry``). + """ + refusal = await _refusal(request, "workflow.kas.retry") + if refusal is not None: + return refusal + body = await _body(request) or {} + raw_node = body.get("nodeId") + if raw_node is not None and (not isinstance(raw_node, str) or not raw_node): + return _error("nodeId must be a step id", "invalid_node", 400) + from kiro_crew.kas_workflows.router import get_router + + workflow_id = request.match_info["workflow_id"] + router = get_router() + try: + retried = await router.retry(workflow_id, raw_node, _body_path(body)) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.retry", "allowed") + return _row_response(router, workflow_id, retriedNodeIds=retried) + + +async def api_kas_run_restart(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs/{workflow_id}/restart — run a finished run again. + + KAS ``_kiro/workflow/invoke`` on a terminal run resets every step and starts + from scratch. + """ + refusal = await _refusal(request, "workflow.kas.restart") + if refusal is not None: + return refusal + from kiro_crew.kas_workflows.router import get_router + + workflow_id = request.match_info["workflow_id"] + router = get_router() + try: + await router.restart(workflow_id) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.restart", "allowed") + return _row_response(router, workflow_id) + + +async def api_kas_step_grant(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/grant — {iterations, path?}. + + Grants an exhausted loop more passes (KAS ``_kiro/workflow/resume`` with + ``extendRepeat``); done iterations are kept and KAS caps the total. + """ + refusal = await _refusal(request, "workflow.kas.grant") + if refusal is not None: + return refusal + body = await _body(request) or {} + iterations = body.get("iterations") + from kiro_crew.kas_workflows import wire + + if ( + isinstance(iterations, bool) + or not isinstance(iterations, int) + or not 1 <= iterations <= wire.MAX_REPEAT_ITERATIONS + ): + return _error( + f"iterations must be a whole number from 1 to {wire.MAX_REPEAT_ITERATIONS}", + "invalid_iterations", + 400, + ) + from kiro_crew.kas_workflows.router import get_router + + workflow_id = request.match_info["workflow_id"] + router = get_router() + try: + await router.grant( + workflow_id, request.match_info["node_id"], iterations, _body_reason(body) + ) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.grant", f"allowed:{iterations}") + return _row_response(router, workflow_id) + + +async def api_kas_step_complete(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/complete — {status, reason?, path?}. + + Ends a paused step as ``completed`` or ``failed``, or ends the loop the run + is parked on at its limit and continues (``completed`` only). KAS + ``_kiro/workflow/update`` ``update_status`` with ``nodeId``. + """ + refusal = await _refusal(request, "workflow.kas.complete") + if refusal is not None: + return refusal + body = await _body(request) or {} + status = body.get("status") + if status not in ("completed", "failed"): + return _error("status must be completed or failed", "invalid_status", 400) + from kiro_crew.kas_workflows.router import get_router + + workflow_id = request.match_info["workflow_id"] + router = get_router() + try: + message = await router.end_step( + workflow_id, + request.match_info["node_id"], + status, + _body_reason(body), + _body_path(body), + ) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.complete", f"allowed:{status}") + return _row_response(router, workflow_id, message=message) + + +async def api_kas_step_cancel(request: web.Request) -> web.Response: + """POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/cancel — {path?}. + + Stops one running step (``session/cancel`` on its session); parallel + siblings keep running and the stopped step can be resumed. + """ + refusal = await _refusal(request, "workflow.kas.step_cancel") + if refusal is not None: + return refusal + body = await _body(request) or {} + from kiro_crew.kas_workflows.router import StepNotStarted, get_router + + workflow_id = request.match_info["workflow_id"] + router = get_router() + try: + await router.cancel_step(workflow_id, request.match_info["node_id"], _body_path(body)) + except StepNotStarted as exc: + return _error(str(_redact_obj(str(exc))), "step_unknown", 404) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.step_cancel", "allowed") + return _row_response(router, workflow_id) + + +#: Most answers one question card may carry, and the longest answer. +_MAX_ANSWERS = 16 +_MAX_ANSWER_CHARS = 2000 + + +def _answers(raw: Any) -> dict[str, Any] | None: + if not isinstance(raw, dict) or not raw or len(raw) > _MAX_ANSWERS: + return None + out: dict[str, Any] = {} + for key, value in raw.items(): + if not isinstance(key, str) or not key: + return None + values = value if isinstance(value, list) else [value] + if not values or len(values) > _MAX_ANSWERS: + return None + if not all(isinstance(v, str) and 0 < len(v) <= _MAX_ANSWER_CHARS for v in values): + return None + out[key] = value + return out + + +async def api_kas_question_answer(request: web.Request) -> web.Response: + """POST /api/workflows/kas/questions/{key} — {answers: {id: str|[str]}} or {dismiss: true}. + + Answers a step's question (its ``user_input`` tool) with one of the offered + answers, or dismisses it so the step goes on without one. A question is + never answered by a chat's approval mode. + """ + refusal = await _refusal(request, "workflow.kas.question") + if refusal is not None: + return refusal + body = await _body(request) + if body is None: + return _error("a JSON object body is required", "invalid_body", 400) + dismiss = body.get("dismiss") is True + answers = None if dismiss else _answers(body.get("answers")) + if not dismiss and answers is None: + return _error("answers must map a question id to its answer", "invalid_answers", 400) + from kiro_crew.kas_workflows.router import get_router + + try: + await get_router().answer_question(request.match_info["key"], answers, dismiss=dismiss) + except Exception as exc: # noqa: BLE001 + return _router_error(exc) + _audit_authorization(request, "workflow.kas.question", "dismissed" if dismiss else "answered") + return web.json_response({"answered": not dismiss, "dismissed": dismiss}) diff --git a/src/kiro_crew/dashboard/handlers/workflows.py b/src/kiro_crew/dashboard/handlers/workflows.py index cb235f3fefcb..1e4b5ea575c9 100644 --- a/src/kiro_crew/dashboard/handlers/workflows.py +++ b/src/kiro_crew/dashboard/handlers/workflows.py @@ -707,6 +707,9 @@ async def api_workflow_author(request: web.Request) -> web.Response: intent = intent.strip() if not intent: return web.json_response({"error": "intent is required"}, status=400) + redirect = _kas_chat_redirect(request) + if redirect is not None: + return redirect author = request.headers.get("X-Session-Key", "") refusal = await _private_memory_refusal(request, "workflow.author") if refusal is not None: @@ -852,6 +855,9 @@ async def api_workflow_run(request: web.Request) -> web.Response: source = body.get("source", "") if not isinstance(source, str) or not source.strip(): return web.json_response({"error": "source is required"}, status=400) + redirect = _kas_chat_redirect(request) + if redirect is not None: + return redirect # ``_opt_int``, not a bare int check: JSON ``true``/``false`` arrive as a # Python ``bool``, an ``int`` subclass, and a ceiling of 1 or 0 ends the run # at its first agent call. @@ -905,6 +911,24 @@ async def api_workflow_run(request: web.Request) -> web.Response: return web.json_response(_redact_obj(out), status=status) +def _kas_chat_redirect(request: web.Request) -> web.Response | None: + """Refuse a NEW Crew script from a chat whose model holds KAS's run_workflow. + + Two engines offered to one model is the confusion ``agent.kas_workflows`` + exists to end: in such a chat a new workflow is a KAS run. Only authoring is + refused -- a saved Crew workflow (``/definitions/{ref}/run``) still runs. The + header only ever narrows what its caller may do, so a forged one refuses + nobody but the forger. + """ + from kiro_crew.kas_workflows.chat import AUTHOR_REDIRECT, has_kas_workflows + + if not has_kas_workflows(request.headers.get("X-Session-Key", "")): + return None + return web.json_response( + {"error": AUTHOR_REDIRECT, "code": "kas_workflows_in_chat"}, status=409 + ) + + async def api_workflow_run_intent(request: web.Request) -> web.Response: """POST /api/workflows/run_intent — launch a run that authors itself. @@ -941,6 +965,9 @@ async def api_workflow_run_intent(request: web.Request) -> web.Response: intent = intent.strip() if not intent: return web.json_response({"error": "intent is required"}, status=400) + redirect = _kas_chat_redirect(request) + if redirect is not None: + return redirect # ``_opt_int``, not a bare int check: JSON ``true``/``false`` arrive as a # Python ``bool``, an ``int`` subclass, and a ceiling of 1 or 0 ends the run # at its first agent call. @@ -980,6 +1007,43 @@ async def api_workflow_run_intent(request: web.Request) -> web.Response: return web.json_response(_redact_obj(out), status=status) +async def api_workflow_engine(request: web.Request) -> web.Response: + """GET /api/workflows/engine — which engine owns workflows on this gateway. + + ``crew`` is Crew's own engine; ``kas`` means the selected harness brings its + own AND the operator opted in (``agent.kas_workflows``), so the dashboard may + offer its recipe library and runs. The answer folds the single opt-in in, so + ``kas`` reports only when the surfaces should actually render; the raw + ``backend``, the ``kas_workflows`` switch value and ``kas_backend`` (whether + the backend COULD serve KAS workflows) ride along so the settings UI can + explain whether the switch has any effect on this backend. + """ + from kiro_crew.config import KiroCrewConfig + from kiro_crew.kas_workflows.engine import ( + ENGINE_CREW, + ENGINE_KAS, + backend_brings_kas_workflows, + kas_workflows_enabled, + ) + + config = await asyncio.to_thread(KiroCrewConfig.load) + backend = config.agent.acp_backend + enabled = kas_workflows_enabled(config) + return web.json_response( + { + "engine": ENGINE_KAS if enabled else ENGINE_CREW, + "backend": backend, + # Whether the backend could serve KAS workflows at all (capability, + # independent of the opt-in): lets the UI say the switch has no + # effect until the backend is Kiro Agent. + "kas_backend": backend_brings_kas_workflows(backend), + # The single opt-in's stored value (``agent.kas_workflows``): the + # settings toggle reflects this even off a Kiro Agent backend. + "kas_workflows": bool(getattr(config.agent, "kas_workflows", False)), + } + ) + + async def api_workflow_runs(request: web.Request) -> web.Response: """GET /api/workflows/runs — list runs (compact, newest first). diff --git a/src/kiro_crew/dashboard/kas_workflow_triggers.py b/src/kiro_crew/dashboard/kas_workflow_triggers.py new file mode 100644 index 000000000000..574418cef4f0 --- /dev/null +++ b/src/kiro_crew/dashboard/kas_workflow_triggers.py @@ -0,0 +1,356 @@ +"""What the dashboard does for Kiro Workflows without a request. + +- The router (:mod:`kiro_crew.kas_workflows.router`) moves its ``revision`` on + every change a surface would render. The dashboard pushes that number to + owner sockets over ``/api/ws`` as one coalesced ``kas_workflow_revision`` + frame, and a client re-reads ``GET /api/workflows/kas/state`` when it + arrives. The frame carries only the integer: the routes stay the one place + run data is served from, redacted. +- A chat's approval mode changing re-decides the step approvals held under its + previous mode (:func:`recheck_step_approvals`), from the mode route and the + approval card's Trust, Trust-reads and YOLO presses. +- A Kiro Agent process crashing sends the chats of runs left with no process + their reconnect turn (:func:`reconnect_after_process_exit`) once KAS's claim on + those runs has lapsed, through a :func:`kiro_crew.runtime_death.subscribe` + listener. Together with the boot pass + (``handlers/kas_workflows.start_kas_boot_recovery``) and each chat's own + ordinary turn (``schedule_reattach``), that is every way an interrupted run + reconnects; none of them repeats on a clock. +- A chat whose run is working or waiting on a person is held off the idle clock + (:func:`idle_held_sessions`, installed as the session manager's idle hold), so + the idle sweep does not stop the process the run lives in. +""" + +from __future__ import annotations + +import asyncio +import dataclasses +import logging +from typing import Any, Callable, Collection + +from kiro_crew import runtime_death +from kiro_crew.kas_workflows import chat as kas_chat + +logger = logging.getLogger(__name__) + +#: The ``/api/ws`` frame type (owner sockets only, ``ws_event_scope._OWNER_ONLY_EVENTS``). +KAS_REVISION_FRAME = "kas_workflow_revision" + +#: The coalescing window: the first move after a quiet window is sent at once, +#: later moves inside it are folded into one trailing frame with the latest value. +REVISION_PUSH_WINDOW_SECS = 0.25 + +#: How long after a crash the reconnect pass waits: KAS's claim window (a dead +#: process's ``run.claim`` holds for one beat interval, ``BEAT_INTERVAL_MS`` 30 s +#: in kiro-agent ``workflow/run-liveness.ts``, and a load inside it is refused as +#: "just claimed by another process") plus the 15 s slack the boot pass adds to +#: KAS's owner window. +EXIT_RECONNECT_WAIT_SECS = 45.0 + +Scheduler = Callable[[float, Callable[[], None]], Any] + + +def revision_publisher( + state: Any, + *, + window_secs: float = REVISION_PUSH_WINDOW_SECS, + schedule: Scheduler | None = None, +) -> Callable[[int], None]: + """The router's ``changed`` hook for *state*: push each revision, coalesced. + + Leading plus trailing edge, the shape ``push_slots_update`` uses: a move + after a quiet window is broadcast at once and arms one window; moves inside + the window only record the latest value, and the window's end sends it once + and re-arms while moves keep coming. *schedule* is ``loop.call_later`` of the + running loop unless a caller supplies one; with no running loop and no + window armed, the frame is sent inline, uncoalesced. Returns at once, as the + hook must: it runs inside the router's own state changes. + """ + latest = 0 + armed = False + owed = False + + def send() -> None: + try: + state.broadcast_ws_owners(KAS_REVISION_FRAME, {"revision": latest}) + except Exception: # noqa: BLE001 -- a lost frame costs a redraw, never the run + logger.debug("kas_workflow_revision push failed", exc_info=True) + + def arm(scheduler: Scheduler) -> None: + nonlocal armed + armed = True + + def flush() -> None: + nonlocal armed, owed + if not owed: + armed = False + return + owed = False + send() + arm(scheduler) + + scheduler(window_secs, flush) + + def publish(revision: int) -> None: + nonlocal latest, owed + latest = revision + if armed: + owed = True + return + scheduler = schedule + if scheduler is None: + try: + scheduler = asyncio.get_running_loop().call_later + except RuntimeError: + send() + return + send() + arm(scheduler) + + return publish + + +async def recheck_step_approvals() -> int: + """Re-decide held step approvals under their chats' current mode; how many were answered. + + Called after a chat's approval mode changes. The router skips every held + approval whose chat's mode did not change, so one call covers every chat. + Nothing is decided while ``agent.kas_workflows`` is off: a held step then + waits for a person. A gateway holding no approval reads no config. Never + raises, so a mode change never fails on it. + """ + from kiro_crew.kas_workflows import router as router_mod + + router = getattr(router_mod, "_ROUTER", None) + try: + if router is None or not router.approvals(): + return 0 + if not await asyncio.to_thread(kas_chat.chat_workflows_enabled): + return 0 + return int(await router.recheck_pending()) + except Exception: # noqa: BLE001 -- the mode change already took; a held step waits + logger.debug("KAS step approval recheck failed", exc_info=True) + return 0 + + +def idle_held_sessions(state: Any) -> frozenset[str]: + """The session keys of chats whose run is working or waiting on a person here. + + The session manager's idle hold (``SessionManager.set_idle_hold``). A run + lives in its chat's Kiro Agent process, and only the chat's own turns move + the idle clock, so without the hold a step still working an idle timeout + after the chat's last turn dies with the process. A run counts while a live + process of this gateway drives it and it is running, or paused on an ask + that waits for a person (``attention``). A run paused for any other reason, + a finished one, one with no live process and one whose chat is gone hold + nothing, so such a chat expires on the usual clock. Never raises: rows that + cannot be read hold nothing for that sweep. + """ + from kiro_crew.dashboard.chat_utils import effective_session_key + from kiro_crew.kas_workflows import router as router_mod + from kiro_crew.kas_workflows import wire + + router = getattr(router_mod, "_ROUTER", None) + if router is None: + return frozenset() + try: + rows = router.rows() + except Exception: # noqa: BLE001 -- the sweep then runs as it would with no runs + logger.warning("KAS run rows unreadable; no chat held off the idle clock", exc_info=True) + return frozenset() + held: set[str] = set() + for row in rows: + status = row.get("status") + waiting = status == wire.STATUS_PAUSED and bool(row.get("attention")) + if not row.get("driven") or (status != wire.STATUS_RUNNING and not waiting): + continue + slot_key = row.get("slotKey") + slot = state.get_slot(slot_key) if isinstance(slot_key, str) else None + if slot is not None: + held.add(effective_session_key(slot)) + return frozenset(held) + + +def _gateway_stopping(state: Any) -> bool: + sessions = getattr(state, "sessions", None) + return ( + getattr(state, "workflow_startup_stopping", False) is True + or getattr(sessions, "admission_closed", False) is True + ) + + +async def reconnect_after_process_exit(state: Any, chats: Collection[str]) -> list[str]: + """Send each of *chats* whose run lost its Kiro Agent process a reconnect turn; the keys sent. + + Run ``EXIT_RECONNECT_WAIT_SECS`` after a process crashed (the + ``runtime_death`` listener), for the chats whose runs that process drove. + Nothing is sent while the gateway is stopping, with no router, or while + ``agent.kas_workflows`` is off: an interrupted run then stays parked, as the + routes refuse to resume it. The router's own bounds pick among *chats* + (``due_reconnects``: one try per chat every ``RECONNECT_INTERVAL_SECS``, at + most ``RECONNECT_MAX_TRIES``). + + A chat whose turn is running is waited for, up to ``BOOT_RECOVERY_TURN_SECS``: + that turn most likely ran on the process that died, and turn admission + reattaches runs only on an ordinary turn, which the failed one is not. A chat + still busy after the wait is left to its own next ordinary turn. + """ + from kiro_crew.kas_workflows import router as router_mod + + router = getattr(router_mod, "_ROUTER", None) + if _gateway_stopping(state) or router is None: + return [] + if not await asyncio.to_thread(kas_chat.chat_workflows_enabled): + return [] + from kiro_crew.dashboard.handlers.kas_workflows import _send_reconnect + from kiro_crew.dashboard.state import load_window_off_loop + + async def one(slot_key: str) -> bool: + slot = state.get_slot(slot_key) + if slot is None: + return False + task = getattr(slot, "task", None) + if getattr(slot, "running", False) and isinstance(task, asyncio.Future): + try: + await asyncio.wait_for( + asyncio.shield(task), timeout=router_mod.BOOT_RECOVERY_TURN_SECS + ) + except asyncio.CancelledError: + if not task.cancelled(): + raise # this pass was cancelled, not the chat's turn + except Exception: # noqa: BLE001 -- a timeout or a failed turn reports itself + logger.debug("chat %s turn did not settle before its reconnect", slot_key) + slot = state.get_slot(slot_key) + if slot is not None: + await load_window_off_loop(slot) # before the checks below (_send_reconnect) + slot = state.get_slot(slot_key) + if slot is None or getattr(slot, "running", False) or _gateway_stopping(state): + return False + return await _send_reconnect(state, router, slot_key) + + due = router.due_reconnects(only=chats) + sent = await asyncio.gather(*(one(slot_key) for slot_key in due)) + return [slot_key for slot_key, ok in zip(due, sent) if ok] + + +def _death_listener( + state: Any, *, schedule: Scheduler | None = None +) -> tuple[Callable[[object, runtime_death.RuntimeDeath], None], Callable[[], None]]: + """The crash listener that schedules :func:`reconnect_after_process_exit`, and its cancel. + + Only a crash counts (``RuntimeDeath.expected`` False). A teardown the gateway + chose itself (an idle expiry, a reset, a recycle) is left to the chat's next + ordinary turn, which reattaches what it stopped; a reconnect after each one + would give a chat holding a paused run a new turn and a new process at every + idle expiry. + + The pass reconnects only the chats whose runs the crashed process drove + (``slots_driven_by``, read at the death): a process started for another + chat's reconnect in the same project claims those runs in KAS's stale-run + sweep, and KAS then refuses their own chat's reconnect. The pass starts + ``EXIT_RECONNECT_WAIT_SECS`` after the crash, once KAS accepts a load of the + dead process's runs; a crash inside that wait moves the start to the same + delay after it, so one pass serves every chat the crashes left without a + process. *schedule* is ``loop.call_later`` of the running loop unless a + caller supplies one, and must return a handle with ``cancel()``. The cancel + drops a pass that has not started. + """ + armed: list[Any] = [] + chats: set[str] = set() + + def cancel() -> None: + while armed: + armed.pop().cancel() + chats.clear() + + def start(loop: asyncio.AbstractEventLoop) -> None: + armed.clear() + due = frozenset(chats) + chats.clear() + + async def _go() -> None: + try: + await reconnect_after_process_exit(state, due) + except asyncio.CancelledError: + raise + except Exception: # noqa: BLE001 -- the chats' next turns still reattach + logger.info("KAS workflow reconnect after a process crash failed", exc_info=True) + + task = loop.create_task(_go(), name="kas-workflow-exit-reconnect") + tasks = getattr(state, "_background_tasks", None) + if isinstance(tasks, set): + tasks.add(task) + task.add_done_callback(tasks.discard) + + def on_death(runtime: object, death: runtime_death.RuntimeDeath) -> None: + from kiro_crew.kas_workflows import router as router_mod + + router = getattr(router_mod, "_ROUTER", None) + if death.expected or _gateway_stopping(state) or router is None: + return + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return + left = router.slots_driven_by(runtime) + if not left: + return + while armed: + armed.pop().cancel() + chats.update(left) + later = schedule if schedule is not None else loop.call_later + armed.append(later(EXIT_RECONNECT_WAIT_SECS, lambda: start(loop))) + + return on_death, cancel + + +#: What :func:`install_kas_workflow_triggers` undoes on the next install or uninstall. +_UNSUBSCRIBE: list[Callable[[], None]] = [] + + +def install_kas_workflow_triggers(state: Any) -> None: + """Give the router *state*'s hooks, listen for Kiro Agent process crashes, hold busy chats. + + The hooks are the bell notes, the marker rows and the revision push; a + process crash schedules :func:`reconnect_after_process_exit`; and + :func:`idle_held_sessions` becomes *state*'s session manager's idle hold. + Installing again replaces the earlier install. + """ + from kiro_crew.kas_workflows.router import dashboard_hooks, install_dashboard_hooks + + hooks = dataclasses.replace(dashboard_hooks(state), changed=revision_publisher(state)) + install_dashboard_hooks(hooks) + _unsubscribe_all() + on_death, cancel_reconnect = _death_listener(state) + _UNSUBSCRIBE.append(runtime_death.subscribe(on_death)) + _UNSUBSCRIBE.append(cancel_reconnect) + set_idle_hold = getattr(getattr(state, "sessions", None), "set_idle_hold", None) + if callable(set_idle_hold): + set_idle_hold(lambda: idle_held_sessions(state)) + _UNSUBSCRIBE.append(lambda: set_idle_hold(None)) + + +def uninstall_kas_workflow_triggers() -> None: + """Remove what :func:`install_kas_workflow_triggers` installed; a no-op when none is.""" + from kiro_crew.kas_workflows.router import install_dashboard_hooks + + install_dashboard_hooks(None) + _unsubscribe_all() + + +def _unsubscribe_all() -> None: + while _UNSUBSCRIBE: + _UNSUBSCRIBE.pop()() + + +__all__ = [ + "EXIT_RECONNECT_WAIT_SECS", + "KAS_REVISION_FRAME", + "REVISION_PUSH_WINDOW_SECS", + "idle_held_sessions", + "install_kas_workflow_triggers", + "recheck_step_approvals", + "reconnect_after_process_exit", + "revision_publisher", + "uninstall_kas_workflow_triggers", +] diff --git a/src/kiro_crew/dashboard/route_access.py b/src/kiro_crew/dashboard/route_access.py index cfc9397f473b..d09b1c654548 100644 --- a/src/kiro_crew/dashboard/route_access.py +++ b/src/kiro_crew/dashboard/route_access.py @@ -193,6 +193,88 @@ class RouteAccess: ("GET", "/api/workflows/runs/{run_id}/agents/{agent_id}/transcript"): RouteAccess( "workflows.step_transcript.read", UNSTABLE ), + # No check of its own (handlers/workflows.py): any caller the gateway auth + # middleware admits, the internal secret included. Reads config.json, writes nothing. + ("GET", "/api/workflows/engine"): RouteAccess("workflows.engine.read", UNSTABLE), + # Kiro Workflows on Kiro Agent (handlers/kas_workflows.py ``_refusal``). The owner gate, + # which a Shared Crew teammate passes too; 403 for an app token and an internal + # caller. 409 ``engine_not_kas`` unless Kiro Agent is the backend and + # ``agent.kas_workflows`` is on; with the switch off and a run still held, the state, + # run, runs, chat runs and step transcript reads and a run's cancel stay open. + # + # Each asks Kiro Agent for the project's recipes on a live process, starting the + # gateway's query process when none is up; the detail also reads the listed + # ``.workflow.json`` file. Neither writes anything. + ("GET", "/api/workflows/kas/recipes"): RouteAccess("workflows.kas.recipes.list", UNSTABLE), + ("GET", "/api/workflows/kas/recipes/detail"): RouteAccess( + "workflows.kas.recipe_detail.fetch", UNSTABLE + ), + # Writes a new recipe file under the project's or the user's workflows folder, + # never over an existing one. + ("POST", "/api/workflows/kas/recipes"): RouteAccess("workflows.kas.recipes.create", UNSTABLE), + # Removes one recipe file Kiro Agent lists for the project and does not mark read-only. + ("DELETE", "/api/workflows/kas/recipes"): RouteAccess("workflows.kas.recipes.delete", UNSTABLE), + # The router's memory only: starts no process, sends nothing, writes nothing. + ("GET", "/api/workflows/kas/state"): RouteAccess("workflows.kas.state.read", UNSTABLE), + ("GET", "/api/workflows/kas/runs/{workflow_id}"): RouteAccess( + "workflows.kas.run.read", UNSTABLE + ), + # Each asks Kiro Agent for runs (starting the query process when none is up) and + # updates the gateway's copy of them; the project list also drops a run deleted + # elsewhere together with its held requests, and the chat list inspects the runs it + # has no step tree for. + ("GET", "/api/workflows/kas/runs"): RouteAccess("workflows.kas.runs.list", UNSTABLE), + ("GET", "/api/workflows/kas/slots/{slot}/runs"): RouteAccess( + "workflows.kas.chat_runs.list", UNSTABLE + ), + # Queues the launch message as the parent chat's next turn; that turn starts the run. + ("POST", "/api/workflows/kas/runs"): RouteAccess("workflows.kas.runs.start", UNSTABLE), + # ``.resolve``: a step this gateway has not seen is inspected and its history + # replayed once with ``session/load``, which brings back the step's open permission + # requests for the router to hold or decide. + ("GET", "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/transcript"): RouteAccess( + "workflows.kas.step_transcript.resolve", UNSTABLE + ), + # Run and step controls, each sent to the Kiro Agent process that drives the run: + # pause, resume, cancel or delete a run; retry its failed steps or run it again; + # reply to a parked step, change its model, give an exhausted loop more passes, end + # a paused step as done or failed, or stop one running step. + ("POST", "/api/workflows/kas/runs/{workflow_id}/{action}"): RouteAccess( + "workflows.kas.run.control", UNSTABLE + ), + ("POST", "/api/workflows/kas/runs/{workflow_id}/retry"): RouteAccess( + "workflows.kas.run.retry", UNSTABLE + ), + ("POST", "/api/workflows/kas/runs/{workflow_id}/restart"): RouteAccess( + "workflows.kas.run.restart", UNSTABLE + ), + ("POST", "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/reply"): RouteAccess( + "workflows.kas.step.reply", UNSTABLE + ), + ("POST", "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/model"): RouteAccess( + "workflows.kas.step_model.change", UNSTABLE + ), + ("POST", "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/grant"): RouteAccess( + "workflows.kas.step.grant", UNSTABLE + ), + ("POST", "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/complete"): RouteAccess( + "workflows.kas.step.complete", UNSTABLE + ), + ("POST", "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/cancel"): RouteAccess( + "workflows.kas.step.cancel", UNSTABLE + ), + # Answer a held approval (a step's permission request or a plan) with one of its + # options, or a step's question (or dismiss the question). + ("POST", "/api/workflows/kas/approvals/{key}"): RouteAccess( + "workflows.kas.approval.answer", UNSTABLE + ), + ("POST", "/api/workflows/kas/questions/{key}"): RouteAccess( + "workflows.kas.question.answer", UNSTABLE + ), + # Sends the chat its reconnect turn now and resets its automatic reconnect tries. + ("POST", "/api/workflows/kas/slots/{slot}/reconnect"): RouteAccess( + "workflows.kas.chat.reconnect", UNSTABLE + ), # Owner dashboard or internal caller (artifacts_parts/canvas_assets.py); a restricted # session is refused. Writes one picture into a store-owned canvas's assets folder. ("POST", "/api/artifacts/{slug}/assets"): RouteAccess( diff --git a/src/kiro_crew/dashboard/server_runtime/mcp_routes.py b/src/kiro_crew/dashboard/server_runtime/mcp_routes.py index 63a74ecdc830..7a8a4e5347d5 100644 --- a/src/kiro_crew/dashboard/server_runtime/mcp_routes.py +++ b/src/kiro_crew/dashboard/server_runtime/mcp_routes.py @@ -831,6 +831,7 @@ def _register_mcp_routes(app: web.Application) -> None: api_workflow_definition_update, api_workflow_definitions, api_workflow_definitions_create, + api_workflow_engine, api_workflow_run, api_workflow_run_cancel, api_workflow_run_get, @@ -858,6 +859,7 @@ def _register_mcp_routes(app: web.Application) -> None: app.router.add_delete( "/api/workflows/definitions/{workflow_ref}", api_workflow_definition_remove ) + app.router.add_get("/api/workflows/engine", api_workflow_engine) app.router.add_get("/api/workflows/runs", api_workflow_runs) app.router.add_get("/api/workflows/runs/{run_id}", api_workflow_run_get) app.router.add_get( @@ -873,6 +875,70 @@ def _register_mcp_routes(app: web.Application) -> None: app.router.add_post("/api/workflows/runs/{run_id}/cancel", api_workflow_run_cancel) app.router.add_post("/api/workflows/runs/{run_id}/rerun", api_workflow_run_rerun) + # KAS's own workflow engine, served only while Kiro Agent is the backend. + from kiro_crew.dashboard.handlers.kas_workflows import ( + api_kas_approval_answer, + api_kas_question_answer, + api_kas_recipe_create, + api_kas_recipe_delete, + api_kas_recipe_detail, + api_kas_recipes, + api_kas_run_control, + api_kas_run_get, + api_kas_run_restart, + api_kas_run_retry, + api_kas_run_start, + api_kas_runs, + api_kas_slot_reconnect, + api_kas_slot_runs, + api_kas_state, + api_kas_step_cancel, + api_kas_step_complete, + api_kas_step_grant, + api_kas_step_model, + api_kas_step_reply, + api_kas_step_transcript, + ) + + # ``/recipes/detail`` is a distinct path from ``/recipes``; register the + # static detail GET before the bare recipes GET for clarity. Create (POST) + # and delete (DELETE) share the ``/recipes`` path by method. + app.router.add_get("/api/workflows/kas/recipes/detail", api_kas_recipe_detail) + app.router.add_get("/api/workflows/kas/recipes", api_kas_recipes) + app.router.add_post("/api/workflows/kas/recipes", api_kas_recipe_create) + app.router.add_delete("/api/workflows/kas/recipes", api_kas_recipe_delete) + app.router.add_get("/api/workflows/kas/state", api_kas_state) + app.router.add_get("/api/workflows/kas/runs", api_kas_runs) + app.router.add_post("/api/workflows/kas/runs", api_kas_run_start) + app.router.add_get("/api/workflows/kas/runs/{workflow_id}", api_kas_run_get) + app.router.add_get( + "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/transcript", + api_kas_step_transcript, + ) + app.router.add_post( + "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/reply", api_kas_step_reply + ) + app.router.add_post( + "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/model", api_kas_step_model + ) + app.router.add_post( + "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/grant", api_kas_step_grant + ) + app.router.add_post( + "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/complete", api_kas_step_complete + ) + app.router.add_post( + "/api/workflows/kas/runs/{workflow_id}/steps/{node_id}/cancel", api_kas_step_cancel + ) + # Before the {action} catch-all, which would otherwise take these names. + app.router.add_post("/api/workflows/kas/runs/{workflow_id}/retry", api_kas_run_retry) + app.router.add_post("/api/workflows/kas/runs/{workflow_id}/restart", api_kas_run_restart) + app.router.add_post("/api/workflows/kas/runs/{workflow_id}/{action}", api_kas_run_control) + app.router.add_post("/api/workflows/kas/approvals/{key}", api_kas_approval_answer) + app.router.add_post("/api/workflows/kas/questions/{key}", api_kas_question_answer) + app.router.add_post("/api/workflows/kas/slots/{slot}/reconnect", api_kas_slot_reconnect) + app.router.add_get("/api/workflows/kas/slots/{slot}/runs", api_kas_slot_runs) + # Artifacts — persistent, versioned LLM-generated UI app.router.add_get("/api/artifacts", api_artifacts_list) app.router.add_post("/api/artifacts", api_artifacts_create) diff --git a/src/kiro_crew/dashboard/server_runtime/workflow_startup.py b/src/kiro_crew/dashboard/server_runtime/workflow_startup.py index afda6b9c7041..61f670a7f0ec 100644 --- a/src/kiro_crew/dashboard/server_runtime/workflow_startup.py +++ b/src/kiro_crew/dashboard/server_runtime/workflow_startup.py @@ -231,6 +231,19 @@ async def _workflow_stop_publication(_app: web.Application) -> None: state.task_runner.defer_workflow_attachment() async def _workflow_shutdown(_app: web.Application) -> None: + # The KAS workflow router owns a session-less query process for catalog + # and history reads; it is stopped here with the workflow service. + from kiro_crew.dashboard.handlers.kas_workflows import cancel_kas_boot_recovery + from kiro_crew.dashboard.kas_workflow_triggers import uninstall_kas_workflow_triggers + from kiro_crew.kas_workflows.router import close_router, install_turn_starter + + cancel_kas_boot_recovery() + install_turn_starter(None) + uninstall_kas_workflow_triggers() + try: + await close_router() + except Exception: # noqa: BLE001 -- shutdown must reach the drain below + logger.debug("KAS workflow router close failed", exc_info=True) task = state.workflow_startup_task if task is None: return @@ -253,6 +266,25 @@ def _kick_workflow_initialization(state: DashboardState) -> None: """Called only after listener bind and successful credential publication.""" if state.workflow_startup_task is not None or state.workflow_startup_stopping: return + # A KAS workflow run's end is shown in its chat as an observe turn; the + # router (created only on first use) sends it through the chat slots. + try: + from kiro_crew.dashboard.handlers.kas_workflows import ( + observe_turn_starter, + start_kas_boot_recovery, + ) + from kiro_crew.dashboard.kas_workflow_triggers import install_kas_workflow_triggers + from kiro_crew.kas_workflows.router import install_turn_starter + + install_turn_starter(observe_turn_starter(state)) + # Bell notes for held asks, the outcome/note rows and the run-change + # frames on /api/ws reach the dashboard only through these hooks. + install_kas_workflow_triggers(state) + # Reattach this gateway's own interrupted runs once KAS's owner window + # has passed; it gates itself on the backend and the KAS switch. + start_kas_boot_recovery(state) + except Exception: # noqa: BLE001 -- a run's end then goes unshown, nothing else + logger.debug("KAS workflow observe starter not installed", exc_info=True) task = asyncio.create_task(_initialize_workflow_service(state), name="workflow-initialization") state.workflow_startup_task = task state._background_tasks.add(task) diff --git a/src/kiro_crew/dashboard/slot_projection.py b/src/kiro_crew/dashboard/slot_projection.py index 2e6924248cde..f125657424b4 100644 --- a/src/kiro_crew/dashboard/slot_projection.py +++ b/src/kiro_crew/dashboard/slot_projection.py @@ -134,6 +134,50 @@ def _running_turn_pin(slot: Any) -> tuple[str, bool] | None: return pin[1], bool(pin[2]) and slot.project == pin[2] +def kas_slot_needs_person(slot_key: str) -> bool: + """Whether a KAS-native workflow run reporting into *slot_key* waits on a person. + + Gap 8: the sidebar's ``needs_input`` flag only ever read the chat's OWN + ``ask_question`` hold (``slot._question_pending``), so a chat whose Kiro + Agent workflow is parked on a step approval, a question or any non-user park + looked merely busy — its "Needs your answer" line and the needs-you filter + never fired. This folds the workflow hold into that same flag. + + Read-only and side-effect free, for a hot per-slot poll: + + * it reads the router singleton that is ALREADY running, through the module + global, and never calls ``get_router()`` — which would construct one, so a + gateway with KAS off (or no run yet) must pay nothing and build nothing; + * ``None`` singleton (KAS never used this process) answers ``False`` at once; + * any error reading the rows answers ``False`` — a sidebar flag must never + raise on the slots poll. + + A run "needs a person" exactly when its row carries ``controls.needsAttention`` + (the one rule ``wire.run_controls`` already derives: a step approval / question + wait, or a non-user park) or a ``blocking`` step — the same predicate the + frontend row uses (``kasModel.needsAttention``). + """ + if not slot_key: + return False + try: + from kiro_crew.kas_workflows import router as _kas_router + + router = getattr(_kas_router, "_ROUTER", None) + if router is None: + return False + for row in router.rows(): + if not isinstance(row, dict) or row.get("slotKey") != slot_key: + continue + controls = row.get("controls") + if isinstance(controls, dict) and controls.get("needsAttention"): + return True + if row.get("blocking"): + return True + except Exception: + return False + return False + + def resolved_row_identity(slot: Any) -> str: """The identity the sidebar renders this slot under: its own local key. @@ -455,7 +499,12 @@ def to_dict( and bool(rows) and last_conv_role == "assistant" ) - needs_input = bool(slot._question_pending) + # Gap 8: a workflow parked on a person counts as needs-input too, so the + # chat's sidebar line, status and the needs-you filter fire for it — not + # only for the chat's own ``ask_question`` hold. + needs_input = bool(slot._question_pending) or kas_slot_needs_person( + str(getattr(slot, "key", "") or "") + ) interrupted = not in_flight and is_turn_interrupted(rows) # Still `interrupted` for the row and the composer; only the bulk Resume # leaves it out (the sidebar's count and `collect_interrupted_idle`). diff --git a/src/kiro_crew/dashboard/state_parts/chat_slot.py b/src/kiro_crew/dashboard/state_parts/chat_slot.py index e1b3a9b241a1..a419a1b07592 100644 --- a/src/kiro_crew/dashboard/state_parts/chat_slot.py +++ b/src/kiro_crew/dashboard/state_parts/chat_slot.py @@ -364,6 +364,7 @@ class _ChatSlot: "_steer_segment_cut", "_compact_command_turn", "_owed_segment_cut", + "_kas_observing", "_native_subagent_tracker", "_native_subagent_output", "_steer_confirmed", @@ -763,6 +764,7 @@ class _ChatSlot: _steer_segment_cut: Callable[[], None] | None _compact_command_turn: bool _owed_segment_cut: Callable[[], None] | None + _kas_observing: bool _native_subagent_tracker: dict[str, dict[str, Any]] _native_subagent_output: dict[str, list[str]] _steer_confirmed: set[str] diff --git a/src/kiro_crew/dashboard/state_parts/slot_ladder.py b/src/kiro_crew/dashboard/state_parts/slot_ladder.py index c66e92fe131f..f64b9ae7c703 100644 --- a/src/kiro_crew/dashboard/state_parts/slot_ladder.py +++ b/src/kiro_crew/dashboard/state_parts/slot_ladder.py @@ -348,6 +348,9 @@ def init_ladder_fields(self: _ChatSlot) -> None: # A segment cut a permission request owes: paid by ``append`` before the # next durable row, dropped when the request lands none. None when idle. self._owed_segment_cut = None + # True while the in-flight turn is a KAS workflow observe turn (published + # and cleared with _acp_client): a steer is refused and the message queues. + self._kas_observing = False # Native kiro-cli subagents run inside the parent ACP turn. Keep their # live and terminal state on the slot so reconnects can hydrate cards. self._native_subagent_tracker = {} diff --git a/src/kiro_crew/dashboard/turn_dispatch.py b/src/kiro_crew/dashboard/turn_dispatch.py index 4855efe5bc1a..f0a79ee9eb6c 100644 --- a/src/kiro_crew/dashboard/turn_dispatch.py +++ b/src/kiro_crew/dashboard/turn_dispatch.py @@ -310,6 +310,27 @@ def tool_approval_timeout_secs() -> float: return window +def person_wait_window_secs() -> float: + """How long a turn waits for a PERSON-ONLY decision: a KAS plan handoff. + + Such a request is the person's call under every approval mode, and an + answer nobody gave is not a decline, so it does not take + ``agent.tool_approval_timeout_secs`` (600s by default) like a tool + approval. It waits as long as the turn can: the turn ceiling (the running + turn's own limit, else :func:`chat_turn_timeout_secs`) and the budget left + in the running turn, each less the same :data:`APPROVAL_TURN_MARGIN_SECS`, + so the "went unanswered" card still lands inside the turn instead of the + ceiling relabelling it a turn timeout. ``0.0`` when no budget is left, which + the caller reads exactly as it reads :func:`tool_approval_timeout_secs`'s. + """ + ceiling = current_turn_limit_secs() or chat_turn_timeout_secs() + window = max(0.0, ceiling - APPROVAL_TURN_MARGIN_SECS) + remaining = _turn_budget_remaining() + if remaining is None: + return window + return min(window, max(0.0, remaining - APPROVAL_TURN_MARGIN_SECS)) + + def format_approval_no_budget_card() -> str: """User-facing text for a prompt that arrived with no time left to answer it. diff --git a/src/kiro_crew/dashboard/ws_event_scope.py b/src/kiro_crew/dashboard/ws_event_scope.py index 457c9b4edf34..22fe1837d52b 100644 --- a/src/kiro_crew/dashboard/ws_event_scope.py +++ b/src/kiro_crew/dashboard/ws_event_scope.py @@ -401,6 +401,13 @@ def strip_owner_only_status(data: dict[str, Any]) -> dict[str, Any]: # failed in the background (``chat_api.crew_steer.CREW_STEER_UNRECORDED_FRAME``, # ``broadcast_ws_owners``). Only the owner's own sends are steers. "crew_steer_unrecorded", + # The Kiro Workflows router's revision (``kas_workflow_triggers.KAS_REVISION_FRAME``), + # sent through ``broadcast_ws_owners``. It carries only an integer, but it + # signals runs on the owner-only ``/api/workflows/kas/*`` surface, so it is + # classified for the same reason as ``dashboard_fields``: an app token's + # denial is audited as ``owner_only``, and a later literal broadcast of the + # name cannot silently start reaching an app token. + "kas_workflow_revision", } ) diff --git a/src/kiro_crew/docs/configuration.md b/src/kiro_crew/docs/configuration.md index fbc19aa11eb5..9fa6414b6ed6 100644 --- a/src/kiro_crew/docs/configuration.md +++ b/src/kiro_crew/docs/configuration.md @@ -504,7 +504,7 @@ key-based route: see the `agent.strands_provider`, `agent.strands_model` and | `agent.apps_trusted` | Per-app grants for third-party execution — the narrow form of apps_allow_third_party. An app whose manifest name appears here is admitted to run Python hooks, its backend, lifecycle scripts, and openCommand; every other third-party app stays blocked. Only a JSON array of app-name strings is honoured, and no wildcard entry is accepted (use apps_allow_third_party to trust all). | `[]` | | `agent.apps_ui_stream_timeout_secs` | Total transfer deadline, in seconds, for ONE response body on the unauthenticated /apps/{name}/ui/ route. Clamped to 5..600; a value that is not a whole number loads as 30. Read per request, so an edit applies without a restart. There is no off switch: the route holds eight descriptor permits, and this deadline is what stops a client that quits draining its socket from holding one for as long as it stays connected — eight such clients would otherwise stop every app UI on the host. Raise it only when a real transfer on this host needs longer than the default allows. | `30` | | `agent.notify_override_expiry` | DM the Slack owner when a time-limited safety override (YOLO) expires. Disable to silence the recurring expiry DM; the dashboard banner still shows. | `true` | -| `agent.kas_workflows` | Developer opt-in to Kiro Agent's (KAS) own workflow engine, off by default. This build has no surface that reads it yet, so setting it changes nothing. No effect unless the backend is Kiro Agent. | `false` | +| `agent.kas_workflows` | Developer opt-in to Kiro Agent's (KAS) own workflow engine, off by default. When on, a dashboard chat's model can start Kiro Agent workflow runs, the dashboard can start, follow and answer them, and the gateway reconnects a chat's interrupted runs when it starts. No effect unless the backend is Kiro Agent. | `false` | **Tool Search restart compatibility:** automatic fresh-session replay after a restart currently applies to direct dashboard conversations. Messaging-channel and dashboard-linked channel sessions continue using native session resume; if a deferred tool remains unavailable after one of those sessions resumes, set `agent.tool_search` to `false` until channel dispatchers support the same replay-settlement contract. diff --git a/src/kiro_crew/kas_workflows/chat.py b/src/kiro_crew/kas_workflows/chat.py index e82fb53fdd17..061bb9613fb9 100644 --- a/src/kiro_crew/kas_workflows/chat.py +++ b/src/kiro_crew/kas_workflows/chat.py @@ -77,6 +77,16 @@ def is_plan_handoff(harness_tool_id: str) -> bool: return harness_tool_id == wire.TOOL_UPDATE_WORKFLOW +def needs_a_person(event: Any) -> bool: + """Whether no approval mode, grant or hook may answer this chat request. + + A KAS plan handoff (:func:`is_plan_handoff`) always waits on the person's + card. The chat model's own questions arrive as ``_kiro/userInput`` and are + answered on the elicitation card (``acp.elicitation``), not here. + """ + return is_plan_handoff(str(getattr(event, "harness_tool_id", "") or "")) + + def is_chat_session_key(session_key: str) -> bool: """Whether *session_key* names a dashboard chat (not a worker or a channel).""" from kiro_crew.validation import infer_use_case @@ -264,11 +274,15 @@ def runs_since(slot_key: str, message_ts: Any) -> tuple[list[dict[str, Any]], li never touched Kiro Workflows has none and holds no run). A run whose start time or the message's cannot be read counts as launched after it, so an unknown is never a reason to let the edit through. Each entry is - ``{"workflowId", "name"}``. Raises :class:`RunsUnreadable` when the router - exists but its rows cannot be read. + ``{"workflowId", "name"}``, the name redacted and capped here: the router's + rows are not redacted, and every door answers these entries to the browser. + Raises :class:`RunsUnreadable` when the router exists but its rows cannot be + read. """ from kiro_crew.kas_workflows import router as router_mod from kiro_crew.kas_workflows import wire + from kiro_crew.kas_workflows.router_base import _MAX_DISPLAY_CHARS + from kiro_crew.platform import redact_via_context router = getattr(router_mod, "_ROUTER", None) if router is None or not slot_key: @@ -287,7 +301,8 @@ def runs_since(slot_key: str, message_ts: Any) -> tuple[list[dict[str, Any]], li created = _epoch(row.get("createdAt")) if since is not None and created is not None and created < since: continue - entry = {"workflowId": row.get("workflowId"), "name": row.get("name") or ""} + name = redact_via_context(str(row.get("name") or ""))[:_MAX_DISPLAY_CHARS] + entry = {"workflowId": row.get("workflowId"), "name": name} if row.get("status") in wire.TERMINAL_RUN_STATUSES: ended.append(entry) else: diff --git a/src/kiro_crew/kas_workflows/router.py b/src/kiro_crew/kas_workflows/router.py index 7ddde4185ee2..9fca845cb983 100644 --- a/src/kiro_crew/kas_workflows/router.py +++ b/src/kiro_crew/kas_workflows/router.py @@ -296,11 +296,31 @@ def __init__( self._marked_ends: dict[str, None] = {} #: Crew "always allow in this step" grants: step session -> grant keys. self._step_grants: dict[str, set[str]] = {} - #: Bumped on every change a surface would render; a cheap poll key. - self.revision = 0 - #: Bumped on every ``recipes_changed`` push (the recipe list's poll key). + #: Backs :attr:`revision`; set directly here so construction fires no hook. + self._revision = 0 + #: Bumped on every ``recipes_changed`` push (the recipe list's change key). self.recipes_revision = 0 + @property + def revision(self) -> int: + """The counter every surface reads as its change key. + + Moved on every change a surface would render, from any of the router's + modules; each move reaches the dashboard's ``changed`` hook at once. + """ + return self._revision + + @revision.setter + def revision(self, value: int) -> None: + self._revision = value + changed = self._hooks.changed + if changed is None: + return + try: + changed(value) + except Exception: # noqa: BLE001 -- a hook costs the signal, never the run + logger.debug("KAS workflow changed hook failed", exc_info=True) + # ── Sinks (run ON a runtime's reader loop: never block) ── def sink_for(self, runtime: Any) -> _RuntimeSink: diff --git a/src/kiro_crew/kas_workflows/router_base.py b/src/kiro_crew/kas_workflows/router_base.py index 2405290160ab..bec55695a6ef 100644 --- a/src/kiro_crew/kas_workflows/router_base.py +++ b/src/kiro_crew/kas_workflows/router_base.py @@ -485,6 +485,8 @@ class DashboardHooks: held step ask (gap 6); ``retire(key)`` marks it read once the ask is gone. - ``append_marker(slot_key, content, meta) -> bool``: append one notice row to a chat's transcript (gap 10), True when written. + - ``changed(revision)``: the router's revision moved; called on the loop by + every bump and must return at once (the dashboard coalesces and pushes). - ``transcript_changed(workflow_id, node_id)``: a step's transcript (``step_transcripts``) changed; called on the loop by every frame that changed it and must return at once (the dashboard coalesces and pushes). @@ -496,6 +498,7 @@ class DashboardHooks: notify: Callable[[str, str, str, str, Mapping[str, Any]], None] | None = None retire: Callable[[str], None] | None = None append_marker: Callable[[str, str, Mapping[str, Any]], bool] | None = None + changed: Callable[[int], None] | None = None transcript_changed: Callable[[str, str], None] | None = None diff --git a/src/kiro_crew/kas_workflows/router_gate.py b/src/kiro_crew/kas_workflows/router_gate.py index a0d5a3e8be36..973dd621b009 100644 --- a/src/kiro_crew/kas_workflows/router_gate.py +++ b/src/kiro_crew/kas_workflows/router_gate.py @@ -350,9 +350,9 @@ async def recheck_pending(self: KasWorkflowRouter) -> int: A step that asked while its chat was in Normal waits for a person. If the person then switches the chat to Trust, that held step must follow - the switch like every later step does, not keep waiting. Called from the - dashboard's state poll, so a mode change lands within one poll. Returns - how many were answered here. + the switch like every later step does, not keep waiting. Called when a + chat's approval mode changes (the dashboard's mode route and approval + card), so the change lands at once. Returns how many were answered here. """ answered = 0 for stale in [k for k in self._decided_under if k not in self._pending]: diff --git a/src/kiro_crew/providers/acp.py b/src/kiro_crew/providers/acp.py index ff16757ba270..cd47a95b063e 100644 --- a/src/kiro_crew/providers/acp.py +++ b/src/kiro_crew/providers/acp.py @@ -1605,6 +1605,7 @@ def session_id(self) -> str: watch_agent_turns = _acp_turns.watch_agent_turns agent_turn_pending = _acp_turns.agent_turn_pending stream_unsolicited = _acp_turns.stream_unsolicited + stream_observe = _acp_turns.stream_observe compact = _acp_turns.compact cancel = _acp_turns.cancel steer = _acp_turns.steer diff --git a/src/kiro_crew/providers/acp_turns.py b/src/kiro_crew/providers/acp_turns.py index 6bcb44a76928..184194817276 100644 --- a/src/kiro_crew/providers/acp_turns.py +++ b/src/kiro_crew/providers/acp_turns.py @@ -25,6 +25,7 @@ class binds it by name, so it reads and writes the session's own state on the in from kiro_crew.acp import relaunch_reload, stale_compaction from kiro_crew.acp.client import AcpClient, AcpError from kiro_crew.acp.launch_tuning import switch_barrier +from kiro_crew.acp.session_provider import AcpSessionProvider from kiro_crew.acp.types import ( ACP_BACKENDS_KIRO_SLASH_COMMANDS, EVENT_COMPACTION_STATUS, @@ -455,6 +456,20 @@ async def stream_unsolicited( await record_live_children_after_turn(client) +async def stream_observe(self: AcpProvider) -> AsyncIterator[LLMEvent]: + """Yield a turn the engine started on this session itself (KAS's wake). + + Sends nothing (:meth:`AcpSessionProvider.stream_observe`). Only a session + on a shared runtime can be observed, which is the only kind a KAS + workflow run is parented by; any other client is refused. + """ + if not isinstance(self._client, AcpSessionProvider): + raise AcpError("This session cannot observe an engine-started turn.") + async with aclosing(self._client.stream_observe()) as events: + async for e in events: + yield self._to_llm_event(e) + + async def compact(self: AcpProvider, context: str = "") -> None: """Trigger native /compact with optional context-preserving prompt. diff --git a/src/kiro_crew/runtime_death.py b/src/kiro_crew/runtime_death.py index 35c649d4a958..334ad4d5b488 100644 --- a/src/kiro_crew/runtime_death.py +++ b/src/kiro_crew/runtime_death.py @@ -17,17 +17,20 @@ already holds, exactly as :func:`kiro_crew.runtime_ownership.outstanding_leases` answers by object identity, because a session that can name a pid can signal it. -Why the tenants PULL the record rather than being pushed it ------------------------------------------------------------ +Why the tenants PULL the record, and the one layer that is pushed it +-------------------------------------------------------------------- A tenant learns of the death the way it already does -- its poisoned session queue raises into whatever turn it had -- and reads this record while handling it. -No layer is woken on its behalf, because none needs to be: a tenant with no turn +No tenant is woken on its behalf, because none needs to be: a tenant with no turn in flight has nothing to recover and re-acquires on its next turn through the ownership registry, which drops a dead runtime on the way past. A sub-agent run parked on a wait cannot, so the sub-agent reaper asks that run's own handle. -So there is no observer registry here; a layer that needs one adds it with its -first consumer. +One layer is pushed the death, through :func:`subscribe`: the dashboard's Kiro +Workflows reconnect. A workflow run lives in its chat's process and can lose it +while no turn is in flight on it, so no tenant's poisoned queue would ever report +it. A listener runs inside the death path: it must return at once and schedule +its own work. Two independent readings of co-tenancy, and why both are needed --------------------------------------------------------------- @@ -64,7 +67,7 @@ import logging import weakref from dataclasses import dataclass -from typing import Any +from typing import Any, Callable from kiro_crew.metrics.chat_runtime_share import record_process_died from kiro_crew.runtime_ownership import RUNTIME_OWNERSHIP @@ -111,6 +114,27 @@ def shared(self) -> bool: #: record -- for the gateway's life. _deaths: "weakref.WeakKeyDictionary[Any, RuntimeDeath]" = weakref.WeakKeyDictionary() +#: Called with ``(runtime, death)`` once per announced death (:func:`subscribe`). +_listeners: list[Callable[[object, RuntimeDeath], None]] = [] + + +def subscribe(listener: Callable[[object, RuntimeDeath], None]) -> Callable[[], None]: + """Call *listener* with ``(runtime, death)`` after each :func:`announce`. + + The listener runs inside the death path, after the record is stored: it must + return at once and schedule anything that waits. One that raises is logged + and skipped. Returns the unsubscribe; calling it again does nothing. + """ + _listeners.append(listener) + + def unsubscribe() -> None: + try: + _listeners.remove(listener) + except ValueError: + pass + + return unsubscribe + def _chat_leases_at_death(runtime: object, death: RuntimeDeath) -> int: """How many chat leases *runtime* held when it died, for the death counter. @@ -169,6 +193,11 @@ def announce( death.expected, death.reason, ) + for listener in list(_listeners): + try: + listener(runtime, death) + except Exception: # noqa: BLE001 -- a listener never breaks the death path + logger.debug("runtime_death: a death listener failed", exc_info=True) return death @@ -346,6 +375,7 @@ def _reset_for_tests() -> None: """Drop all death state. Tests only -- there is one record per gateway.""" _deaths.clear() _shared_streaks.clear() + _listeners.clear() __all__ = [ @@ -355,4 +385,5 @@ def _reset_for_tests() -> None: "clear_shared_deaths", "note_shared_death", "shared_deaths", + "subscribe", ] diff --git a/src/kiro_crew/security_posture_sinks_gateway.py b/src/kiro_crew/security_posture_sinks_gateway.py index 42c55869dc9e..c6bab6fe277c 100644 --- a/src/kiro_crew/security_posture_sinks_gateway.py +++ b/src/kiro_crew/security_posture_sinks_gateway.py @@ -654,6 +654,20 @@ "These values can contain model-authored text or tool results, so every nested key and " "value passes through the credential chain (inside URLs too) before egress.", ), + ( + "Kiro Workflows API responses", + "dashboard/handlers/kas_workflows.py", + "Run rows, recipe details, step transcripts and error text the Kiro Workflows " + "routes serve to the dashboard. Each JSON body and error passes through the " + "credential + exfiltration-URL chain (_redact_obj) on its way out.", + ), + ( + "Kiro Workflows rewind refusal", + "kas_workflows/chat.py", + "The run names a refused rewind or edit-resend answers in its 409 body. They " + "are read from the router's rows, which Kiro Agent and the recipe author " + "supply, and pass through redact_via_context where the refusal is built.", + ), ( "Kiro Workflows run messages", "kas_workflows/router.py", diff --git a/test/conftest.py b/test/conftest.py index 19bb5b83639e..81049a9e0dc7 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -440,6 +440,7 @@ def bundled_python_with_user_site(monkeypatch: pytest.MonkeyPatch) -> None: from conftest_resets_dashboard import ( # noqa: E402,F401 -- bound for pytest and importers _forget_dashboard_plain_caches, _forget_seen_notifications_file, + _fresh_kas_workflow_dashboard_state, _isolate_builtin_template_scan, _no_full_chat_lapse_timers, _reset_creator_titles, diff --git a/test/conftest_resets_dashboard.py b/test/conftest_resets_dashboard.py index e145c6564a31..c16c3a27ec23 100644 --- a/test/conftest_resets_dashboard.py +++ b/test/conftest_resets_dashboard.py @@ -85,6 +85,29 @@ def _forget_seen_notifications_file(_floor_monkeypatch): _floor_monkeypatch.setattr(module, "_seen_file", None, raising=False) +@per_test_guard +def _fresh_kas_workflow_dashboard_state(_floor_monkeypatch): + """Start every test with no Kiro Workflows boot recovery, trigger install or death listener. + + ``handlers.kas_workflows._BOOT_RECOVERY`` holds the one boot-recovery task a process + starts, so a task one test started, bound to that test's loop, would make every later + ``start_kas_boot_recovery`` on the worker return without starting one. + ``kas_workflow_triggers._UNSUBSCRIBE`` holds what an install undoes, so a later + install would call into an earlier test's dashboard state. ``runtime_death._listeners`` + holds the crash listener that install subscribes, so a death a later test announces + would schedule a reconnect for an earlier test's chats. Each module is only reset when + it is loaded, so the floor imports nothing. + """ + for name, attr in ( + ("kiro_crew.dashboard.handlers.kas_workflows", "_BOOT_RECOVERY"), + ("kiro_crew.dashboard.kas_workflow_triggers", "_UNSUBSCRIBE"), + ("kiro_crew.runtime_death", "_listeners"), + ): + module = sys.modules.get(name) + if module is not None: + _floor_monkeypatch.setattr(module, attr, []) + + _DASH = "kiro_crew.dashboard." #: Module -> the dicts and ordered maps production code only fills in place. Each is a memo diff --git a/test/fixtures/dashboard_mcp_route_table.txt b/test/fixtures/dashboard_mcp_route_table.txt index 81884f12846d..ee7ad5ec5a29 100644 --- a/test/fixtures/dashboard_mcp_route_table.txt +++ b/test/fixtures/dashboard_mcp_route_table.txt @@ -297,6 +297,8 @@ HEAD /api/workflows/definitions/{workflow_ref} api_workflow_definition_get GET /api/workflows/definitions/{workflow_ref} api_workflow_definition_get PATCH /api/workflows/definitions/{workflow_ref} api_workflow_definition_update DELETE /api/workflows/definitions/{workflow_ref} api_workflow_definition_remove +HEAD /api/workflows/engine api_workflow_engine +GET /api/workflows/engine api_workflow_engine HEAD /api/workflows/runs api_workflow_runs GET /api/workflows/runs api_workflow_runs HEAD /api/workflows/runs/{run_id} api_workflow_run_get @@ -309,6 +311,34 @@ GET /api/workflows/runs/{run_id}/update-definition api_workflow_run_update_previ POST /api/workflows/runs/{run_id}/update-definition api_workflow_run_update_definition POST /api/workflows/runs/{run_id}/cancel api_workflow_run_cancel POST /api/workflows/runs/{run_id}/rerun api_workflow_run_rerun +HEAD /api/workflows/kas/recipes/detail api_kas_recipe_detail +GET /api/workflows/kas/recipes/detail api_kas_recipe_detail +HEAD /api/workflows/kas/recipes api_kas_recipes +GET /api/workflows/kas/recipes api_kas_recipes +POST /api/workflows/kas/recipes api_kas_recipe_create +DELETE /api/workflows/kas/recipes api_kas_recipe_delete +HEAD /api/workflows/kas/state api_kas_state +GET /api/workflows/kas/state api_kas_state +HEAD /api/workflows/kas/runs api_kas_runs +GET /api/workflows/kas/runs api_kas_runs +POST /api/workflows/kas/runs api_kas_run_start +HEAD /api/workflows/kas/runs/{workflow_id} api_kas_run_get +GET /api/workflows/kas/runs/{workflow_id} api_kas_run_get +HEAD /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/transcript api_kas_step_transcript +GET /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/transcript api_kas_step_transcript +POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/reply api_kas_step_reply +POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/model api_kas_step_model +POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/grant api_kas_step_grant +POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/complete api_kas_step_complete +POST /api/workflows/kas/runs/{workflow_id}/steps/{node_id}/cancel api_kas_step_cancel +POST /api/workflows/kas/runs/{workflow_id}/retry api_kas_run_retry +POST /api/workflows/kas/runs/{workflow_id}/restart api_kas_run_restart +POST /api/workflows/kas/runs/{workflow_id}/{action} api_kas_run_control +POST /api/workflows/kas/approvals/{key} api_kas_approval_answer +POST /api/workflows/kas/questions/{key} api_kas_question_answer +POST /api/workflows/kas/slots/{slot}/reconnect api_kas_slot_reconnect +HEAD /api/workflows/kas/slots/{slot}/runs api_kas_slot_runs +GET /api/workflows/kas/slots/{slot}/runs api_kas_slot_runs HEAD /api/artifacts api_artifacts_list GET /api/artifacts api_artifacts_list POST /api/artifacts api_artifacts_create diff --git a/test/test_acp_bindings.py b/test/test_acp_bindings.py index 32c258751207..202abd46c7b4 100644 --- a/test/test_acp_bindings.py +++ b/test/test_acp_bindings.py @@ -209,6 +209,7 @@ class binds it by name (``m = _owner.m``, or ``staticmethod(_owner.f)``). The in "steer_upgrade_notice": ("property", False, "bb418bb7ece8", "acp"), "stream": ("function", "agen", "fa113e1bf480", "acp_turns"), "stream_command": ("function", "agen", "c5944af5c808", "acp_turns"), + "stream_observe": ("function", "agen", "2ae10f4cbd2c", "acp_turns"), "supports_effort": ("function", False, "a6632a57e602", "acp_model_effort"), "supports_refusal_steer": ("property", False, "a6632a57e602", "acp"), "supports_steer": ("property", False, "a6632a57e602", "acp"), diff --git a/test/test_chat_mode_security.py b/test/test_chat_mode_security.py index 92b14b63b6c0..769c0330759a 100644 --- a/test/test_chat_mode_security.py +++ b/test/test_chat_mode_security.py @@ -1222,6 +1222,35 @@ async def test_app_yolo_approval_is_refused_and_audited_as_the_app(state) -> Non assert audit.log_api_access.call_args.kwargs["caller"] == "crew-keyboard" +@pytest.mark.parametrize("body", [{"mode": "trust", "slot": "s1"}, {"mode": "trust"}]) +@pytest.mark.asyncio +async def test_switching_to_trust_leaves_a_person_only_card_pending(state, body) -> None: + """The Trust sweep approves pending cards, but never a KAS plan handoff. + + A card chat_runner marked ``person_only`` stays for the person; its sibling + ordinary tool card is approved as before. + """ + slot = state.get_or_create_slot("s1", origin=SlotOrigin.USER) + loop = asyncio.get_running_loop() + plan = loop.create_future() + tool = loop.create_future() + plan_row = slot.append( + "permission", + "Approve the workflow plan", + json.dumps({"request_id": "req-p", "person_only": "1"}), + ) + tool_row = slot.append("permission", "Running: ls", json.dumps({"request_id": "req-t"})) + slot.register_approval("req-p", plan, plan_row) + slot.register_approval("req-t", tool, tool_row) + + async with _client(state) as client: + resp = await client.post("/api/chat/mode", json=body) + assert resp.status == 200 + + assert not plan.done(), "the plan still waits for the person" + assert tool.result() == "approved" + + @pytest.mark.asyncio async def test_app_trust_does_not_persist_linked_channel_trust(state) -> None: slot = state.get_or_create_slot("s1", origin=SlotOrigin.USER) diff --git a/test/test_chat_runner_base_surface.py b/test/test_chat_runner_base_surface.py index ee021d27a4c9..d2efd9d8e0fa 100644 --- a/test/test_chat_runner_base_surface.py +++ b/test/test_chat_runner_base_surface.py @@ -317,7 +317,6 @@ ), ), "tool_approval": ( - ("_CREDENTIAL_HINT_CLASSES", "value", "frozenset"), ("_SPEC_HOOKS_UNREADABLE_BLOCK", "value", "str"), ( "_audit_name_grant_refusal", @@ -325,11 +324,6 @@ "(*, session_key: 'str', slot: 'Any', event: 'Any', refusal: 'Refusal', tier: 'str') -> 'None'", ), ("_auto_approve_reason", "function", "(slot: 'Any', yolo_active: 'bool') -> 'str'"), - ( - "_credential_tool_hint_for", - "async function", - "(reason: 'str', cause: 'str', subject: 'str' = '') -> 'str'", - ), ("_name_grant_refusal_for", "async function", "(event: 'object') -> 'Refusal | None'"), ("_native_crew_should_auto_approve", "function", "(native_tracker, state, slot) -> 'bool'"), ("_persistable_session_policy", "function", "(slot: 'Any', yolo_active: 'bool') -> 'str'"), @@ -474,6 +468,12 @@ ), ("_STEER_NOTICE_BOUND_SECS", "value", "float"), ("_steer_repeat_loop_notice", "async function", "(client: 'Any', notice: 'str') -> 'bool'"), + ("_CREDENTIAL_HINT_CLASSES", "value", "frozenset"), + ( + "_credential_tool_hint_for", + "async function", + "(reason: 'str', cause: 'str', subject: 'str' = '') -> 'str'", + ), ( "_steer_policy_notice", "async function", diff --git a/test/test_chat_runner_coverage_approval.py b/test/test_chat_runner_coverage_approval.py index 36aee10a2a3c..6592515f16b9 100644 --- a/test/test_chat_runner_coverage_approval.py +++ b/test/test_chat_runner_coverage_approval.py @@ -30,6 +30,7 @@ from kiro_crew import name_grant from kiro_crew.dashboard import chat_runner +from kiro_crew.providers.base import LLMEvent from kiro_crew.trust_patterns import ( GrantDeadline, base_trust_patterns, @@ -68,6 +69,66 @@ def _vouch_for_the_program(self): ): yield + @pytest.mark.asyncio + async def test_a_kas_plan_handoff_asks_even_in_trust(self, tmp_path): + """KAS's ``update_workflow`` plan approval passes no grant rung, Trust included.""" + state, client = _runner_state(tmp_path) + slot = _slot() + slot._trust = True + plan = _permission( + title="Add 2 workflow steps to wf_1", + tool_input="{}", + tool_kind="other", + is_shell=False, + ) + plan.harness_tool_id = "update_workflow" + _set_stream(client, [plan, _complete()]) + prompted: list[str] = [] + + def _allow_once_when_registered(): + future = slot._approval_futures.get("req-cov-1") + if future is not None and not future.done(): + prompted.append("card") + future.set_result("approved") + + state.push_slots_update.side_effect = _allow_once_when_registered + await _drive(state, slot) + + assert prompted == ["card"], "the plan reached the person's card" + client.approve_tool.assert_awaited_once_with("req-cov-1") + + @staticmethod + def _kas_question(*, answers_only: bool = True) -> LLMEvent: + """A ``user_input`` question the chat's own KAS session asks. + + The shape of kiro-agent's legacy bridge (``acp-event-adapter.ts`` + ``handleUserInputViaPermissionRequest``): the question as the title, one + ``allow_once`` option per answer, no reject, no ``_meta.kiro.toolId``. + """ + question = _permission( + title="Which branch should I target?", + tool_input="", + tool_kind="other", + is_shell=False, + ) + question.options = [{"id": "q1-main", "label": "main"}, {"id": "q1-dev", "label": "dev"}] + question.kas_builtin_ids = True + question.answers_only = answers_only + return question + + @pytest.mark.asyncio + async def test_a_kas_tool_approval_under_trust_is_still_auto_approved(self, tmp_path): + """Control: a KAS request that offers a reject is a tool approval, and Trust answers it.""" + state, client = _runner_state(tmp_path) + slot = _slot() + slot._trust = True + _set_stream(client, [self._kas_question(answers_only=False), _complete()]) + + await _drive(state, slot) + + client.approve_tool.assert_awaited_once_with("req-cov-1") + assert not [m for m in slot.messages if m.get("role") == "permission"] + @pytest.mark.asyncio async def test_a_non_shell_approval_mints_no_shell_witness(self, tmp_path): """GPT 5.6 round-22: a non-shell approval must not pin a shell program. @@ -1089,6 +1150,25 @@ async def test_timed_redirect_grant_under_a_chat_long_base_grant_carries_its_dea class TestRunChatApprovalWindow: + @pytest.mark.asyncio + async def test_a_trust_reads_press_rechecks_held_step_approvals(self, tmp_path): + """The card's Trust-reads press changes the chat's mode, so held Kiro + Workflows steps are re-decided under it once.""" + state, client = _runner_state(tmp_path) + slot = _slot() + _set_stream(client, [_permission(), _complete()]) + state.push_slots_update.side_effect = lambda: _answer_card(slot, "approved_trust_reads") + + with patch( + "kiro_crew.dashboard.kas_workflow_triggers.recheck_step_approvals", + new=AsyncMock(return_value=0), + ) as recheck: + await _drive(state, slot) + + assert slot._trust_reads is True + recheck.assert_awaited_once_with() + client.approve_tool.assert_awaited_once_with("req-cov-1") + @pytest.mark.asyncio async def test_non_shell_card_separates_display_from_collision_free_trust_key(self, tmp_path): state, client = _runner_state(tmp_path) diff --git a/test/test_chat_runner_kas_observe.py b/test/test_chat_runner_kas_observe.py new file mode 100644 index 000000000000..0c3adcaf0bed --- /dev/null +++ b/test/test_chat_runner_kas_observe.py @@ -0,0 +1,375 @@ +"""The chat turn that shows KAS's own end-of-run wake turn (an observe turn). + +Driven through a real ``_run_chat`` with a scripted provider, the harness of +``test_chat_runner_coverage``: the observe message makes the turn read +``stream_observe()`` instead of sending a prompt, its text lands in the chat, +and an observe turn that read nothing is not retried as an empty response. +""" + +from __future__ import annotations + +import threading +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from chat_runner_coverage_helpers import _async_iter, _complete, _drive, _runner_state, _slot + +from kiro_crew.acp.types import EVENT_TEXT_CHUNK +from kiro_crew.hooks import HOOK_EVENT_USER_PROMPT_SUBMIT +from kiro_crew.kas_workflows import router as router_mod +from kiro_crew.kas_workflows.router import KasWorkflowRouter +from kiro_crew.providers.base import LLMEvent +from kiro_crew.testing.wait import async_wait_until, await_until + + +async def _no_runtime(): # pragma: no cover - never called by these tests + raise AssertionError("no query runtime is needed") + + +def _kas_client(client, session_id: str = "acp-parent") -> None: + client.client = MagicMock( + pop_pending_oauth_requests=MagicMock(return_value=[]), + runtime=SimpleNamespace(acp_backend="kas", is_alive=lambda: True), + session_id=session_id, + ) + + +def _scripted(client, observed: list) -> dict: + calls = {"observe": 0, "stream": 0} + + def _observe(*_a, **_kw): + calls["observe"] += 1 + return _async_iter(observed) + + def _stream(*_a, **_kw): + calls["stream"] += 1 + return _async_iter([_complete()]) + + client.stream_observe = MagicMock(side_effect=_observe) + client.stream = MagicMock(side_effect=_stream) + client.stream_command = MagicMock(side_effect=_stream) + return calls + + +@pytest.fixture +def router(monkeypatch, tmp_path): + router = KasWorkflowRouter(_no_runtime, screen=lambda _c: None) + monkeypatch.setattr(router_mod, "_ROUTER", router) + return router + + +def _texts(slot, role: str) -> list[str]: + return [m.get("content") or "" for m in slot.messages if m.get("role") == role] + + +@pytest.mark.asyncio +async def test_an_observe_turn_streams_the_engines_turn_and_sends_no_prompt(tmp_path, router): + state, client = _runner_state(tmp_path) + state.sessions.get_or_create.return_value = (client, False, False) + _kas_client(client) + calls = _scripted( + client, + [LLMEvent(kind=EVENT_TEXT_CHUNK, text="The run found three issues."), _complete()], + ) + slot = _slot() + message = router.prepare_observe(slot.key, "investigate", "completed", "acp-parent") + await _drive(state, slot, message) + assert calls == {"observe": 1, "stream": 0} + assert any("three issues" in t for t in _texts(slot, "assistant")) + # Not a prompt the person submitted: no UserPromptSubmit hook ran for it. + fired = [c.args[0] for c in state._hook_store.fire.await_args_list if c.args] + assert HOOK_EVENT_USER_PROMPT_SUBMIT not in fired + + +@pytest.mark.asyncio +async def test_an_empty_observe_turn_says_so_and_is_not_retried(tmp_path, router): + state, client = _runner_state(tmp_path) + state.sessions.get_or_create.return_value = (client, False, False) + _kas_client(client) + calls = _scripted(client, [_complete(synthetic_completion=True)]) + slot = _slot() + message = router.prepare_observe(slot.key, "investigate", "completed", "acp-parent") + await _drive(state, slot, message) + # Neither replayed nor continued: one observe, no prompt sent afterwards. + assert calls == {"observe": 1, "stream": 0} + notices = _texts(slot, "notice") + assert any("did not reply to the workflow" in n for n in notices) + assert not any("returned nothing" in n for n in notices) + + +@pytest.mark.asyncio +async def test_an_observe_turn_on_another_session_reads_nothing(tmp_path, router): + state, client = _runner_state(tmp_path) + state.sessions.get_or_create.return_value = (client, False, False) + _kas_client(client, session_id="acp-newer") + calls = _scripted(client, [_complete()]) + slot = _slot() + message = router.prepare_observe(slot.key, "investigate", "completed", "acp-parent") + await _drive(state, slot, message) + assert calls == {"observe": 0, "stream": 0} + assert any("no longer connected" in t for t in _texts(slot, "assistant")) + + +@pytest.mark.asyncio +async def test_a_forged_observe_message_reads_nothing(tmp_path, router): + state, client = _runner_state(tmp_path) + state.sessions.get_or_create.return_value = (client, False, False) + _kas_client(client) + calls = _scripted(client, [_complete()]) + slot = _slot() + forged = "[Workflow `x` completed] Kiro Agent's reply follows (observe " + "0" * 32 + ")" + await _drive(state, slot, forged) + assert calls == {"observe": 0, "stream": 0} + assert any("expired" in t for t in _texts(slot, "assistant")) + + +def test_the_dashboard_starter_skips_a_closed_or_busy_chat(monkeypatch): + from kiro_crew.dashboard.handlers.kas_workflows import observe_turn_starter + + idle = SimpleNamespace(running=False, enqueue_or_run_prompt=MagicMock(return_value=True)) + busy = SimpleNamespace(running=True, enqueue_or_run_prompt=MagicMock(return_value=False)) + slots = {"idle": idle, "busy": busy} + state = SimpleNamespace(get_slot=slots.get, push_slots_update=MagicMock()) + start = observe_turn_starter(state) + assert start("gone", "m") is False + # A chat mid-turn has KAS's nudge in that turn: nothing separate to read. + assert start("busy", "m") is False + busy.enqueue_or_run_prompt.assert_not_called() + assert start("idle", "m") is True + assert idle.enqueue_or_run_prompt.call_args.args[0] == "m" + + +class _ColdChat(SimpleNamespace): + """A chat restored at gateway start: its transcript window is not read yet.""" + + def __init__(self) -> None: + super().__init__(running=False, window_pending=True, events=[]) + loop_thread = threading.get_ident() + chat = self + + class _Window: + def read(self, _slot): + where = "off the loop" if threading.get_ident() != loop_thread else "on the loop" + chat.events.append(f"read {where}") + return () + + self._lazy_window = _Window() + + def load_window(self, *_prefetched) -> None: + self.window_pending = False + self.events.append("loaded") + + def enqueue_or_run_prompt(self, message, *_args, **_kwargs) -> bool: + self.events.append("queued with the window pending" if self.window_pending else "queued") + return True + + +def _cold_gateway(chat: _ColdChat) -> SimpleNamespace: + return SimpleNamespace( + get_slot={"chat-1": chat}.get, push_slots_update=MagicMock(), _background_tasks=set() + ) + + +@pytest.mark.asyncio +async def test_the_dashboard_starter_reads_a_cold_chats_window_off_the_loop_first(router): + from kiro_crew.dashboard.handlers.kas_workflows import observe_turn_starter + + # Given: a chat restored at gateway start, and an observe turn for it + chat = _ColdChat() + state = _cold_gateway(chat) + message = router.prepare_observe("chat-1", "investigate", "completed", "acp-parent") + + # When: the router starts the observe turn + assert observe_turn_starter(state)("chat-1", message) is True + (task,) = state._background_tasks + await await_until(task, what="the observe turn's start") + + # Then: the window was read on a worker thread and loaded before the turn was queued + assert chat.events == ["read off the loop", "loaded", "queued"] + assert router.take_observe("chat-1", router.observe_token(message)) == "acp-parent" + + +@pytest.mark.asyncio +async def test_a_cold_chat_that_starts_a_turn_while_its_window_is_read_gets_no_observe(router): + from kiro_crew.dashboard.handlers.kas_workflows import observe_turn_starter + + # Given: a cold chat whose person starts a turn while its window is read + chat = _ColdChat() + read = chat._lazy_window.read + + def read_while_a_turn_starts(slot): + chat.running = True + return read(slot) + + chat._lazy_window.read = read_while_a_turn_starts + state = _cold_gateway(chat) + message = router.prepare_observe("chat-1", "investigate", "completed", "acp-parent") + + # When: the router starts the observe turn + observe_turn_starter(state)("chat-1", message) + (task,) = state._background_tasks + await await_until(task, what="the observe turn's start") + + # Then: nothing is queued behind that turn, and the observe token is gone + assert chat.events == ["read off the loop", "loaded"] + assert router.take_observe("chat-1", router.observe_token(message)) is None + + +# ── Typing while an observe turn runs (G4) ── +# +# A message the person types while the observe turn reads Kiro Agent's woken turn +# is the chat's NEXT ordinary turn, exactly as typing during any running turn: it +# waits on the slot queue, is never steered into the observe turn (which sends +# nothing, so a steer would land in Kiro Agent's own turn) and never dropped by +# it, and runs once the observe turn ends -- also when that turn ends on its 20 s +# no-reply window (a synthetic completion with nothing read). + + +def _typing_observe(state, slot, events, typed: str, seen: dict): + """A ``stream_observe`` that, mid-turn, has the person type *typed*.""" + from kiro_crew.dashboard import chat_runner + from kiro_crew.dashboard.chat_delivery import steer_into_running_turn + + async def _observe(*_a, **_kw): + seen["observe"] += 1 + # The composer first offers a running turn a steer, and queues on refusal. + seen["steer"] = await steer_into_running_turn(state, slot, typed, user_origin=True) + seen["queued"] = not slot.enqueue_or_run_prompt(typed, chat_runner._run_chat, state) + for event in events: + yield event + + return _observe + + +async def _run_and_drain(state, slot, message: str) -> None: + """Start *message* as the dashboard's starter does, then await every turn it leads to.""" + import asyncio + + from test_chat_runner_coverage import _quiet_sel + + from kiro_crew.dashboard import chat_runner + + slot._empty_response_retries = 2 + with _quiet_sel(): + assert slot.enqueue_or_run_prompt(message, chat_runner._run_chat, state) is True + + def _drained() -> bool: + task = slot.task + running = task is not None and hasattr(task, "done") and not task.done() + return not running and not slot._queue + + # Wait on the state, not a fixed poll: every turn the start leads to has + # run and nothing is queued behind it (testing-conventions rule D1). + await async_wait_until(_drained) + task = slot.task + if task is not None and hasattr(task, "done") and task.done(): + await asyncio.shield(task) + + +def _typing_harness(tmp_path, observed: list, typed: str): + from unittest.mock import AsyncMock + + state, client = _runner_state(tmp_path) + state.sessions.get_or_create.return_value = (client, False, False) + _kas_client(client) + client.client.supports_steer = True + client.client.steer = AsyncMock() + slot = _slot() + seen = {"observe": 0, "stream": [], "steer": None, "queued": None} + client.stream_observe = MagicMock( + side_effect=_typing_observe(state, slot, observed, typed, seen) + ) + + def _stream(message, *_a, **_kw): + seen["stream"].append(message) + return _async_iter( + [LLMEvent(kind=EVENT_TEXT_CHUNK, text="Next steps: fix them."), _complete()] + ) + + client.stream = MagicMock(side_effect=_stream) + client.stream_command = MagicMock(side_effect=_stream) + return state, client, slot, seen + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "observed", + [ + pytest.param( + [LLMEvent(kind=EVENT_TEXT_CHUNK, text="The run found three issues."), _complete()], + id="engine-replied", + ), + # The 20 s no-reply window: the reader ends the turn with a synthetic + # completion and nothing read. + pytest.param([_complete(synthetic_completion=True)], id="no-reply-timeout"), + ], +) +async def test_a_message_typed_during_an_observe_turn_is_the_next_turn(tmp_path, router, observed): + state, client, slot, seen = _typing_harness(tmp_path, observed, "what should we fix first?") + message = router.prepare_observe(slot.key, "investigate", "completed", "acp-parent") + await _run_and_drain(state, slot, message) + from kiro_crew.dashboard.chat_delivery import STEER_UNAVAILABLE + + assert seen["observe"] == 1 + # Never steered into the observe turn: it sends nothing, so a steer would + # land inside Kiro Agent's own woken turn. + assert seen["steer"] == STEER_UNAVAILABLE + client.client.steer.assert_not_awaited() + # Queued, like typing during any running turn ... + assert seen["queued"] is True + # ... and run once the observe turn ended, as one ordinary prompt. + assert len(seen["stream"]) == 1 + assert "what should we fix first?" in seen["stream"][0] + assert not slot._queue + users = _texts(slot, "user") + assert any("what should we fix first?" in t for t in users) + assert any("fix them" in t for t in _texts(slot, "assistant")) + + +@pytest.mark.asyncio +async def test_a_steer_during_an_ordinary_turn_is_still_offered(tmp_path, router): + """Control: only the observe turn refuses a steer; an ordinary turn takes it.""" + from unittest.mock import AsyncMock + + from kiro_crew.dashboard.chat_delivery import STEER_UNAVAILABLE, steer_into_running_turn + + state, client = _runner_state(tmp_path) + state.sessions.get_or_create.return_value = (client, False, False) + _kas_client(client) + client.client.supports_steer = True + client.client.steer = AsyncMock() + slot = _slot() + seen: dict = {} + + async def _stream(*_a, **_kw): + seen["steer"] = await steer_into_running_turn(state, slot, "and also", user_origin=True) + yield LLMEvent(kind=EVENT_TEXT_CHUNK, text="ok") + yield _complete() + + client.stream = MagicMock(side_effect=_stream) + await _drive(state, slot, "hello") + assert seen["steer"] != STEER_UNAVAILABLE + client.client.steer.assert_awaited() + + +@pytest.mark.parametrize(("switch", "reattached"), [(True, ["chat-cov-1"]), (False, [])]) +@pytest.mark.asyncio +async def test_an_ordinary_turn_reattaches_only_while_the_switch_is_on( + tmp_path, router, monkeypatch, switch, reattached +): + # Turn admission's code runs on chat_runner's globals (chat_turn.compose). + from kiro_crew.dashboard import chat_runner + + state, client = _runner_state(tmp_path) + state.sessions.get_or_create.return_value = (client, False, False) + _kas_client(client) + _scripted(client, []) + seen: list[str] = [] + router.schedule_reattach = lambda slot_key, _provider: seen.append(slot_key) + monkeypatch.setattr(chat_runner, "kas_workflows_enabled", lambda _cfg: switch) + slot = _slot() + + await _drive(state, slot, "hello") + + assert seen == reattached diff --git a/test/test_held_note_turn_starts.py b/test/test_held_note_turn_starts.py index 80d6a16c51f2..12521020a9cf 100644 --- a/test/test_held_note_turn_starts.py +++ b/test/test_held_note_turn_starts.py @@ -82,6 +82,18 @@ ("dashboard/handlers/taskrunner.py", "api_taskrunner_to_chat"): ( "starts a turn only on the fresh slot it just created, which holds no note" ), + ("dashboard/handlers/kas_workflows.py", "api_kas_run_start"): ( + "a Kiro Workflows launch, which turn admission answers itself without sending " + "the model a prompt; the hold waits for this turn's cycle end" + ), + ("dashboard/handlers/kas_workflows.py", "_send_reconnect"): ( + "a Kiro Workflows reconnect, which turn admission answers itself without " + "sending the model a prompt; the hold waits for this turn's cycle end" + ), + ("dashboard/handlers/kas_workflows.py", "observe_turn_starter"): ( + "the turn that reads a finished run's result from the turn Kiro Agent started " + f"on the chat, with no prompt of its own: {_AUTOMATIC}" + ), ("dashboard/chat_turn/slash_commands.py", "_turn_slash_gate"): ( "re-enters the turn already running with the expanded prompt; that turn's " "start decided the hold" diff --git a/test/test_kas_slot_needs_person.py b/test/test_kas_slot_needs_person.py new file mode 100644 index 000000000000..a720be827690 --- /dev/null +++ b/test/test_kas_slot_needs_person.py @@ -0,0 +1,72 @@ +"""Gap 8: a Kiro Agent workflow parked on a person folds into the slot's +``needs_input`` flag, through ``slot_projection.kas_slot_needs_person``. + +The helper reads the ALREADY-running router singleton (never constructs one) and +answers ``False`` on any doubt, so a gateway with KAS off pays nothing and the +sidebar flag never raises on the slots poll. +""" + +from kiro_crew.dashboard import slot_projection +from kiro_crew.kas_workflows import router as kas_router + + +class _FakeRouter: + def __init__(self, rows): + self._rows = rows + + def rows(self): + return self._rows + + +def test_empty_slot_key_is_false(): + assert slot_projection.kas_slot_needs_person("") is False + + +def test_no_router_singleton_is_false(monkeypatch): + # KAS never ran in this process: the module global is None and the helper + # must NOT call get_router() (which would build one). + monkeypatch.setattr(kas_router, "_ROUTER", None, raising=False) + assert slot_projection.kas_slot_needs_person("s1") is False + + +def test_needs_attention_row_for_this_slot(monkeypatch): + rows = [{"workflowId": "wf1", "slotKey": "s1", "controls": {"needsAttention": True}}] + monkeypatch.setattr(kas_router, "_ROUTER", _FakeRouter(rows), raising=False) + assert slot_projection.kas_slot_needs_person("s1") is True + # A run reporting into a different chat does not light THIS one. + assert slot_projection.kas_slot_needs_person("s2") is False + + +def test_blocking_step_counts(monkeypatch): + rows = [ + { + "workflowId": "wf1", + "slotKey": "s1", + "controls": {"needsAttention": False}, + "blocking": {"nodeId": "n"}, + } + ] + monkeypatch.setattr(kas_router, "_ROUTER", _FakeRouter(rows), raising=False) + assert slot_projection.kas_slot_needs_person("s1") is True + + +def test_a_running_run_with_no_hold_is_false(monkeypatch): + rows = [ + { + "workflowId": "wf1", + "slotKey": "s1", + "controls": {"needsAttention": False}, + "blocking": None, + } + ] + monkeypatch.setattr(kas_router, "_ROUTER", _FakeRouter(rows), raising=False) + assert slot_projection.kas_slot_needs_person("s1") is False + + +def test_rows_raising_is_swallowed(monkeypatch): + class _Bad: + def rows(self): + raise RuntimeError("boom") + + monkeypatch.setattr(kas_router, "_ROUTER", _Bad(), raising=False) + assert slot_projection.kas_slot_needs_person("s1") is False diff --git a/test/test_kas_workflow_mode_recheck.py b/test/test_kas_workflow_mode_recheck.py new file mode 100644 index 000000000000..e3a88eb9ef1b --- /dev/null +++ b/test/test_kas_workflow_mode_recheck.py @@ -0,0 +1,87 @@ +"""A chat's approval mode change re-decides its held Kiro Workflows step approvals. + +The mode route (``POST /api/chat/mode``) and the approval card's Trust press each +await ``kas_workflow_triggers.recheck_step_approvals`` once after the change took; +a refused change and an ordinary approve do not. What the re-check decides is +tested in ``test_kas_workflow_triggers.py``. +""" + +from __future__ import annotations + +import asyncio +import json +from unittest.mock import AsyncMock, patch + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer +from chat_mode_security_helpers import ( # noqa: F401 -- fixtures are requested by name + _hermetic_home, + _isolate_safety_override, + state_fixture, +) + +from kiro_crew.dashboard.chat_handlers import api_chat_mode, api_chat_slot_approve +from kiro_crew.dashboard.state import SlotOrigin, row_mid + +_RECHECK = "kiro_crew.dashboard.kas_workflow_triggers.recheck_step_approvals" + + +@web.middleware +async def _dashboard_owner_request(request: web.Request, handler): + request["app"] = "" + request["user"] = "local-app" + return await handler(request) + + +def _app(state) -> web.Application: + app = web.Application(middlewares=[_dashboard_owner_request]) + app["state"] = state + app.router.add_post("/api/chat/mode", api_chat_mode) + app.router.add_post("/api/chat/slots/{slot}/approve", api_chat_slot_approve) + return app + + +@pytest.mark.asyncio +async def test_a_mode_change_rechecks_held_step_approvals(state): + state.get_or_create_slot("s1", origin=SlotOrigin.USER) + with patch(_RECHECK, new=AsyncMock(return_value=0)) as recheck: + async with TestClient(TestServer(_app(state))) as client: + resp = await client.post("/api/chat/mode", json={"mode": "trust", "slot": "s1"}) + assert resp.status == 200 + recheck.assert_awaited_once_with() + + +@pytest.mark.asyncio +async def test_a_refused_mode_change_rechecks_nothing(state): + state.get_or_create_slot("s1", origin=SlotOrigin.USER) + with patch(_RECHECK, new=AsyncMock(return_value=0)) as recheck: + async with TestClient(TestServer(_app(state))) as client: + resp = await client.post("/api/chat/mode", json={"mode": "bogus", "slot": "s1"}) + assert resp.status == 400 + recheck.assert_not_awaited() + + +@pytest.mark.parametrize(("action", "rechecks"), [("trust", 1), ("approved", 0)]) +@pytest.mark.asyncio +async def test_the_cards_trust_press_rechecks_and_an_approve_does_not(state, action, rechecks): + slot = state.get_or_create_slot("selected", origin=SlotOrigin.USER) + row = slot.append( + "permission", "Tool", json.dumps({"request_id": "req-1", "trust_grantable": "1"}) + ) + future = asyncio.get_running_loop().create_future() + slot.register_approval("req-1", future, row) + with patch(_RECHECK, new=AsyncMock(return_value=0)) as recheck: + async with TestClient(TestServer(_app(state))) as client: + resp = await client.post( + "/api/chat/slots/selected/approve", + json={ + "origin": "native", + "request_id": "req-1", + "request_mid": row_mid(row), + "action": action, + }, + ) + assert resp.status == 200, await resp.text() + assert future.done() + assert recheck.await_count == rechecks diff --git a/test/test_kas_workflow_triggers.py b/test/test_kas_workflow_triggers.py new file mode 100644 index 000000000000..6985710ca79d --- /dev/null +++ b/test/test_kas_workflow_triggers.py @@ -0,0 +1,682 @@ +"""The dashboard's Kiro Workflows triggers. + +The revision push over ``/api/ws``, the re-decision of held step approvals when a +chat's approval mode changes, and the reconnect a Kiro Agent process exit sends. +""" + +from __future__ import annotations + +import asyncio +import threading +from types import SimpleNamespace + +import pytest +from kas_workflow_helpers import ( + ChatProvider, + FakeRuntime, + driven, + listed_run, + make_router, + name_chat_session, + step_node, +) + +from kiro_crew import runtime_death +from kiro_crew.dashboard import kas_workflow_triggers as triggers +from kiro_crew.kas_workflows import chat as kas_chat +from kiro_crew.kas_workflows import router as router_mod +from kiro_crew.kas_workflows import wire +from kiro_crew.testing.wait import async_wait_until + + +@pytest.fixture(autouse=True) +def _tmp_path_is_a_recent_project(_floor_monkeypatch, tmp_path): + """tmp_path is the run's project; listing it as recent keeps the real confinement.""" + _floor_monkeypatch.setattr( + "kiro_crew.kas_workflows.project_root.recent_project_dirs", lambda: [str(tmp_path)] + ) + + +class _Owners: + """A state whose owner fan-out records every frame.""" + + def __init__(self) -> None: + self.frames: list[tuple[str, dict]] = [] + + def broadcast_ws_owners(self, msg_type: str, data: dict) -> None: + self.frames.append((msg_type, dict(data))) + + +class _Timers: + """A scheduler that records each armed window; the test fires them by hand.""" + + def __init__(self) -> None: + self.armed: list[tuple[float, object]] = [] + + def __call__(self, delay: float, callback) -> None: + self.armed.append((delay, callback)) + + def fire(self) -> None: + _delay, callback = self.armed.pop(0) + callback() + + +def _revisions(state: _Owners) -> list[int]: + assert all(t == triggers.KAS_REVISION_FRAME for t, _ in state.frames) + return [d["revision"] for _t, d in state.frames] + + +def test_a_burst_sends_one_leading_and_one_trailing_frame_with_the_latest_value(): + state, timers = _Owners(), _Timers() + publish = triggers.revision_publisher(state, window_secs=0.25, schedule=timers) + + publish(1) + publish(2) + publish(3) + assert _revisions(state) == [1] + assert [d for d, _cb in timers.armed] == [0.25] + + timers.fire() + assert _revisions(state) == [1, 3] + # The trailing frame re-arms; a quiet window then disarms. + timers.fire() + assert _revisions(state) == [1, 3] + assert timers.armed == [] + + +def test_a_move_after_a_quiet_window_is_sent_at_once(): + state, timers = _Owners(), _Timers() + publish = triggers.revision_publisher(state, schedule=timers) + + publish(1) + timers.fire() + publish(2) + assert _revisions(state) == [1, 2] + + +def test_with_no_running_loop_the_frame_is_sent_inline(): + state = _Owners() + publish = triggers.revision_publisher(state) + + publish(4) + publish(5) + assert _revisions(state) == [4, 5] + + +@pytest.mark.asyncio +async def test_on_a_running_loop_the_window_is_armed_on_that_loop(): + state = _Owners() + publish = triggers.revision_publisher(state, window_secs=3600) + + publish(1) + publish(2) + assert _revisions(state) == [1] + + +def test_a_failing_fan_out_is_swallowed(): + class _Broken: + def broadcast_ws_owners(self, _t, _d): + raise RuntimeError("socket gone") + + publish = triggers.revision_publisher(_Broken()) + publish(1) + + +def test_install_adds_the_push_to_the_dashboard_hooks_and_uninstall_removes_them( + monkeypatch, +): + monkeypatch.setattr(router_mod, "_ROUTER", None) + monkeypatch.setattr(router_mod, "_HOOKS", None) + state = _Owners() + + triggers.install_kas_workflow_triggers(state) + hooks = router_mod._HOOKS + assert hooks is not None + assert hooks.notify is not None and hooks.append_marker is not None + assert hooks.changed is not None + hooks.changed(9) + assert _revisions(state) == [9] + + triggers.uninstall_kas_workflow_triggers() + assert router_mod._HOOKS is None + + +# ── A chat's mode change re-decides its held step approvals ── + + +async def _no_refusal(_cmd: str): + return None + + +async def _held_step(tmp_path, mode: list[str]): + """A router holding one step approval of chat-1's run, asked under *mode*.""" + chat_rt = FakeRuntime() + chat_rt.answers[wire.METHOD_NEW] = { + "workflowId": "w1", + "initialState": { + "status": "running", + "workflowName": "investigate", + "parentSessionId": "acp-parent", + }, + } + router = make_router(name_grant=_no_refusal, audit=lambda **_f: None) + sink = router.sink_for(chat_rt) + launch = router.prepare_launch("chat-1", str(tmp_path), "bundled://investigate", {}) + await router.start_in_session(chat_rt, "acp-parent", launch) + sink.on_notification( + wire.NOTIFY_RUN_START, + {"workflowId": "w1", "nodeTree": [{"type": "step", "id": "a", "label": "Plan"}]}, + ) + sink.on_notification( + wire.NOTIFY_NODE_START, + {"workflowId": "w1", "nodeId": "a", "type": "step", "sessionId": "step-1"}, + ) + router.note_chat_session("chat-1", ChatProvider(chat_rt), lambda: (mode[0], mode[0])) + sink.on_step_request( + 12, + "step-1", + "session/request_permission", + { + "sessionId": "step-1", + "toolCall": {"title": "Run it", "rawInput": {"command": "npm test"}}, + "options": [ + {"optionId": "yes", "kind": "allow_once", "name": "Allow"}, + {"optionId": "no", "kind": "reject_once", "name": "Reject"}, + ], + }, + ) + await async_wait_until(lambda: router.approvals()) + return router, chat_rt + + +@pytest.mark.asyncio +async def test_recheck_with_no_router_reads_no_config(monkeypatch): + monkeypatch.setattr(router_mod, "_ROUTER", None) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: pytest.fail("read config")) + + assert await triggers.recheck_step_approvals() == 0 + + +@pytest.mark.asyncio +async def test_recheck_with_nothing_held_reads_no_config(monkeypatch): + monkeypatch.setattr(router_mod, "_ROUTER", make_router()) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: pytest.fail("read config")) + + assert await triggers.recheck_step_approvals() == 0 + + +@pytest.mark.asyncio +async def test_with_the_switch_off_a_held_step_keeps_waiting(tmp_path, monkeypatch): + mode = ["normal"] + router, chat_rt = await _held_step(tmp_path, mode) + monkeypatch.setattr(router_mod, "_ROUTER", router) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: False) + mode[0] = "trust" + + assert await triggers.recheck_step_approvals() == 0 + assert len(router.approvals()) == 1 + assert chat_rt.responses == [] + + +@pytest.mark.asyncio +async def test_a_chat_switched_to_trust_releases_its_held_step(tmp_path, monkeypatch): + mode = ["normal"] + router, chat_rt = await _held_step(tmp_path, mode) + monkeypatch.setattr(router_mod, "_ROUTER", router) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + mode[0] = "trust" + + assert await triggers.recheck_step_approvals() == 1 + assert router.approvals() == [] + assert chat_rt.responses == [(12, {"outcome": {"outcome": "selected", "optionId": "yes"}})] + + +@pytest.mark.asyncio +async def test_a_failing_recheck_answers_zero(monkeypatch): + class _Broken: + def approvals(self): + return [{"key": "k"}] + + async def recheck_pending(self): + raise RuntimeError("runtime gone") + + monkeypatch.setattr(router_mod, "_ROUTER", _Broken()) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + + assert await triggers.recheck_step_approvals() == 0 + + +# ── A chat whose run works or waits is held off the idle clock ── + + +def _run_state(status: str, *, asks: bool = False) -> dict: + state = { + "status": status, + "workflowName": "walk", + "parentSessionId": "acp-parent", + "root": { + "nodeId": "w1", + "type": "sequence", + "status": status, + "children": [step_node("ask", status, "s1")], + }, + } + if asks: + state["attention"] = [{"kind": "question", "nodeId": "ask", "sessionId": "s1"}] + return state + + +def _chat_run_router(state: dict, *, live_process: bool) -> router_mod.KasWorkflowRouter: + """A router whose run w1 belongs to chat-1, driven by a live process or by none. + + The router holds its driving process weakly, so the router keeps it here. + """ + router = make_router() + name_chat_session(router, "chat-1", "acp-parent") + if live_process: + router._test_process = driven(router, state) # type: ignore[attr-defined] + else: + router.mirror.apply_load({"workflowId": "w1", "state": state, "nodePlan": []}) + return router + + +@pytest.mark.parametrize( + "state,live_process,held", + [ + pytest.param(_run_state("running"), True, True, id="running"), + pytest.param(_run_state("paused", asks=True), True, True, id="waiting_on_a_person"), + pytest.param(_run_state("paused"), True, False, id="paused_with_no_ask"), + pytest.param(_run_state("completed"), True, False, id="finished"), + pytest.param(_run_state("running"), False, False, id="no_live_process"), + ], +) +def test_a_chat_is_held_while_its_run_works_or_waits_on_a_person( + monkeypatch, state, live_process, held +): + monkeypatch.setattr(router_mod, "_ROUTER", _chat_run_router(state, live_process=live_process)) + + keys = triggers.idle_held_sessions(_gateway(_Chat())) + + assert keys == (frozenset({"dashboard:chat-1"}) if held else frozenset()) + + +def test_a_run_whose_chat_is_gone_holds_nothing(monkeypatch): + router = _chat_run_router(_run_state("running"), live_process=True) + monkeypatch.setattr(router_mod, "_ROUTER", router) + + assert triggers.idle_held_sessions(_gateway(None)) == frozenset() + + +def test_unreadable_rows_hold_nothing(monkeypatch): + class _Broken: + def rows(self): + raise RuntimeError("mirror broken") + + monkeypatch.setattr(router_mod, "_ROUTER", _Broken()) + + assert triggers.idle_held_sessions(_gateway(_Chat())) == frozenset() + + +def test_install_hands_the_session_manager_the_hold_and_uninstall_takes_it_back(monkeypatch): + monkeypatch.setattr(router_mod, "_HOOKS", None) + monkeypatch.setattr( + router_mod, "_ROUTER", _chat_run_router(_run_state("running"), live_process=True) + ) + holds: list[object] = [] + gateway = _gateway(_Chat()) + gateway.sessions = SimpleNamespace(admission_closed=False, set_idle_hold=holds.append) + + triggers.install_kas_workflow_triggers(gateway) + assert len(holds) == 1 and callable(holds[0]) + assert holds[0]() == frozenset({"dashboard:chat-1"}) + + triggers.uninstall_kas_workflow_triggers() + assert holds[1:] == [None] + + +# ── A Kiro Agent process exit reconnects the runs it left without a process ── + + +@pytest.fixture(autouse=True) +def _no_listener_outlives_a_test(): + yield + triggers._unsubscribe_all() + + +def _undriven_router() -> router_mod.KasWorkflowRouter: + """A router that mirrors one paused run of chat-1 that no live process drives.""" + router = make_router() + name_chat_session(router, "chat-1", "acp-parent") + listed_run(router, "w1", "paused") + return router + + +class _Chat: + def __init__(self, *, running: bool = False, task=None) -> None: + self.key = "chat-1" + self.running = running + self.task = task + self.sent: list[str] = [] + + def enqueue_or_run_prompt(self, message, *_args, **_kwargs): + self.sent.append(message) + return True + + +def _gateway(chat: _Chat | None, *, stopping: bool = False) -> SimpleNamespace: + return SimpleNamespace( + get_slot=lambda key: chat if chat is not None and key == chat.key else None, + push_slots_update=lambda: None, + workflow_startup_stopping=stopping, + sessions=SimpleNamespace(admission_closed=False), + _background_tasks=set(), + ) + + +def _is_reconnect(message: str) -> bool: + return router_mod.KasWorkflowRouter.reconnect_token(message) is not None + + +CHAT_1 = frozenset({"chat-1"}) + + +@pytest.mark.asyncio +async def test_with_the_switch_off_an_exit_sends_nothing(monkeypatch): + router = _undriven_router() + monkeypatch.setattr(router_mod, "_ROUTER", router) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: False) + chat = _Chat() + + assert await triggers.reconnect_after_process_exit(_gateway(chat), CHAT_1) == [] + assert chat.sent == [] + assert "chat-1" not in router._reconnect_tries + + +@pytest.mark.asyncio +async def test_an_idle_chat_gets_one_reconnect_turn(monkeypatch): + monkeypatch.setattr(router_mod, "_ROUTER", _undriven_router()) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + chat = _Chat() + + assert await triggers.reconnect_after_process_exit(_gateway(chat), CHAT_1) == ["chat-1"] + assert len(chat.sent) == 1 and _is_reconnect(chat.sent[0]) + # The router's interval bound holds: a second exit right after sends nothing. + assert await triggers.reconnect_after_process_exit(_gateway(chat), CHAT_1) == [] + + +@pytest.mark.asyncio +async def test_a_chat_the_crash_did_not_reach_gets_no_turn_and_keeps_its_tries(monkeypatch): + router = _undriven_router() + monkeypatch.setattr(router_mod, "_ROUTER", router) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + chat = _Chat() + + assert await triggers.reconnect_after_process_exit(_gateway(chat), {"chat-2"}) == [] + assert chat.sent == [] + assert "chat-1" not in router._reconnect_tries + + +@pytest.mark.asyncio +async def test_a_busy_chat_is_reconnected_once_its_turn_settles(monkeypatch): + router = _undriven_router() + monkeypatch.setattr(router_mod, "_ROUTER", router) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + turn = asyncio.get_running_loop().create_future() + chat = _Chat(running=True, task=turn) + + pass_ = asyncio.ensure_future(triggers.reconnect_after_process_exit(_gateway(chat), CHAT_1)) + await async_wait_until(lambda: "chat-1" in router._reconnect_tries) + assert chat.sent == [] + chat.running = False + turn.set_result(None) + + assert await pass_ == ["chat-1"] + assert len(chat.sent) == 1 and _is_reconnect(chat.sent[0]) + + +@pytest.mark.asyncio +async def test_a_chat_still_busy_after_its_turn_is_left_to_its_next_turn(monkeypatch): + router = _undriven_router() + monkeypatch.setattr(router_mod, "_ROUTER", router) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + turn = asyncio.get_running_loop().create_future() + chat = _Chat(running=True, task=turn) + + pass_ = asyncio.ensure_future(triggers.reconnect_after_process_exit(_gateway(chat), CHAT_1)) + await async_wait_until(lambda: "chat-1" in router._reconnect_tries) + # The failed turn ends, and a queued one starts at once. + turn.set_result(None) + + assert await pass_ == [] + assert chat.sent == [] + + +class _ColdChat(_Chat): + """A chat restored at gateway start: its transcript window is not read yet.""" + + def __init__(self) -> None: + super().__init__() + self.window_pending = True + self.events: list[str] = [] + loop_thread = threading.get_ident() + chat = self + + class _Window: + def read(self, _slot): + where = "off the loop" if threading.get_ident() != loop_thread else "on the loop" + chat.events.append(f"read {where}") + return () + + self._lazy_window = _Window() + + def load_window(self, *_prefetched) -> None: + self.window_pending = False + self.events.append("loaded") + + def enqueue_or_run_prompt(self, message, *args, **kwargs): + self.events.append("queued with the window pending" if self.window_pending else "queued") + return super().enqueue_or_run_prompt(message, *args, **kwargs) + + +@pytest.mark.asyncio +async def test_a_cold_chat_reads_its_window_off_the_loop_before_its_reconnect_turn(monkeypatch): + # Given: a chat restored at gateway start, whose run's process crashed + monkeypatch.setattr(router_mod, "_ROUTER", _undriven_router()) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + chat = _ColdChat() + + # When: the crash pass sends it its reconnect turn + assert await triggers.reconnect_after_process_exit(_gateway(chat), CHAT_1) == ["chat-1"] + + # Then: the window was read on a worker thread and loaded before the turn was queued + assert chat.events == ["read off the loop", "loaded", "queued"] + assert len(chat.sent) == 1 and _is_reconnect(chat.sent[0]) + + +@pytest.mark.asyncio +async def test_a_turn_started_while_a_cold_chat_reads_its_window_gets_no_reconnect_behind_it( + monkeypatch, +): + # Given: a cold chat whose run's process crashed, and a person who starts a + # turn in it while its window is read + monkeypatch.setattr(router_mod, "_ROUTER", _undriven_router()) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + chat = _ColdChat() + read = chat._lazy_window.read + + def read_while_a_turn_starts(slot): + chat.running = True + return read(slot) + + chat._lazy_window.read = read_while_a_turn_starts + + # When: the crash pass reaches the chat + sent = await triggers.reconnect_after_process_exit(_gateway(chat), CHAT_1) + + # Then: the busy check saw the turn, and no reconnect turn is queued behind it + assert sent == [] and chat.sent == [] + assert chat.events == ["read off the loop", "loaded"] + + +@pytest.mark.asyncio +async def test_a_stopping_gateway_sends_nothing(monkeypatch): + monkeypatch.setattr(router_mod, "_ROUTER", _undriven_router()) + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: True) + chat = _Chat() + + assert await triggers.reconnect_after_process_exit(_gateway(chat, stopping=True), CHAT_1) == [] + assert chat.sent == [] + + +def _process_of(router: router_mod.KasWorkflowRouter, wid: str, slot_key: str) -> FakeRuntime: + """A live process driving run *wid* of chat *slot_key*; the router keeps it here.""" + name_chat_session(router, slot_key, f"acp-{slot_key}") + state = {**_run_state("running"), "parentSessionId": f"acp-{slot_key}"} + runtime = driven(router, state, wid=wid) + router._test_processes = [*getattr(router, "_test_processes", []), runtime] + return runtime + + +def _recorded_passes(monkeypatch) -> tuple[router_mod.KasWorkflowRouter, list[tuple]]: + router = make_router() + monkeypatch.setattr(router_mod, "_ROUTER", router) + passes: list[tuple] = [] + + async def recorder(state, chats): + passes.append((state, set(chats))) + return [] + + monkeypatch.setattr(triggers, "reconnect_after_process_exit", recorder) + return router, passes + + +@pytest.mark.asyncio +async def test_each_crash_schedules_one_pass_until_uninstalled(monkeypatch): + monkeypatch.setattr(router_mod, "_HOOKS", None) + monkeypatch.setattr(triggers, "EXIT_RECONNECT_WAIT_SECS", 0.0) + router, passes = _recorded_passes(monkeypatch) + process = _process_of(router, "w1", "chat-1") + gateway = _gateway(None) + + def crash_once() -> None: + runtime_death.announce(process, reason="exit", expected=False, leases=0, acp_sessions=1) + + triggers.install_kas_workflow_triggers(gateway) + triggers.install_kas_workflow_triggers(gateway) # a second install replaces the first + crash_once() + await async_wait_until(lambda: passes == [(gateway, {"chat-1"})]) + await async_wait_until(lambda: not gateway._background_tasks) + + triggers.uninstall_kas_workflow_triggers() + crash_once() + assert not gateway._background_tasks + assert passes == [(gateway, {"chat-1"})] + + +class _Handle: + def __init__(self, delay: float, callback) -> None: + self.delay = delay + self.callback = callback + self.cancelled = False + + def cancel(self) -> None: + self.cancelled = True + + +class _Later: + """A ``call_later`` that records each armed handle; the test fires them by hand.""" + + def __init__(self) -> None: + self.handles: list[_Handle] = [] + + def __call__(self, delay: float, callback) -> _Handle: + handle = _Handle(delay, callback) + self.handles.append(handle) + return handle + + def live(self) -> list[_Handle]: + return [h for h in self.handles if not h.cancelled] + + +def _death(*, expected: bool) -> runtime_death.RuntimeDeath: + reason = "provider shutdown" if expected else "exit" + return runtime_death.RuntimeDeath( + pid=None, reason=reason, expected=expected, leases=1, acp_sessions=1 + ) + + +@pytest.mark.asyncio +async def test_a_teardown_the_gateway_chose_sends_no_reconnect(monkeypatch): + router, _passes = _recorded_passes(monkeypatch) + process = _process_of(router, "w1", "chat-1") + later = _Later() + on_death, _cancel = triggers._death_listener(_gateway(None), schedule=later) + + on_death(process, _death(expected=True)) + + assert later.handles == [] + + +@pytest.mark.asyncio +async def test_a_crash_of_a_process_that_drove_no_run_sends_no_reconnect(monkeypatch): + router, _passes = _recorded_passes(monkeypatch) + _process_of(router, "w1", "chat-1") + later = _Later() + on_death, _cancel = triggers._death_listener(_gateway(None), schedule=later) + + on_death(FakeRuntime(), _death(expected=False)) + + assert later.handles == [] + + +@pytest.mark.asyncio +async def test_a_crash_reconnects_its_own_chats_only_after_the_claim_window(monkeypatch): + router, passes = _recorded_passes(monkeypatch) + process = _process_of(router, "w1", "chat-1") + _process_of(router, "w2", "chat-2") + gateway = _gateway(None) + later = _Later() + on_death, _cancel = triggers._death_listener(gateway, schedule=later) + + process.alive = False + on_death(process, _death(expected=False)) + assert passes == [] + [handle] = later.live() + # KAS's claim on a dead process's run holds 30 s, one beat interval. + assert handle.delay == triggers.EXIT_RECONNECT_WAIT_SECS > 30 + + handle.callback() + await async_wait_until(lambda: passes == [(gateway, {"chat-1"})]) + + +@pytest.mark.asyncio +async def test_a_second_crash_inside_the_wait_moves_the_one_pass_after_it(monkeypatch): + router, passes = _recorded_passes(monkeypatch) + first_process = _process_of(router, "w1", "chat-1") + second_process = _process_of(router, "w2", "chat-2") + gateway = _gateway(None) + later = _Later() + on_death, _cancel = triggers._death_listener(gateway, schedule=later) + + on_death(first_process, _death(expected=False)) + on_death(second_process, _death(expected=False)) + + first, second = later.handles + assert first.cancelled and not second.cancelled + second.callback() + await async_wait_until(lambda: passes == [(gateway, {"chat-1", "chat-2"})]) + await async_wait_until(lambda: not gateway._background_tasks) + assert passes == [(gateway, {"chat-1", "chat-2"})] + + +@pytest.mark.asyncio +async def test_the_cancel_drops_a_pass_that_has_not_started(monkeypatch): + router, _passes = _recorded_passes(monkeypatch) + process = _process_of(router, "w1", "chat-1") + later = _Later() + on_death, cancel = triggers._death_listener(_gateway(None), schedule=later) + on_death(process, _death(expected=False)) + + cancel() + + assert later.live() == [] diff --git a/test/test_kas_workflows_boot_recovery.py b/test/test_kas_workflows_boot_recovery.py new file mode 100644 index 000000000000..82e94d5a7830 --- /dev/null +++ b/test/test_kas_workflows_boot_recovery.py @@ -0,0 +1,396 @@ +"""KAS workflow boot recovery (parity row 7, the owner's option B). + +At gateway start Crew reattaches only ITS OWN interrupted runs: those Kiro Agent +lists for a known project folder whose parent session is one of this gateway's +chats, not finished, not driven by a live process here, and ``paused`` (Kiro +Agent's list reconciles a run whose owner stopped beating to ``paused``). Each +chat gets one reconnect turn. KAS's ``_kiro/workflow/resumeAll`` is never called: +it would take over IDE and other clients' runs. The folders the router lists and +the session map's part are tested in ``test_kas_workflows_recovery.py``. +""" + +from __future__ import annotations + +import asyncio +import weakref +from types import SimpleNamespace +from typing import Any + +import pytest +from kas_workflow_helpers import FakeRuntime, name_chat_session + +from kiro_crew.kas_workflows import router as router_mod +from kiro_crew.kas_workflows import wire +from kiro_crew.kas_workflows.router import STALE_RUNNING_PAUSE_REASON, KasWorkflowRouter +from kiro_crew.testing.wait import await_until, finished + +pytestmark = pytest.mark.asyncio + + +@pytest.fixture(autouse=True) +def _tmp_path_is_a_recent_project(_floor_monkeypatch, tmp_path): + """Boot recovery lists only confined folders; tmp_path sits outside the home root.""" + _floor_monkeypatch.setattr( + "kiro_crew.kas_workflows.project_root.recent_project_dirs", lambda: [str(tmp_path)] + ) + + +def _run(wid: str, chat: str, status: str = "paused", n: int = 0, **extra) -> dict[str, Any]: + """A list row of a run *chat* started: its parent is that chat's session ``s-``.""" + return { + "workflowId": wid, + "status": status, + "name": wid, + "parentSessionId": f"s-{chat}", + "createdAt": f"2026-11-0{n + 1}T00:00:00Z", + **extra, + } + + +def _router(runs: list[dict[str, Any]], chats: list[str]): + """A router whose query process lists *runs* for every folder, *chats* named on turns.""" + reader = FakeRuntime() + reader.answers[wire.METHOD_LIST] = {"runs": runs} + + async def factory(): + return reader + + router = KasWorkflowRouter(factory, screen=lambda _c: None) + for chat in chats: + name_chat_session(router, chat, f"s-{chat}") + return router, reader + + +STALE = {"pauseReason": STALE_RUNNING_PAUSE_REASON} + + +class _Chats: + def __init__(self, open_chats: set[str]): + self.open_chats = open_chats + self.sent: list[str] = [] + + def exists(self, slot_key: str) -> bool: + return slot_key in self.open_chats + + async def reconnect(self, slot_key: str) -> bool: + self.sent.append(slot_key) + return True + + +def _outcome(outcomes, wid): + return next(o for w, _s, o in outcomes if w == wid) + + +async def test_a_stale_run_is_recovered_once_per_chat(): + router, reader = _router( + [_run("w1", "chat-1", **STALE), _run("w2", "chat-1", pauseReason="Paused by user")], + ["chat-1"], + ) + chats = _Chats({"chat-1"}) + outcomes = await router.recover_on_boot(chats.exists, chats.reconnect) + assert chats.sent == ["chat-1"] # one reconnect turn for both of its runs + assert _outcome(outcomes, "w1") == "reattached" + assert _outcome(outcomes, "w2") == "reattached" + # The verdict is KAS's list row; nothing loads or resumes from the query process. + assert {m for m, _p in reader.calls} == {wire.METHOD_LIST} + # The automatic reconnect counts it as this chat's first try, so it does not double up. + assert router._reconnect_tries["chat-1"][0] == 1 + + +async def test_a_run_with_a_live_owner_is_left_alone(): + router, _reader = _router([_run("w1", "chat-1", "running")], ["chat-1"]) + chats = _Chats({"chat-1"}) + outcomes = await router.recover_on_boot(chats.exists, chats.reconnect) + assert chats.sent == [] + assert _outcome(outcomes, "w1") == "skipped: a live owner still holds it" + + +async def test_an_ide_run_no_chat_here_started_is_never_touched(): + # KAS lists "ide-run" (the IDE started it); no chat of this gateway is its parent. + router, reader = _router( + [_run("w1", "chat-1", **STALE), _run("ide-run", "ide", **STALE)], ["chat-1"] + ) + chats = _Chats({"chat-1"}) + outcomes = await router.recover_on_boot(chats.exists, chats.reconnect) + assert [w for w, _s, _o in outcomes] == ["w1"] + assert chats.sent == ["chat-1"] + assert {m for m, _p in reader.calls} == {wire.METHOD_LIST} + + +async def test_a_finished_run_is_not_considered_and_each_outcome_is_logged(caplog): + router, _reader = _router( + [_run("done", "chat-1", "completed"), _run("w1", "chat-1", **STALE)], ["chat-1"] + ) + chats = _Chats({"chat-1"}) + with caplog.at_level("INFO", logger=router_mod.logger.name): + outcomes = await router.recover_on_boot(chats.exists, chats.reconnect) + assert "done" not in {w for w, _s, _o in outcomes} + assert "run w1 (chat chat-1) reattached" in caplog.text + + +async def test_a_gone_chat_is_skipped_not_recreated(): + router, _reader = _router( + [_run("w-gone", "chat-gone", **STALE), _run("w-mine", "chat-2", **STALE)], + ["chat-gone", "chat-2"], + ) + chats = _Chats({"chat-2"}) + outcomes = await router.recover_on_boot(chats.exists, chats.reconnect) + assert chats.sent == ["chat-2"] + assert _outcome(outcomes, "w-gone") == "skipped: its chat no longer exists" + assert _outcome(outcomes, "w-mine") == "reattached" + + +async def test_chats_are_capped_per_boot_most_recent_first(): + chat_keys = [f"chat-{n}" for n in range(4)] + router, _reader = _router( + [_run(f"w{n}", f"chat-{n}", n=n, **STALE) for n in range(4)], chat_keys + ) + chats = _Chats(set(chat_keys)) + outcomes = await router.recover_on_boot(chats.exists, chats.reconnect, max_chats=2) + assert sorted(chats.sent) == ["chat-2", "chat-3"] + assert _outcome(outcomes, "w0") == "skipped: over the 2-chat boot cap" + + +async def _peak_while_held(concurrency: int, *, want: int, timeout: float | None = None) -> int: + """Boot-recover five chats with every reconnect held open; the peak once *want* run. + + The wait for *want* reconnects in flight at once is bounded, so a recovery that + never runs that many fails naming the bound instead of hanging. The held + reconnects are released and the recovery awaited either way. + """ + chat_keys = [f"chat-{n}" for n in range(5)] + router, _reader = _router( + [_run(f"w{n}", f"chat-{n}", n=n, **STALE) for n in range(5)], chat_keys + ) + in_flight = 0 + peak = 0 + enough = asyncio.Event() + release = asyncio.Event() + + async def reconnect(_slot_key: str) -> bool: + nonlocal in_flight, peak + in_flight += 1 + peak = max(peak, in_flight) + if in_flight >= want: + enough.set() + try: + await release.wait() + finally: + in_flight -= 1 + return True + + recovery = asyncio.ensure_future( + router.recover_on_boot(lambda _s: True, reconnect, concurrency=concurrency) + ) + try: + await await_until( + enough, + timeout=timeout, + what=f"{want} reconnects in flight at once with concurrency={concurrency}", + ) + # Every reconnect task has run up to its first wait by the time the + # event wakes this test, so a fan-out past the bound shows in the peak. + return peak + finally: + release.set() + await finished(recovery, "the boot recovery after its reconnects were released") + + +async def test_reconnects_run_at_most_concurrency_at_a_time(): + # Given: five chats to reconnect at boot, each reconnect held open + # When: the recovery runs with a concurrency of two + # Then: two reconnects are in flight at once, never more + assert await _peak_while_held(2, want=2) == 2 + + +async def test_a_serial_recovery_fails_the_concurrency_check_by_name(): + # Given: a recovery that runs one reconnect at a time + # When: the check waits for two reconnects in flight at once + # Then: it fails naming the bound instead of hanging + with pytest.raises(AssertionError, match="2 reconnects in flight at once with concurrency=1"): + await _peak_while_held( + 1, + want=2, + timeout=0.2, # flake-ok: the expiry is the result under test, no second one starts + ) + + +async def test_a_run_already_driven_here_is_not_considered(): + router, reader = _router([_run("w1", "chat-1", **STALE)], ["chat-1"]) + driver = FakeRuntime() + router._route_run("w1", weakref.ref(driver)) + chats = _Chats({"chat-1"}) + assert await router.recover_on_boot(chats.exists, chats.reconnect) == [] + assert chats.sent == [] + assert {m for m, _p in reader.calls} == {wire.METHOD_LIST} + + +# ── The gateway side: gate and wiring ── + + +def _config(backend: str, switch: bool): + return SimpleNamespace(agent=SimpleNamespace(acp_backend=backend, kas_workflows=switch)) + + +@pytest.mark.parametrize(("backend", "switch"), [("kas", False), ("", True), ("", False)]) +async def test_switch_off_or_a_non_kas_backend_does_nothing(monkeypatch, backend, switch): + from kiro_crew.dashboard.handlers import kas_workflows as handlers + from kiro_crew.kas_workflows.engine import ENGINE_KAS, engine_for + + if backend == "kas": + assert engine_for(backend) == ENGINE_KAS + slept: list[float] = [] + + async def sleep(secs: float) -> None: + slept.append(secs) + + def no_router(): + raise AssertionError("the router must not be reached") + + monkeypatch.setattr(router_mod, "get_router", no_router) + result = await handlers.recover_runs_on_boot( + SimpleNamespace(), sleep=sleep, load_config=lambda: _config(backend, switch) + ) + assert result == [] and slept == [] + + +async def test_the_gateway_waits_out_kas_abandonment_then_reconnects(monkeypatch): + from kiro_crew.dashboard.handlers import kas_workflows as handlers + + slept: list[float] = [] + + async def sleep(secs: float) -> None: + slept.append(secs) + + seen: dict[str, Any] = {} + + class _Router: + async def recover_on_boot(self, chat_exists, reconnect, *, folders): + seen["exists"] = chat_exists("chat-1"), chat_exists("chat-x") + seen["folders"] = list(folders) + seen["sent"] = await reconnect("chat-1"), await reconnect("chat-x") + return [("w1", "chat-1", "reattached")] + + def prepare_reconnect(self, slot_key): + return f"Reconnect workflow runs (reconnect {'0' * 32})" + + started: list[str] = [] + slot = SimpleNamespace(key="chat-1", project="/work/app", running=False, task=None) + slot.enqueue_or_run_prompt = lambda message, *_a, **_k: started.append(message) or True + no_project = SimpleNamespace(key="chat-2", project="", running=False, task=None) + state = SimpleNamespace( + get_slot=lambda k: slot if k == "chat-1" else None, + push_slots_update=lambda: None, + _slots={"chat-1": slot, "chat-2": no_project}, + ) + monkeypatch.setattr(router_mod, "get_router", lambda: _Router()) + result = await handlers.recover_runs_on_boot( + state, sleep=sleep, load_config=lambda: _config("kas", True) + ) + assert result == [("w1", "chat-1", "reattached")] + assert slept == [router_mod.OWNER_ABANDON_SECS + router_mod.BOOT_RECOVERY_SLACK_SECS] + assert router_mod.OWNER_ABANDON_SECS == 135.0 # KAS STALE_AFTER_MS, 4.5 x 30s beats + # The open chats' folders go to the router, a chat with no project left out. + assert seen == {"exists": (True, False), "folders": ["/work/app"], "sent": (True, False)} + assert len(started) == 1 and router_mod.KasWorkflowRouter.reconnect_token(started[0]) + + +async def test_a_busy_chat_is_left_to_its_own_turn(monkeypatch): + from kiro_crew.dashboard.handlers import kas_workflows as handlers + + class _Router: + async def recover_on_boot(self, chat_exists, reconnect, *, folders): + return [("w1", "chat-1", str(await reconnect("chat-1")))] + + async def sleep(_secs: float) -> None: + return None + + slot = SimpleNamespace(key="chat-1", project="/work/app", running=True) + slot.enqueue_or_run_prompt = lambda *_a, **_k: pytest.fail("a busy chat gets no extra turn") + state = SimpleNamespace(get_slot=lambda _k: slot, push_slots_update=lambda: None) + monkeypatch.setattr(router_mod, "get_router", lambda: _Router()) + result = await handlers.recover_runs_on_boot( + state, sleep=sleep, load_config=lambda: _config("kas", True) + ) + assert result == [("w1", "chat-1", "False")] + + +async def test_a_turn_started_while_a_cold_chat_reads_its_window_is_left_to_itself(monkeypatch): + from kiro_crew.dashboard.handlers import kas_workflows as handlers + + # Given: a chat restored at gateway start, in which the person starts a turn + # while the boot pass reads its transcript window + class _Router: + async def recover_on_boot(self, chat_exists, reconnect, *, folders): + return [("w1", "chat-1", str(await reconnect("chat-1")))] + + async def sleep(_secs: float) -> None: + return None + + slot = SimpleNamespace(key="chat-1", project="/work/app", running=False, window_pending=True) + + def read(_slot): + slot.running = True + return () + + slot._lazy_window = SimpleNamespace(read=read) + slot.load_window = lambda *_p: setattr(slot, "window_pending", False) + slot.enqueue_or_run_prompt = lambda *_a, **_k: pytest.fail("a busy chat gets no extra turn") + state = SimpleNamespace(get_slot=lambda _k: slot, push_slots_update=lambda: None) + monkeypatch.setattr(router_mod, "get_router", lambda: _Router()) + + # When: the boot pass reaches the chat + result = await handlers.recover_runs_on_boot( + state, sleep=sleep, load_config=lambda: _config("kas", True) + ) + + # Then: the window was loaded, the busy check saw the turn and sent nothing + assert result == [("w1", "chat-1", "False")] and slot.window_pending is False + + +async def test_boot_recovery_starts_once_per_process_and_stops_at_shutdown(monkeypatch): + from kiro_crew.dashboard.handlers import kas_workflows as handlers + + # Given: a boot pass that waits until it is stopped + started: list[object] = [] + began, release = asyncio.Event(), asyncio.Event() + + async def recover(state): + started.append(state) + began.set() + await release.wait() + + monkeypatch.setattr(handlers, "recover_runs_on_boot", recover) + state = SimpleNamespace(_background_tasks=set()) + + # When: the gateway starts it twice, then shuts down + handlers.start_kas_boot_recovery(state) + handlers.start_kas_boot_recovery(state) + (task,) = list(state._background_tasks) + await await_until(began) + handlers.cancel_kas_boot_recovery() + await await_until(asyncio.gather(task, return_exceptions=True)) + + # Then: one pass ran, tracked with the state's tasks, and the shutdown cancelled it + assert started == [state] + assert task.cancelled() + assert state._background_tasks == set() + + +async def test_a_failed_boot_recovery_ends_its_task_without_raising(monkeypatch): + from kiro_crew.dashboard.handlers import kas_workflows as handlers + + # Given: a boot pass that fails + async def recover(_state): + raise RuntimeError("Kiro Agent did not answer") + + monkeypatch.setattr(handlers, "recover_runs_on_boot", recover) + state = SimpleNamespace(_background_tasks=set()) + + # When: the gateway starts it + handlers.start_kas_boot_recovery(state) + (task,) = list(state._background_tasks) + await await_until(asyncio.gather(task, return_exceptions=True)) + + # Then: the task ended without raising, so the failure stops nothing else at startup + assert task.done() and not task.cancelled() and task.exception() is None diff --git a/test/test_kas_workflows_chat_session.py b/test/test_kas_workflows_chat_session.py new file mode 100644 index 000000000000..6aec025c9561 --- /dev/null +++ b/test/test_kas_workflows_chat_session.py @@ -0,0 +1,272 @@ +"""KAS's own workflow surface in dashboard chats (``agent.kas_workflows``). + +Covers the three places the setting reaches: the ``_meta`` a KAS session start +carries, which chats Crew's own workflow tool then redirects, and the gateway +config that turns it on. +""" + +from __future__ import annotations + +import asyncio +from unittest.mock import AsyncMock, MagicMock + +import pytest +from aiohttp.test_utils import make_mocked_request + +from kiro_crew.acp.harness import SessionExtras +from kiro_crew.acp.runtime import AcpRuntime +from kiro_crew.acp.types import ACP_BACKEND_KAS, METHOD_SESSION_LOAD +from kiro_crew.agent_sdk.tool_search import with_client_meta_settings +from kiro_crew.kas_workflows import chat +from kiro_crew.testing.ids import UNALLOCATABLE_PID + + +@pytest.fixture(autouse=True) +def _clean_enabled_chats(_floor_monkeypatch): + _floor_monkeypatch.setattr(chat, "_ENABLED_CHATS", {}) + + +@pytest.fixture(autouse=True) +def _clean_workflow_sessions(_floor_monkeypatch): + """No KAS session starts out recorded as last driven with workflows on.""" + _floor_monkeypatch.setattr(chat, "_WORKFLOW_SESSIONS", {}) + + +@pytest.fixture(autouse=True) +def _fast_runtime_start(_floor_monkeypatch): + """The same two pins test_acp_runtime applies to a faked session start.""" + import kiro_crew.acp.session_handle as sh + from kiro_crew.kiro_cli import SPEC_PERMISSIONS_MIN_VERSION + + _floor_monkeypatch.setattr(sh, "_MCP_DRAIN_NO_REPORT_CEILING", 0.05, raising=False) + _floor_monkeypatch.setattr( + "kiro_crew.kiro_cli.installed_kiro_cli_version", lambda: SPEC_PERMISSIONS_MIN_VERSION + ) + + +def _kas_runtime(monkeypatch, *, sink: bool = True): + rt = AcpRuntime(work_dir="/tmp") + proc = MagicMock() + proc.stdout = asyncio.StreamReader() + proc.stdin = MagicMock() + proc.stdin.drain = AsyncMock() + proc.returncode = None + proc.pid = UNALLOCATABLE_PID + rt._process = proc + rt._pid = UNALLOCATABLE_PID + rt._initialized = True + rt._can_load_session = True + rt._acp_backend = ACP_BACKEND_KAS + rt._workflow_sink = MagicMock() if sink else None + sent: list[tuple[str, dict]] = [] + + async def _fake_send(method, params, timeout=None): + sent.append((method, params)) + if method == METHOD_SESSION_LOAD: + return {"modes": {"currentModeId": "kirocrew"}, "models": []} + return {} + + async def _fake_agents( + agent, *, member_dispatch=False, crew_panel=False, session_key="", session_cwd=None + ): + return SessionExtras(custom_agents=[{"id": agent, "prompt": "p", "tools": []}]) + + monkeypatch.setattr(rt, "_send_and_await", _fake_send) + monkeypatch.setattr(rt, "_kas_custom_agents", _fake_agents) + return rt, sent + + +def _workflows_meta(params: dict): + return params.get("_meta", {}).get("kiro", {}).get("settings", {}).get("workflows") + + +# ── The session-start envelope ── + + +@pytest.mark.asyncio +async def test_an_opted_in_chat_resumes_with_workflows_on_beside_its_agents(monkeypatch): + monkeypatch.setattr(chat, "chat_workflows_enabled", lambda: True) + rt, sent = _kas_runtime(monkeypatch) + await rt.load_session("", "sid-1", cwd="/work", agent="kirocrew", session_key="chat-abc") + params = sent[0][1] + assert _workflows_meta(params) == {"enabled": True} + # The agent batch shares _meta.kiro and must survive the merge, and its + # allowlist must name KAS's workflow tools: it filters native tools too. + assert params["_meta"]["kiro"]["customAgents"] == [ + {"id": "kirocrew", "prompt": "p", "tools": list(chat.WORKFLOW_CHAT_TOOLS)} + ] + assert chat.has_kas_workflows("chat-abc") + assert chat.has_kas_workflows("dashboard:chat-abc") + + +@pytest.mark.asyncio +async def test_the_setting_off_sends_enabled_false_and_forgets_the_chat(monkeypatch): + chat._ENABLED_CHATS["chat-abc"] = None + # Crew last loaded this session with the surface on. + chat.note_workflow_session("sid-1", on=True) + monkeypatch.setattr(chat, "chat_workflows_enabled", lambda: False) + rt, sent = _kas_runtime(monkeypatch) + await rt.load_session("", "sid-1", cwd="/work", agent="kirocrew", session_key="chat-abc") + # Gap 5b: the switch-off state is sent EXPLICITLY. Without it KAS falls back + # to the persisted value, and a chat that ran with the surface on would keep + # its /workflow-* commands and steering across a reload. The agent batch + # still names no workflow tools. + assert _workflows_meta(sent[0][1]) == {"enabled": False} + assert sent[0][1]["_meta"]["kiro"]["customAgents"][0]["tools"] == [] + assert not chat.has_kas_workflows("chat-abc") + + +def test_workflow_tools_join_only_the_active_agents_list_without_mutating_it(): + mine = {"id": "kirocrew", "tools": ["fs_read", "run_workflow"]} + other = {"id": "helper", "tools": ["fs_read"]} + star = {"id": "wild", "tools": "*"} + out = chat.with_workflow_tools([mine, other, star], "kirocrew") + assert out is not None + assert out[0]["tools"] == [ + "fs_read", + "run_workflow", + "inspect_workflow", + "update_workflow", + "save_workflow_definition", + "validate_workflow", + "send_message", + ] + assert mine["tools"] == ["fs_read", "run_workflow"], "the caller's batch is not mutated" + assert out[1] is other and out[2] is star + assert chat.with_workflow_tools([star], "wild")[0]["tools"] == "*" + assert chat.with_workflow_tools(None, "kirocrew") is None + + +@pytest.mark.parametrize("session_key", ["subagent:abc", "cron:daily", "taskrunner_1", ""]) +@pytest.mark.asyncio +async def test_only_a_dashboard_chat_gets_the_surface(monkeypatch, session_key): + monkeypatch.setattr(chat, "chat_workflows_enabled", lambda: True) + rt, sent = _kas_runtime(monkeypatch) + await rt.load_session("", "sid-1", cwd="/work", agent="kirocrew", session_key=session_key) + assert _workflows_meta(sent[0][1]) is None + assert not chat.has_kas_workflows(session_key) + + +@pytest.mark.asyncio +async def test_a_runtime_with_no_sink_never_turns_it_on(monkeypatch): + monkeypatch.setattr(chat, "chat_workflows_enabled", lambda: True) + rt, sent = _kas_runtime(monkeypatch, sink=False) + await rt.load_session("", "sid-1", cwd="/work", agent="kirocrew", session_key="chat-abc") + assert _workflows_meta(sent[0][1]) is None + + +def test_the_workflow_setting_merges_into_an_existing_kiro_envelope(): + params = {"_meta": {"kiro": {"customAgents": [1], "settings": {"other": 2}}, "x": 3}} + merged = with_client_meta_settings(params, chat.workflow_settings(True)) + assert merged == { + "_meta": { + "kiro": {"customAgents": [1], "settings": {"other": 2, "workflows": {"enabled": True}}}, + "x": 3, + } + } + + +def test_enabled_chats_stay_bounded(monkeypatch): + monkeypatch.setattr(chat, "chat_workflows_enabled", lambda: True) + monkeypatch.setattr(chat, "_MAX_ENABLED_CHATS", 2) + for n in range(3): + asyncio.run(chat.wants_workflows(f"chat-{n}")) + assert list(chat._ENABLED_CHATS) == ["chat-1", "chat-2"] + + +# ── Crew's own workflow tool in such a chat ── + + +def _request(session_key: str): + headers = {"X-Session-Key": session_key} if session_key else {} + return make_mocked_request("POST", "/api/workflows/run_intent", headers=headers) + + +def test_crew_authoring_is_redirected_only_in_a_chat_with_the_surface(): + from kiro_crew.dashboard.handlers.workflows import _kas_chat_redirect + + chat._ENABLED_CHATS["chat-abc"] = None + refused = _kas_chat_redirect(_request("chat-abc")) + assert refused is not None and refused.status == 409 + assert b"run_workflow" in refused.body and b"kas_workflows_in_chat" in refused.body + # The MCP stub names the chat with the dashboard: prefix; same chat. + assert _kas_chat_redirect(_request("dashboard:chat-abc")) is not None + assert _kas_chat_redirect(_request("chat-other")) is None + assert _kas_chat_redirect(_request("")) is None + + +# ── The config that turns it on ── + + +def test_the_setting_is_off_by_default_and_patchable(tmp_path, monkeypatch): + from kiro_crew.config import KiroCrewConfig + from kiro_crew.dashboard.handlers.core import _editable_config_spec + + assert KiroCrewConfig().agent.kas_workflows is False + assert _editable_config_spec("agent.kas_workflows") == {"type": "bool"} + + +# ── The chat's approval mode, as a workflow step reads it ── + + +class _Slot: + def __init__(self, *, trust=False, trust_reads=False, scope=""): + self._trust = trust + self._trust_reads = trust_reads + self._trust_scope = scope + + +class _State: + def __init__(self, yolo=False, reaches=True): + self.yolo = yolo + self.reaches = reaches + + def is_yolo_active(self): + return self.yolo + + def yolo_reaches(self, slot): + return self.reaches + + +@pytest.mark.parametrize( + ("state", "slot", "expected"), + [ + (_State(), _Slot(), ("normal", "")), + (_State(), _Slot(trust_reads=True), ("trust_reads", "trust_reads")), + (_State(), _Slot(trust=True, trust_reads=True), ("trust", "trust")), + (_State(yolo=True), _Slot(), ("trust", "yolo")), + # The ``--approval yolo`` grant on a channel-linked chat: it does not reach the step. + (_State(yolo=True, reaches=False), _Slot(), ("normal", "")), + ], +) +def test_step_mode_reader_uses_the_chats_own_precedence(state, slot, expected): + from kiro_crew.dashboard.chat_runner import _kas_step_mode_reader + + assert _kas_step_mode_reader(state, slot)() == expected + + +def test_step_mode_reader_reads_live_not_at_capture(): + from kiro_crew.dashboard.chat_runner import _kas_step_mode_reader + + slot = _Slot() + read = _kas_step_mode_reader(_State(), slot) + assert read()[0] == "normal" + slot._trust = True + assert read()[0] == "trust" + + +# ── who waits for a person: a plan handoff only ── + + +def test_a_plan_handoff_needs_a_person(): + plan = MagicMock(harness_tool_id="update_workflow", kas_builtin_ids=True) + assert chat.needs_a_person(plan) is True + + +def test_any_other_kas_request_does_not(): + # The chat model's own questions are ``_kiro/userInput`` requests on the + # elicitation path, never a permission request held here. + for tool_id in ("", "run_workflow", "fs_write"): + assert ( + chat.needs_a_person(MagicMock(harness_tool_id=tool_id, kas_builtin_ids=True)) is False + ) diff --git a/test/test_kas_workflows_l4_recipes.py b/test/test_kas_workflows_l4_recipes.py new file mode 100644 index 000000000000..dc3d1969b58e --- /dev/null +++ b/test/test_kas_workflows_l4_recipes.py @@ -0,0 +1,305 @@ +"""Recipe routes: ``/state`` recipesRevision, recipe detail, create, delete. + +Covers the recipe list following ``recipes_changed``, creating and deleting +recipes, and the recipe detail route. The owner / +engine gate is the shared ``_refusal`` (stubbed here, pinned by the routes that +already use it); the last test proves the new routes still refuse when the +switch is off, because their operations are not in the read-only-when-held set. +""" + +from __future__ import annotations + +import asyncio +import json +import os +from types import SimpleNamespace + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer +from kas_workflow_helpers import FakeRuntime, make_router + +import kiro_crew.dashboard.handlers.kas_workflows as kas_handlers +from kiro_crew.dashboard import server +from kiro_crew.kas_workflows import router as router_mod +from kiro_crew.kas_workflows import wire +from kiro_crew.testing.links import make_dir_link + +pytestmark = pytest.mark.asyncio + + +@pytest.fixture(autouse=True) +def _tmp_path_is_a_recent_project(_floor_monkeypatch, tmp_path): + """These tests use tmp_path as the project, which sits outside the home root. + + Listing it as a recent project keeps the real project-root confinement in + the path under test instead of switching it off. + """ + _floor_monkeypatch.setattr( + "kiro_crew.kas_workflows.project_root.recent_project_dirs", lambda: [str(tmp_path)] + ) + + +@pytest.fixture +def kas(monkeypatch): + router = make_router(audit=lambda **_k: None) + reader = FakeRuntime() + # _reader() returns the first live runtime in _runtimes, so recipe listings + # (recipes / recipe_detail / delete) read this one's answers. + router.sink_for(reader) + + refusals: list[str] = [] + + async def no_refusal(_request, operation): + refusals.append(operation) + return None + + audits: list[tuple[str, str]] = [] + monkeypatch.setattr(router_mod, "_ROUTER", router) + monkeypatch.setattr(kas_handlers, "_refusal", no_refusal) + monkeypatch.setattr( + kas_handlers, "_audit_authorization", lambda _r, op, outcome: audits.append((op, outcome)) + ) + return SimpleNamespace(router=router, reader=reader, refusals=refusals, audits=audits) + + +def _app() -> web.Application: + app = web.Application() + app["state"] = SimpleNamespace(get_slot=lambda _k: None) + server._register_mcp_routes(app) + return app + + +# ── Gap 16F: the recipe list's poll key ── + + +async def test_state_carries_the_recipes_revision(kas): + kas.router.recipes_revision = 4 + async with TestClient(TestServer(_app())) as client: + state = await (await client.get("/api/workflows/kas/state")).json() + assert state["recipesRevision"] == 4 + assert "workflow.kas.state" in kas.refusals + + +# ── Gap 27F: recipe detail route ── + + +async def test_recipe_detail_route_returns_steps_for_a_listed_file(kas, tmp_path): + recipe_file = tmp_path / ".kiro" / "workflows" / "r.workflow.json" + recipe_file.parent.mkdir(parents=True) + recipe_file.write_text( + json.dumps( + { + "name": "r", + "steps": [ + {"type": "step", "id": "plan", "agent": "wf-planner", "prompt": "Plan it."} + ], + } + ) + ) + kas.reader.answers[wire.METHOD_LIST_RECIPES] = { + "recipes": [{"name": "r", "source": str(recipe_file)}] + } + async with TestClient(TestServer(_app())) as client: + missing = await client.get( + "/api/workflows/kas/recipes/detail", params={"cwd": str(tmp_path)} + ) + assert missing.status == 400, "source is required" + resp = await client.get( + "/api/workflows/kas/recipes/detail", + params={"cwd": str(tmp_path), "source": str(recipe_file)}, + ) + assert resp.status == 200, await resp.text() + body = await resp.json() + assert body["definitionAvailable"] is True + assert [(s["nodeId"], s["prompt"]) for s in body["steps"]] == [("plan", "Plan it.")] + assert body["recipe"]["group"] == "workspace" + assert "workflow.kas.recipe_detail" in kas.refusals + + +# ── Gap 18: create a recipe file (create-exclusive, path-confined) ── + + +async def test_create_route_writes_a_scaffold_once(kas, tmp_path): + async with TestClient(TestServer(_app())) as client: + assert ( + await client.post( + "/api/workflows/kas/recipes", + json={"cwd": str(tmp_path), "name": "ok", "scope": "x"}, + ) + ).status == 400, "bad scope" + assert ( + await client.post( + "/api/workflows/kas/recipes", + json={"cwd": str(tmp_path), "name": "../evil", "scope": "workspace"}, + ) + ).status == 400, "a name that is not a safe basename" + resp = await client.post( + "/api/workflows/kas/recipes", + json={"cwd": str(tmp_path), "name": "my-wf", "scope": "workspace"}, + ) + assert resp.status == 201, await resp.text() + source = (await resp.json())["source"] + again = await client.post( + "/api/workflows/kas/recipes", + json={"cwd": str(tmp_path), "name": "my-wf", "scope": "workspace"}, + ) + assert again.status == 409, "create is exclusive" + assert source == os.path.join( + os.path.realpath(str(tmp_path)), ".kiro", "workflows", "my-wf.workflow.json" + ) + written = json.loads(open(source, encoding="utf-8").read()) + assert written["name"] == "my-wf" and written["steps"], "a valid launchable scaffold" + assert ("workflow.kas.recipe_create", "allowed:my-wf") in kas.audits + + +async def test_create_refuses_a_symlinked_kiro_that_escapes_the_project(kas, tmp_path): + # `.kiro` is a symlink out of the project, so /.kiro/workflows resolves + # outside it. The write must be refused before any directory is created. + outside = tmp_path / "outside" + outside.mkdir() + project = tmp_path / "proj" + project.mkdir() + make_dir_link(project / ".kiro", outside) + async with TestClient(TestServer(_app())) as client: + resp = await client.post( + "/api/workflows/kas/recipes", + json={"cwd": str(project), "name": "x", "scope": "workspace"}, + ) + assert resp.status == 400, await resp.text() + assert (await resp.json())["code"] == "recipe_path_escape" + assert not (outside / "workflows").exists(), "nothing was written outside the project" + + +# ── Gap 18: delete only a listed, non-built-in recipe file ── + + +async def test_delete_route_removes_only_a_listed_editable_file(kas, tmp_path): + recipe_file = tmp_path / ".kiro" / "workflows" / "r.workflow.json" + recipe_file.parent.mkdir(parents=True) + recipe_file.write_text("{}") + kas.reader.answers[wire.METHOD_LIST_RECIPES] = { + "recipes": [{"name": "r", "source": str(recipe_file)}, {"name": "g", "builtIn": True}] + } + async with TestClient(TestServer(_app())) as client: + unknown = await client.delete( + "/api/workflows/kas/recipes", + params={"cwd": str(tmp_path), "source": str(tmp_path / "nope.workflow.json")}, + ) + assert unknown.status == 404, "a source KAS does not list cannot be deleted" + read_only = await client.delete( + "/api/workflows/kas/recipes", params={"cwd": str(tmp_path), "source": "bundled://g"} + ) + assert read_only.status == 409, "a built-in has no file to delete" + assert recipe_file.exists() + ok = await client.delete( + "/api/workflows/kas/recipes", params={"cwd": str(tmp_path), "source": str(recipe_file)} + ) + assert ok.status == 200, await ok.text() + assert not recipe_file.exists() + assert ("workflow.kas.recipe_delete", "allowed") in kas.audits + + +async def test_delete_refuses_a_listed_file_behind_a_symlinked_kiro(kas, tmp_path): + # KAS lists what it finds under /.kiro/workflows with symlinks + # followed, so a project whose `.kiro` points outside it makes KAS list an + # outside file. The delete must confine the file's REAL directory exactly as + # create confines its write, and leave the outside file alone. + outside = tmp_path / "outside" + (outside / "workflows").mkdir(parents=True) + victim = outside / "workflows" / "r.workflow.json" + victim.write_text("{}") + project = tmp_path / "proj" + project.mkdir() + make_dir_link(project / ".kiro", outside) + listed = project / ".kiro" / "workflows" / "r.workflow.json" + kas.reader.answers[wire.METHOD_LIST_RECIPES] = { + "recipes": [{"name": "r", "source": str(listed)}] + } + async with TestClient(TestServer(_app())) as client: + resp = await client.delete( + "/api/workflows/kas/recipes", params={"cwd": str(project), "source": str(listed)} + ) + assert resp.status == 400, await resp.text() + assert (await resp.json())["code"] == "recipe_path_escape" + assert victim.exists(), "nothing outside the project was removed" + assert ("workflow.kas.recipe_delete", "allowed") not in kas.audits + + +# ── Path checks run off the event loop ── + + +def _on_a_running_loop() -> bool: + try: + asyncio.get_running_loop() + except RuntimeError: + return False + return True + + +async def test_every_route_that_names_a_project_checks_its_paths_off_the_event_loop( + kas, tmp_path, monkeypatch +): + # Given: a project with one listed recipe file, and path checks that note where they run + recipe_file = tmp_path / ".kiro" / "workflows" / "r.workflow.json" + recipe_file.parent.mkdir(parents=True) + recipe_file.write_text(json.dumps({"name": "r", "steps": []})) + kas.reader.answers[wire.METHOD_LIST_RECIPES] = { + "recipes": [{"name": "r", "source": str(recipe_file)}] + } + seen: list[tuple[str, bool]] = [] + project_dir, global_root = kas_handlers._project_dir, kas_handlers._global_workflows_root + + def noted_project_dir(*args, **kwargs): + seen.append(("project", _on_a_running_loop())) + return project_dir(*args, **kwargs) + + def noted_global_root(): + seen.append(("global root", _on_a_running_loop())) + return global_root() + + monkeypatch.setattr(kas_handlers, "_project_dir", noted_project_dir) + monkeypatch.setattr(kas_handlers, "_global_workflows_root", noted_global_root) + cwd = {"cwd": str(tmp_path)} + + # When: each route that names a project or a recipe directory is called + async with TestClient(TestServer(_app())) as client: + statuses = [ + (await client.get("/api/workflows/kas/recipes", params=cwd)).status, + (await client.get("/api/workflows/kas/runs", params=cwd)).status, + ( + await client.get( + "/api/workflows/kas/recipes/detail", params={**cwd, "source": str(recipe_file)} + ) + ).status, + ( + await client.post( + "/api/workflows/kas/recipes", json={**cwd, "name": "new", "scope": "workspace"} + ) + ).status, + ( + await client.delete( + "/api/workflows/kas/recipes", params={**cwd, "source": str(recipe_file)} + ) + ).status, + ] + + # Then: each answered, and every check ran on a worker thread + assert statuses == [200, 200, 200, 201, 200] + assert [what for what, _on_loop in seen].count("project") == 5 + assert ("global root", False) in seen + assert not any(on_loop for _what, on_loop in seen) + + +# ── Gap 5 inheritance: the new routes refuse while the switch is off ── + + +async def test_the_new_recipe_routes_refuse_when_the_switch_is_off(): + # A read-only-when-held op stays open when off; a recipe op must not, so it + # is never added to that set. This is what makes the new routes 409 off-KAS. + for op in ( + "workflow.kas.recipe_create", + "workflow.kas.recipe_delete", + "workflow.kas.recipe_detail", + ): + assert op not in kas_handlers._READ_ONLY_WHEN_HELD diff --git a/test/test_kas_workflows_optin_gate.py b/test/test_kas_workflows_optin_gate.py new file mode 100644 index 000000000000..834d1864c39e --- /dev/null +++ b/test/test_kas_workflows_optin_gate.py @@ -0,0 +1,259 @@ +"""The single ``agent.kas_workflows`` opt-in gate. + +One gateway setting replaced the per-device preview flag and the separate +chat-workflows toggle. Every KAS surface now asks one question -- +:func:`kiro_crew.kas_workflows.engine.kas_workflows_enabled` -- which is true +only when the backend is Kiro Agent AND the operator opted in. These tests pin +that gate across the (backend x switch) matrix at each place it is read: the +engine endpoint, the route refusal, boot recovery and the chat surface. +""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest +from aiohttp.test_utils import make_mocked_request + +from kiro_crew.kas_workflows.engine import ( + ENGINE_CREW, + ENGINE_KAS, + backend_brings_kas_workflows, + engine_for, + kas_workflows_enabled, +) + +# `kas` is a native-workflows backend; `""` is not. (engine_for pins this.) +KAS = "kas" +NON_KAS = "" + + +def _cfg(backend: str, switch: bool): + return SimpleNamespace(agent=SimpleNamespace(acp_backend=backend, kas_workflows=switch)) + + +# ── The gate itself: both halves must hold ── + + +@pytest.mark.parametrize( + ("backend", "switch", "expected"), + [(KAS, True, True), (KAS, False, False), (NON_KAS, True, False), (NON_KAS, False, False)], +) +def test_gate_requires_kas_backend_and_the_switch(backend, switch, expected): + assert engine_for(KAS) == ENGINE_KAS # the fixture names the Kiro Agent engine + assert kas_workflows_enabled(_cfg(backend, switch)) is expected + + +def test_backend_capability_is_independent_of_the_switch(): + assert backend_brings_kas_workflows(KAS) is True + assert backend_brings_kas_workflows(NON_KAS) is False + + +def test_a_configless_object_is_off(): + assert kas_workflows_enabled(SimpleNamespace()) is False + + +# ── /api/workflows/engine answers for each (backend x switch) pair ── + + +async def _engine_answer(backend, switch, monkeypatch): + from kiro_crew.dashboard.handlers import workflows as wf + + monkeypatch.setattr( + "kiro_crew.config.KiroCrewConfig.load", staticmethod(lambda: _cfg(backend, switch)) + ) + resp = await wf.api_workflow_engine(make_mocked_request("GET", "/api/workflows/engine")) + return json.loads(resp.text) + + +@pytest.mark.parametrize( + ("backend", "switch", "engine"), + [ + (KAS, True, ENGINE_KAS), + (KAS, False, ENGINE_CREW), + (NON_KAS, True, ENGINE_CREW), + (NON_KAS, False, ENGINE_CREW), + ], +) +@pytest.mark.asyncio +async def test_engine_endpoint_reports_kas_only_when_enabled(backend, switch, engine, monkeypatch): + body = await _engine_answer(backend, switch, monkeypatch) + assert body["engine"] == engine + # Raw backend and the two explainer fields ride along for the settings UI. + assert body["backend"] == backend + assert body["kas_backend"] is (backend == KAS) + assert body["kas_workflows"] is switch + + +# ── The KAS routes refuse unless the gate is open ── + + +async def _refusal_response(backend, switch, monkeypatch): + from kiro_crew.dashboard.handlers import kas_workflows as handlers + + monkeypatch.setattr( + "kiro_crew.config.KiroCrewConfig.load", staticmethod(lambda: _cfg(backend, switch)) + ) + + async def _owner_ok(_request, _operation): + return None + + monkeypatch.setattr( + "kiro_crew.dashboard.handlers._shared.require_owner_dashboard_request", _owner_ok + ) + return await handlers._refusal(make_mocked_request("GET", "/api/workflows/kas/state"), "op") + + +@pytest.mark.asyncio +async def test_routes_answer_only_when_enabled(monkeypatch): + # Open gate -> no refusal. + assert await _refusal_response(KAS, True, monkeypatch) is None + + +@pytest.mark.parametrize(("backend", "switch"), [(KAS, False), (NON_KAS, True), (NON_KAS, False)]) +@pytest.mark.asyncio +async def test_routes_refuse_engine_not_kas_when_off(backend, switch, monkeypatch): + resp = await _refusal_response(backend, switch, monkeypatch) + assert resp is not None and resp.status == 409 + assert b"engine_not_kas" in resp.body + + +# ── Boot recovery and the chat surface read the same gate ── + + +def test_boot_recovery_follows_the_gate(): + from kiro_crew.dashboard.handlers.kas_workflows import boot_recovery_enabled + + assert boot_recovery_enabled(_cfg(KAS, True)) is True + assert boot_recovery_enabled(_cfg(KAS, False)) is False + assert boot_recovery_enabled(_cfg(NON_KAS, True)) is False + + +def test_chat_surface_follows_the_gate(monkeypatch): + from kiro_crew.kas_workflows import chat + from kiro_crew.kas_workflows import router as router_mod + + # The dashboard's turn starter is installed, so the gate alone decides. + monkeypatch.setattr(router_mod, "_TURN_STARTER", object()) + monkeypatch.setattr("kiro_crew.config.live.snapshot", lambda: _cfg(KAS, True)) + assert chat.chat_workflows_enabled() is True + monkeypatch.setattr("kiro_crew.config.live.snapshot", lambda: _cfg(KAS, False)) + assert chat.chat_workflows_enabled() is False + monkeypatch.setattr("kiro_crew.config.live.snapshot", lambda: _cfg(NON_KAS, True)) + assert chat.chat_workflows_enabled() is False + + +# ── Gap 5: switch off but the router still holds a run — reads + Stop stay open ── + + +class _FakeRouter: + def __init__(self, held: int) -> None: + self._rows = [{"workflowId": f"wf_{i:08x}"} for i in range(held)] + + def rows(self) -> list[dict]: + return self._rows + + +_READS = [ + "workflow.kas.state", + "workflow.kas.run", + "workflow.kas.slot_runs", + "workflow.kas.step_transcript", + "workflow.kas.runs", +] +# Launch and control (other than Stop) and every answer stay refused. +_REFUSED_CONTROLS = [ + "workflow.kas.start", + "workflow.kas.grant", + "workflow.kas.retry", + "workflow.kas.restart", + "workflow.kas.approve", + "workflow.kas.question", + "workflow.kas.step_reply", + "workflow.kas.step_model", + "workflow.kas.recipes", + "workflow.kas.reconnect", +] + + +async def _refusal_held(operation, *, backend, held, monkeypatch, action=None): + from kiro_crew.dashboard.handlers import kas_workflows as handlers + + monkeypatch.setattr( + "kiro_crew.config.KiroCrewConfig.load", staticmethod(lambda: _cfg(backend, False)) + ) + + async def _owner_ok(_request, _operation): + return None + + monkeypatch.setattr( + "kiro_crew.dashboard.handlers._shared.require_owner_dashboard_request", _owner_ok + ) + monkeypatch.setattr("kiro_crew.kas_workflows.router.get_router", lambda: _FakeRouter(held)) + req = make_mocked_request("POST", "/api/workflows/kas/x") + if action is not None: + req._match_info = {"action": action} # the control route's path param + return await handlers._refusal(req, operation) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", _READS) +async def test_off_but_held_allows_reads(operation, monkeypatch): + assert await _refusal_held(operation, backend=KAS, held=1, monkeypatch=monkeypatch) is None + + +@pytest.mark.asyncio +async def test_off_but_held_allows_only_stop_among_controls(monkeypatch): + assert ( + await _refusal_held( + "workflow.kas.control", backend=KAS, held=1, monkeypatch=monkeypatch, action="cancel" + ) + is None + ) + for action in ("resume", "pause", "delete"): + resp = await _refusal_held( + "workflow.kas.control", backend=KAS, held=1, monkeypatch=monkeypatch, action=action + ) + assert resp is not None and resp.status == 409 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", _REFUSED_CONTROLS) +async def test_off_but_held_refuses_launch_and_control(operation, monkeypatch): + resp = await _refusal_held(operation, backend=KAS, held=1, monkeypatch=monkeypatch) + assert resp is not None and resp.status == 409 and b"engine_not_kas" in resp.body + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", [*_READS, "workflow.kas.control"]) +async def test_off_with_no_held_runs_refuses_everything(operation, monkeypatch): + # Origin/main: with nothing held, even the reads refuse. + resp = await _refusal_held( + operation, backend=KAS, held=0, monkeypatch=monkeypatch, action="cancel" + ) + assert resp is not None and resp.status == 409 + + +@pytest.mark.asyncio +async def test_off_on_a_non_kas_backend_has_no_read_window(monkeypatch): + # Not a Kiro Agent backend: no read-only window even if a stray row is held. + resp = await _refusal_held( + "workflow.kas.state", backend=NON_KAS, held=1, monkeypatch=monkeypatch + ) + assert resp is not None and resp.status == 409 + + +# ── Gap 5b: workflow_settings sends an EXPLICIT enabled ── + + +def test_workflow_settings_sends_explicit_enabled(): + from kiro_crew.agent_sdk.tool_search import with_client_meta_settings + from kiro_crew.kas_workflows.chat import workflow_settings + + on = with_client_meta_settings({}, workflow_settings(True)) + assert on["_meta"]["kiro"]["settings"]["workflows"] == {"enabled": True} + + off = with_client_meta_settings({}, workflow_settings(False)) + # Explicit False, not absent. + assert off["_meta"]["kiro"]["settings"]["workflows"] == {"enabled": False} diff --git a/test/test_kas_workflows_parity_routes.py b/test/test_kas_workflows_parity_routes.py new file mode 100644 index 000000000000..165a7a2d9e19 --- /dev/null +++ b/test/test_kas_workflows_parity_routes.py @@ -0,0 +1,684 @@ +"""The ``/api/workflows/kas`` parity routes, through the real route table. + +Owner and engine checks are the existing ``_refusal`` (stubbed here; it is +pinned by the routes that already use it). Each test drives the route the +dashboard calls and reads the KAS verb the fake process received. +""" + +from __future__ import annotations + +import threading +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer +from chat_runner_coverage_helpers import _slot, _state +from kas_workflow_helpers import ( + LOOP_PLAN, + driven, + failed_state, + loop_state, + make_router, + name_chat_session, + parallel_state, + question_request, +) + +import kiro_crew.dashboard.handlers.kas_workflows as kas_handlers +from kiro_crew.dashboard import server +from kiro_crew.dashboard.chat_utils import _dequeue_next_message +from kiro_crew.kas_workflows import router as router_mod +from kiro_crew.kas_workflows import wire +from kiro_crew.testing.wait import FALLBACK_TIMEOUT_SECS, async_wait_until + +pytestmark = pytest.mark.asyncio + + +@pytest.fixture +def kas(monkeypatch): + router = make_router(audit=lambda **_k: None) + refusals: list[str] = [] + + async def no_refusal(_request, operation): + refusals.append(operation) + return None + + audits: list[tuple[str, str]] = [] + monkeypatch.setattr(router_mod, "_ROUTER", router) + monkeypatch.setattr(kas_handlers, "_refusal", no_refusal) + monkeypatch.setattr( + kas_handlers, "_audit_authorization", lambda _r, op, outcome: audits.append((op, outcome)) + ) + return SimpleNamespace(router=router, refusals=refusals, audits=audits) + + +def _app() -> web.Application: + app = web.Application() + app["state"] = SimpleNamespace(get_slot=lambda _k: None) + server._register_mcp_routes(app) + return app + + +async def test_the_read_routes_decide_nothing_and_send_no_turn(kas, tmp_path, monkeypatch): + monkeypatch.setattr( + "kiro_crew.kas_workflows.project_root.recent_project_dirs", lambda: [str(tmp_path)] + ) + kas.router.recheck_pending = AsyncMock(side_effect=AssertionError("decided on a read")) + + def no_reconnect(): + raise AssertionError("a read sent a reconnect") + + kas.router.due_reconnects = no_reconnect + async with TestClient(TestServer(_app())) as client: + state = await client.get("/api/workflows/kas/state") + assert state.status == 200, await state.text() + runs = await client.get("/api/workflows/kas/runs", params={"cwd": str(tmp_path)}) + assert runs.status == 200, await runs.text() + kas.router.recheck_pending.assert_not_awaited() + + +async def test_grant_route_calls_resume_with_extend_repeat(kas): + rt = driven(kas.router, loop_state(), LOOP_PLAN) + async with TestClient(TestServer(_app())) as client: + bad = await client.post( + "/api/workflows/kas/runs/w1/steps/loop/grant", json={"iterations": 0} + ) + assert bad.status == 400 + resp = await client.post( + "/api/workflows/kas/runs/w1/steps/loop/grant", json={"iterations": 3} + ) + assert resp.status == 200, await resp.text() + body = await resp.json() + assert body["workflowId"] == "w1" and body["row"]["workflowId"] == "w1" + assert rt.calls[-1][0] == wire.METHOD_RESUME + assert rt.calls[-1][1]["extendRepeat"] == {"nodeId": "loop", "additionalIterations": 3} + assert ("workflow.kas.grant", "allowed:3") in kas.audits + assert "workflow.kas.grant" in kas.refusals + + +async def test_complete_route_maps_a_kas_refusal_to_409(kas): + rt = driven(kas.router, loop_state(), LOOP_PLAN) + rt.answers[wire.METHOD_UPDATE] = {"updated": False, "message": "only completed"} + async with TestClient(TestServer(_app())) as client: + assert ( + await client.post( + "/api/workflows/kas/runs/w1/steps/loop/complete", json={"status": "x"} + ) + ).status == 400 + resp = await client.post( + "/api/workflows/kas/runs/w1/steps/loop/complete", json={"status": "failed"} + ) + assert resp.status == 409 + assert "only completed" in (await resp.json())["error"] + rt.answers[wire.METHOD_UPDATE] = {"updated": True, "message": "done"} + ok = await client.post( + "/api/workflows/kas/runs/w1/steps/loop/complete", + json={"status": "completed", "reason": "enough", "path": "loop"}, + ) + assert ok.status == 200 + assert (await ok.json())["message"] == "done" + assert rt.calls[-1][1]["statusReason"] == "enough" + + +async def test_retry_and_restart_routes_are_not_taken_by_the_action_route(kas): + rt = driven(kas.router, failed_state()) + rt.answers[wire.METHOD_RETRY] = {"retriedNodeIds": ["code"]} + async with TestClient(TestServer(_app())) as client: + resp = await client.post("/api/workflows/kas/runs/w1/retry", json={}) + assert resp.status == 200, await resp.text() + assert (await resp.json())["retriedNodeIds"] == ["code"] + bad = await client.post("/api/workflows/kas/runs/w1/retry", json={"nodeId": 3}) + assert bad.status == 400 + again = await client.post("/api/workflows/kas/runs/w1/restart", json={}) + assert again.status == 200, await again.text() + assert [m for m, _ in rt.calls][-2:] == [wire.METHOD_RETRY, wire.METHOD_INVOKE] + + +async def test_step_cancel_route_sends_session_cancel(kas): + rt = driven(kas.router, parallel_state()) + async with TestClient(TestServer(_app())) as client: + missing = await client.post("/api/workflows/kas/runs/w1/steps/nope/cancel", json={}) + assert missing.status == 404 + resp = await client.post("/api/workflows/kas/runs/w1/steps/b/cancel", json={"path": "b"}) + assert resp.status == 200, await resp.text() + assert rt.notifications == [(wire.METHOD_SESSION_CANCEL, {"sessionId": "sb"})] + + +async def test_questions_are_in_state_and_answered_by_key(kas): + rt = driven(kas.router, parallel_state()) + kas.router._step_runtime["sa"] = kas.router._run_runtime["w1"] + kas.router.sink_for(rt).on_step_request( + 5, "sa", "session/request_permission", question_request() + ) + await async_wait_until(lambda: kas.router.questions(), timeout=FALLBACK_TIMEOUT_SECS) + async with TestClient(TestServer(_app())) as client: + state = await (await client.get("/api/workflows/kas/state")).json() + (held,) = state["questions"] + assert state["approvals"] == [] + key = held["key"] + assert ( + await client.post(f"/api/workflows/kas/questions/{key}", json={"answers": {}}) + ).status == 400 + wrong = await client.post( + f"/api/workflows/kas/questions/{key}", json={"answers": {"tc-9": "Oracle"}} + ) + assert wrong.status == 409 + resp = await client.post( + f"/api/workflows/kas/questions/{key}", json={"answers": {"tc-9": "Postgres"}} + ) + assert resp.status == 200 + assert await resp.json() == {"answered": True, "dismissed": False} + assert rt.responses == [(5, {"outcome": {"outcome": "selected", "optionId": "pg"}})] + + +async def test_a_question_can_be_dismissed(kas): + rt = driven(kas.router, parallel_state()) + kas.router._step_runtime["sa"] = kas.router._run_runtime["w1"] + kas.router.sink_for(rt).on_step_request( + 6, "sa", "session/request_permission", question_request() + ) + await async_wait_until(lambda: kas.router.questions(), timeout=FALLBACK_TIMEOUT_SECS) + key = kas.router.questions()[0]["key"] + async with TestClient(TestServer(_app())) as client: + resp = await client.post(f"/api/workflows/kas/questions/{key}", json={"dismiss": True}) + assert await resp.json() == {"answered": False, "dismissed": True} + assert rt.responses == [(6, {"outcome": {"outcome": "cancelled"}})] + + +async def test_run_control_route_pauses_a_run_on_the_process_that_drives_it(kas): + # Given: a running run its chat's Kiro Agent process drives + rt = driven(kas.router, parallel_state()) + + # When: the dashboard pauses it with a reason + async with TestClient(TestServer(_app())) as client: + resp = await client.post("/api/workflows/kas/runs/w1/pause", json={"reason": "lunch"}) + assert resp.status == 200, await resp.text() + body = await resp.json() + + # Then: Kiro Agent got the pause for that run, and the answer carries the run's row + method, params = rt.calls[-1] + assert method == wire.METHOD_PAUSE and params["workflowId"] == "w1" + assert body["workflowId"] == "w1" and body["row"]["workflowId"] == "w1" + assert ("workflow.kas.pause", "allowed") in kas.audits + + +async def test_run_control_route_refuses_an_unknown_action_and_an_undriven_run(kas): + # Given: a run that no live Kiro Agent process drives + kas.router.mirror.apply_load({"workflowId": "w1", "state": parallel_state()}) + + # When: the dashboard asks for an action that does not exist, then pauses the run + async with TestClient(TestServer(_app())) as client: + unknown = await client.post("/api/workflows/kas/runs/w1/explode", json={}) + unknown_body = await unknown.json() + paused = await client.post("/api/workflows/kas/runs/w1/pause") + paused_body = await paused.json() + + # Then: the unknown action is a 400, and the pause a 409 saying to open the run's chat + assert unknown.status == 400 and unknown_body["code"] == "invalid_action" + assert paused.status == 409 and paused_body["code"] == "kas_workflow_error" + assert "Open the run's chat" in paused_body["error"] + assert not any(op.startswith("workflow.kas.") for op, _ in kas.audits) + + +def _park_step_a(kas, rt) -> None: + """Step ``a`` of run ``w1`` parks for the person's next message, as KAS reports it.""" + kas.router.sink_for(rt).on_notification( + wire.NOTIFY_NODE_PAUSED, + { + "workflowId": "w1", + "nodeId": "a", + "reason": "Step requested user input via send_message.", + "attention": [{"kind": "question", "nodeId": "a", "sessionId": "sa"}], + }, + ) + + +async def test_step_reply_route_sends_the_reply_as_a_prompt_on_the_steps_session(kas): + # Given: a run whose step a is parked for the person's next message + rt = driven(kas.router, parallel_state()) + _park_step_a(kas, rt) + + # When: the dashboard posts the person's reply to that step + async with TestClient(TestServer(_app())) as client: + resp = await client.post( + "/api/workflows/kas/runs/w1/steps/a/reply", json={"text": " Use the v2 schema. "} + ) + assert resp.status == 200, await resp.text() + body = await resp.json() + + # Then: the reply reached Kiro Agent as a prompt on step a's own session + assert body == {"sent": True} + assert rt.calls[-1] == ( + wire.METHOD_SESSION_PROMPT, + {"sessionId": "sa", "prompt": [{"type": "text", "text": "Use the v2 schema."}]}, + ) + assert ("workflow.kas.step_reply", "allowed") in kas.audits + + +async def test_step_reply_route_refuses_a_missing_text_an_unknown_step_and_a_busy_step(kas): + # Given: a run whose steps are both running, none waiting for a reply + rt = driven(kas.router, parallel_state()) + + # When: the dashboard posts no text, a reply to a step that never started, and a + # reply to a running step + async with TestClient(TestServer(_app())) as client: + no_text = await client.post("/api/workflows/kas/runs/w1/steps/a/reply", json={}) + no_text_body = await no_text.json() + unknown = await client.post( + "/api/workflows/kas/runs/w1/steps/nope/reply", json={"text": "hi"} + ) + unknown_body = await unknown.json() + busy = await client.post("/api/workflows/kas/runs/w1/steps/a/reply", json={"text": "hi"}) + busy_body = await busy.json() + + # Then: each is refused with its own code, and Kiro Agent got no prompt + assert no_text.status == 400 and no_text_body["code"] == "invalid_reply" + assert unknown.status == 404 and unknown_body["code"] == "step_unknown" + assert busy.status == 409 and "not waiting" in busy_body["error"] + assert not any(m == wire.METHOD_SESSION_PROMPT for m, _ in rt.calls) + + +async def test_step_transcript_route_answers_404_for_a_step_that_never_started(kas): + # Given: a running run with steps a and b + driven(kas.router, parallel_state()) + + # When: the dashboard reads the chat of a step the run does not have + async with TestClient(TestServer(_app())) as client: + resp = await client.get("/api/workflows/kas/runs/w1/steps/nope/transcript") + body = await resp.json() + + # Then: the answer is 404 step_unknown + assert resp.status == 404 and body["code"] == "step_unknown" + + +def _permission_request() -> dict: + return { + "sessionId": "sa", + "toolCall": {"title": "Run it", "rawInput": {"command": "npm test"}}, + "options": [ + {"optionId": "yes", "kind": "allow_once", "name": "Allow"}, + {"optionId": "no", "kind": "reject_once", "name": "Reject"}, + ], + } + + +async def test_approval_route_answers_a_held_step_permission_request(kas): + # Given: step a of a driven run holds a permission request for the person + rt = driven(kas.router, parallel_state()) + kas.router._step_runtime["sa"] = kas.router._run_runtime["w1"] + kas.router.sink_for(rt).on_step_request( + 12, "sa", "session/request_permission", _permission_request() + ) + await async_wait_until(lambda: kas.router.approvals(), timeout=FALLBACK_TIMEOUT_SECS) + key = kas.router.approvals()[0]["key"] + + # When: the dashboard posts no option, then the person's Allow + async with TestClient(TestServer(_app())) as client: + missing = await client.post(f"/api/workflows/kas/approvals/{key}", json={}) + missing_body = await missing.json() + resp = await client.post(f"/api/workflows/kas/approvals/{key}", json={"optionId": "yes"}) + assert resp.status == 200, await resp.text() + body = await resp.json() + + # Then: the empty answer is a 400, and Kiro Agent got the Allow for that request + assert missing.status == 400 and missing_body["code"] == "invalid_option" + assert body == {"answered": True} + assert rt.responses == [(12, {"outcome": {"outcome": "selected", "optionId": "yes"}})] + assert ("workflow.kas.approve", "answered:yes") in kas.audits + + +async def test_approval_route_answers_409_for_a_request_no_longer_held(kas): + # Given: no permission request is held + + # When: the dashboard answers a key the router does not hold + async with TestClient(TestServer(_app())) as client: + resp = await client.post("/api/workflows/kas/approvals/gone", json={"optionId": "yes"}) + body = await resp.json() + + # Then: the answer is a 409 and nothing is audited as answered + assert resp.status == 409 and body["code"] == "kas_workflow_error" + assert ("workflow.kas.approve", "answered:yes") not in kas.audits + + +async def test_slot_runs_route_answers_a_chats_runs_with_what_the_router_holds(kas): + # Given: run w1 belongs to chat-1's Kiro Agent session + driven(kas.router, parallel_state()) + name_chat_session(kas.router, "chat-1", "acp-parent") + + # When: the dashboard reads chat-1's runs + async with TestClient(TestServer(_app())) as client: + resp = await client.get("/api/workflows/kas/slots/chat-1/runs") + assert resp.status == 200, await resp.text() + body = await resp.json() + + # Then: the answer lists w1 with the held approvals, questions and the revision + assert [run["workflowId"] for run in body["runs"]] == ["w1"] + assert body["approvals"] == [] and body["questions"] == [] + assert body["revision"] == kas.router.revision + assert "workflow.kas.slot_runs" in kas.refusals + + +async def test_slot_runs_route_maps_a_failed_listing_to_409(kas, monkeypatch): + # Given: Kiro Agent refuses to list a chat's runs + async def refused(_slot_key): + raise router_mod.KasWorkflowError("Kiro Agent could not list the runs.") + + monkeypatch.setattr(kas.router, "chat_runs", refused) + + # When: the dashboard reads the chat's runs + async with TestClient(TestServer(_app())) as client: + resp = await client.get("/api/workflows/kas/slots/chat-1/runs") + body = await resp.json() + + # Then: the refusal is a 409 carrying Kiro Agent's reason + assert resp.status == 409 and body["error"] == "Kiro Agent could not list the runs." + + +async def test_slot_reconnect_route_sends_an_open_chat_its_reconnect_turn(kas, tmp_path): + # Given: an idle open chat whose automatic reconnects ran out + sent: list[str] = [] + slot = SimpleNamespace(key="chat-1", project=str(tmp_path)) + slot.enqueue_or_run_prompt = lambda message, *_a, **_k: sent.append(message) or True + kas.router._reconnect_tries["chat-1"] = 99 + + # When: the dashboard asks to reconnect that chat, and then a chat that is not open + async with TestClient(TestServer(_app_with({"chat-1": slot}))) as client: + resp = await client.post("/api/workflows/kas/slots/chat-1/reconnect") + body = await resp.json() + closed = await client.post("/api/workflows/kas/slots/gone/reconnect") + closed_body = await closed.json() + + # Then: the open chat got one reconnect turn and its tries start over; the closed one is a 400 + assert resp.status == 202 and body == {"slot": "chat-1"} + assert len(sent) == 1 and router_mod.KasWorkflowRouter.reconnect_token(sent[0]) + assert "chat-1" not in kas.router._reconnect_tries + assert closed.status == 400 and closed_body["code"] == "invalid_slot" + assert kas.audits.count(("workflow.kas.reconnect", "allowed")) == 1 + + +def test_launch_options_are_shape_checked(): + assert kas_handlers._launch_options({"model": "claude-opus-4", "effort": "high"}) == { + "model": "claude-opus-4", + "effort": "high", + } + assert kas_handlers._launch_options({"model": "auto", "effort": ""}) == {} + for bad in ({"model": "a b"}, {"effort": 3}): + assert isinstance(kas_handlers._launch_options(bad), web.Response) + + +def test_a_launch_option_ending_in_a_newline_is_refused(): + # Given: a model id and an effort level that each end in a newline + for bad in ({"model": "some-model\n"}, {"effort": "high\n"}): + # When / Then: the body is refused instead of reaching the launch with the newline + assert isinstance(kas_handlers._launch_options(bad), web.Response) + + +async def test_run_start_passes_model_and_effort_to_the_launch(kas, tmp_path, monkeypatch): + slot = SimpleNamespace(key="chat-1", project=str(tmp_path)) + started: list[str] = [] + slot.enqueue_or_run_prompt = lambda message, *_a, **_k: started.append(message) or True + app = web.Application() + app["state"] = SimpleNamespace( + get_slot=lambda k: slot if k == "chat-1" else None, push_slots_update=lambda: None + ) + server._register_mcp_routes(app) + async with TestClient(TestServer(app)) as client: + bad = await client.post( + "/api/workflows/kas/runs", + json={"slot": "chat-1", "source": "bundled://x", "model": "a b"}, + ) + assert bad.status == 400 + resp = await client.post( + "/api/workflows/kas/runs", + json={"slot": "chat-1", "source": "bundled://x", "model": "m-1", "effort": "low"}, + ) + assert resp.status == 202, await resp.text() + (launch,) = kas.router._launches.values() + assert (launch.model, launch.effort) == ("m-1", "low") + assert started and "launch" in started[0] + + +async def test_run_start_fits_the_display_name_to_kas_run_label_rules(kas, tmp_path): + # KAS rejects a runLabel over 100 characters or holding a double quote or a + # control character, and the launch only reaches KAS after this route + # answered 202, so the route rewrites the name to fit instead. + slot = SimpleNamespace(key="chat-1", project=str(tmp_path)) + slot.enqueue_or_run_prompt = lambda *_a, **_k: True + app = web.Application() + app["state"] = SimpleNamespace( + get_slot=lambda k: slot if k == "chat-1" else None, push_slots_update=lambda: None + ) + server._register_mcp_routes(app) + long_name = ' Nightly "fix"\nrun ' + "x" * 200 + async with TestClient(TestServer(app)) as client: + resp = await client.post( + "/api/workflows/kas/runs", + json={"slot": "chat-1", "source": "bundled://x", "runLabel": long_name}, + ) + assert resp.status == 202, await resp.text() + blank = await client.post( + "/api/workflows/kas/runs", + json={"slot": "chat-1", "source": "bundled://x", "runLabel": " \n\t "}, + ) + assert blank.status == 202, await blank.text() + first, second = kas.router._launches.values() + assert first.run_label is not None + assert first.run_label.startswith("Nightly 'fix' run xxx") + assert len(first.run_label) <= 100 + assert '"' not in first.run_label and "\n" not in first.run_label + assert second.run_label is None + + +class _ColdChat(SimpleNamespace): + """A chat restored at gateway start: its transcript window is not read yet.""" + + def __init__(self, project: str) -> None: + super().__init__(key="chat-1", project=project, window_pending=True, events=[]) + loop_thread = threading.get_ident() + chat = self + + class _Window: + def read(self, _slot): + where = "off the loop" if threading.get_ident() != loop_thread else "on the loop" + chat.events.append(f"read {where}") + return () + + self._lazy_window = _Window() + + def load_window(self, *_prefetched) -> None: + self.window_pending = False + self.events.append("loaded") + + def enqueue_or_run_prompt(self, message, *_args, **_kwargs) -> bool: + self.events.append("queued with the window pending" if self.window_pending else "queued") + return True + + +def _app_with(chats: dict) -> web.Application: + app = web.Application() + app["state"] = SimpleNamespace(get_slot=chats.get, push_slots_update=lambda: None) + server._register_mcp_routes(app) + return app + + +async def test_a_launch_reads_a_cold_chats_window_off_the_loop_before_it_queues(kas, tmp_path): + # Given: a chat restored at gateway start, its window not read yet + chat = _ColdChat(str(tmp_path)) + + # When: a run is launched in it + async with TestClient(TestServer(_app_with({"chat-1": chat}))) as client: + resp = await client.post( + "/api/workflows/kas/runs", json={"slot": "chat-1", "source": "bundled://x"} + ) + assert resp.status == 202, await resp.text() + + # Then: the window was read on a worker thread and loaded before the launch was queued + assert chat.events == ["read off the loop", "loaded", "queued"] + + +async def test_a_launch_into_a_chat_closed_while_its_window_is_read_is_refused(kas, tmp_path): + # Given: a cold chat that is closed while its window is read + chat = _ColdChat(str(tmp_path)) + chats = {"chat-1": chat} + read = chat._lazy_window.read + + def read_while_closed(slot): + chats.pop("chat-1") + return read(slot) + + chat._lazy_window.read = read_while_closed + + # When: a run is launched in it + async with TestClient(TestServer(_app_with(chats))) as client: + resp = await client.post( + "/api/workflows/kas/runs", json={"slot": "chat-1", "source": "bundled://x"} + ) + body = await resp.json() + + # Then: the launch is refused as naming no open chat, and nothing is queued or registered + assert resp.status == 400 and body["code"] == "invalid_slot" + assert "queued" not in chat.events and not kas.router._launches + + +async def test_workflow_turns_queued_behind_a_busy_turn_never_merge(kas, tmp_path, monkeypatch): + # Given: a busy chat, with queued messages set to merge into one turn + state, slot = _state(tmp_path), _slot("chat-1") + slot.project = str(tmp_path) + slot._turn_admission_reserved = True + monkeypatch.setattr(state, "get_slot", lambda key: slot if key == "chat-1" else None) + monkeypatch.setattr(state, "push_slots_update", lambda: None) + + async def no_turn(*_args, **_kwargs): + return None + + # When: two runs are launched and a reconnect is sent before the turn ends, + # with a message of the person's between them + app = web.Application() + app["state"] = state + server._register_mcp_routes(app) + async with TestClient(TestServer(app)) as client: + for _ in range(2): + resp = await client.post( + "/api/workflows/kas/runs", json={"slot": "chat-1", "source": "bundled://x"} + ) + assert resp.status == 202 and (await resp.json())["queued"] is True + assert slot.enqueue_or_run_prompt("also check the docs", no_turn, state) is False + assert await kas_handlers._send_reconnect(state, kas.router, "chat-1") is True + turns = [] + while slot._queue: + text, consumed = _dequeue_next_message(slot, merge_enabled=True) + turns.append((len(consumed), router_mod.KasWorkflowRouter.is_turn_action(text))) + + # Then: each launch and the reconnect is a turn of its own that the chat answers + assert turns == [(1, True), (1, True), (1, False), (1, True)] + + +async def test_a_driverless_finished_run_offers_only_delete(kas): + kas.router.mirror.apply_load({"workflowId": "w1", "state": failed_state()}) + async with TestClient(TestServer(_app())) as client: + row = await (await client.get("/api/workflows/kas/runs/w1")).json() + assert row["actions"] == ["delete"] + assert row["questions"] == [] + + +def _model_options(model: str) -> list[dict]: + """A step session's ``configOptions`` as Kiro Agent sends them: auto, and Opus with levels.""" + options = [ + { + "type": "select", + "id": "model", + "currentValue": model, + "options": [ + {"value": "auto", "name": "Auto"}, + { + "value": "claude-opus-5.5", + "name": "Claude Opus 5.5", + "description": "Claude Opus 5.5 model", + "_meta": { + "kiro": {"effortLevels": ["low", "high"], "defaultEffortLevel": "high"} + }, + }, + ], + } + ] + if model == "claude-opus-5.5": + options.append( + { + "type": "select", + "id": "effortLevel", + "currentValue": "high", + "options": [{"value": "low"}, {"value": "high"}], + } + ) + return options + + +def _step_on_auto(kas) -> object: + """Run ``w1``'s step ``b`` running on auto, its session's options reported.""" + rt = driven(kas.router, parallel_state()) + kas.router._step_transcripts.open("sb", ("w1", "b"), complete=True) + kas.router._step_transcripts.note_models("sb", _model_options("auto")) + rt.answers[wire.METHOD_SESSION_SET_CONFIG_OPTION] = lambda p: { + "configOptions": _model_options(p["value"]) + } + return rt + + +async def test_model_route_sets_a_steps_model_on_its_runs_process(kas): + # Given: a running step on auto + rt = _step_on_auto(kas) + + # When: the dashboard posts a new model for it + async with TestClient(TestServer(_app())) as client: + resp = await client.post( + "/api/workflows/kas/runs/w1/steps/b/model", + json={"model": "claude-opus-5.5", "path": "b"}, + ) + assert resp.status == 200, await resp.text() + answer = await resp.json() + shown = await (await client.get("/api/workflows/kas/runs/w1/steps/b/transcript")).json() + + # Then: Kiro Agent got the set on the step's session, and the step chat names it + assert rt.calls[-1] == ( + wire.METHOD_SESSION_SET_CONFIG_OPTION, + {"sessionId": "sb", "configId": "model", "value": "claude-opus-5.5"}, + ) + assert answer == {"model": "claude-opus-5.5", "effort": "high"} + assert (shown["model"], shown["effort"], shown["defaultEffort"]) == ( + "claude-opus-5.5", + "high", + "high", + ) + assert [o["id"] for o in shown["modelOptions"]] == ["auto", "claude-opus-5.5"] + assert shown["effortOptions"] == ["low", "high"] + assert ("workflow.kas.step_model", "allowed") in kas.audits + assert "workflow.kas.step_model" in kas.refusals + + +@pytest.mark.parametrize( + "body", + [{}, {"model": 3}, {"model": " "}, {"effort": 5}, {"model": "m" * 201}, {"effort": "e" * 201}], +) +async def test_model_route_refuses_a_malformed_body_unsent(kas, body): + rt = _step_on_auto(kas) + async with TestClient(TestServer(_app())) as client: + resp = await client.post("/api/workflows/kas/runs/w1/steps/b/model", json=body) + assert resp.status == 400 and (await resp.json())["code"] == "invalid_model" + assert not any(m == wire.METHOD_SESSION_SET_CONFIG_OPTION for m, _ in rt.calls) + + +async def test_model_route_maps_an_unknown_step_and_a_refusal(kas): + rt = _step_on_auto(kas) + async with TestClient(TestServer(_app())) as client: + missing = await client.post( + "/api/workflows/kas/runs/w1/steps/nope/model", json={"model": "auto"} + ) + refused = await client.post( + "/api/workflows/kas/runs/w1/steps/b/model", json={"model": "gpt-9"} + ) + assert missing.status == 404 and (await missing.json())["code"] == "step_unknown" + assert refused.status == 409 + assert "does not offer that model" in (await refused.json())["error"] + assert not any(m == wire.METHOD_SESSION_SET_CONFIG_OPTION for m, _ in rt.calls) diff --git a/test/test_kas_workflows_project_root.py b/test/test_kas_workflows_project_root.py index 599a41eb0791..892030eb2a23 100644 --- a/test/test_kas_workflows_project_root.py +++ b/test/test_kas_workflows_project_root.py @@ -1,6 +1,7 @@ """A Kiro Workflows project directory is confined to an allowed root before any filesystem use. -The router's ``_project`` takes the directory a caller names. It must refuse a +The two entry points are the dashboard handler (``_project_dir``, request data) +and the router (``_project``, what the handler hands it). Each must refuse a directory outside every root even when it exists, must not be led out of a root by a symlink, and must not stat a path outside every root at all. """ @@ -13,6 +14,7 @@ import pytest +import kiro_crew.dashboard.handlers.kas_workflows as kas_handlers from kiro_crew.kas_workflows import project_root from kiro_crew.kas_workflows import router as router_mod from kiro_crew.kas_workflows.router import KasWorkflowError @@ -32,6 +34,53 @@ def roots(tmp_path, _floor_monkeypatch): return home, outside +def test_handler_accepts_a_project_under_home(roots): + home, _ = roots + assert kas_handlers._project_dir(str(home / "proj")) == os.path.realpath(home / "proj") + + +def test_handler_refuses_an_existing_directory_outside_every_root(roots): + _, outside = roots + assert kas_handlers._project_dir(str(outside)) is None + + +def test_handler_refuses_a_dotdot_escape_from_home(roots): + home, outside = roots + assert kas_handlers._project_dir(str(home / ".." / outside.name)) is None + + +def test_handler_refuses_a_symlink_in_home_that_leads_outside(roots): + home, outside = roots + make_dir_link(home / "link", outside) + assert kas_handlers._project_dir(str(home / "link")) is None + + +def test_handler_refuses_a_sibling_that_only_shares_the_home_prefix(roots, tmp_path): + home, _ = roots + sibling = tmp_path / (home.name + "-other") + sibling.mkdir() + assert kas_handlers._project_dir(str(sibling)) is None + + +def test_handler_refuses_relative_and_non_string_values(roots): + assert kas_handlers._project_dir("proj") is None + assert kas_handlers._project_dir(None) is None + assert kas_handlers._project_dir(["/"]) is None + + +def test_handler_accepts_a_recent_project_outside_home(roots, _floor_monkeypatch): + _, outside = roots + _floor_monkeypatch.setattr(project_root, "recent_project_dirs", lambda: [str(outside)]) + assert kas_handlers._project_dir(str(outside)) == os.path.realpath(outside) + + +def test_handler_accepts_a_server_held_chat_project_outside_home(roots): + _, outside = roots + assert kas_handlers._project_dir(str(outside), server_held=str(outside)) == os.path.realpath( + outside + ) + + def test_nothing_outside_every_root_is_stat_ed(roots, _floor_monkeypatch): _, outside = roots touched: list[str] = [] diff --git a/test/test_kas_workflows_round4.py b/test/test_kas_workflows_round4.py index 41e62ed3feea..ddc0c3f04999 100644 --- a/test/test_kas_workflows_round4.py +++ b/test/test_kas_workflows_round4.py @@ -793,6 +793,36 @@ def test_recipes_changed_bumps_the_recipes_revision() -> None: assert router.recipes_revision == 1 +# ── The dashboard's push: every revision move reaches the ``changed`` hook ── + + +def test_every_revision_bump_reaches_the_changed_hook() -> None: + router = _router() + seen: list[int] = [] + router.set_dashboard_hooks(DashboardHooks(changed=seen.append)) + sink = router.sink_for(FakeRuntime()) + sink.on_notification(wire.NOTIFY_RECIPES_CHANGED, {"recipes": []}) + sink.on_notification( + wire.NOTIFY_RUN_START, + {"workflowId": "w1", "workflowName": "investigate", "nodeTree": []}, + ) + assert router.revision >= 2 + assert seen == list(range(1, router.revision + 1)) + + +def test_a_changed_hook_that_raises_leaves_the_revision_moved() -> None: + router = _router() + + def broken(_revision: int) -> None: + raise RuntimeError("socket gone") + + router.set_dashboard_hooks(DashboardHooks(changed=broken)) + sink = router.sink_for(FakeRuntime()) + sink.on_notification(wire.NOTIFY_RECIPES_CHANGED, {"recipes": []}) + assert router.revision == 1 + assert router.recipes_revision == 1 + + # ── Gap 27: recipe detail from the listed file only ── diff --git a/test/test_kas_workflows_round4_l2.py b/test/test_kas_workflows_round4_l2.py new file mode 100644 index 000000000000..50abcbaf6d7c --- /dev/null +++ b/test/test_kas_workflows_round4_l2.py @@ -0,0 +1,558 @@ +"""Structured questions, the person-only wait, and the rewind guard. + +- Gap 13: the rich question model a workflow step's ``_kiro/userInput`` is held + as (descriptions, the recommended answer, sub-option toggles, free-form + questions), and the ``userInput`` capability every KAS session declares. +- Gap 4: a chat's own plan approval waits for the person, + bounded only by the turn's own ceiling, not the 600 s approval window. +- Gap 3: Edit & resend is refused while a run started from the edited message or + after it is live. +""" + +from __future__ import annotations + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer +from chat_test_helpers import _make_app, _make_state +from turn_harness import APPROVED, SlotSpec, TurnRecord, TurnScript, run_turn + +from kiro_crew.acp import kas_wire +from kiro_crew.acp.types import ( + EVENT_COMPLETE, + EVENT_PERMISSION_REQUEST, + EVENT_TEXT_CHUNK, + STOP_REASON_END_TURN, + AcpEvent, +) +from kiro_crew.config.loader import APPROVAL_TURN_MARGIN_SECS +from kiro_crew.dashboard import turn_dispatch as td +from kiro_crew.kas_workflows import asks +from kiro_crew.kas_workflows import chat as kas_chat +from kiro_crew.testing.synthetic_credentials import github_classic + +# ── fixtures ──────────────────────────────────────────────────────────────── + +_RICH = { + "sessionId": "sess-1", + "toolCallId": "tc-1", + "question": "How should I ship it?", + "options": [ + {"title": "Draft PR", "description": "Open it as a draft"}, + { + "title": "Full PR", + "description": "Ready for review", + "recommended": True, + "subOptionsLabel": "Include:", + "subOptions": [ + {"title": "Tests", "description": "unit tests"}, + {"title": "Docs"}, + {"title": "Changelog"}, + ], + }, + {"title": "Later", "recommended": True}, # a second recommendation is ignored + {"title": "Draft PR"}, # duplicate title dropped + {"description": "no title: dropped"}, + ], +} + +_FREE = { + "sessionId": "sess-1", + "toolCallId": "tc-2", + "question": "What is the ticket id?", + "options": [], +} + + +def _rich(**over: Any) -> asks.PendingQuestion: + return asks.question_from_user_input( + {**_RICH, **over}, + key="k", + request_id=7, + session_id="sess-1", + owner=("wf_1", "step"), + created_at=1.0, + runtime=None, + path=None, + slot="chat-1", + ) + + +def _free() -> asks.PendingQuestion: + return asks.question_from_user_input( + _FREE, + key="k2", + request_id=8, + session_id="sess-1", + owner=("", ""), + created_at=1.0, + runtime=None, + path=None, + slot="chat-1", + ) + + +# ── gap 13: the question model ────────────────────────────────────────────── + + +class TestTheRichQuestion: + def test_the_payload_keeps_descriptions_recommended_and_sub_options(self) -> None: + payload = _rich().to_payload() + (item,) = payload["questions"] + assert item["id"] == "tc-1" + assert item["prompt"] == "How should I ship it?" + assert item["multiSelect"] is False + assert item["freeText"] is False + assert item["options"] == [ + {"label": "Draft PR", "description": "Open it as a draft"}, + { + "label": "Full PR", + "description": "Ready for review", + "recommended": True, + "subOptions": [ + {"label": "Tests", "description": "unit tests"}, + {"label": "Docs"}, + {"label": "Changelog"}, + ], + "subOptionsLabel": "Include:", + }, + # Only the first recommendation counts, so "pre-select" is unambiguous. + {"label": "Later"}, + ] + + def test_a_question_with_no_options_is_free_form(self) -> None: + (item,) = _free().to_payload()["questions"] + assert item["options"] == [] + assert item["freeText"] is True + + @pytest.mark.parametrize( + ("answer", "text"), + [ + ("Draft PR", "Draft PR"), + (["Draft PR"], "Draft PR"), + # Sub-options ride KAS's own notation, in offered order. + (["Full PR", "Docs", "Tests"], "Full PR [Tests, Docs]"), + (["Full PR"], "Full PR"), + ("Full PR", "Full PR"), + ], + ) + def test_an_answer_becomes_kas_answer_text(self, answer: Any, text: str) -> None: + q = _rich() + assert q.answer_value({"tc-1": answer}) == text + assert q.answer_result({"tc-1": answer}) == {"action": "answered", "answer": text} + + @pytest.mark.parametrize( + "answers", + [ + {"other": "Draft PR"}, + {"tc-1": "Nope"}, + {"tc-1": ["Full PR", "Nope"]}, + {"tc-1": ["Full PR", "Docs", "Docs"]}, + {"tc-1": ["Draft PR", "Docs"]}, # a sub-option of ANOTHER answer + {"tc-1": []}, + {"tc-1": ""}, + ], + ) + def test_an_answer_it_does_not_offer_is_refused(self, answers: dict) -> None: + with pytest.raises(ValueError): + _rich().answer_value(answers) + + def test_a_free_form_answer_is_the_typed_text(self) -> None: + q = _free() + assert q.answer_value({"tc-2": " JIRA-12 "}) == "JIRA-12" + with pytest.raises(ValueError): + q.answer_value({"tc-2": " "}) + with pytest.raises(ValueError): + q.answer_value({"tc-2": "x" * 4001}) + + def test_dismissing_answers_with_a_not_agreement_text(self) -> None: + # KAS reads any reply but a non-empty ``answered`` as "move on", so a + # dismissal is an ``answered`` saying nobody agreed. + unseen = asks.user_input_no_answer(person=False) + declined = asks.user_input_no_answer(person=True) + assert unseen["action"] == declined["action"] == "answered" + assert unseen["answer"] and declined["answer"] and unseen != declined + assert _rich().dismiss_result() == unseen + assert _rich().dismiss_result(person=True) == declined + assert asks.dismiss_result_for(kas_wire.METHOD_USER_INPUT) == unseen + assert asks.dismiss_result_for("session/request_permission") == { + "outcome": {"outcome": "cancelled"} + } + + def test_a_bare_allow_takes_the_recommended_answer_with_every_sub_option(self) -> None: + assert _rich().default_answer() == "Full PR [Tests, Docs, Changelog]" + assert _free().default_answer() is None + + def test_question_text_is_redacted_and_controls_neutralized(self, monkeypatch) -> None: + monkeypatch.setattr(asks, "_redact", lambda text: text.replace("SECRET", "[redacted]")) + q = _rich( + question="Use SECRET?", + options=[{"title": "a\u202eb SECRET", "description": "x\u0000y"}], + ) + assert q.prompt == "Use [redacted]?" + assert q.options[0].label == "a b [redacted]" + assert q.options[0].description == "x y" + # The answer sent back is the title KAS sent, not the display copy. + assert q.answer_value({"tc-1": q.options[0].label}) == "a\u202eb SECRET" + + +# ── gap 13: the handshake ─────────────────────────────────────────────────── + + +class TestTheCapabilityIsDeclaredEitherWay: + """Every KAS session declares ``userInput``, answered through the elicitation + path; the Kiro Workflows switch only picks which handler answers, never + whether KAS may ask.""" + + @pytest.mark.parametrize("enabled", [True, False]) + def test_the_kas_harness_declares_user_input_with_the_switch_on_or_off( + self, monkeypatch, enabled + ) -> None: + from kiro_crew.acp.harness.kas import KasHarness + + monkeypatch.setattr(kas_chat, "chat_workflows_enabled", lambda: enabled) + caps = KasHarness().client_capabilities + assert caps["_meta"]["kiro"]["userInput"] is True + assert caps["_meta"]["kiro"]["openExternalUrl"] is True + + +# ── gap 4: a person-only ask waits for the person ─────────────────────────── + +_CEILING = 3600 +_DONE = AcpEvent(kind=EVENT_COMPLETE, stop_reason=STOP_REASON_END_TURN) +_AFTER = AcpEvent(kind=EVENT_TEXT_CHUNK, text="after") + + +def _plan_event() -> AcpEvent: + return AcpEvent( + kind=EVENT_PERMISSION_REQUEST, + request_id="req-1", + title="Add 2 workflow steps to wf_1", + tool_kind="other", + harness_tool_id="update_workflow", + ) + + +def _declined_at(record: TurnRecord) -> float: + [reject] = [call for call in record.calls("reject_tool") if call.args == ("req-1",)] + return reject.at + + +@pytest.fixture(autouse=True) +def _isolate_turn_deadline(): + prev = td._TURN_DEADLINE.get() + td._TURN_DEADLINE.set(None) + try: + yield + finally: + td._TURN_DEADLINE.set(prev) + + +class TestThePersonOnlyWait: + def test_the_window_is_the_turn_ceiling_less_the_margin(self, monkeypatch) -> None: + monkeypatch.setattr( + td, + "current_turn_limit_secs", + lambda: _CEILING, # flake-ok: arithmetic on a stubbed ceiling, nothing waits on it + ) + assert td.person_wait_window_secs() == _CEILING - APPROVAL_TURN_MARGIN_SECS + + @pytest.mark.asyncio + async def test_a_plan_handoff_outlives_the_approval_window(self) -> None: + record = await run_turn( + TurnScript(events=[_plan_event(), _AFTER, _DONE]), + config={ + "agent": {"tool_approval_timeout_secs": 300, "chat_turn_timeout_secs": _CEILING} + }, + ) + # Not 300 s: the person had the whole turn. + assert _declined_at(record) == _CEILING - APPROVAL_TURN_MARGIN_SECS + assert record.stop_reason == STOP_REASON_END_TURN + + @pytest.mark.asyncio + async def test_an_ordinary_approval_keeps_the_window(self) -> None: + tool = AcpEvent( + kind=EVENT_PERMISSION_REQUEST, request_id="req-1", title="fs_write", tool_kind="edit" + ) + record = await run_turn( + TurnScript(events=[tool, _AFTER, _DONE]), + config={ + "agent": {"tool_approval_timeout_secs": 300, "chat_turn_timeout_secs": _CEILING} + }, + ) + assert _declined_at(record) == 300 + + @pytest.mark.asyncio + async def test_an_unattended_slot_keeps_its_deny_fast_window(self) -> None: + record = await run_turn( + TurnScript(events=[_plan_event(), _AFTER, _DONE]), + slot=SlotSpec(key="worker-1", app="issue-radar"), + ) + assert _declined_at(record) == 180 + + @pytest.mark.asyncio + async def test_a_person_still_answers_it(self) -> None: + record = await run_turn( + TurnScript(events=[_plan_event(), _AFTER, _DONE], answers={"req-1": APPROVED}), + config={ + "agent": {"tool_approval_timeout_secs": 300, "chat_turn_timeout_secs": _CEILING} + }, + ) + assert [c.args for c in record.calls("approve_tool")] == [("req-1",)] + assert record.calls("reject_tool") == [] + + +# ── gap 3: editing an earlier message while a run is live ─────────────────── + + +class _Router: + def __init__(self, rows: list[dict]) -> None: + self._rows = rows + + def rows(self) -> list[dict]: + return self._rows + + +def _row( + status: str, created: str, slot: str = "src", wid: str = "wf_1", name: str = "build" +) -> dict: + return { + "workflowId": wid, + "name": name, + "status": status, + "createdAt": created, + "slotKey": slot, + } + + +@pytest.fixture +def router(monkeypatch): + from kiro_crew.kas_workflows import router as router_mod + + def _install(rows: list[dict]) -> None: + monkeypatch.setattr(router_mod, "_ROUTER", _Router(rows)) + + return _install + + +class TestRunsSince: + def test_no_router_means_nothing_is_guarded(self, monkeypatch) -> None: + from kiro_crew.kas_workflows import router as router_mod + + monkeypatch.setattr(router_mod, "_ROUTER", None) + assert kas_chat.runs_since("src", "2026-05-21T16:00:02Z") == ([], []) + + def test_runs_before_the_message_and_other_chats_do_not_count(self, router) -> None: + router( + [ + _row("running", "2026-05-21T16:00:01Z", wid="before"), + _row("running", "2026-05-21T16:00:05Z", slot="other", wid="elsewhere"), + _row("running", "2026-05-21T16:00:05Z", wid="after"), + _row("completed", "2026-05-21T16:00:06Z", wid="done"), + ] + ) + live, ended = kas_chat.runs_since("src", "2026-05-21T16:00:02Z") + assert [r["workflowId"] for r in live] == ["after"] + assert [r["workflowId"] for r in ended] == ["done"] + + def test_an_unreadable_time_counts_as_after(self, router) -> None: + router([_row("paused", "not a time")]) + assert [r["workflowId"] for r in kas_chat.runs_since("src", "2026-05-21T16:00:02Z")[0]] == [ + "wf_1" + ] + + +def _populate(state, key: str = "src"): + slot = state.get_or_create_slot(key) + slot.title = "My Chat" + slot._titled = True + slot.append("user", "first", "msg msg-u", ts="2026-05-21T16:00:00Z") + slot.append("assistant", "a1", "msg msg-a", ts="2026-05-21T16:00:01Z") + slot.append("user", "second", "msg msg-u", ts="2026-05-21T16:00:02Z") + slot.append("assistant", "a2", "msg msg-a", ts="2026-05-21T16:00:03Z") + slot.drain() + return slot + + +class TestTheRewindRoute: + @pytest.fixture(autouse=True) + def _no_run(self, _floor_monkeypatch): + _floor_monkeypatch.setattr( + "kiro_crew.dashboard.chat_rewind._run_chat", AsyncMock(return_value=None) + ) + + @pytest.mark.asyncio + async def test_a_live_run_since_the_message_refuses_the_edit(self, tmp_path, router) -> None: + router([_row("paused", "2026-05-21T16:00:02.500Z")]) + state = _make_state(tmp_path) + slot = _populate(state) + state.sessions._session_map.get = MagicMock(return_value="") + async with TestClient(TestServer(_make_app(state))) as client: + resp = await client.post( + "/api/chat/slots/src/rewind", json={"at_message_index": 2, "content": "edited"} + ) + assert resp.status == 409 + body = await resp.json() + assert body["code"] == kas_chat.REWIND_REFUSED_CODE + assert body["runs"] == [{"workflowId": "wf_1", "name": "build"}] + # Nothing changed: the history and the conversation are as they were. + assert [m["content"] for m in slot.messages] == ["first", "a1", "second", "a2"] + state.sessions.discard_conversation.assert_not_awaited() + + @pytest.mark.asyncio + async def test_a_refused_rewind_redacts_the_run_name(self, tmp_path, router) -> None: + # Given: a live run whose name carries a GitHub token + token = github_classic() + router([_row("paused", "2026-05-21T16:00:02.500Z", name=f"deploy {token}")]) + state = _make_state(tmp_path) + _populate(state) + state.sessions._session_map.get = MagicMock(return_value="") + # When: the person rewinds past the run's launch + async with TestClient(TestServer(_make_app(state))) as client: + resp = await client.post( + "/api/chat/slots/src/rewind", json={"at_message_index": 2, "content": "edited"} + ) + assert resp.status == 409 + raw = await resp.text() + body = await resp.json() + # Then: the refusal names the run with the token masked + assert body["runs"][0]["workflowId"] == "wf_1" + assert body["runs"][0]["name"].startswith("deploy ") + assert token not in raw + + @pytest.mark.asyncio + async def test_an_earlier_message_than_the_run_is_still_refused(self, tmp_path, router) -> None: + router([_row("running", "2026-05-21T16:00:02.500Z")]) + state = _make_state(tmp_path) + _populate(state) + async with TestClient(TestServer(_make_app(state))) as client: + resp = await client.post( + "/api/chat/slots/src/rewind", json={"at_message_index": 0, "content": "edited"} + ) + assert resp.status == 409 + + @pytest.mark.asyncio + async def test_an_ended_run_or_an_older_one_lets_the_edit_through( + self, tmp_path, router + ) -> None: + router( + [ + _row("completed", "2026-05-21T16:00:02.500Z", wid="ended"), + _row("running", "2026-05-21T15:00:00Z", wid="older"), + ] + ) + state = _make_state(tmp_path) + _populate(state) + state.sessions._session_map.get = MagicMock(return_value="") + async with TestClient(TestServer(_make_app(state))) as client: + resp = await client.post( + "/api/chat/slots/src/rewind", json={"at_message_index": 2, "content": "edited"} + ) + assert resp.status == 200 + + +class _UnreadableRouter: + def rows(self) -> list[dict]: + raise RuntimeError("mirror torn down mid-read") + + +class TestTheGuardHasNoOpenDoor: + """The rewind guard fails closed and covers edit-resend too.""" + + def test_an_unreadable_router_refuses_rather_than_allows(self, monkeypatch) -> None: + from kiro_crew.kas_workflows import router as router_mod + + monkeypatch.setattr(router_mod, "_ROUTER", _UnreadableRouter()) + with pytest.raises(kas_chat.RunsUnreadable): + kas_chat.runs_since("src", "2026-05-21T16:00:02Z") + body = kas_chat.rewind_refusal("src", "2026-05-21T16:00:02Z") + assert body is not None + assert body["code"] == kas_chat.REWIND_REFUSED_CODE + assert body["runs"] == [] + + def test_no_live_run_means_no_refusal(self, router) -> None: + router([_row("completed", "2026-05-21T16:00:05Z")]) + assert kas_chat.rewind_refusal("src", "2026-05-21T16:00:02Z") is None + + @pytest.mark.asyncio + async def test_edit_resend_refuses_a_live_run_since_the_message( + self, tmp_path, router, monkeypatch + ) -> None: + from kiro_crew.dashboard.chat_regenerate import api_chat_slot_edit_resend + + monkeypatch.setattr( + "kiro_crew.dashboard.chat_regenerate._run_chat", AsyncMock(return_value=None) + ) + router([_row("running", "2026-05-21T16:00:02.500Z")]) + state = _make_state(tmp_path) + state.sessions.discard_conversation = AsyncMock(return_value=True) + state.sessions.aflush = AsyncMock() + state.sessions._session_map.get = MagicMock(return_value="") + slot = _populate(state) + app = web.Application() + app["state"] = state + app.router.add_post("/api/chat/slots/{slot}/edit-resend", api_chat_slot_edit_resend) + async with TestClient(TestServer(app)) as client: + resp = await client.post( + "/api/chat/slots/src/edit-resend", + json={"ts": "2026-05-21T16:00:02Z", "content": "edited"}, + ) + assert resp.status == 409 + body = await resp.json() + assert body["code"] == kas_chat.REWIND_REFUSED_CODE + assert body["runs"] == [{"workflowId": "wf_1", "name": "build"}] + assert [m["content"] for m in slot.messages] == ["first", "a1", "second", "a2"] + state.sessions.discard_conversation.assert_not_awaited() + + @pytest.mark.asyncio + async def test_a_refused_edit_resend_redacts_the_run_name( + self, tmp_path, router, monkeypatch + ) -> None: + from kiro_crew.dashboard.chat_regenerate import api_chat_slot_edit_resend + + # Given: a live run whose name carries a GitHub token + monkeypatch.setattr( + "kiro_crew.dashboard.chat_regenerate._run_chat", AsyncMock(return_value=None) + ) + token = github_classic() + router([_row("running", "2026-05-21T16:00:02.500Z", name=f"deploy {token}")]) + state = _make_state(tmp_path) + state.sessions.discard_conversation = AsyncMock(return_value=True) + state.sessions.aflush = AsyncMock() + state.sessions._session_map.get = MagicMock(return_value="") + _populate(state) + app = web.Application() + app["state"] = state + app.router.add_post("/api/chat/slots/{slot}/edit-resend", api_chat_slot_edit_resend) + # When: the person edits and resends a message from before the run + async with TestClient(TestServer(app)) as client: + resp = await client.post( + "/api/chat/slots/src/edit-resend", + json={"ts": "2026-05-21T16:00:02Z", "content": "edited"}, + ) + assert resp.status == 409 + raw = await resp.text() + # Then: the token appears nowhere in the refusal + assert token not in raw + + @pytest.mark.asyncio + async def test_rewind_refuses_when_the_router_is_unreadable( + self, tmp_path, monkeypatch + ) -> None: + from kiro_crew.kas_workflows import router as router_mod + + monkeypatch.setattr( + "kiro_crew.dashboard.chat_rewind._run_chat", AsyncMock(return_value=None) + ) + monkeypatch.setattr(router_mod, "_ROUTER", _UnreadableRouter()) + state = _make_state(tmp_path) + slot = _populate(state) + async with TestClient(TestServer(_make_app(state))) as client: + resp = await client.post( + "/api/chat/slots/src/rewind", json={"at_message_index": 2, "content": "edited"} + ) + assert resp.status == 409 + assert [m["content"] for m in slot.messages] == ["first", "a1", "second", "a2"] diff --git a/test/test_kas_workflows_round5.py b/test/test_kas_workflows_round5.py new file mode 100644 index 000000000000..febe76a4e0dd --- /dev/null +++ b/test/test_kas_workflows_round5.py @@ -0,0 +1,59 @@ +"""Edge cases of the KAS workflow HTTP routes. + +The step transcript route sends its whole body through the same recursive +key-and-value redaction as every other KAS read, so a credential-shaped value +in a field the transcript builder passes through raw (a tool name, a session's +model id) never reaches the browser. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer + +import kiro_crew.dashboard.handlers.kas_workflows as kas_handlers +from kiro_crew.dashboard import server +from kiro_crew.kas_workflows import router as router_mod +from kiro_crew.testing.synthetic_credentials import github_classic + +pytestmark = pytest.mark.asyncio + +#: A GitHub token of the real shape, built at run time: the redactor removes it +#: wherever it appears, while it keeps an AWS key ID visible. +_KEY = github_classic() + + +class _TranscriptRouter: + async def step_transcript(self, workflow_id, node_id, path=None): + return { + "workflowId": workflow_id, + "nodeId": node_id, + "session": {"modelId": f"model-{_KEY}", "agentMode": "a"}, + "entries": [{"type": "tool", "name": f"probe {_KEY}", "kind": "execute"}], + } + + +@pytest.fixture +def app(monkeypatch): + async def no_refusal(_request, _operation): + return None + + monkeypatch.setattr(router_mod, "_ROUTER", _TranscriptRouter()) + monkeypatch.setattr(router_mod, "get_router", lambda: router_mod._ROUTER) + monkeypatch.setattr(kas_handlers, "_refusal", no_refusal) + application = web.Application() + application["state"] = SimpleNamespace(get_slot=lambda _k: None) + server._register_mcp_routes(application) + return application + + +async def test_the_step_transcript_body_is_redacted_whole(app): + async with TestClient(TestServer(app)) as client: + resp = await client.get("/api/workflows/kas/runs/wf_1/steps/a/transcript") + assert resp.status == 200, await resp.text() + text = await resp.text() + assert _KEY not in text + assert '"workflowId": "wf_1"' in text or '"workflowId":"wf_1"' in text diff --git a/test/test_runtime_death_subscribe.py b/test/test_runtime_death_subscribe.py new file mode 100644 index 000000000000..beffc21110bc --- /dev/null +++ b/test/test_runtime_death_subscribe.py @@ -0,0 +1,86 @@ +"""A process death reaches the one layer that subscribes to it (``runtime_death.subscribe``). + +The record every tenant pulls is pinned in ``test_runtime_death_is_a_process_event.py``; +this file pins the push: a listener hears each death once, after the record is stored, +and nothing it does can break the death path. +""" + +import asyncio +from types import SimpleNamespace + +import pytest + +from kiro_crew import runtime_death +from kiro_crew.acp.runtime import AcpRuntime + + +@pytest.fixture(autouse=True) +def _clean_death_state(): + runtime_death._reset_for_tests() + yield + runtime_death._reset_for_tests() + + +def _runtime() -> AcpRuntime: + rt = AcpRuntime(memory_mode="persistent") + rt._process = SimpleNamespace(returncode=-15, stdin=None) + rt._session_queues["s0"] = asyncio.Queue() + return rt + + +def test_a_subscriber_hears_each_death_once(): + heard: list[tuple[object, runtime_death.RuntimeDeath, bool]] = [] + runtime_death.subscribe( + lambda runtime, death: heard.append( + (runtime, death, runtime_death.death_of(runtime) is death) + ) + ) + rt = _runtime() + + rt._mark_dead(rt._exit_reason(-15)) + rt._mark_dead("a later path noticing the same death") + + assert len(heard) == 1 + runtime, death, stored_first = heard[0] + assert runtime is rt + assert stored_first, "the listener runs after the record is stored" + assert rt.is_alive() is False + + +def test_a_failing_subscriber_breaks_nothing(): + later: list[object] = [] + + def broken(_runtime, _death): + raise RuntimeError("listener bug") + + runtime_death.subscribe(broken) + runtime_death.subscribe(lambda runtime, _death: later.append(runtime)) + rt = _runtime() + + rt._mark_dead(rt._exit_reason(-15)) + + assert runtime_death.death_of(rt) is not None + assert later == [rt] + + +def test_an_unsubscribed_listener_hears_nothing(): + heard: list[object] = [] + unsubscribe = runtime_death.subscribe(lambda runtime, _death: heard.append(runtime)) + + unsubscribe() + unsubscribe() + rt = _runtime() + rt._mark_dead(rt._exit_reason(-15)) + + assert heard == [] + + +def test_the_test_reset_drops_every_subscriber(): + heard: list[object] = [] + runtime_death.subscribe(lambda runtime, _death: heard.append(runtime)) + + runtime_death._reset_for_tests() + rt = _runtime() + rt._mark_dead(rt._exit_reason(-15)) + + assert heard == [] diff --git a/test/test_security_posture.py b/test/test_security_posture.py index 467728a57a02..d002ccb170c9 100644 --- a/test/test_security_posture.py +++ b/test/test_security_posture.py @@ -1241,6 +1241,10 @@ def test_a_partially_covered_sink_says_so(self): # redacted_for_app (apps/app_redaction.py) is redact_via_context under # always_scan, the same pass in the caller's thread. "redacted_for_app(", + # _redact_obj (dashboard/handlers/workflows.py) runs redact_exfiltration_urls + # THEN redact_credentials on every string, dict keys included; the + # Kiro Workflows routes import it rather than defining their own pair. + "_redact_obj(", ) for label, module, detail in security_posture._REDACTION_SINKS: text = (pkg / module).read_text(encoding="utf-8") diff --git a/test/test_state_parts_facade.py b/test/test_state_parts_facade.py index d05180dfe0f9..850394aca606 100644 --- a/test/test_state_parts_facade.py +++ b/test/test_state_parts_facade.py @@ -551,6 +551,7 @@ "_hook_continuation_depth": ("value", "0"), "_human_seen": ("value", "False"), "_infra_retries": ("value", "0"), + "_kas_observing": ("value", "False"), "_last_enqueue_ts": ("value", "''"), "_last_stop_reason": ("value", "''"), "_last_turn_auth_required": ("value", "False"), diff --git a/test/test_ws_event_scoping_frames.py b/test/test_ws_event_scoping_frames.py index 77b319541360..e584a5cb25d3 100644 --- a/test/test_ws_event_scoping_frames.py +++ b/test/test_ws_event_scoping_frames.py @@ -931,3 +931,49 @@ def test_it_is_the_name_the_push_actually_broadcasts(self): from kiro_crew.dashboard.handlers import member_dashboard_fields assert member_dashboard_fields.FIELD_FRAME in ws_event_scope._OWNER_ONLY_EVENTS + + +# --------------------------------------------------------------------------- +# Owner-only: the Kiro Workflows revision frame +# --------------------------------------------------------------------------- + + +class TestKasWorkflowRevisionFrameIsOwnerOnly: + """The revision frame signals runs on the owner-only ``/api/workflows/kas/*`` + surface; it goes out on ``broadcast_ws_owners``, and its classification makes an + app token's denial the audited ``owner_only`` one.""" + + FRAME = {"revision": 7} + + def test_a_wildcard_manifest_does_not_receive_it(self): + state = _make_state() + assert ( + ws_event_allowed( + "kas_workflow_revision", + self.FRAME, + app="mochi-pet", + allowed_events=build_allowed_event_set(["*"]), + state=state, + ) + is False + ) + + def test_the_denial_is_audited_as_owner_only(self): + state = _make_state() + with patch("kiro_crew.sel.sel") as sel_mock: + ws_event_allowed( + "kas_workflow_revision", + self.FRAME, + app="mochi-pet", + allowed_events=build_allowed_event_set(["*"]), + state=state, + ) + outcomes = [ + c.kwargs.get("outcome") for c in sel_mock.return_value.log_api_access.call_args_list + ] + assert outcomes == ["denied:owner_only"] + + def test_it_is_the_name_the_push_actually_broadcasts(self): + from kiro_crew.dashboard import kas_workflow_triggers, ws_event_scope + + assert kas_workflow_triggers.KAS_REVISION_FRAME in ws_event_scope._OWNER_ONLY_EVENTS