diff --git a/docs/system-specs/modules/learn-cron-dashboard.md b/docs/system-specs/modules/learn-cron-dashboard.md index 75460cf1d772..8858f9041df2 100644 --- a/docs/system-specs/modules/learn-cron-dashboard.md +++ b/docs/system-specs/modules/learn-cron-dashboard.md @@ -4902,8 +4902,10 @@ that wake only exists because the fire-time guard already proved the loop self-armed. A cron injection, a sub-agent sharing the slot or an app-driven turn carries neither mark; those pass an empty initiator and the crew/member refusal stands (visibly, via the notice row). The wake mark is self-arm -provenance ONLY — `set_project` / `reset_conversation` stay human-only, so a -wake can never retarget the slot's project. The arm-time admission check for a self-armed loop requires the +provenance ONLY — `set_project` / `chat_tag` stay human-only, so a +wake can never retarget the slot's project. `reset_conversation` admits one wake: a +conductor's own patrol wake at a round close, under the checks in +`session_directive_apply._refuse_unvouched_wake_reset` (the conductor round-reset RFC). The arm-time admission check for a self-armed loop requires the slot's mode to be UNCHANGED between authorization and commit (the external rule stays "never into crew/member"). **Stated decision on later mode changes:** a self-armed loop keeps firing if its slot later changes mode, because the diff --git a/docs/system-specs/modules/session.md b/docs/system-specs/modules/session.md index ba3d385e45f8..a678712c4e8a 100644 --- a/docs/system-specs/modules/session.md +++ b/docs/system-specs/modules/session.md @@ -4113,7 +4113,7 @@ Security properties (enforced in `session_directive.decode` plus the applier): - **Native sub-agent calls refused**: they surface as flat events in the parent loop but have no independently bindable slot, so the applier declines them. - **SEL audit on every application**: `apply_session_directive` emits a tool-invocation event tagged `source="mcp-directive"` with outcome `success` / `denied` (e.g. a `set_project` sensitive-path block) / `error`, since the effect now runs in the consumer rather than in the tool body or an HTTP endpoint. -The applier reuses the SAME effect cores the HTTP endpoints call — `authorize_and_add_nudge` / `authorize_and_update_nudge` / `svc.remove` for the monitor trio, `slot.project` plus the recent-projects save for `set_project`, `deliver_ws_owners` for `suggest_followup`, and `post_question_card` for `ask_question` — so behavior is unchanged except that `ask_question` is now non-blocking (full contract in `learn-cron-dashboard.md` → "Agent Questions"). `reset_conversation` is the one directive whose core is not reachable inline: it queues `SessionManager.discard_conversation` on the slot for `chat_runner._consume_pending_reset` to apply at a turn boundary, because the discard is a full provider teardown and the producer is mid-turn — the same deferral `set_project` uses, and the reason the immediate route (`POST /api/chat/slots/{slot}/reset-conversation`) answers 409 on a busy slot rather than tearing down a turn mid-write. It queues the session key THIS TURN ran on, passed in by the consumer, never re-resolved from the slot: `linked_session_key` is mutable, so a cron or workflow injection that rebinds the slot between the request and the consume would otherwise discard whatever the slot points at by then and leave the caller's conversation alone. Only the END-OF-TURN consume may apply a discard (`allow_discard`); the two earlier consume points run just before a turn acquires the session, where a teardown lands under a channel turn already streaming on it. Even at that boundary it does not assume: the discard goes through `discard_conversation(..., skip_if_busy=True)`, which refuses under the same session lock that pops the session, mirroring `reset`'s own guard. Probing from the consumer and tearing down afterwards would leave a window in which a channel message acquires the session's semaphore and begins streaming a reply the teardown then destroys — and the semaphore is the stricter signal anyway, since `provider.has_active_turn()` cannot see a turn holding the semaphore with no prompt in flight yet. A refusal returns False and changes nothing, replay flag and session map included, so the consumer leaves the flag armed for a later boundary. The sid clear runs in the SAME tick as the pop, with no await between them — deferring it past the shutdown awaits lets a concurrent channel turn map a SUCCESSOR session under the key while the old provider is still shutting down, and the clear then erases the successor's pointer instead of the discarded one. Sub-agent children are the other wait — `discard_conversation` releases the shared runtime they run on, so a running or queued child, or an in-flight completion-event delivery, also leaves the flag ARMED rather than killing the child's work. Both that consume and the route's 409 read one predicate, `chat_utils.subagents_attached_async`, so the two cannot drift. The queued flag is in-memory slot state: a gateway restart while it sits armed drops the reset the confirmation promised, which is accepted rather than persisted — the cost is one un-applied reset the caller can ask for again, against durable state for a transient intent. `set_project` and `reset_conversation` additionally require structural user-turn provenance: injected cron, task-runner, sub-agent, auto-nudge, orchestration, app-authenticated unattended turns, and app-authored Spec Builder seed/handoff prompts cannot retarget a borrowed destination slot even when its session key is user-facing. Spec Builder rejects app-token message and decision submissions before they can enter its human-provenance relay or durable decision ledger. Queue entries preserve this provenance, replacement text adopts the editor's provenance, and mixed or untagged merges fail closed. +The applier reuses the SAME effect cores the HTTP endpoints call — `authorize_and_add_nudge` / `authorize_and_update_nudge` / `svc.remove` for the monitor trio, `slot.project` plus the recent-projects save for `set_project`, `deliver_ws_owners` for `suggest_followup`, and `post_question_card` for `ask_question` — so behavior is unchanged except that `ask_question` is now non-blocking (full contract in `learn-cron-dashboard.md` → "Agent Questions"). `reset_conversation` is the one directive whose core is not reachable inline: it queues `SessionManager.discard_conversation` on the slot for `chat_runner._consume_pending_reset` to apply at a turn boundary, because the discard is a full provider teardown and the producer is mid-turn — the same deferral `set_project` uses, and the reason the immediate route (`POST /api/chat/slots/{slot}/reset-conversation`) answers 409 on a busy slot rather than tearing down a turn mid-write. It queues the session key THIS TURN ran on, passed in by the consumer, never re-resolved from the slot: `linked_session_key` is mutable, so a cron or workflow injection that rebinds the slot between the request and the consume would otherwise discard whatever the slot points at by then and leave the caller's conversation alone. Only the END-OF-TURN consume may apply a discard (`allow_discard`); the two earlier consume points run just before a turn acquires the session, where a teardown lands under a channel turn already streaming on it. Even at that boundary it does not assume: the discard goes through `discard_conversation(..., skip_if_busy=True)`, which refuses under the same session lock that pops the session, mirroring `reset`'s own guard. Probing from the consumer and tearing down afterwards would leave a window in which a channel message acquires the session's semaphore and begins streaming a reply the teardown then destroys — and the semaphore is the stricter signal anyway, since `provider.has_active_turn()` cannot see a turn holding the semaphore with no prompt in flight yet. A refusal returns False and changes nothing, replay flag and session map included, so the consumer leaves the flag armed for a later boundary. The sid clear runs in the SAME tick as the pop, with no await between them — deferring it past the shutdown awaits lets a concurrent channel turn map a SUCCESSOR session under the key while the old provider is still shutting down, and the clear then erases the successor's pointer instead of the discarded one. Sub-agent children are the other wait — `discard_conversation` releases the shared runtime they run on, so a running or queued child, or an in-flight completion-event delivery, also leaves the flag ARMED rather than killing the child's work. Both that consume and the route's 409 read one predicate, `chat_utils.subagents_attached_async`, so the two cannot drift. The queued flag is in-memory slot state: a gateway restart while it sits armed drops the reset the confirmation promised, which is accepted rather than persisted — the cost is one un-applied reset the caller can ask for again, against durable state for a transient intent. `set_project` and `reset_conversation` additionally require structural user-turn provenance: injected cron, task-runner, sub-agent, auto-nudge, orchestration, app-authenticated unattended turns, and app-authored Spec Builder seed/handoff prompts cannot retarget a borrowed destination slot even when its session key is user-facing. One auto-nudge case is admitted for `reset_conversation` only: a `kirocrew-conductor` slot's own patrol wake, when that wake's loop is the slot's current active loop, the keystone-gated self-arm record (`autonudge_selfarm`) vouches the slot armed it itself, and no question card or tool approval is pending. Such a queued discard also waits at the consume while a question or approval is pending (`_pending_discard_from_wake`). Spec Builder rejects app-token message and decision submissions before they can enter its human-provenance relay or durable decision ledger. Queue entries preserve this provenance, replacement text adopts the editor's provenance, and mixed or untagged merges fail closed. Gateway-off (the default topology this targets), the model's tool result is the tool's OWN returned line delivered over kiro-cli's MCP pipe; the applier's confirmation string and SEL audit are recorded on KiroCrew's own surfaces (transcript / WS / hooks) and do NOT rewrite the model's tool result. Each tool therefore phrases its own message as a *request* that the consumer applies (and may refuse — no interactive session, invalid/sensitive path, capped/paused loop) rather than asserting the effect already landed. diff --git a/src/kiro_crew/agent.py b/src/kiro_crew/agent.py index 635dfda52126..72db6b1175f6 100644 --- a/src/kiro_crew/agent.py +++ b/src/kiro_crew/agent.py @@ -4396,6 +4396,14 @@ def _install_aim_capabilities() -> None: dispatch the next round in the same turn. Do not wait for the user: the one Round-0 go-ahead covers every round. +**Drop your chat at a round close.** Every patrol turn re-sends this whole +chat; the ledgers already hold your state. Once the next round is dispatched, +`session_ledger_record` `goal`, `next` (the open item ids, their worker keys and +their PRs) and `patrol_base`, then call `reset_conversation` as the last act of +that turn. The next wake resumes from the ledger snapshot it carries. Never +reset mid-round, and never while a question to the person is unanswered. A +refused reset changes nothing: carry on. + **Rounds are not gated, but spend is bounded.** Count from the ledger. With no budget from the user, a goal holds at most 20 ledger items in total, re-plans included (or the size of a larger Round-0 plan the user approved); a re-plan @@ -5013,6 +5021,10 @@ def _install_aim_capabilities() -> None: "@kirocrew-core/send_notification", "@kirocrew-core/ask_question", "@kirocrew-core/nothing_to_do", + # Dropping its own chat at a round close. The directive consumer admits it + # from a patrol wake only on the slot's own live self-armed loop, with no + # question or approval pending (``session_directive_apply``). + "@kirocrew-core/reset_conversation", ) diff --git a/src/kiro_crew/agent_materialization/conductor_agents.py b/src/kiro_crew/agent_materialization/conductor_agents.py index 85006a774263..3e7ff17f055f 100644 --- a/src/kiro_crew/agent_materialization/conductor_agents.py +++ b/src/kiro_crew/agent_materialization/conductor_agents.py @@ -179,7 +179,7 @@ def _conductor_mcp_servers(config: dict[str, Any]) -> dict[str, Any]: "kirocrew-conductor": ( frozenset({"session", "report", "tool_search", "@kirocrew-core"}) | _HISTORY_CORE_VERBS - | {"@kirocrew-core/select_crew"} + | {"@kirocrew-core/select_crew", "@kirocrew-core/reset_conversation"} | _HISTORY_DASHBOARD_VERBS | {"@kirocrew-dashboard/chat_folder_file_self"} | _HISTORY_WORK_VERBS @@ -188,7 +188,7 @@ def _conductor_mcp_servers(config: dict[str, Any]) -> dict[str, Any]: "kirocrew-ledger-conductor": ( frozenset({"session", "report", "tool_search"}) | _HISTORY_CORE_VERBS - | {"@kirocrew-core/select_crew"} + | {"@kirocrew-core/select_crew", "@kirocrew-core/reset_conversation"} | _HISTORY_DASHBOARD_VERBS | {"@kirocrew-dashboard/chat_folder_file_self"} | _HISTORY_WORK_VERBS diff --git a/src/kiro_crew/autonudge_authz.py b/src/kiro_crew/autonudge_authz.py index de73dd643b99..88212cea4bd9 100644 --- a/src/kiro_crew/autonudge_authz.py +++ b/src/kiro_crew/autonudge_authz.py @@ -36,7 +36,7 @@ is_channel_key, scrub_loop_text, ) -from kiro_crew.autonudge_selfarm import forget_self_arm, record_self_arm +from kiro_crew.autonudge_selfarm import WAKE_RESET_AGENTS, forget_self_arm, record_self_arm from kiro_crew.config.loader import workspace_dir_for from kiro_crew.monitoring.limits import validate_runtime_secs from kiro_crew.monitoring.models import ( @@ -960,6 +960,11 @@ def _deny(reason: str, status: int) -> tuple[None, str, int]: # Set only on the dashboard branch, when a crew/member slot is armed by its # own turn; channel-bound loops have no slot mode and stay False. self_armed = False + # Whether the keystone-gated self-arm record is written for this loop: a + # crew/member self-arm, or a conductor slot armed by its own turn -- the + # record is what lets that loop's wake reset the conversation + # (``session_directive_apply``). The ``self_armed`` bit's meaning is unchanged. + self_recorded = False if is_channel_key(slot_key): # Channel-bound loop (Slack / Discord ...). Validate the session is # routable so a nudge fired later has somewhere to reply. @@ -1074,6 +1079,10 @@ def _webex_admission() -> bool: return _deny(external_arm_refusal(slot_mode), 409) self_armed = True _audit("self_armed") + self_recorded = self_armed or ( + str(getattr(authorized_slot, "agent", "") or "") in WAKE_RESET_AGENTS + and is_self_arm(slot_key, initiator_slot_key) + ) if str(getattr(authorized_slot, "memory_mode", "persistent")) != "persistent": return _deny("incognito and temporary sessions cannot host automation loops", 403) @@ -1234,7 +1243,7 @@ def _critical_invoked_audit() -> None: ): return _deny("monitor authorization requires a rollback-capable loop store", 503) reserved_loop_id: str | None = None - if self_armed or owner_credentials_grant: + if self_recorded or owner_credentials_grant: # Reserve a COLLISION-FREE id before touching the trust record. The # record is an upsert keyed by loop id, so an id already held by a live # loop would overwrite that loop's entry -- and the add's conflict @@ -1253,13 +1262,18 @@ def _critical_invoked_audit() -> None: break if reserved_loop_id is None: return _deny("could not reserve a loop id — loop not armed", 503) - if self_armed: + if self_recorded: try: assert reserved_loop_id is not None await asyncio.to_thread(record_self_arm, reserved_loop_id, slot_key) except OSError: - logger.error("self-arm record unavailable; loop not armed", exc_info=True) - return _deny("self-arm record unavailable — loop not armed", 503) + if self_armed: + logger.error("self-arm record unavailable; loop not armed", exc_info=True) + return _deny("self-arm record unavailable — loop not armed", 503) + # An ordinary slot needs no record to be armed: without one, its + # wakes are simply refused a conversation reset (fail closed there). + logger.warning("self-arm record unavailable; loop armed unrecorded", exc_info=True) + self_recorded = False if owner_credentials_grant: assert monitor is not None and reserved_loop_id is not None @@ -1272,7 +1286,7 @@ def _critical_invoked_audit() -> None: monitor.target, ) except OSError: - if self_armed: + if self_recorded: await asyncio.to_thread(forget_self_arm, reserved_loop_id) logger.error("monitor credential provenance unavailable; loop not armed", exc_info=True) return _deny("monitor credential authorization unavailable — loop not armed", 503) @@ -1280,7 +1294,7 @@ def _critical_invoked_audit() -> None: def _forget_orphaned_trust() -> None: if reserved_loop_id is None: return - if self_armed: + if self_recorded: forget_self_arm(reserved_loop_id) # never raises if owner_credentials_grant: autonudge_provider_trust.forget_monitor_owner_credentials(reserved_loop_id) diff --git a/src/kiro_crew/autonudge_selfarm.py b/src/kiro_crew/autonudge_selfarm.py index 05e47a276314..f146a345e841 100644 --- a/src/kiro_crew/autonudge_selfarm.py +++ b/src/kiro_crew/autonudge_selfarm.py @@ -1,4 +1,9 @@ -"""Authenticated record of which nudge loops a crew/member session armed ITSELF. +"""Authenticated record of which nudge loops a session armed ITSELF. + +Written when a crew/member slot, or a slot running one of +:data:`WAKE_RESET_AGENTS`, arms a loop from its own turn. Two readers: the +crew/member fire-time guard below, and the conductor wake-reset gate +(``session_directive_apply._refuse_unvouched_wake_reset``). ``NudgeLoop.self_armed`` is the one bit that relaxes the crew/member external-arm refusal at fire time (``GatewayOrchestrator._fire_dashboard_nudge``), @@ -47,6 +52,10 @@ logger = logging.getLogger(__name__) +#: The agents whose patrol wake may drop its own chat: the goal conductor and its +#: deprecated alias name (``conductor_agents.DEPRECATED_AGENT_SPECS``). +WAKE_RESET_AGENTS: frozenset[str] = frozenset({"kirocrew-conductor", "kirocrew-ledger-conductor"}) + SELF_ARM_RECORD_NAME = "autonudge-self-armed.json" _LOCK_NAME = SELF_ARM_RECORD_NAME + ".lock" diff --git a/src/kiro_crew/builtin_skills/goal-conductor/SKILL.md b/src/kiro_crew/builtin_skills/goal-conductor/SKILL.md index 7b24786d5f8f..a1fa720757f1 100644 --- a/src/kiro_crew/builtin_skills/goal-conductor/SKILL.md +++ b/src/kiro_crew/builtin_skills/goal-conductor/SKILL.md @@ -443,6 +443,33 @@ Both are needs-human stops (see the checklist): the loop stays armed, and the first cycle after the answer resumes. Put `items used: N of 20` in every round report. +**Then drop your chat.** Every patrol turn re-sends your whole conversation, +and a conductor that runs for days pays for it on every quiet cycle. Your state +already lives in the two ledgers, and each wake carries their snapshot. So once +the next round is dispatched, end that same turn with two calls, in order: + +1. `session_ledger_record` with everything the next turn needs: + - `goal` — the goal, one line; + - `next` — the round number, and for each open item its item id, its + worker key and its PR number (or "no PR yet"); + - `patrol_base` — unchanged from Patrol (`cycles= runtime=`). + + Check the item ids, worker keys and PRs against a fresh `work_ledger_read`, + not against memory: the work ledger is the record, `next` is the pointer. +2. `reset_conversation`, as the last call of the turn. It lands at the turn + boundary; the next wake starts from the ledger snapshot alone. + +Never reset when: + +- a question to the user is unanswered — the answer would arrive in a chat + that no longer holds the question; +- the round is still running — reset only at a round close; +- the session ledger write failed — the reset would drop the only copy. + +The gateway refuses a reset from a loop it cannot vouch for, or while a +question card or tool approval is pending. A refused reset changes nothing: +carry on in the same chat and try again at the next round close. + ### Goal changes mid-flight The user can message you any time. Apply a changed goal **at the round @@ -638,7 +665,8 @@ what the composer renders: granted by name too, and only these: `monitor_start`, `monitor_update`, `autonudge_stop`, `wait`, `resource_status`, `list_sessions`, `session_ledger_read`, `session_ledger_record`, `skill_search`, `skill_fetch`, - `select_crew`, `send_message`, `send_notification`, `ask_question`. That covers + `select_crew`, `send_message`, `send_notification`, `ask_question`, + `reset_conversation`. That covers every core call this procedure asks you to make; **any other core tool is mounted but prompts**, including `task_run`, `workflow_run` and the `spawn_*` family, which this charter forbids you to route a work item to in the first diff --git a/src/kiro_crew/dashboard/chat_runner.py b/src/kiro_crew/dashboard/chat_runner.py index 9d66f41c99b7..8cdf385a4bfc 100644 --- a/src/kiro_crew/dashboard/chat_runner.py +++ b/src/kiro_crew/dashboard/chat_runner.py @@ -5036,6 +5036,18 @@ async def _consume_pending_reset( slot.key, ) return torn_down + from kiro_crew.dashboard.session_directive_apply import _slot_has_pending_interaction + + if getattr(slot, "_pending_discard_from_wake", False) and _slot_has_pending_interaction( + state, slot + ): + # A patrol wake's reset never lands while a person is being asked + # something: the answer would reach a chat with no memory of it. + logger.debug( + "Deferring queued conversation discard for slot %s: question or approval pending", + slot.key, + ) + return torn_down try: # ``skip_if_busy`` rather than a busy-probe here: the check and the # teardown have to be ONE atomic step under the session lock. A @@ -5066,6 +5078,7 @@ async def _consume_pending_reset( slot.forget_session_model_state() if slot._pending_discard_conversation_key == discard_key: slot._pending_discard_conversation_key = None + slot._pending_discard_from_wake = False # The discarded conversation's MCP report describes a session that no # longer exists; the fresh one will report for itself. if slot.clear_mcp_report(): diff --git a/src/kiro_crew/dashboard/session_directive_apply.py b/src/kiro_crew/dashboard/session_directive_apply.py index 452c9ab57c07..4166761457e3 100644 --- a/src/kiro_crew/dashboard/session_directive_apply.py +++ b/src/kiro_crew/dashboard/session_directive_apply.py @@ -369,8 +369,20 @@ async def apply_session_directive_outcome( f"Error: {kind} targets this turn's chat slot, and this turn " f"holds none (this turn is {session_key!r}). Nothing was changed." ) - if kind in _USER_SURFACE_DIRECTIVES and ( - not producer_is_user_facing or not _has_user_surface(session_key) + # The one non-human producer a user-surface directive admits: a conductor's + # patrol wake dropping its own chat at a round close. Admission here only + # skips the human-turn refusal below; ``_refuse_unvouched_wake_reset`` + # decides it, before anything is queued. + wake_reset = bool( + kind == "reset_conversation" + and producer_is_self_wake + and not producer_is_user_facing + and _has_user_surface(session_key) + ) + if ( + kind in _USER_SURFACE_DIRECTIVES + and not wake_reset + and (not producer_is_user_facing or not _has_user_surface(session_key)) ): # A cron turn can run on a user's slot and a sub-agent can share its # parent's slot. Positive admission prevents either from silently @@ -396,8 +408,10 @@ async def apply_session_directive_outcome( # deactivated, by raising that bound (``_monitor_update``). # Everything else -- a cron injection, an app-driven turn, a # sub-agent sharing the slot -- carries neither mark and is refused. This is - # NOT the user-surface gate below: ``set_project`` / ``reset_conversation`` - # stay human-only, a wake must never retarget the slot's project. + # NOT the user-surface gate above: ``set_project`` / ``chat_tag`` stay + # human-only, a wake must never retarget the slot's project, and + # ``reset_conversation`` admits a wake only through + # ``_refuse_unvouched_wake_reset``. self_arm_ok = bool(producer_is_user_facing or producer_is_self_wake) try: if producer_is_self_wake and kind in _ARMING_DIRECTIVES: @@ -455,7 +469,16 @@ async def apply_session_directive_outcome( elif kind == "set_project": result = await _set_project(state, slot, args) elif kind == "reset_conversation": - result = await _reset_conversation(slot, session_key, args) + if wake_reset: + await _refuse_unvouched_wake_reset(state, slot, session_key, producer_wake_loop_id) + result = await _reset_conversation(slot, session_key, args, from_wake=wake_reset) + if wake_reset: + logger.warning( + "session-directive: patrol wake reset the conversation for " + "session_key=%r loop_id=%r", + session_key, + producer_wake_loop_id, + ) elif kind == "chat_tag": result = await _apply_chat_tag(state, slot, session_key, args) elif kind == "suggest_followup": @@ -1570,7 +1593,79 @@ def _validate() -> tuple[str, str | None, bool]: ) -async def _reset_conversation(slot: Any, session_key: str, args: dict[str, Any]) -> str: +def _slot_has_pending_interaction(state: Any, slot: Any) -> bool: + """Whether *slot* waits on a person: a question card or a tool approval. + + Reads the same registries the dashboard's waiting lanes do: the slot's + question records (blocking and non-blocking), its own approval futures, and + the gateway coordinator's approvals owned by the slot. + """ + if getattr(slot, "_question_pending", None): + return True + futures = getattr(slot, "_approval_futures", None) or {} + if any(not fut.done() for fut in futures.values()): + return True + pending_for = getattr(state, "pending_coordinator_approvals", None) + return bool(callable(pending_for) and pending_for(getattr(slot, "key", ""))) + + +async def _refuse_unvouched_wake_reset( + state: Any, slot: Any, session_key: str, wake_loop_id: str +) -> None: + """Refuse a patrol wake's ``reset_conversation`` unless the gateway can vouch for it. + + Admitted only when the slot runs a conductor agent, the wake comes from this + slot's CURRENT, active loop, the + keystone-gated self-arm record says that loop was armed by this slot's own + turn (so never a cron, a sub-agent, a person's dashboard arm or the + bind-time default patrol), and nothing in the slot waits on a person -- a + reset would drop the context the answer is meant for. + """ + from kiro_crew.autonudge import get_instance + from kiro_crew.autonudge_selfarm import WAKE_RESET_AGENTS, is_recorded_self_arm + + refused = "Conversation NOT reset: " + if str(getattr(slot, "agent", "") or "") not in WAKE_RESET_AGENTS: + raise _DirectiveDenied( + refused + "only a conductor's patrol wake may drop its own conversation." + ) + + def _live_loop() -> Any: + svc = get_instance() + binding = _binding(session_key) + current = svc.get_by_slot(binding) if svc is not None and binding else None + if ( + not wake_loop_id + or current is None + or getattr(current, "id", "") != wake_loop_id + or not getattr(current, "active", False) + ): + raise _DirectiveDenied( + refused + "the loop that delivered this wake is not this session's live monitor." + ) + return current + + current = _live_loop() + vouched = await asyncio.to_thread( + is_recorded_self_arm, wake_loop_id, str(getattr(current, "slot_key", "")) + ) + if not vouched: + raise _DirectiveDenied( + refused + "the loop that delivered this wake was not armed by this session's " + "own turn, so its wake may not drop the conversation." + ) + # Re-read after the await: a Pause, Stop or replacement can land while the + # trust read is off-loop. From here to the queued flag nothing yields. + _live_loop() + if _slot_has_pending_interaction(state, slot): + raise _DirectiveDenied( + refused + "a question card or a tool approval is still pending in this session." + ) + + +async def _reset_conversation( + slot: Any, session_key: str, args: dict[str, Any], *, from_wake: bool = False +) -> str: """Queue a conversation discard for this slot's next turn boundary. Deferred rather than applied here because the caller is mid-turn: a discard @@ -1592,6 +1687,9 @@ async def _reset_conversation(slot: Any, session_key: str, args: dict[str, Any]) in the tab: the record is the user's, the context was the conversation's. """ slot._pending_discard_conversation_key = session_key + # A wake's discard re-checks, where it lands, that nobody is waiting on an + # answer (``chat_runner``); a person's own reset does not. + slot._pending_discard_from_wake = from_wake return ( "Conversation reset queued. It lands at a turn boundary — normally the " "end of this turn, later if a turn is still in flight on the session or " diff --git a/src/kiro_crew/dashboard/state.py b/src/kiro_crew/dashboard/state.py index fbbc0f133dcf..a18a80fd1b80 100644 --- a/src/kiro_crew/dashboard/state.py +++ b/src/kiro_crew/dashboard/state.py @@ -2817,6 +2817,7 @@ class _ChatSlot: "_stop_escalated_card_id", "_pending_reset_history_key", "_pending_discard_conversation_key", + "_pending_discard_from_wake", "_pending_model_pick", "_eager_spawn_task", "_eager_spawn_failures", @@ -3465,6 +3466,9 @@ def __init__( # called from inside the turn it wants to end, and the immediate route # refuses a busy slot rather than tearing down a turn mid-write. self._pending_discard_conversation_key: str | None = None + # True when a patrol wake queued that discard: it then also waits, at + # the boundary, while a question card or tool approval is pending. + self._pending_discard_from_wake: bool = False # Set by session_set_model on an idle slot; consumed at the start of the # next turn (session_control.apply_pending_model_pick), which re-checks # the caller's authorization and commits the model in one synchronous diff --git a/src/kiro_crew/mcp_tools/control.py b/src/kiro_crew/mcp_tools/control.py index 6504996b8bc5..08a2720bdf24 100644 --- a/src/kiro_crew/mcp_tools/control.py +++ b/src/kiro_crew/mcp_tools/control.py @@ -954,7 +954,10 @@ def schemas(*, names_only: bool = False) -> list[dict[str, Any]]: "\n\n" "Restrictions: headless callers (cron jobs, subagents, task runners) " "are rejected — a cron turn can run on a user's dashboard slot and a " - "subagent shares its parent's slot, so neither may wipe it." + "subagent shares its parent's slot, so neither may wipe it. A " + "monitor wake is rejected too, unless it comes from the session's " + "own live loop that the session armed itself and no question card " + "or tool approval is pending." "\n\n" "The reset lands at a turn BOUNDARY, not inline, so this tool returns " "cleanly without tearing down its own caller mid-write. Normally that " diff --git a/test/test_agent_refactor_contracts.py b/test/test_agent_refactor_contracts.py index bfd313ea51f8..b3112c093ab5 100644 --- a/test/test_agent_refactor_contracts.py +++ b/test/test_agent_refactor_contracts.py @@ -64,9 +64,9 @@ "_BUNDLED_CFG_DIR": "value host", "_CC_MCP_JSON": "value host", "_CONDUCTOR_AGENT_FILENAME": "value str 923f5ca0627d569f", - "_CONDUCTOR_CORE_GRANTS": "value tuple 7ca1ae8facf7fc35", + "_CONDUCTOR_CORE_GRANTS": "value tuple 7152a6eb169c7c40", "_CONDUCTOR_DASHBOARD_GRANTS": "value tuple 0b859d2b54e84503", - "_CONDUCTOR_SYSTEM_PROMPT": "value str 1a9f0b08e1074817", + "_CONDUCTOR_SYSTEM_PROMPT": "value str 9b04f32e268ef3fa", "_CREW_ONLY_HOOK_EVENTS": "value frozenset 9d900cfb866f983a", "_DEFAULT_KIRO_HOOKS_DIR": "value host", "_DEFAULT_SPEC_OBSERVATION_ATTEMPTS": "value int 4e07408562bedb8b", diff --git a/test/test_agent_refactor_spec_bytes.py b/test/test_agent_refactor_spec_bytes.py index 4be201ef5760..ee6bbce61ef6 100644 --- a/test/test_agent_refactor_spec_bytes.py +++ b/test/test_agent_refactor_spec_bytes.py @@ -404,12 +404,12 @@ def materialize(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str) "events": "01735c00e0c643328e919d7c144abc1ebf0423198c2411f6fff1c1b9d490fed4", "files": { "kirocrew-dashboard-manager.json": "19ba319895584c84459f46e7c343b60f098739ea91598f3603a8a97e1088e548", - "kirocrew-conductor.json": "ca0497feaab4c6f57806041223e6ab655ac197a9ed1cbcbe0f3911f980bf8955", + "kirocrew-conductor.json": "69904c7620745aab85461373adcd2bd9a13144f1c608bd0510413ddc0c1d1435", "kirocrew-dashboard-author.json": "cbe7acbded8bd0255c466d21fd8e990014452f9b3cd4afb9b74d5ee6354b3366", "kirocrew-guest.json": "3ac87f33f4968a07c6f3dc45b29922d7002d38e93caabefa5005a7a1794fce38", "kirocrew-heartbeat.json": "7a212fc757669b2be5d1b141d58bac4bafc3dd9e19e206a68994f20f4c4f6ed4", "kirocrew-knowledge.json": "efcde26b5961417a7c9ed665ee20038461b5283b74099423cb8ee474400335f5", - "kirocrew-ledger-conductor.json": "a0d4e412a3f61ca2df05ab2269a55856d53747b73e9abe441a62a2ee9231e476", + "kirocrew-ledger-conductor.json": "b27a9e1e59cb22259e9fc44910717f2f8bd943e176ef8bedd0f0d7ac4dabab64", "kirocrew-lite.json": "0fda63413108908840a34020f9b11d1418f283a1dca92d14a748f8e25fe3ebee", "kirocrew-pipeline-conductor.json": "15f792950cbe8a2957df0a7977fc199e6ca77b6ef65826ea9512023d2ca77b68", "kirocrew-research.json": "95db2f43ca38f7033495b8bd79d989fda7bb6147bc79ee0dc3b954b961fe0f94", @@ -425,12 +425,12 @@ def materialize(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str) "events": "e56f172582bf1559f232e7ffdff02aaeb09009f1ea03ab445d8950c71fddb40c", "files": { "kirocrew-dashboard-manager.json": "19ba319895584c84459f46e7c343b60f098739ea91598f3603a8a97e1088e548", - "kirocrew-conductor.json": "ca0497feaab4c6f57806041223e6ab655ac197a9ed1cbcbe0f3911f980bf8955", + "kirocrew-conductor.json": "69904c7620745aab85461373adcd2bd9a13144f1c608bd0510413ddc0c1d1435", "kirocrew-dashboard-author.json": "cbe7acbded8bd0255c466d21fd8e990014452f9b3cd4afb9b74d5ee6354b3366", "kirocrew-guest.json": "3ac87f33f4968a07c6f3dc45b29922d7002d38e93caabefa5005a7a1794fce38", "kirocrew-heartbeat.json": "7a212fc757669b2be5d1b141d58bac4bafc3dd9e19e206a68994f20f4c4f6ed4", "kirocrew-knowledge.json": "efcde26b5961417a7c9ed665ee20038461b5283b74099423cb8ee474400335f5", - "kirocrew-ledger-conductor.json": "a0d4e412a3f61ca2df05ab2269a55856d53747b73e9abe441a62a2ee9231e476", + "kirocrew-ledger-conductor.json": "b27a9e1e59cb22259e9fc44910717f2f8bd943e176ef8bedd0f0d7ac4dabab64", "kirocrew-lite.json": "0fda63413108908840a34020f9b11d1418f283a1dca92d14a748f8e25fe3ebee", "kirocrew-pipeline-conductor.json": "15f792950cbe8a2957df0a7977fc199e6ca77b6ef65826ea9512023d2ca77b68", "kirocrew-research.json": "95db2f43ca38f7033495b8bd79d989fda7bb6147bc79ee0dc3b954b961fe0f94", @@ -446,12 +446,12 @@ def materialize(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str) "events": "69ccf91fca126b49eb87a7fff1bbc60fcb77257837ba68b80e430e0e7663513e", "files": { "kirocrew-dashboard-manager.json": "b0acd94a2340838b47536162b679deb66d8d8ff2876d3352437ca15248b18356", - "kirocrew-conductor.json": "395a99b5dcbc35a8776e456ff3fe9538e95a86c5fc8d647a07f64b31d557bc9f", + "kirocrew-conductor.json": "aa427a68dbbf7001830735d8d395adfa43f4273ead308a7a841559161d9c885e", "kirocrew-dashboard-author.json": "359ad2ebfe08f8a558f0323f5eabf2a734d11ca4ed27c2bcfd7c2a49de328941", "kirocrew-guest.json": "3ac87f33f4968a07c6f3dc45b29922d7002d38e93caabefa5005a7a1794fce38", "kirocrew-heartbeat.json": "7a212fc757669b2be5d1b141d58bac4bafc3dd9e19e206a68994f20f4c4f6ed4", "kirocrew-knowledge.json": "efcde26b5961417a7c9ed665ee20038461b5283b74099423cb8ee474400335f5", - "kirocrew-ledger-conductor.json": "0e5acf6902f5fa54bcb1054a752c9a24a660045398f112c8bb75a14a3b279e6f", + "kirocrew-ledger-conductor.json": "ae0f5a5932a88ca53323148a10e2a2af750a0744d3c96b45588a3ab651533491", "kirocrew-lite.json": "0fda63413108908840a34020f9b11d1418f283a1dca92d14a748f8e25fe3ebee", "kirocrew-pipeline-conductor.json": "df61fdd14e749c5c5170a8a375f09dcd925126cfa832c651a125684c82f6ec2f", "kirocrew-research.json": "7f8cdc2b1236723558fcf2a72e285a516cc57295b5a4d333c60f2abff52cd7e9", @@ -469,12 +469,12 @@ def materialize(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str) "events": "0a861cfa593edb1b0684989f72d3776369d42cff9307bc35a9b6b403a0149c33", "files": { "kirocrew-dashboard-manager.json": "19ba319895584c84459f46e7c343b60f098739ea91598f3603a8a97e1088e548", - "kirocrew-conductor.json": "395a99b5dcbc35a8776e456ff3fe9538e95a86c5fc8d647a07f64b31d557bc9f", + "kirocrew-conductor.json": "aa427a68dbbf7001830735d8d395adfa43f4273ead308a7a841559161d9c885e", "kirocrew-dashboard-author.json": "359ad2ebfe08f8a558f0323f5eabf2a734d11ca4ed27c2bcfd7c2a49de328941", "kirocrew-guest.json": "3ac87f33f4968a07c6f3dc45b29922d7002d38e93caabefa5005a7a1794fce38", "kirocrew-heartbeat.json": "7a212fc757669b2be5d1b141d58bac4bafc3dd9e19e206a68994f20f4c4f6ed4", "kirocrew-knowledge.json": "efcde26b5961417a7c9ed665ee20038461b5283b74099423cb8ee474400335f5", - "kirocrew-ledger-conductor.json": "0e5acf6902f5fa54bcb1054a752c9a24a660045398f112c8bb75a14a3b279e6f", + "kirocrew-ledger-conductor.json": "ae0f5a5932a88ca53323148a10e2a2af750a0744d3c96b45588a3ab651533491", "kirocrew-lite.json": "0fda63413108908840a34020f9b11d1418f283a1dca92d14a748f8e25fe3ebee", "kirocrew-pipeline-conductor.json": "df61fdd14e749c5c5170a8a375f09dcd925126cfa832c651a125684c82f6ec2f", "kirocrew-research.json": "73ebc574c2e06451ecf999e408277952084e0ace9c14dbb05d92279441c9e461", @@ -490,12 +490,12 @@ def materialize(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str) "events": "7475ef17e9a3bf2213ec617929886924d72166b630429b260083cbc967e282a8", "files": { "kirocrew-dashboard-manager.json": "19ba319895584c84459f46e7c343b60f098739ea91598f3603a8a97e1088e548", - "kirocrew-conductor.json": "aeac4fe880e72c5ad6671c034573ef1247b78ae0e9c5469e8a43a9873f72d402", + "kirocrew-conductor.json": "b213549c9b6f8b359a4659486701baf7294f1a47ae4a51f7b6ddd4a87d0b4a4b", "kirocrew-dashboard-author.json": "cbe7acbded8bd0255c466d21fd8e990014452f9b3cd4afb9b74d5ee6354b3366", "kirocrew-guest.json": "3ac87f33f4968a07c6f3dc45b29922d7002d38e93caabefa5005a7a1794fce38", "kirocrew-heartbeat.json": "7a212fc757669b2be5d1b141d58bac4bafc3dd9e19e206a68994f20f4c4f6ed4", "kirocrew-knowledge.json": "efcde26b5961417a7c9ed665ee20038461b5283b74099423cb8ee474400335f5", - "kirocrew-ledger-conductor.json": "fdfb5c54a05e97ddd0fff3832bcd564f472c492c9ac3313be0a94975063a277e", + "kirocrew-ledger-conductor.json": "07401e43c16833a76040d9778a67a1ec250db07eff7539c4c2883ea95fb3ab97", "kirocrew-lite.json": "0fda63413108908840a34020f9b11d1418f283a1dca92d14a748f8e25fe3ebee", "kirocrew-pipeline-conductor.json": "15f792950cbe8a2957df0a7977fc199e6ca77b6ef65826ea9512023d2ca77b68", "kirocrew-research.json": "ad8e9fd513c46576706a7e1e20f457edc7cc12269253f0b1c49e70822ad2c35c", @@ -511,12 +511,12 @@ def materialize(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str) "events": "7f89fffedd78c7e8f925b7a24ba93a8151c3a6c28f72a0a3625efc7819873e33", "files": { "kirocrew-dashboard-manager.json": "19ba319895584c84459f46e7c343b60f098739ea91598f3603a8a97e1088e548", - "kirocrew-conductor.json": "6996ea7b4b278b083c65f385cd0f5bbd13b57e86e6d7dfb0bd26bcbaf3dd624c", + "kirocrew-conductor.json": "97f1e8101d83f80ef2e2fca3dfcd10ba7ca7cf717a0ccede8e30e72e5d00249a", "kirocrew-dashboard-author.json": "816d5e5dd9988c2122f0c2363110deeb3f6384a41400e478ee617e9dfbe4fef3", "kirocrew-guest.json": "3ac87f33f4968a07c6f3dc45b29922d7002d38e93caabefa5005a7a1794fce38", "kirocrew-heartbeat.json": "7a212fc757669b2be5d1b141d58bac4bafc3dd9e19e206a68994f20f4c4f6ed4", "kirocrew-knowledge.json": "efcde26b5961417a7c9ed665ee20038461b5283b74099423cb8ee474400335f5", - "kirocrew-ledger-conductor.json": "db66c24e891c51173339d22f5020d9612ccfa9690fa401112abc3d7ff8424767", + "kirocrew-ledger-conductor.json": "c8738c33bf127320fe9a529378da1f77ad5b22ac4bfbf353f88dd01489bfbe6a", "kirocrew-lite.json": "0fda63413108908840a34020f9b11d1418f283a1dca92d14a748f8e25fe3ebee", "kirocrew-pipeline-conductor.json": "d2b625fae62dd96700adad19b15a877e98e8eb541ec0f4431ad394fa57848408", "kirocrew-research.json": "bfa2bd9e571af9040c35d0ff1394d5248e504b8ff6888274f8c3b9071ce03e89", @@ -532,12 +532,12 @@ def materialize(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str) "events": "0a861cfa593edb1b0684989f72d3776369d42cff9307bc35a9b6b403a0149c33", "files": { "kirocrew-dashboard-manager.json": "4b96a77d13a14751d940d8f1d25ab578674db0fdf88e14222bf01b3cc5c86cd8", - "kirocrew-conductor.json": "14eba9ea393872c3fcff065abc1b7c8349f9d8c5e3f836f82f72a93fe2ff6420", + "kirocrew-conductor.json": "8a5cb2e9ed5a08b1b0c8ac48b0c2fd9969bc88894fbc9ab5954b9b31546c8c7a", "kirocrew-dashboard-author.json": "d44d7f9bbb91f12cd6107609ca7c80b7bf81d6656bf884192e6c97241d39821d", "kirocrew-guest.json": "2423a7b447fbcedec2a64ab54a89d181cb2357456c8ddcfc189dc2afe3525780", "kirocrew-heartbeat.json": "6dbd5042238c4b0565f250dd4e235f0f77b01f7d7e6091a127a29ec25e183cc3", "kirocrew-knowledge.json": "5275c0f70b6b42581c9c9841a572c16673b3a5ede1317936f4d4d870e2a883a0", - "kirocrew-ledger-conductor.json": "270fac427dbbca23bb4a99706667b4983fb5f082bffb8234ca7ba2a74b859ebe", + "kirocrew-ledger-conductor.json": "8f53c18731bfbd22aae1a08cfe1c9d975c5b780a1ca19325f3d7f67e4eb7b4d1", "kirocrew-lite.json": "0fda63413108908840a34020f9b11d1418f283a1dca92d14a748f8e25fe3ebee", "kirocrew-pipeline-conductor.json": "eeb3d7c5c5547a0bde29b6a14f1bbd7daba80ef34ad95faebe316c6f60ca14aa", "kirocrew-research.json": "76f1490c68081e1b3bc5454f6b6b1a2e7c833b84d19c401652ec03639d5d3d01", @@ -553,12 +553,12 @@ def materialize(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str) "events": "4331a4594c606ff23230558f9f6a6fc14e0fe3b58842e3365bcd40c4150d5d0f", "files": { "kirocrew-dashboard-manager.json": "19ba319895584c84459f46e7c343b60f098739ea91598f3603a8a97e1088e548", - "kirocrew-conductor.json": "8d45dca878c8fddb4937d1164437ea41c4239f13ab05e07e0381dbeead71ef02", + "kirocrew-conductor.json": "c06618472a32f3ff0f43353a0531d30c4e27526c156f47d905b808b099b0564b", "kirocrew-dashboard-author.json": "d867f2989cb8864b75c88ebfb052c6131ebe1ab123a9020329273edb296cd499", "kirocrew-guest.json": "3ac87f33f4968a07c6f3dc45b29922d7002d38e93caabefa5005a7a1794fce38", "kirocrew-heartbeat.json": "7a212fc757669b2be5d1b141d58bac4bafc3dd9e19e206a68994f20f4c4f6ed4", "kirocrew-knowledge.json": "efcde26b5961417a7c9ed665ee20038461b5283b74099423cb8ee474400335f5", - "kirocrew-ledger-conductor.json": "8a040bcf6850c448c02ee34c791cd65554d6ad0ce41b6cb0b9a6174394e92023", + "kirocrew-ledger-conductor.json": "0a09d70d3fed148486c3928f5d79ba9a39eb2b17190033e37c4eb8742a0635e4", "kirocrew-lite.json": "0fda63413108908840a34020f9b11d1418f283a1dca92d14a748f8e25fe3ebee", "kirocrew-pipeline-conductor.json": "ecdb121fc3044ec746ae1ec6dc1ad587c4267999dc8e6f084a72a4d89b3b9016", "kirocrew-research.json": "6347bfc693d07431fec38ad367d8fef920f9a1831d1d2bc083de293b2b3f7899", diff --git a/test/test_autonudge_member_self_arm.py b/test/test_autonudge_member_self_arm.py index 40d1ef01721f..cb5dd1ec68ed 100644 --- a/test/test_autonudge_member_self_arm.py +++ b/test/test_autonudge_member_self_arm.py @@ -1426,9 +1426,13 @@ async def test_an_ordinary_slot_is_untouched_by_the_rule(self) -> None: @pytest.mark.asyncio async def test_a_self_wake_does_not_unlock_the_user_surface_directives() -> None: - """The wake mark is self-arm provenance ONLY. ``set_project`` and - ``reset_conversation`` stay behind the authenticated-human gate: a loop's - wake must never retarget the slot's project or discard its conversation.""" + """The wake mark is self-arm provenance ONLY. ``set_project`` stays behind + the authenticated-human gate: a loop's wake must never retarget the slot's + project. + + ``reset_conversation`` is left out of this sentence on purpose: a + conductor's own vouched patrol wake may drop its chat at a round close. That + one exception and its refusals are pinned in test_conductor_wake_reset.py.""" with patch.object(sda, "_audit") as audit: result = await sda.apply_session_directive( SimpleNamespace(), diff --git a/test/test_chat_runner_coverage.py b/test/test_chat_runner_coverage.py index 202366936c2b..ba42ee6ffffd 100644 --- a/test/test_chat_runner_coverage.py +++ b/test/test_chat_runner_coverage.py @@ -2003,6 +2003,39 @@ async def test_discard_passes_replay_through_and_clears_the_flag(self, tmp_path) ) assert slot._pending_discard_conversation_key is None + @pytest.mark.asyncio + async def test_a_wake_discard_waits_while_a_question_is_pending(self, tmp_path): + """A patrol wake's reset is refused at queue time while someone is being + asked something; it must not land later into that state either.""" + state, slot = _state(tmp_path), _slot() + slot._pending_discard_conversation_key = "dashboard:chat-cov-1" + slot._pending_discard_from_wake = True + slot._question_pending = {"card-1": {"blocking": False}} + + torn_down = await chat_runner._consume_pending_reset(state, slot, allow_discard=True) + + assert torn_down is False + state.sessions.discard_conversation.assert_not_awaited() + assert slot._pending_discard_conversation_key == "dashboard:chat-cov-1" + + slot._question_pending = {} + await chat_runner._consume_pending_reset(state, slot, allow_discard=True) + + state.sessions.discard_conversation.assert_awaited_once() + assert slot._pending_discard_conversation_key is None + assert slot._pending_discard_from_wake is False + + @pytest.mark.asyncio + async def test_a_persons_discard_does_not_wait_on_a_pending_question(self, tmp_path): + state, slot = _state(tmp_path), _slot() + slot._pending_discard_conversation_key = "dashboard:chat-cov-1" + slot._question_pending = {"card-1": {"blocking": False}} + + await chat_runner._consume_pending_reset(state, slot, allow_discard=True) + + state.sessions.discard_conversation.assert_awaited_once() + assert slot._pending_discard_conversation_key is None + @pytest.mark.asyncio async def test_the_discard_always_asks_for_no_replay(self, tmp_path): """One value, not a plumbed choice: replaying the transcript into the diff --git a/test/test_conductor_agent.py b/test/test_conductor_agent.py index 26aac644fb16..8571cb3f3011 100644 --- a/test/test_conductor_agent.py +++ b/test/test_conductor_agent.py @@ -248,8 +248,7 @@ def test_core_grants_are_named_verbs_never_the_whole_server(self, tmp_path, monk case, because they reach ``allowed_tools_to_permissions`` as separate patterns and a family could classify differently: persistent work (``task_run``, the ``workflow_*`` group), agent fan-out (the ``spawn_*`` - group), session and workspace mutation (``set_project``, - ``reset_conversation``), egress (``deploy_artifact``, ``browser``, + group), workspace mutation (``set_project``), egress (``deploy_artifact``, ``browser``, ``ops_mission_control_api``) and the ``artifact_*`` writes. Spelled as literals, deliberately: deriving the expectation from @@ -274,6 +273,10 @@ def test_core_grants_are_named_verbs_never_the_whole_server(self, tmp_path, monk "@kirocrew-core/send_notification", "@kirocrew-core/ask_question", "@kirocrew-core/nothing_to_do", + # Granted on purpose: the conductor drops its own chat at a round + # close. The directive consumer still refuses it from any wake it + # cannot vouch for (test_conductor_wake_reset.py). + "@kirocrew-core/reset_conversation", } # The bare server is what this test exists to keep out: it would re-grant # all 74 registered core tools, including every verb named below. @@ -290,9 +293,9 @@ def test_core_grants_are_named_verbs_never_the_whole_server(self, tmp_path, monk "spawn_sub_agents", "spawn_steer", "spawn_continue", - # Mutating the caller's own session or project out from under it. + # Mutating the caller's own project out from under it. + # (``reset_conversation`` moved to the granted set above, on purpose.) "set_project", - "reset_conversation", # Egress and machine reach. "deploy_artifact", "browser", @@ -681,6 +684,7 @@ def test_grants_pass_through_the_governance_ceiling(self, tmp_path, monkeypatch) "@kirocrew-core/send_notification", "@kirocrew-core/ask_question", "@kirocrew-core/nothing_to_do", + "@kirocrew-core/reset_conversation", "@kirocrew-dashboard/chat_folder_tree", "@kirocrew-dashboard/chat_folder_create", "@kirocrew-dashboard/chat_folder_file_self", @@ -712,6 +716,7 @@ def test_kas_permissions_are_derived_from_the_filtered_grants(self, tmp_path, mo "kirocrew-core/monitor_start", "kirocrew-core/monitor_update", "kirocrew-core/nothing_to_do", + "kirocrew-core/reset_conversation", "kirocrew-core/resource_status", "kirocrew-core/select_crew", "kirocrew-core/send_message", @@ -877,6 +882,7 @@ def log_api_access(self, **kw): "@kirocrew-core/send_notification", "@kirocrew-core/ask_question", "@kirocrew-core/nothing_to_do", + "@kirocrew-core/reset_conversation", "@kirocrew-dashboard/chat_folder_tree", "@kirocrew-dashboard/chat_folder_create", "@kirocrew-dashboard/chat_folder_file_self", diff --git a/test/test_conductor_wake_reset.py b/test/test_conductor_wake_reset.py new file mode 100644 index 000000000000..69ba3f2d827b --- /dev/null +++ b/test/test_conductor_wake_reset.py @@ -0,0 +1,416 @@ +"""A conductor's patrol wake may drop its own chat -- and only that wake. + +``reset_conversation`` is a user-surface directive: a turn a person started may +call it. The one non-human producer it admits is a monitor wake that the gateway +can vouch for (``session_directive_apply._refuse_unvouched_wake_reset``): the +wake's loop is this slot's current, active loop, the keystone-gated self-arm +record says the slot armed it itself, and nothing in the slot waits on a person. + +The authorizer half: an ordinary dashboard slot arming itself through the +directive consumer now writes that self-arm record too, so a conductor that is +not in crew/member mode can be vouched for. An outside arm never writes it. +""" + +from __future__ import annotations + +import asyncio +import logging +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from kiro_crew import autonudge, autonudge_authz, autonudge_selfarm +from kiro_crew.autonudge_authz import authorize_and_add_nudge +from kiro_crew.dashboard import session_directive_apply as sda + +SESSION = "dashboard:chat-1" +BINDING = "chat-1" +LOOP_ID = "a1b2c3d4" + + +class _Svc: + """The loop store as the wake gate reads it: one current loop per slot.""" + + def __init__(self, current: Any) -> None: + self.current = current + + def get_by_slot(self, binding: str) -> Any: + return self.current if binding == BINDING else None + + def get_by_id(self, loop_id: str) -> Any: + return None + + +def _loop(loop_id: str = LOOP_ID, *, active: bool = True) -> SimpleNamespace: + return SimpleNamespace(id=loop_id, slot_key=BINDING, active=active) + + +def _slot(**over: Any) -> SimpleNamespace: + base: dict[str, Any] = { + "key": BINDING, + "agent": "kirocrew-conductor", + "_app": "", + "messages": [], + "_question_pending": {}, + "_approval_futures": {}, + "_pending_discard_conversation_key": None, + } + base.update(over) + return SimpleNamespace(**base) + + +def _state(coordinator: list[dict] | None = None) -> SimpleNamespace: + return SimpleNamespace(pending_coordinator_approvals=lambda _key: list(coordinator or [])) + + +@pytest.fixture +def wake_env(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + """A live, self-recorded loop on the slot; each test breaks one fact.""" + env: dict[str, Any] = {"svc": _Svc(_loop()), "recorded": {(LOOP_ID, BINDING)}, "audits": []} + monkeypatch.setattr(autonudge, "get_instance", lambda: env["svc"]) + monkeypatch.setattr( + autonudge_selfarm, + "is_recorded_self_arm", + lambda loop_id, slot_key: (loop_id, slot_key) in env["recorded"], + ) + monkeypatch.setattr(sda, "_binding", lambda key: BINDING if key == SESSION else None) + monkeypatch.setattr(sda, "_has_user_surface", lambda key: key == SESSION) + monkeypatch.setattr(sda, "_audit", lambda key, kind, outcome: env["audits"].append(outcome)) + return env + + +async def _wake_reset(slot: Any, state: Any, *, loop_id: str = LOOP_ID, **flags: Any) -> str: + flags.setdefault("producer_is_self_wake", True) + return await sda.apply_session_directive( + state, + slot, + SESSION, + "reset_conversation", + {}, + producer_wake_loop_id=loop_id, + **flags, + ) + + +# ── admitted ──────────────────────────────────────────────────────────────── + + +@pytest.mark.asyncio +async def test_vouched_wake_queues_the_reset_and_logs_the_loop( + wake_env: dict[str, Any], caplog: pytest.LogCaptureFixture +) -> None: + slot = _slot() + with caplog.at_level(logging.WARNING, logger=sda.logger.name): + result = await _wake_reset(slot, _state()) + assert result.startswith("Conversation reset queued") + assert slot._pending_discard_conversation_key == SESSION + warnings = [r for r in caplog.records if r.levelno == logging.WARNING] + assert any(LOOP_ID in r.getMessage() and SESSION in r.getMessage() for r in warnings) + assert "denied" not in wake_env["audits"] + + +# ── refused: the loop cannot be vouched for ───────────────────────────────── + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("case", "loop_id"), + [ + ("no loop id on the wake", ""), + ("no loop on the slot", LOOP_ID), + ("a different loop is current", LOOP_ID), + ("the loop is stopped", LOOP_ID), + ("the slot did not arm it itself", LOOP_ID), + ], +) +async def test_unvouched_wake_is_refused(wake_env: dict[str, Any], case: str, loop_id: str) -> None: + if case == "no loop on the slot": + wake_env["svc"] = _Svc(None) + elif case == "a different loop is current": + wake_env["svc"] = _Svc(_loop("ffffffff")) + wake_env["recorded"].add(("ffffffff", BINDING)) + elif case == "the loop is stopped": + wake_env["svc"] = _Svc(_loop(active=False)) + elif case == "the slot did not arm it itself": + # A cron, a person's dashboard arm or the bind-time default patrol: a + # live loop with no self-arm record. + wake_env["recorded"].clear() + slot = _slot() + result = await _wake_reset(slot, _state(), loop_id=loop_id) + assert result.startswith("Conversation NOT reset"), case + assert slot._pending_discard_conversation_key is None, case + assert wake_env["audits"][-1] == "denied", case + + +@pytest.mark.asyncio +async def test_the_store_being_down_refuses(wake_env: dict[str, Any]) -> None: + wake_env["svc"] = None + slot = _slot() + result = await _wake_reset(slot, _state()) + assert result.startswith("Conversation NOT reset") + assert slot._pending_discard_conversation_key is None + + +# ── refused: something waits on a person ──────────────────────────────────── + + +@pytest.mark.asyncio +async def test_pending_question_card_refuses(wake_env: dict[str, Any]) -> None: + slot = _slot(_question_pending={"card-1": {"blocking": False}}) + result = await _wake_reset(slot, _state()) + assert "question card or a tool approval" in result + assert slot._pending_discard_conversation_key is None + + +@pytest.mark.asyncio +async def test_pending_slot_approval_refuses(wake_env: dict[str, Any]) -> None: + future: asyncio.Future[bool] = asyncio.get_running_loop().create_future() + slot = _slot(_approval_futures={"ap-1": future}) + result = await _wake_reset(slot, _state()) + assert "question card or a tool approval" in result + assert slot._pending_discard_conversation_key is None + future.cancel() + + +@pytest.mark.asyncio +async def test_settled_slot_approval_does_not_refuse(wake_env: dict[str, Any]) -> None: + future: asyncio.Future[bool] = asyncio.get_running_loop().create_future() + future.set_result(True) + slot = _slot(_approval_futures={"ap-1": future}) + result = await _wake_reset(slot, _state()) + assert result.startswith("Conversation reset queued") + + +@pytest.mark.asyncio +async def test_pending_coordinator_approval_refuses(wake_env: dict[str, Any]) -> None: + slot = _slot() + result = await _wake_reset(slot, _state([{"slot": BINDING}])) + assert "question card or a tool approval" in result + assert slot._pending_discard_conversation_key is None + + +# ── refused: not a wake at all ────────────────────────────────────────────── + + +@pytest.mark.asyncio +async def test_a_turn_with_neither_mark_is_still_refused(wake_env: dict[str, Any]) -> None: + """A cron, app or sub-agent turn carries neither the human nor the wake + mark, so it meets the user-surface refusal exactly as before.""" + slot = _slot() + result = await _wake_reset(slot, _state(), producer_is_self_wake=False) + assert result.startswith("Error: reset_conversation only works from a user-facing session") + assert slot._pending_discard_conversation_key is None + + +@pytest.mark.asyncio +async def test_a_wake_still_may_not_set_the_project(wake_env: dict[str, Any]) -> None: + result = await sda.apply_session_directive( + _state(), + _slot(), + SESSION, + "set_project", + {"path": "/tmp/elsewhere"}, + producer_is_self_wake=True, + producer_wake_loop_id=LOOP_ID, + ) + assert result.startswith("Error: set_project only works from a user-facing session") + + +@pytest.mark.asyncio +async def test_a_human_turn_keeps_its_old_path(wake_env: dict[str, Any]) -> None: + """A person's turn never meets the wake checks: no loop needed, and a + pending card is the person's own business.""" + wake_env["svc"] = _Svc(None) + slot = _slot(_question_pending={"card-1": {"blocking": False}}) + result = await sda.apply_session_directive( + _state(), slot, SESSION, "reset_conversation", {}, producer_is_user_facing=True + ) + assert result.startswith("Conversation reset queued") + + +# ── authorizer: who gets the self-arm record ──────────────────────────────── + + +class _RecordingSvc: + def __init__(self) -> None: + self.added: list[dict[str, Any]] = [] + + def get_by_slot(self, slot_key: str) -> Any: + return None + + def get_by_id(self, loop_id: str) -> Any: + return None + + async def add(self, **kw: Any) -> Any: + self.added.append(kw) + return SimpleNamespace( + id=kw.get("loop_id") or "loop-1", + slot_key=kw["slot_key"], + idle_secs=kw["idle_secs"], + max_cycles=kw["max_cycles"], + monitor=None, + gate=kw.get("gate", False), + ) + + +@pytest.fixture +def arm_env(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str]]: + monkeypatch.setattr( + autonudge_authz, "sel", lambda: SimpleNamespace(log_tool_invocation=lambda **kw: None) + ) + writes: list[tuple[str, str]] = [] + monkeypatch.setattr( + autonudge_authz, "record_self_arm", lambda loop_id, slot: writes.append((loop_id, slot)) + ) + return writes + + +async def _arm(svc: Any, tmp_path: Path, initiator: str, agent: str = "kirocrew-conductor") -> Any: + slot = SimpleNamespace(workspace="default", mode="", memory_mode="persistent", agent=agent) + return await authorize_and_add_nudge( + svc=svc, + state=SimpleNamespace(_slots={BINDING: slot}, sessions=None, channel_transports={}), + slot_key=BINDING, + message="patrol the ledger", + stop_sentinel_path=str(tmp_path / "stop"), + source="mcp-directive", + caller="session-directive", + initiator_slot_key=initiator, + ) + + +@pytest.mark.asyncio +async def test_conductor_slot_arming_itself_is_recorded( + arm_env: list[tuple[str, str]], tmp_path: Path +) -> None: + svc = _RecordingSvc() + loop, error, status = await _arm(svc, tmp_path, BINDING) + assert error is None and status == 200 and loop is not None + assert arm_env == [(loop.id, BINDING)] + assert svc.added[0]["loop_id"] == loop.id + # The crew/member fire-time bit is untouched on an ordinary slot. + assert "self_armed" not in svc.added[0] + + +@pytest.mark.asyncio +async def test_outside_arm_of_a_conductor_slot_is_not_recorded( + arm_env: list[tuple[str, str]], tmp_path: Path +) -> None: + svc = _RecordingSvc() + loop, error, status = await _arm(svc, tmp_path, "") + assert status == 200 and loop is not None + assert arm_env == [] + assert "loop_id" not in svc.added[0] + + +@pytest.mark.asyncio +async def test_ordinary_slot_still_arms_when_the_record_is_down( + monkeypatch: pytest.MonkeyPatch, arm_env: list[tuple[str, str]], tmp_path: Path +) -> None: + """The record only buys a wake reset; losing it must not cost the loop.""" + + def _down(loop_id: str, slot: str) -> None: + raise OSError("trust root unavailable") + + forgotten: list[str] = [] + monkeypatch.setattr(autonudge_authz, "record_self_arm", _down) + monkeypatch.setattr(autonudge_authz, "forget_self_arm", forgotten.append) + svc = _RecordingSvc() + loop, error, status = await _arm(svc, tmp_path, BINDING) + assert error is None and status == 200 and loop is not None + assert len(svc.added) == 1 + assert forgotten == [] + + +@pytest.mark.asyncio +async def test_ordinary_slot_record_is_forgotten_when_the_arm_fails( + monkeypatch: pytest.MonkeyPatch, arm_env: list[tuple[str, str]], tmp_path: Path +) -> None: + """A record written for an arm that never committed must not outlive it.""" + from kiro_crew.autonudge_service.model import NudgeAdmissionRefused + + forgotten: list[str] = [] + monkeypatch.setattr(autonudge_authz, "forget_self_arm", forgotten.append) + + class _RefusingSvc(_RecordingSvc): + async def add(self, **kw: Any) -> Any: + raise NudgeAdmissionRefused("session changed") + + loop, error, status = await _arm(_RefusingSvc(), tmp_path, BINDING) + assert loop is None and status == 409 + assert [loop_id for loop_id, _slot in arm_env] == forgotten + assert len(forgotten) == 1 + + +@pytest.mark.asyncio +async def test_a_pause_during_the_trust_read_refuses(wake_env: dict[str, Any]) -> None: + """The loop is re-read after the off-loop trust read: a Pause that lands + inside that await must still win.""" + calls: list[str] = [] + + def _record_then_pause(loop_id: str, slot_key: str) -> bool: + calls.append(loop_id) + wake_env["svc"].current.active = False + return True + + import kiro_crew.autonudge_selfarm as selfarm + + selfarm_patch = pytest.MonkeyPatch() + selfarm_patch.setattr(selfarm, "is_recorded_self_arm", _record_then_pause) + try: + slot = _slot() + result = await _wake_reset(slot, _state()) + finally: + selfarm_patch.undo() + assert calls == [LOOP_ID] + assert result.startswith("Conversation NOT reset") + assert slot._pending_discard_conversation_key is None + + +@pytest.mark.asyncio +async def test_only_a_wake_reset_is_marked_to_wait_at_the_boundary( + wake_env: dict[str, Any], +) -> None: + wake_slot = _slot(_pending_discard_from_wake=False) + await _wake_reset(wake_slot, _state()) + assert wake_slot._pending_discard_from_wake is True + + person_slot = _slot(_pending_discard_from_wake=True) + await sda.apply_session_directive( + _state(), person_slot, SESSION, "reset_conversation", {}, producer_is_user_facing=True + ) + assert person_slot._pending_discard_from_wake is False + + +@pytest.mark.asyncio +@pytest.mark.parametrize("agent", ["", "kirocrew", "kirocrew-worker"]) +async def test_a_non_conductor_wake_is_refused(wake_env: dict[str, Any], agent: str) -> None: + """A self-armed loop on any other agent's slot passes every loop check, so + the agent check is what keeps the exception to the conductor.""" + slot = _slot(agent=agent) + result = await _wake_reset(slot, _state()) + assert result.startswith("Conversation NOT reset"), agent + assert slot._pending_discard_conversation_key is None + + +@pytest.mark.asyncio +async def test_the_deprecated_conductor_alias_is_admitted(wake_env: dict[str, Any]) -> None: + slot = _slot(agent="kirocrew-ledger-conductor") + result = await _wake_reset(slot, _state()) + assert result.startswith("Conversation reset queued") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("agent", ["", "kirocrew", "kirocrew-worker"]) +async def test_other_agents_arming_themselves_are_not_recorded( + arm_env: list[tuple[str, str]], tmp_path: Path, agent: str +) -> None: + """The record's only ordinary-slot reader is the conductor wake-reset gate, + so no other agent's self-arm writes it.""" + svc = _RecordingSvc() + loop, error, status = await _arm(svc, tmp_path, BINDING, agent=agent) + assert status == 200 and loop is not None + assert arm_env == [] + assert "loop_id" not in svc.added[0]