Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/system-specs/modules/learn-cron-dashboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/system-specs/modules/session.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
12 changes: 12 additions & 0 deletions src/kiro_crew/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
)


Expand Down
4 changes: 2 additions & 2 deletions src/kiro_crew/agent_materialization/conductor_agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
28 changes: 21 additions & 7 deletions src/kiro_crew/autonudge_authz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -1272,15 +1286,15 @@ 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)

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)
Expand Down
11 changes: 10 additions & 1 deletion src/kiro_crew/autonudge_selfarm.py
Original file line number Diff line number Diff line change
@@ -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``),
Expand Down Expand Up @@ -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"

Expand Down
30 changes: 29 additions & 1 deletion src/kiro_crew/builtin_skills/goal-conductor/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<C> runtime=<R>`).

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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading