Skip to content
Open
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
19 changes: 19 additions & 0 deletions docs/system-specs/modules/memory-skills-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -6281,6 +6281,25 @@ by an earlier gateway process, gets the line once on its next turn instead
(`pinned_memory_upkeep.intro_due`). While it is off, neither appears, so a session
where it is off is not told to pin anything.

- **Auto-pin (`dashboard/handlers/cron_lesson_autopin.py`).** While the feature is
on, a lesson the agent's own `learn_add` saves on a turn a person opened in a
dashboard chat is pinned to that chat, through `handlers/pinned_memory.pin_lesson`
(the route's lock and every check an agent's pin runs). Asked only for internal
auth with a session key the transport attests (`session_key_is_attested`), a turn a
person is in (its frozen opener, `slot._turn_row`, is a person's by
`memory_origin_gate.classify_turn`, or a person's steer that the turn has read,
`steerState` `consumed`, is in it; a steer still `written`, `requeued` or taken back
does not count), a
key (the row the save wrote, or on an exact repeat the row that already holds it:
`LessonWriteResult.match_key`), and a stored row that is a standing rule (its own
`applies` unstated or `always`; an `on_topic` finding is not pinned). A lesson a
stored one contains or resembles (`DEDUPED`) carries no `match_key` and pins
nothing: that row can say the opposite ("Never use tabs" contains "use tabs").
`remember_and_pin` (`pin_follows`) pins on its own and is not asked. A new pin draws
the one "Pinned: ..." row and the lessons route draws no "Lesson saved" row; the
route answers `pin` with the outcome and `learn_add` says it. A pin whose lesson was
replaced by one the chat already pins is dropped with no notice (`_settle`).

- **Upkeep reminder (`pinned_memory_upkeep.py`).** While the feature is on, a chat's
next turn carries one `[Kiro Crew pinned memory]` line at each of four stages; no
extra turn runs and nothing is shown to the person. `warn`: the context reading
Expand Down
126 changes: 126 additions & 0 deletions src/kiro_crew/dashboard/handlers/cron_lesson_autopin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
"""Pin a lesson a person taught to the chat they taught it in.

With ``memory.pinned_memory`` on, a lesson saved on a turn that a person sent in a
dashboard chat is also pinned to that chat, so it comes back whole after every
compaction without the agent having to decide to pin it. The pin goes through the
pin route's own path (its lock, binding, mode and size checks, and its one
"Pinned: ..." chat row); this module only decides whether to ask.

Asked only when every one of these holds:

- the request is the agent's own ``learn_add`` (internal auth, a session key the
transport attests), and not ``remember_and_pin``, which pins on its own;
- a person is in the turn the chat is running: its frozen opener
(``slot._turn_row``) is a person's (``memory_origin_gate.classify_turn``), or a
person's message was steered into it after it opened. A worker hand-off, a nudge,
a cron wake or another session's message alone never counts;
- the lesson is in the store under a key: the row this save wrote, or the stored row
that already holds the exact rule (``match_key``, on an exact repeat). A lesson a
stored one contains or resembles is never pinned: that row can say the opposite;
- that stored row is a standing rule (``applies`` unstated or ``always``), read from
the row itself, since a repeat or an enrichment keeps the tier the row already had:
a finding tiered ``on_topic`` stays out of the always-sent block.
"""

from __future__ import annotations

import asyncio
import json
import logging
from typing import Any

logger = logging.getLogger(__name__)

#: Tiers a lesson auto-pins at: a standing rule, stated or not.
_STANDING = ("unstated", "always")


def _person_in_turn(slot: Any, classify: Any, human: str) -> bool:
"""Whether a person opened *slot*'s running turn or steered a message into it.

The rows after the opener are the ones admitted into this turn; a message still
queued for the next turn has its own role and does not count. A steer counts only
once the turn has read it (``consumed``): one still ``written``, taken back or
requeued may never reach the turn.
"""
opener = getattr(slot, "_turn_row", None)
if opener is None:
return False
if classify(opener) == human:
return True
rows = getattr(slot, "messages", None) or []
after = next((i for i, row in enumerate(rows) if row is opener), None)
return after is not None and any(
classify(row) == human and _read_by_turn(row) for row in rows[after + 1 :]
)


