Skip to content
Closed
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
28 changes: 28 additions & 0 deletions docs/system-specs/modules/memory-skills-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -6421,6 +6421,34 @@ where it is off is not told to pin anything.
transcript the channel file, `slot_history_key`) is refused first as
`unsupported_chat`, with nothing read or written. Modes are those of *Mode, right
before each write and send* above; with `off` every call answers `off`.
- **A starter's pins** (the pinned-memory RFC,
section 11). With `chat`, the tool's `list`, `pin` and `unpin` act on a chat the
caller started (`handlers/pinned_memory._worker_of`): the attested caller's slot
must be the worker slot's creator (`caller_access._created_by_other`, the fence
`session_create` stamps and a handoff never moves); a worker not held in memory is
reached when the crew log's creation record names the caller
(`session_status._creation_parent`). Both chats must be bound to one store. The
whole check runs again once the worker's lock is held, and the starter's binding is
checked again before anything is read out or written. Every refusal of that kind answers
`not_your_worker` and names no record or chat. Each call with `chat` that passes the
input checks leaves one SEL event (`caller_access._audit`, operation
`pinned_memory_<op>`, the target slot): `denied` on `not_your_worker`, else `allowed`
(`_audit_reach`). `remember_and_pin` does not take
`chat`. A starter's pin carries `by`, the starter's slot key, which only the route
writes; a chat's own pin has none, so its stored line is unchanged. The starter
lists and unpins only its own pins there; the worker's own `unpin` of one answers
`pinned_by_starter` unless a person opened the worker's running turn or steered a
message into it (`_person_in_turn` of `cron_lesson_autopin.py`, the check auto-pin
uses), so a person removes a starter's pin by asking the worker; a starter pin of a record the worker pinned first takes it
over. The worker's block tags each with `, from your starter` and opens with
"Memories pinned for this chat"; `_fit` sends a starter's pins first; the left-out
line and the upkeep reminder's left-out names (`measure`, `_measured`) name only the
chat's own pins, and the starter's `pin` answer carries `fits`
(`starter_pins_fit`, which settles the list as the next send would; it writes
no list and gives no notice). A takeover of a record saved again since the worker pinned it pins the
life it has now. A replaced lesson keeps `by`, and a lesson dropped because its
successor was pinned already hands `by` to that pin (`_hand_over`). A fork copies
`by` with the list. The chat line for a starter's pin is still `Pinned: ...`.
- **Limits.** A mid-turn steer whose text was already written to kiro-cli cannot be
recalled: a mode change stops every send that starts after it, not one already
delivered.
Expand Down
187 changes: 178 additions & 9 deletions src/kiro_crew/dashboard/handlers/pinned_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import json
import logging
import time
from dataclasses import replace
from typing import TYPE_CHECKING, Any

from aiohttp import web
Expand All @@ -32,6 +33,8 @@
logger = logging.getLogger(__name__)

_OPS = ("list", "pin", "unpin", "remember_and_pin")
#: The ops a starter may send for a worker it started (``chat``).
_STARTER_OPS = ("list", "pin", "unpin")
#: Ops an older caller may still send, and the op that replaced each.
#: Characters of a memory the visible row and a listing quote.
_SHORT_TEXT = 80
Expand All @@ -56,6 +59,14 @@ def _slot(state: DashboardState, session_key: str) -> Any:
return memory_changes.slot_for_session(state, session_key)


def _person_asked(slot: Any) -> bool:
"""Whether a person opened *slot*'s running turn or steered a message into it."""
from kiro_crew.dashboard.handlers.cron_lesson_autopin import _person_in_turn
from kiro_crew.memory_origin_gate import TURN_HUMAN, classify_turn

return slot is not None and _person_in_turn(slot, classify_turn, TURN_HUMAN)


def _conversation_log(state: DashboardState) -> Any:
log = getattr(state, "conversation_log", None)
if log is not None:
Expand Down Expand Up @@ -142,12 +153,72 @@ async def api_pinned_memory(request: web.Request) -> web.Response:
return _bad(f"op must be one of {', '.join(_OPS)}", "op_invalid")
if await asyncio.to_thread(pm.configured_mode) == pm.MODE_OFF:
return _refusal("off")
if "chat" in body:
answer = await _for_worker(state, session_key, op, body)
_audit_reach(state, session_key, op, body.get("chat"), answer)
return answer
async with _session_locks.setdefault(session_key, asyncio.Lock()):
# The binding is taken once the lock is held: a call that waited behind
# another sees the chat's mode as it is now.
return await _answer(state, session_key, op, body)


async def _for_worker(
state: DashboardState, session_key: str, op: str, body: dict[str, Any]
) -> web.Response:
"""*op* on the worker chat ``body["chat"]`` names, for the chat that started it."""
first = await _worker_of(state, session_key, body.get("chat"), op)
if isinstance(first, web.Response):
return first
async with _session_locks.setdefault(first[0], asyncio.Lock()):
# Asked again under the worker's lock: who created it and which store the
# starter reads may have changed while this call waited.
worker = await _worker_of(state, session_key, body.get("chat"), op)
if isinstance(worker, web.Response):
return worker
worker_key, starter, starter_binding = worker
if worker_key != first[0]:
return _refusal("not_your_worker")
return await _answer(
state,
worker_key,
op,
body,
starter=starter,
starter_binding=starter_binding,
)


