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
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:
@@ -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)
|
||||
Reference in New Issue
Block a user