def _read_by_turn(row: dict[str, Any]) -> bool:
"""Whether the turn read *row*: any row but a steer, and a steer once ``consumed``."""
from kiro_crew.dashboard.chat_delivery import STEER_STATE_CONSUMED

meta = row.get("meta")
if not isinstance(meta, dict) or meta.get("steer") is not True:
return True
return meta.get("steerState") == STEER_STATE_CONSUMED


def _stored_tier(vectors: Any, key: str) -> str:
"""The tier of the stored lesson *key*; ``""`` when it cannot be read."""
from kiro_crew.vector_memory_runtime.lessons import _lesson_applies

row = vectors.get_semantic(key)
if not row:
return ""
try:
return _lesson_applies(json.loads(row.get("value_json") or "null"))
except ValueError:
return ""


async def maybe_pin(
request: Any,
state: Any,
session_key: str,
body: dict[str, Any],
*,
stored: bool,
key: str | None,
vectors: Any,
) -> str:
"""Pin the saved lesson *key* to *session_key*'s chat when a person taught it.

Returns ``""`` when no pin was asked for, else the pin route's outcome:
``pinned``, ``already_pinned``, or the reason it refused. Never raises: the
lesson is already saved.
"""
try:
if (
not stored
or not key
or vectors is None
or body.get("pin_follows") is True
or request.get("internal_auth") is not True
or not session_key.startswith("dashboard:")
):
return ""
from kiro_crew import pinned_memory
from kiro_crew.member_memory_auth import session_key_is_attested
from kiro_crew.memory_origin_gate import TURN_HUMAN, classify_turn
from kiro_crew.shared_crew import memory_changes

if await asyncio.to_thread(pinned_memory.configured_mode) == pinned_memory.MODE_OFF:
return ""
slot = memory_changes.slot_for_session(state, session_key)
if not _person_in_turn(slot, classify_turn, TURN_HUMAN):
return ""
if not await asyncio.to_thread(session_key_is_attested, request, session_key):
return ""
if await asyncio.to_thread(_stored_tier, vectors, key) not in _STANDING:
return ""
from kiro_crew.dashboard.handlers import pinned_memory as pin_route

return await pin_route.pin_lesson(state, session_key, key)
except Exception:
logger.warning("auto-pin of a taught lesson failed for %s", session_key, exc_info=True)
return "failed"
22 changes: 21 additions & 1 deletion src/kiro_crew/dashboard/handlers/cron_lessons.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,8 @@ async def api_lessons_create(request: web.Request) -> web.Response:
stored = result.stored
# The row this write landed on, so the chat's saved-lesson row can open it.
saved_key = result.key
# The row that already held it, on an exact repeat only.
matched_key = result.match_key
if origin is not None and origin.gate.loggable:
await asyncio.to_thread(record_origin_gate, vs, origin.gate, session_key=sk)
# Redacted through the SAME chain this handler already applies to a lesson's
Expand Down Expand Up @@ -777,6 +779,7 @@ async def api_lessons_create(request: web.Request) -> web.Response:
winner_repo_scope = None
# JSONL rows have no semantic key to open.
saved_key = None
matched_key = None
# Refreshed unconditionally, and deliberately so. Gating the push on the
# write having landed would be wrong: a DECLINING
# outcome can still have mutated the store. ``write_lesson``'s second pass
Expand Down Expand Up @@ -823,7 +826,21 @@ async def api_lessons_create(request: web.Request) -> web.Response:
pin_draws_row = (
body.get("pin_follows") is True and bool(saved_key) and str(outcome) == "inserted"
)
if not pin_draws_row:
# A lesson a person taught is pinned to their chat; that pin draws the one row.
from kiro_crew.dashboard.handlers.cron_lesson_autopin import maybe_pin