def _audit_reach(
state: DashboardState, session_key: str, op: str, chat: object, answer: web.Response
) -> None:
"""Record in the SEL whether the caller was let act on another chat's pins.

Every ``not_your_worker`` answer is a denial; any other answer past the input
checks means the creator fence let the call through. Never raises.
"""
from kiro_crew.dashboard.session_control_parts.caller_access import (
_audit,
caller_slot_key,
)

if answer.status != 200:
return
try:
data = json.loads(answer.text or "{}")
denied = data.get("reason") == "not_your_worker"
_audit(
caller_session_key=session_key,
operation=f"pinned_memory_{op}",
# The caller's own words: a key it probed is recorded, at a bounded length.
slot_key=(caller_slot_key(state, str(chat).strip()) or str(chat).strip())[:200],
outcome="denied" if denied else "allowed",
detail={"code": "not_your_worker"} if denied else None,
)
except Exception:
logger.debug("pinned memory: reach not audited", exc_info=True)


async def pin_lesson(state: DashboardState, session_key: str, key: str) -> str:
"""Pin the lesson *key* to *session_key*'s chat, as an attested ``op=pin`` would.

Expand All @@ -169,6 +240,60 @@ async def pin_lesson(state: DashboardState, session_key: str, key: str) -> str:
return str(data.get("reason") or data.get("code") or "failed")


async def _worker_of(
state: DashboardState, session_key: str, chat: object, op: str
) -> tuple[str, str, pm.Binding] | web.Response:
"""The worker chat *chat* names, when the attested caller started it.

Answers ``(worker's session key, caller's slot key, caller's binding)``. The caller
must be the slot's creator (the creator fence ``session_create`` stamps; a handoff
does not move it), and a refusal names neither the target nor any record, so a
wrong key learns nothing about another chat. The stores are compared again under
the worker's lock.
"""
from kiro_crew.dashboard.chat_utils_slots import slot_history_key
from kiro_crew.dashboard.session_control_parts.caller_access import (
_created_by_other,
caller_slot_key,
)

if not isinstance(chat, str) or not chat.strip():
return _bad("chat must be a session key session_create returned", "chat_invalid")
if op not in _STARTER_OPS:
return _bad(f"with chat, op must be one of {', '.join(_STARTER_OPS)}", "op_invalid")
caller = caller_slot_key(state, session_key)
if not caller:
return _refusal("not_your_worker")
target_key = caller_slot_key(state, chat.strip())
slot = state.get_slot(target_key) if target_key else None
if slot is not None:
if slot.key == caller or _created_by_other(slot, caller):
return _refusal("not_your_worker")
worker_key = slot_history_key(slot)
else:
# A worker not held in memory (closed, or left unrestored after a restart):
# the crew log's creation record, which no sandboxed process writes, names its
# creator. The pin lands in its stored list and is sent at its next injection.
worker_key = await asyncio.to_thread(_stored_worker_of, chat.strip(), caller)
if not worker_key:
return _refusal("not_your_worker")
own = await _bind(session_key, _conversation_log(state))
if isinstance(own, web.Response):
return own
return worker_key, caller, own


def _stored_worker_of(chat: str, caller: str) -> str:
"""The session key of the stored chat *chat* names, when *caller* created it; else ``""``."""
from kiro_crew.dashboard.chat_utils_slots import _history_key_for
from kiro_crew.dashboard.session_control_parts.session_status import _creation_parent

slot_key = chat.removeprefix("dashboard:")
if not slot_key or slot_key == caller or _creation_parent(slot_key) != caller:
return ""
return _history_key_for(slot_key)


async def _bind(session_key: str, log: Any) -> pm.Binding | web.Response:
"""The chat's binding, or the refusal that names why pin code may not act for it."""
try:
Expand Down Expand Up @@ -253,9 +378,19 @@ def _read_failed() -> web.Response:


