feat(7833): each moment declares which kinds of record its search may consider, editable in Settings > Moments
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Failing after 1m35s
CI & Build / integration (push) Successful in 1m58s
CI & Build / Build & push image (push) Skipped

The kind x moment table (services/record_kinds.py):
- every record search fires at a door: the operator message, or a
  catalog moment (work.change for the write path);
- each door considers a set of kinds (snippet, note, lesson, process,
  task:issue/work/spike/plan); a kind left out is never searched there;
- the shipped defaults are today's behaviour; a user's change is stored
  per door, and putting a door back removes it.

Both note arms read it, replacing their fixed kind lists, and a reserved
slot whose kind is turned off is not reserved. The review re-run
searches the same kinds. Settings > Moments shows and edits the table,
with each cell's lines shown and opens from the record ledger.
list_moments returns it as record_kinds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 14:24:53 -05:00
co-authored by Claude Opus 5.5
parent b0fab00fe2
commit 9cbdfb205c
17 changed files with 654 additions and 43 deletions
+11 -1
View File
@@ -15,6 +15,7 @@ from __future__ import annotations
from grimoire.mcp._context import current_user_id
from grimoire.services import moment_actions as actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import record_kinds as record_kinds_svc
from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import rule_adherence as adherence_svc
from grimoire.services import rule_field_judgments as weights_svc
@@ -44,9 +45,18 @@ async def list_moments() -> dict:
`via: "default"` ships with the product, `via: "install"` is this
install's own mapping. `removed_defaults` are shipped defaults this install
switched off.
`record_kinds` is the kind×moment table: for each point where a record
search fires (`message`, the operator's message, and the catalog moments
that have one), the kinds of record it may consider, the shipped default,
and each kind's lines shown and opened there. A kind left out is never
pushed at that point; search for it yourself when you need it. The
operator changes the table in Settings › Moments.
"""
uid = current_user_id()
out = moments_svc.catalog()
out.update(await actions_svc.actions_by_moment(current_user_id()))
out.update(await actions_svc.actions_by_moment(uid))
out["record_kinds"] = await record_kinds_svc.table(uid)
return out
+34
View File
@@ -22,6 +22,7 @@ from grimoire.services import moment_actions as moment_actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import record_deliveries as record_deliveries_svc
from grimoire.services import record_kinds as record_kinds_svc
from grimoire.services import rule_adherence as adherence_svc
from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
@@ -259,6 +260,39 @@ async def adherence_route():
))
@retrieval_bp.route("/record-kinds", methods=["GET"])
@login_required
async def record_kinds_route():
"""The kind×moment table: which kinds of record each door's search may
consider, the shipped default beside each, and each cell's lines and
opens over `?days=` (default 30)."""
try:
days = max(1, min(int(request.args.get("days") or 30), 365))
except ValueError:
return jsonify({"error": "days must be a whole number"}), 400
return jsonify(await record_kinds_svc.table(get_current_user_id(), days=days))
@retrieval_bp.route("/record-kinds", methods=["PUT"])
@login_required
async def set_record_kinds_route():
"""Set one door's kinds. Body: `{"door", "kinds": [...]}`, or
`{"door", "kinds": null}` to put the door back to its shipped default.
Answers with the whole table."""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict) or not isinstance(data.get("door"), str):
return jsonify({"error": "door is required"}), 400
kinds = data.get("kinds")
if kinds is not None and (
not isinstance(kinds, list) or not all(isinstance(k, str) for k in kinds)
):
return jsonify({"error": "kinds must be a list of kinds, or null"}), 400
try:
return jsonify(await record_kinds_svc.set_kinds(get_current_user_id(), data["door"], kinds))
except ValueError as e:
return jsonify({"error": str(e)}), 400
@retrieval_bp.route("/record-reach", methods=["GET"])
@login_required
async def record_reach_route():
+8
View File
@@ -917,9 +917,14 @@ async def semantic_search_notes(
demote_superseded: bool = True,
system_id: int | None = None,
report: dict | None = None,
record_kinds: Sequence[str] | None = None,
) -> list[tuple[float, Note]]:
"""Return up to *limit* (score, note) pairs most relevant to *query*.
`record_kinds` narrows to the kinds of the kind×moment table
(`record_kinds`: `snippet`, `task:issue`, …), the vocabulary the
injected arms filter by. It composes with every other filter.
Scores are cosine similarities in [-1, 1]; only notes at or above
*threshold* are returned, sorted highest-first.
@@ -1086,6 +1091,9 @@ async def semantic_search_notes(
stmt = stmt.where(
or_(Note.status.is_(None), Note.task_kind.in_(tkinds))
)
if record_kinds is not None:
from grimoire.services.record_kinds import kinds_clause
stmt = stmt.where(kinds_clause(record_kinds))
if exclude_ids:
stmt = stmt.where(NoteEmbedding.note_id.notin_(exclude_ids))
# OVER-FETCH when a re-rank follows, so the demotion can actually
+3
View File
@@ -25,6 +25,7 @@ from grimoire.services import knowledge as knowledge_svc
from grimoire.services import notes as notes_svc
from grimoire.services import projects as projects_svc
from grimoire.services import record_refs as record_refs_svc
from grimoire.services import record_kinds
from grimoire.services import shape_ledger as shape_ledger_svc
from grimoire.services import snippets as snippets_svc
from grimoire.services import task_claims as task_claims_svc
@@ -698,6 +699,7 @@ async def build_autoinject_hint(
rp.NoteMoment(
user_id=user_id, query=q, project_id=project_id,
seen=frozenset(already), named=frozenset(named_ids),
kinds=await record_kinds.kinds_for(user_id, rp.AUTO_INJECT.door),
),
floor=cfg["threshold"], budget=cfg["top_k"], io=_note_io(),
)
@@ -1474,6 +1476,7 @@ async def build_write_path_hint(
user_id=user_id, query=query, project_id=project_id,
seen=frozenset(excluded), in_menu=frozenset(seen),
still_scored=frozenset(pulled),
kinds=await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door),
),
floor=cfg["threshold"], budget=remaining, io=_note_io(),
)
+2 -8
View File
@@ -34,6 +34,7 @@ from grimoire.models.record_delivery import ASKED, DIRECT, PUSHED, RecordDeliver
from grimoire.models.retrieval_log import RetrievalLog
from grimoire.services import rule_deliveries
from grimoire.services.access import readable_notes_clause
from grimoire.services.record_kinds import kind_of
from grimoire.services.background import spawn
logger = logging.getLogger(__name__)
@@ -88,13 +89,6 @@ def flush(kept: set[int] | None = None) -> None:
spawn(_insert(rows), site="record_delivery_write")
def _kind(note_type: str | None, status: str | None, task_kind: str | None) -> str:
# A task is told by its status; its kind says what sort of task it is.
if status is not None:
return f"task:{task_kind or 'work'}"
return note_type or "note"
async def _kinds(session, user_id: int, ids) -> dict[int, str]:
"""`{note_id: kind}` for the ids this user may read; any other id is left
out, so the ledger never records a record its reader could not open."""
@@ -102,7 +96,7 @@ async def _kinds(session, user_id: int, ids) -> dict[int, str]:
select(Note.id, Note.note_type, Note.status, Note.task_kind)
.where(Note.id.in_(list(ids)), readable_notes_clause(user_id))
)).all()
return {int(i): _kind(t, s, k) for i, t, s, k in rows}
return {int(i): kind_of(t, s, k) for i, t, s, k in rows}
async def _insert(rows: list[dict]) -> None:
+226
View File
@@ -0,0 +1,226 @@
"""Which kinds of record each moment may consider: the kind×moment table.
WHY THIS EXISTS
A record is not useful at every point in the work. A reusable snippet answers
"what am I about to write", an issue answers "has this failed before", a plan
answers nothing a line could. A search that considers every kind at every
moment puts them all in one ranking, and the line that wins is whichever
resembles the words best, not whichever the moment needs. So each moment a
record search fires at declares the kinds it may consider, and the search is
narrowed to them before it ranks anything.
Kinds attach to moments BY KIND, never one record at a time: there are
thousands of records and a handful of kinds, so a per-record mount would
never be kept up.
THE VOCABULARY
A kind is a record's `note_type` (`snippet`, `note`, `lesson`, `process`)
or, for a task, `task:` and its `task_kind` (`task:issue`, `task:work`,
`task:spike`, `task:plan`). The same strings label the record ledger
(`record_deliveries`), so a cell's lines and opens are read under the
name it is edited by.
DEFAULTS ARE CODE, CHANGES ARE STORED
Each door ships its defaults here, and they improve with the product. A
user's change is stored per door (setting `record_kinds`), so a door the
user never touched keeps following the shipped default, and putting a door
back to its default removes the stored change.
THE DOORS
A door is a point where a record search fires: a catalog moment
(`work.change`), or the operator's message, which is when a session first
hears what the work is and is not a moment rules mount on, so it has its
own key (`message`).
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from typing import Iterable
from sqlalchemy import and_, false, or_
from grimoire.models.note import Note, TaskKind
logger = logging.getLogger(__name__)
TASK_PREFIX = "task:"
NOTE_KINDS: tuple[str, ...] = ("snippet", "note", "lesson", "process")
TASK_KINDS: tuple[str, ...] = tuple(f"{TASK_PREFIX}{k.value}" for k in TaskKind)
KINDS: tuple[str, ...] = NOTE_KINDS + TASK_KINDS
LABELS: dict[str, str] = {
"snippet": "Snippets",
"note": "Notes",
"lesson": "Lessons",
"process": "Processes",
"task:issue": "Issues",
"task:work": "Work tasks",
"task:spike": "Spikes",
"task:plan": "Plans (old plan tasks)",
}
SETTING_KEY = "record_kinds"
MESSAGE = "message"
@dataclass(frozen=True)
class Door:
"""A point where a record search fires, and what it considers by default."""
key: str
"""A catalog moment, or `message`."""
label: str
fires: str
default: frozenset[str]
sources: tuple[str, ...] = ()
"""The surfacing sources its lines are recorded under in the record
ledger, which is where each cell's lines and opens are read from."""
DOORS: dict[str, Door] = {
MESSAGE: Door(
MESSAGE, "The operator's message", "once per operator turn",
frozenset(KINDS), sources=("auto_inject", "lesson_slot"),
),
# What is about to be written: code to reuse, and what was already tried
# (an issue, a dev-log, a lesson). The open to-do list resembles the code
# and answers nothing, so work tasks are left out.
"work.change": Door(
"work.change", "Altering the thing being worked on", "before every write or edit",
frozenset({"snippet", "note", "lesson", "task:issue"}),
sources=("write_path_semantic",),
),
}
def kind_of(note_type: str | None, status: str | None, task_kind: str | None) -> str:
"""The kind a record is counted and filtered under. A task is told by its
status; its `task_kind` says which sort of task."""
if status is not None:
return f"{TASK_PREFIX}{task_kind or 'work'}"
return note_type or "note"
def clean(kinds: Iterable[str] | None) -> frozenset[str]:
"""Known kinds only. An unknown one is dropped, not refused, when read
back, so a stored value never breaks a search."""
return frozenset(k for k in (kinds or ()) if k in KINDS)
def search_kinds(kinds: frozenset[str]) -> list[str] | None:
"""What a search is narrowed to: None when every kind is allowed, so an
unfiltered door stays exactly unfiltered (a record with a type outside
the vocabulary is still reachable there)."""
return None if set(KINDS) <= kinds else sorted(kinds)
def kinds_clause(kinds: Iterable[str]):
"""A WHERE clause on `Note` matching exactly the given kinds."""
kinds = list(kinds)
notes = [k for k in kinds if not k.startswith(TASK_PREFIX)]
tasks = [k[len(TASK_PREFIX):] for k in kinds if k.startswith(TASK_PREFIX)]
parts = []
if notes:
parts.append(and_(Note.status.is_(None), Note.note_type.in_(notes)))
if tasks:
kind = Note.task_kind.in_(tasks)
if "work" in tasks:
# A task with no kind is counted as work (`kind_of`).
kind = or_(kind, Note.task_kind.is_(None))
parts.append(and_(Note.status.isnot(None), kind))
return or_(*parts) if parts else false()
async def _stored(user_id: int) -> dict[str, frozenset[str]]:
from grimoire.services.settings import get_setting
try:
raw = json.loads(await get_setting(user_id, SETTING_KEY, "{}") or "{}")
except Exception: # noqa: BLE001 - a bad stored value falls back to defaults
logger.debug("record kinds setting unreadable", exc_info=True)
return {}
if not isinstance(raw, dict):
return {}
return {k: clean(v) for k, v in raw.items() if k in DOORS and isinstance(v, list)}
async def kinds_for(user_id: int, door: str) -> frozenset[str]:
"""The kinds this user's door considers: their change, or the default."""
spec = DOORS[door]
return (await _stored(user_id)).get(door, spec.default)
async def _evidence(user_id: int, days: int) -> dict[str, dict[str, dict]] | None:
"""`{door: {kind: {"delivered", "opened"}}}` from the record ledger: the
lines each door pushed of each kind, and how many were opened. None when
the ledger could not be read, so a failed read is not shown as zero."""
from grimoire.services import record_deliveries
try:
reach = await record_deliveries.summary(user_id, days=days)
except Exception: # noqa: BLE001 - the table stands without its evidence
logger.exception("record kinds evidence read failed")
return None
out: dict[str, dict[str, dict]] = {d: {} for d in DOORS}
for row in reach["by_kind"]:
for src in row["sources"]:
for door in DOORS.values():
if src["way"] == "pushed" and src["source"] in door.sources:
cell = out[door.key].setdefault(row["kind"], {"delivered": 0, "opened": 0})
cell["delivered"] += src["delivered"]
cell["opened"] += src["opened"]
return out
async def table(user_id: int, days: int = 30) -> dict:
"""Every door with its kinds, and each cell's lines and opens over the
last `days`, for the settings view and the MCP readout."""
stored = await _stored(user_id)
evidence = await _evidence(user_id, days)
return {
"days": days,
"evidence_failed": evidence is None,
"kinds": [{"kind": k, "label": LABELS[k]} for k in KINDS],
"doors": [
{
"door": d.key, "label": d.label, "fires": d.fires,
"kinds": sorted(stored.get(d.key, d.default), key=KINDS.index),
"default": sorted(d.default, key=KINDS.index),
"changed": d.key in stored,
"evidence": (evidence or {}).get(d.key, {}),
}
for d in DOORS.values()
],
}
async def set_kinds(user_id: int, door: str, kinds: list[str] | None) -> dict:
"""Set a door's kinds, or put it back to the default with None.
Refuses an unknown door or kind rather than storing one that would never
match: a cell that looks set and does nothing is the failure this table
exists to end. A set equal to the default is stored as no change, so the
door keeps following the shipped default.
"""
from grimoire.services.settings import set_setting
if door not in DOORS:
raise ValueError(f"unknown door {door!r}; doors are: {', '.join(DOORS)}")
if kinds is not None:
unknown = [k for k in kinds if k not in KINDS]
if unknown:
raise ValueError(f"unknown kind(s) {unknown}; kinds are: {', '.join(KINDS)}")
stored = {k: sorted(v, key=KINDS.index) for k, v in (await _stored(user_id)).items()}
if kinds is None or frozenset(kinds) == DOORS[door].default:
stored.pop(door, None)
else:
stored[door] = sorted(set(kinds), key=KINDS.index)
await set_setting(user_id, SETTING_KEY, json.dumps(stored))
return await table(user_id)
+42 -23
View File
@@ -35,7 +35,7 @@ import time
from dataclasses import dataclass, field
from typing import Any, Callable
from grimoire.services import cue_gate, rule_order
from grimoire.services import cue_gate, record_kinds, rule_order
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line
logger = logging.getLogger(__name__)
@@ -1124,8 +1124,11 @@ class NoteArm:
surfaced_as: str
"""The `source` its surfacing rows carry."""
note_type: tuple[str, ...] | None = None
task_kind: str | None = None
door: str = record_kinds.MESSAGE
"""Its row in the kind×moment table (`record_kinds.DOORS`): the kinds it
may consider come from there, the user's own or the shipped default, and
a kind absent there is unreachable from this arm, not merely outranked."""
include_global_kinds: bool = True
"""Lessons are project-independent, so they join the candidate set
from wherever they were learned."""
@@ -1150,7 +1153,7 @@ class NoteArm:
AUTO_INJECT = NoteArm(
"auto_inject", surfaced_as="auto_inject", slots=(REUSE_SLOT, LESSON_SLOT),
gated=True,
door=record_kinds.MESSAGE, gated=True,
tuning=Surface(
name="auto_inject",
floor_key="kb_autoinject_threshold",
@@ -1163,17 +1166,13 @@ AUTO_INJECT = NoteArm(
),
declared=Declared("the notes menu offered at the prompt boundary"),
)
# Snippets AND recorded experience: an issue saying "we tried this and it
# deadlocked" is prior art for the code about to be written. `task_kind`
# keeps the open to-do list out — a task resembles the code and answers
# nothing. Lessons too: the arm is kind-FILTERED, so a kind absent here is
# unreachable, not merely outranked. No reserved
# slot: this arm fires before every Write and Edit, and the field is already
# narrow enough that the 200:1 dilution a slot answers does not happen.
# The kinds it considers are the `work.change` row of the kind×moment table,
# where the default and its reasons live. No reserved slot: this arm fires
# before every Write and Edit, and the field is already narrow enough that the
# 200:1 dilution a slot answers does not happen.
WRITE_PATH = NoteArm(
"write_path", surfaced_as="write_path_semantic",
note_type=("snippet", "note", LESSON_NOTE_TYPE), task_kind="issue",
withholds=True, gated=True,
door="work.change", withholds=True, gated=True,
tuning=Surface(
name="write_path",
floor_key="kb_writepath_threshold",
@@ -1201,16 +1200,13 @@ NOTE_SURFACED_SOURCES: tuple[str, ...] = (
def note_search_filters(arm: NoteArm) -> dict:
"""The arm's constant search keywords — which kinds, whose records.
"""The arm's constant search keywords — whose records. Which kinds is the
kind×moment table's, per user (`record_kinds.kinds_for`).
Read by `retrieval_review` too: a re-run that searched with different
visibility or kinds from the arm's would judge a menu nobody was shown.
"""
out: dict = {}
if arm.note_type:
out["note_type"] = arm.note_type
if arm.task_kind:
out["task_kind"] = arm.task_kind
if arm.include_global_kinds:
out["include_global_kinds"] = True
out["scope"] = arm.scope
@@ -1253,6 +1249,11 @@ class NoteMoment:
"""Of `in_menu`, those the search must still score (a pulled snippet's
resemblance to the payload is evidence for the shape ledger)."""
kinds: frozenset[str] | None = None
"""The kinds this user's door considers (`record_kinds.kinds_for`). None
is the door's shipped default; an empty set means the arm searches
nothing."""
@dataclass
class NoteResult:
@@ -1293,8 +1294,10 @@ def _note_band(hits: list) -> list:
async def _reserve_note_slot(
io: NoteIO, arm: NoteArm, slot: NoteSlot, moment: NoteMoment, menu: list,
*, floor: float, budget: int, shown: set[int], capped: bool = False,
kinds: tuple[str, ...] | None = None,
) -> tuple[list, int | None]:
"""Guarantee `slot.kinds` one line, if one clears the arm's own bar.
"""Guarantee `kinds` (the slot's kinds the door allows; all of
`slot.kinds` by default) one line, if one clears the arm's own bar.
WHY A SLOT AT ALL. Ranking by raw cosine is blind to what KIND of record
answers what kind of ask, and the corpus makes that fatal: Grimoire's
@@ -1319,7 +1322,8 @@ async def _reserve_note_slot(
Returns the possibly-changed menu and the id the slot spent.
"""
if any(_record_kind(n) in slot.kinds for _s, n in menu):
kinds = kinds or slot.kinds
if any(_record_kind(n) in kinds for _s, n in menu):
return menu, None
# Under the gate the budget is a ceiling for every line, so a slot that
# only extends has no room once the menu is full.
@@ -1333,7 +1337,7 @@ async def _reserve_note_slot(
"limit": 1, "threshold": floor, "project_id": moment.project_id or None,
"exclude_ids": set(on_menu),
# KIND-FILTERED, so the slot can only be spent on what it is for.
"note_type": slot.kinds, "scope": arm.scope, "report": report,
"note_type": kinds, "scope": arm.scope, "report": report,
}
if slot.include_global_kinds:
kwargs["include_global_kinds"] = True
@@ -1357,7 +1361,7 @@ async def _reserve_note_slot(
# this menu already carries.
placed = [
(s, n) for s, n in found
if _record_kind(n) in slot.kinds and int(n.id) not in on_menu
if _record_kind(n) in kinds and int(n.id) not in on_menu
][:1]
if not placed:
return menu, None
@@ -1394,6 +1398,15 @@ async def run_note_arm(
search → withhold this response's menu → fresh/repeat split → call row →
band → reserved slots → surfacing rows. Fails open to an empty result.
"""
allowed = (
moment.kinds if moment.kinds is not None
else record_kinds.DOORS[arm.door].default
)
if not allowed:
# The table turned every kind off at this door: nothing is searched,
# so no call row either; a row would read as a search that found
# nothing.
return NoteResult()
try:
gate = (
await _gate(io, moment.user_id, arm.source, moment.project_id)
@@ -1408,6 +1421,7 @@ async def run_note_arm(
"limit": budget + len(scored), "threshold": floor,
"project_id": moment.project_id or None,
**note_search_filters(arm), "report": report,
"record_kinds": record_kinds.search_kinds(allowed),
}
if arm.withholds:
kwargs["exclude_ids"] = set(moment.in_menu - scored)
@@ -1479,9 +1493,14 @@ async def run_note_arm(
# a slot that picks one does not book a surfacing the lookup booked.
shown = set(moment.seen | moment.named)
for slot in arm.slots:
# A slot reserves a line for a kind; one the table turned off at
# this door has nothing to reserve it for.
kinds = tuple(k for k in slot.kinds if k in allowed)
if not kinds:
continue
menu, slot_id = await _reserve_note_slot(
io, arm, slot, moment, menu, floor=floor, budget=budget,
shown=shown, capped=gate is not None,
shown=shown, capped=gate is not None, kinds=kinds,
)
if slot_id is not None:
result.slot_ids[slot.source] = slot_id
@@ -163,10 +163,14 @@ async def _rerun_notes(
"""
# Imported here: plugin_context imports retrieval_telemetry, which reads
# this module's judged block.
from grimoire.services import record_kinds
from grimoire.services import retrieval_pipeline as rp
from grimoire.services.embeddings import document_title, semantic_search_notes
from grimoire.services.retrieval_pipeline import _menu_name, _menu_passage, _record_kind
# The kinds the door considers NOW: the table keeps no history, so a call
# made before a change is re-run against the current row.
kinds = await record_kinds.kinds_for(user_id, rp.AUTO_INJECT.door)
rep: dict = {}
hits = await semantic_search_notes(
user_id, row.query or "",
@@ -174,6 +178,7 @@ async def _rerun_notes(
threshold=row.threshold if row.threshold is not None else 0.0,
project_id=row.project_id or None,
**rp.note_search_filters(rp.AUTO_INJECT),
record_kinds=record_kinds.search_kinds(kinds),
report=rep,
)
postdated = [int(n.id) for _s, n in hits if _after(n.created_at, row.created_at)]