# An exact repeat is not ``stored`` as submitted, but the row that already holds
# it says what the person taught, so it is the one pinned.
auto_pin = await maybe_pin(
request,
state,
sk,
body,
stored=stored or bool(matched_key),
key=saved_key or matched_key,
vectors=vs if saved_key or matched_key else None,
)
if not pin_draws_row and auto_pin != "pinned":
await _surface_lesson_saved(
request, state, sk, rule, outcome, saved_key, store=_lesson_silo
)
Expand All @@ -848,6 +865,9 @@ async def api_lessons_create(request: web.Request) -> web.Response:
# The row the lesson landed on, so pinned memory can pin it by the id it has.
if stored and saved_key:
response["key"] = saved_key
# What the auto-pin of a lesson a person taught did; absent when none was asked.
if auto_pin:
response["pin"] = auto_pin
# ``winner`` is additive too, and sent only on the outcome that has one: the
# stored lesson a ``deduped`` write lost to, with that row's own scope.
if winner:
Expand Down
21 changes: 21 additions & 0 deletions src/kiro_crew/dashboard/handlers/pinned_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,27 @@ async def api_pinned_memory(request: web.Request) -> web.Response:
return await _answer(state, session_key, op, body)


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.

For the lessons route, which pins a lesson a person taught on its own; the caller
has attested *session_key*. Takes this route's lock and runs every check an
agent's own pin runs. Returns ``pinned``, ``already_pinned`` or the refusal reason.
"""
if await asyncio.to_thread(pm.configured_mode) == pm.MODE_OFF:
return "off"
body = {"op": "pin", "kind": "directive", "id": key}
async with _session_locks.setdefault(session_key, asyncio.Lock()):
answer = await _answer(state, session_key, "pin", body)
try:
data = json.loads(answer.text or "{}")
except ValueError:
return "failed"
if data.get("ok") is True:
return str(data.get("outcome") or "pinned")
return str(data.get("reason") or data.get("code") or "failed")


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
24 changes: 24 additions & 0 deletions src/kiro_crew/mcp_tools/learn.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,30 @@ def learn_add(name: str, args: dict[str, Any]) -> str:
if applies:
payload["applies"] = applies
d = mcp_core._post("/api/lessons", payload)
return _with_pin_note(d, _learn_add_reply(d, rule, repo_scope))


_AUTO_PIN_NOTES = {
"pinned": " Pinned to this chat: a person taught it here, so it is sent again after "
"every compaction.",
"already_pinned": " It was already pinned to this chat.",
}


def _with_pin_note(d: Any, reply: str) -> str:
"""*reply* with what pinning a lesson a person taught did, when the route asked.

The route asks only on a turn a person sent, with pinned memory on; ``pin`` is
absent otherwise, and so is the note.
"""
pin = d.get("pin") if isinstance(d, dict) else None
if not isinstance(pin, str) or not pin:
return reply
return reply + _AUTO_PIN_NOTES.get(pin, f" Saved, but not pinned to this chat ({pin}).")


def _learn_add_reply(d: Any, rule: str, repo_scope: Any) -> str:
"""The ``learn_add`` answer for the lessons route's reply *d*."""
err_val = d.get("error")
if err_val:
# The gateway's 400 ``missing_session_key`` is the same missing identity
Expand Down
10 changes: 10 additions & 0 deletions src/kiro_crew/pinned_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,16 @@ def _settle(pins: Pins, vectors: Any, *, now: float, kinds: frozenset[str]) -> _
out.said.append((SAID_REPLACED, moved))
out.entries.append((moved, successor))
continue
if live is not None and any(
p.ref == ("directive", live[0])
and bool(p.incarnation)
and p.incarnation == live[1].incarnation
for p in pins.pins
):
# The lesson that replaced it is pinned already, in its current life (a
# person taught the correction here, which pinned it): the old pin goes,
# and nothing is said, since the rule the person sees is still pinned.
continue
out.said.append((SAID_DELETED, pin))
return _fit(out)