async def _answer(
state: DashboardState, session_key: str, op: str, body: dict[str, Any]
state: DashboardState,
session_key: str,
op: str,
body: dict[str, Any],
*,
starter: str = "",
starter_binding: pm.Binding | None = None,
) -> web.Response:
"""Read, check and change the list; the caller holds the session's lock."""
"""Read, check and change the list; the caller holds the session's lock.

With *starter*, the call comes from the chat that started *session_key*'s chat
(:func:`_worker_of`): it sees and changes only the pins it made there.
"""
slot = _slot(state, session_key)
if slot is not None and not _transcript_is_session_file(slot, session_key):
# Every reader (compaction, mid-turn, this route) opens the session key's
Expand All @@ -266,6 +401,9 @@ async def _answer(
binding = await _bind(session_key, log)
if isinstance(binding, web.Response):
return binding
if starter and (starter_binding is None or binding.store != starter_binding.store):
# A pin names a record of one store: a starter pins only onto a worker of its own.
return _refusal("not_your_worker")
if op == "remember_and_pin" and binding.mode != "persistent":
# Incognito may list, pin and unpin existing memories; it saves none.
return _refusal("restricted_session")
Expand All @@ -284,11 +422,18 @@ async def _answer(
records = await _records(vectors, current) if vectors is not None else {}
except Exception:
return _read_failed()
if starter_binding is not None and not await asyncio.to_thread(pm.still_bound, starter_binding):
# The starter's own chat turned stricter or moved store while this ran.
return _refusal("not_your_worker")
if op == "list":
# Avoid measuring the pins of a chat that is already restricted.
if not await asyncio.to_thread(pm.still_bound, binding):
return _refusal("restricted_session")
# Pins of another store are listed by reference only, so they can be unpinned.
# A starter sees only the pins it made on its worker, and not the worker's size.
if starter:
visible = replace(current, pins=tuple(p for p in current.pins if p.by == starter))
return web.json_response({"ok": True, "pins": _listing(visible, records)})
upkeep = {**pinned_memory_upkeep.summary(session_key), "total": pm.HARD_CHARS}
if not stale:
try:
Expand All @@ -307,8 +452,12 @@ async def _answer(
kind, record_id = target
if op == "unpin":
pin = current.find(kind, record_id)
if pin is None:
if pin is None or (starter and pin.by != starter):
return _refusal("not_pinned")
if pin.by and not starter and not _person_asked(slot):
# The worker's routine cleanup must not drop the rules its starter gave it;
# a person removes one by asking the worker on a turn they opened.
return _refusal("pinned_by_starter")
after = current.without(kind, record_id)
if not after.pins:
after = pm.Pins(store)
Expand All @@ -326,7 +475,7 @@ async def _answer(
await _visible_row(state, slot, binding, "unpinned", shown)
await _upkeep(session_key, after, vectors, pinned=False)
return web.json_response({"ok": True, "outcome": "unpinned", **_sizes(after)})
return await _pin(state, slot, binding, vectors, current, records, kind, record_id)
return await _pin(state, slot, binding, vectors, current, records, kind, record_id, starter)


async def _not_saved(binding: pm.Binding) -> web.Response:
Expand Down Expand Up @@ -361,10 +510,12 @@ async def _pin(
records: dict[tuple[str, str], pm.Record],
kind: str,
record_id: str,
starter: str = "",
) -> web.Response:
"""Pin one live record of the chat's own store."""
"""Pin one live record of the chat's own store; *starter* marks it as the starter's."""
session_key, store = binding.session_key, binding.store
if current.find(kind, record_id) is not None:
existing = current.find(kind, record_id)
if existing is not None and (not starter or existing.by == starter):
return _refusal("already_pinned", **_sizes(current))
try:
record = await asyncio.to_thread(pm.read_record, vectors, kind, record_id)
Expand All @@ -384,9 +535,19 @@ async def _pin(
life = await asyncio.to_thread(pm.life_for_pin, vectors, kind, record_id)
if not life:
return _refusal("no_identity")
pin = pm.Pin(kind, record_id, life, time.time())
# A list held for another store was refused before this, unless it is empty.
after = pm.Pins(store, (*current.pins, pin))
if existing is not None:
# The worker pinned it first; the starter's pin takes it over, in place, as
# the life it reads now (one deleted and saved again is a new pin).
pin = (
replace(existing, by=starter)
if existing.incarnation == life
else pm.Pin(kind, record_id, life, time.time(), by=starter)
)
after = pm.Pins(store, tuple(pin if p.ref == pin.ref else p for p in current.pins))
else:
pin = pm.Pin(kind, record_id, life, time.time(), by=starter)
# A list held for another store was refused before this, unless it is empty.
after = pm.Pins(store, (*current.pins, pin))
try:
saved = await asyncio.to_thread(
lambda: pm.save(
Expand All @@ -399,13 +560,21 @@ async def _pin(
return await _not_saved(binding)
await _visible_row(state, slot, binding, "pinned", pm.row_text(kind, record_id, record.text))
await _upkeep(session_key, after, vectors, pinned=True)
fits: dict[str, Any] = {}
if starter:
try:
fits["fits"] = await asyncio.to_thread(pm.starter_pins_fit, after, vectors, starter)
except Exception:
# The pin is kept; only the size answer is missing.
logger.debug("pinned memory: fit not measured for %s", session_key, exc_info=True)
return web.json_response(
{
"ok": True,
"outcome": "pinned",
"kind": kind,
"id": record_id,
**_sizes(after),
**fits,
}
)

Expand Down
9 changes: 9 additions & 0 deletions src/kiro_crew/mcp_tools/catalog/learn.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,15 @@ def schemas() -> list[dict[str, Any]]:
"maxLength": 512,
"description": "For pin and unpin: the memory's id.",
},
"chat": {
"type": "string",
"maxLength": 512,
"description": (
"For list, pin and unpin: act on a chat you started "
"(the key session_create returned); its worker cannot "
"unpin what you pin."
),
},
"content": {
"type": "string",
"maxLength": 2000,
Expand Down
Loading
Loading