"""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 records are offered: a catalog moment (`work.change` before a write, `work.start` when a task is taken up), 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. # Not lessons: an edit's words resemble a lesson far more often than the # edit is its situation. A lesson reaches an edit through a situation # confirmed for it (`lesson_situations`), once per session. "work.change": Door( "work.change", "Altering the thing being worked on", "before every write or edit", frozenset({"snippet", "note", "task:issue"}), sources=("write_path_semantic", "write_path_place", "write_path_sync", "write_path_linked"), ), # Taking up a task: what is recorded in the task's own areas, named by id # in the reply that set it in progress. Notes for what is known there, # open issues for what is still wrong there. "work.start": Door( "work.start", "Taking up a piece of work", "when a task is set in progress", frozenset({"note", "task:issue"}), ), } 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() # A pointer line names at most this many records of a kind; the count says # how many there were. POINTER_IDS = 3 _PLURALS = { "snippet": "snippets", "note": "notes", "lesson": "lessons", "process": "processes", "task:issue": "issues", "task:work": "tasks", "task:spike": "spikes", "task:plan": "plans", } def opener(kind: str) -> str: """The MCP call that opens a record of this kind.""" if kind.startswith(TASK_PREFIX): return "get_task" return {"snippet": "get_snippet", "lesson": "get_lesson", "process": "get_process"}.get(kind, "get_note") def pointer_line( pointers: dict[str, list[int]], lead: str, *, capped_at: int | None = None, ) -> tuple[str, list[int]] | None: """One line naming records by id, per kind, with the call that opens each kind; and the ids it named. None when there is nothing to point at. A line and a passage per record is what a payload cannot afford for everything that may bear on the work; an id costs a few characters, and the session is the one placed to judge whether to open it. A kind with more records than it names says how many; `capped_at` is the depth the lookup stopped at, so a count that reached it reads as "at least". """ named: list[int] = [] phrases: list[str] = [] for kind in KINDS: ids = pointers.get(kind) or [] if not ids: continue shown = ids[:POINTER_IDS] named.extend(shown) count = "" if len(ids) > len(shown): count = f"{len(ids)}+ " if capped_at and len(ids) >= capped_at else f"{len(ids)} " phrases.append( f"{count}{_PLURALS[kind]} " + ", ".join(f"#{i}" for i in shown) + f" (`{opener(kind)}(id)`)" ) if not phrases: return None return ( f"> {lead}: " + "; ".join(phrases) + ". Open one if it may bear on the work.", named, ) 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, # A door whose lines reach the session in a tool reply rather # than a plugin hook has no session to record them against. "measured": bool(d.sources), "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)