Expand Down
14 changes: 11 additions & 3 deletions src/kiro_crew/vector_memory_runtime/lessons.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,11 @@ def resolve_exact_rule(
existing["key"],
)
return ExactRuleMatch(
vm.LessonWriteResult(vm.LessonWriteOutcome.UNCHANGED, "kept_stored_clause")
vm.LessonWriteResult(
vm.LessonWriteOutcome.UNCHANGED,
"kept_stored_clause",
match_key=existing["key"],
)
)
if fields is not None:
# Mapping row: a re-submit that changes nothing the fields express
Expand All @@ -446,7 +450,9 @@ def resolve_exact_rule(
# (correcting a category means delete + re-add). The string form
# never stored a category for anything to have depended on.
if negative == stored_negative:
return ExactRuleMatch(vm.LessonWriteResult(vm.LessonWriteOutcome.UNCHANGED))
return ExactRuleMatch(
vm.LessonWriteResult(vm.LessonWriteOutcome.UNCHANGED, match_key=existing["key"])
)
stored_category = decoded.get("category")
enriched: dict[str, object] = {
"rule": stored_rule,
Expand Down Expand Up @@ -477,7 +483,9 @@ def resolve_exact_rule(
# rewrites it as a mapping, upgrading the row in place.
target_text = base if not negative else f"{base}{_LESSON_NEGATIVE_SEP}{negative}"
if target_text == existing_val:
return ExactRuleMatch(vm.LessonWriteResult(vm.LessonWriteOutcome.UNCHANGED))
return ExactRuleMatch(
vm.LessonWriteResult(vm.LessonWriteOutcome.UNCHANGED, match_key=existing["key"])
)
target = {"rule": base, "category": category, "negative": negative}
# The caller's preflight validated the value built from the SUBMITTED rule;
# this one differs, so validate what is actually written.
Expand Down
6 changes: 6 additions & 0 deletions src/kiro_crew/vector_memory_runtime/write_outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,12 @@ class LessonWriteResult:
#: ``ENRICHED``. The chat row for a saved lesson carries it so the dashboard
#: can open that row. ``None`` on every outcome that wrote nothing.
key: str | None = None
#: On ``UNCHANGED``, the semantic key of the stored row that already holds this
#: exact rule, so a caller can act on the lesson as stored (pinned memory pins
#: it). ``None`` on every other outcome, ``DEDUPED`` included: a row that contains
#: the rule or is close to it can say the opposite. ``key`` keeps meaning "the
#: row this call wrote".
match_key: str | None = None

def __bool__(self) -> bool:
"""``wrote`` -- the exact predicate the old ``bool`` return answered.
Expand Down
15 changes: 15 additions & 0 deletions test/test_lesson_saved_card.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,21 @@ async def test_a_save_no_pin_row_follows_keeps_its_lesson_row(self, outcome, key
assert resp.status == 200
assert len(_lesson_rows(slot)) == 1

@pytest.mark.parametrize("pin, rows", [("pinned", 0), ("already_pinned", 1), ("", 1)])
async def test_a_lesson_a_person_taught_draws_one_row(self, monkeypatch, pin, rows) -> None:
from kiro_crew.dashboard.handlers import cron_lesson_autopin

async def _maybe(*a, **k):
return pin

monkeypatch.setattr(cron_lesson_autopin, "maybe_pin", _maybe)
slot = _ChatSlot(SLOT)
resp, _ = await self._post(
LessonWriteOutcome.INSERTED, slot=slot, key="lesson.0123456789ab"
)
assert resp.status == 200
assert len(_lesson_rows(slot)) == rows

async def test_the_memory_tab_add_draws_nothing(self) -> None:
slot = _ChatSlot(SLOT)
resp, _ = await self._post(
Expand Down
Loading
Loading