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
+32 -1
View File
@@ -1,4 +1,4 @@
import { apiGet, apiPost, apiDelete } from "@/api/client";
import { apiGet, apiPost, apiPut, apiDelete } from "@/api/client";
import type { RuleEnforcement, RuleSalience, RuleTrigger } from "@/api/rulebooks";
/**
@@ -279,6 +279,37 @@ export interface AdherencePayload {
by_moment: MomentAdherenceRow[];
}
/** One door of the kind×moment table: where a record search fires, and
* the kinds of record it may consider. */
export interface RecordKindsDoor {
/** A catalog moment, or `message` for the operator's message. */
door: string;
label: string;
fires: string;
kinds: string[];
default: string[];
/** The user changed this door; otherwise it follows the shipped default. */
changed: boolean;
/** Lines this door pushed of each kind, and how many were opened. */
evidence: Record<string, WayCounts>;
}
export interface RecordKindsTable {
days: number;
evidence_failed: boolean;
kinds: { kind: string; label: string }[];
doors: RecordKindsDoor[];
}
export function getRecordKinds(days = 30): Promise<RecordKindsTable> {
return apiGet(`/api/retrieval/record-kinds?days=${days}`);
}
/** `kinds: null` puts the door back to its shipped default. */
export function setRecordKinds(door: string, kinds: string[] | null): Promise<RecordKindsTable> {
return apiPut("/api/retrieval/record-kinds", { door, kinds });
}
/** How a record arrived in front of a session. */
export type RecordWay = "pushed" | "asked" | "direct";
@@ -4,6 +4,7 @@ import { useMomentsStore } from "@/stores/moments";
import MomentProposals from "@/components/MomentProposals.vue";
import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
import WeightProposals from "@/components/WeightProposals.vue";
import RecordKinds from "@/components/RecordKinds.vue";
import RecordReach from "@/components/RecordReach.vue";
import RuleAdherence from "@/components/RuleAdherence.vue";
import { getAdherence, getRecordReach } from "@/api/moments";
@@ -172,6 +173,7 @@ onMounted(async () => {
<WeightProposals />
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
<RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" />
<RecordKinds :days="days" />
<ul class="moment-list">
<li v-for="m in catalog" :key="m.name" class="moment-row">
+130
View File
@@ -0,0 +1,130 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { apiErrorMessage } from "@/api/client";
import { getRecordKinds, setRecordKinds } from "@/api/moments";
import type { RecordKindsDoor, RecordKindsTable } from "@/api/moments";
/**
* The kind×moment table: for each point where a record search fires, which
* kinds of record it may consider. A kind left unticked is never pushed
* there; a session can still search for it. Each box shows the lines that
* door pushed of that kind and how many were opened, so a change is made
* against its own evidence. A change saves as soon as it is made.
*/
const props = defineProps<{ days: number }>();
const table = ref<RecordKindsTable | null>(null);
const failed = ref(false);
const saving = ref<string | null>(null);
const saveError = ref("");
async function load() {
try {
table.value = await getRecordKinds(props.days);
failed.value = false;
} catch {
failed.value = true;
}
}
async function save(door: string, kinds: string[] | null) {
saving.value = door;
saveError.value = "";
try {
table.value = await setRecordKinds(door, kinds);
} catch (e) {
saveError.value = apiErrorMessage(e, "The change could not be saved.");
} finally {
saving.value = null;
}
}
function toggle(row: RecordKindsDoor, kind: string, on: boolean) {
const next = on ? [...row.kinds, kind] : row.kinds.filter((k) => k !== kind);
void save(row.door, next);
}
function evidenceText(row: RecordKindsDoor, kind: string): string {
const c = row.evidence[kind];
return c ? `${c.opened} of ${c.delivered} opened` : "none shown";
}
onMounted(load);
</script>
<template>
<section class="kinds" aria-labelledby="kinds-title">
<h3 id="kinds-title" class="sub-title">Which records each moment considers</h3>
<p v-if="failed" class="error-msg">
The table could not be loaded.
<button type="button" class="btn-text" @click="load">Try again</button>
</p>
<p v-else-if="!table" class="empty-msg">Loading the table…</p>
<template v-else>
<p class="field-hint">
A search for records runs at each point below. An unticked kind is never shown there;
a session can still search for it. Beside each kind: lines shown there over the last
{{ table.days }} days, and how many were opened.
</p>
<p v-if="table.evidence_failed" class="error-msg">
The counts could not be read, so they are missing below, not zero.
</p>
<p v-if="saveError" class="error-msg" role="alert">{{ saveError }}</p>
<fieldset
v-for="row in table.doors" :key="row.door" class="door"
:disabled="saving === row.door"
>
<legend class="door-head">
<span class="door-label">{{ row.label }}</span>
<code class="moment-name">{{ row.door }}</code>
<span class="door-fires">{{ row.fires }}</span>
<span v-if="!row.changed" class="door-default">shipped default</span>
</legend>
<ul class="kind-list">
<li v-for="k in table.kinds" :key="k.kind" class="kind-cell">
<label class="kind-label">
<input
type="checkbox" :checked="row.kinds.includes(k.kind)"
@change="toggle(row, k.kind, ($event.target as HTMLInputElement).checked)"
/>
{{ k.label }}
</label>
<span v-if="!table.evidence_failed" class="kind-evidence">{{ evidenceText(row, k.kind) }}</span>
</li>
</ul>
<button v-if="row.changed" type="button" class="btn-text door-reset" @click="save(row.door, null)">
Back to the shipped default
</button>
</fieldset>
</template>
</section>
</template>
<style scoped>
.kinds { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.door {
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-md);
padding: var(--fs-space-2) var(--fs-space-3);
margin: 0;
display: flex; flex-direction: column; gap: var(--fs-space-2);
}
.door:disabled { opacity: var(--fs-disabled-opacity); }
.door-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); padding: 0 var(--fs-space-1); }
.door-label { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
.door-fires,
.door-default,
.kind-evidence { font-size: var(--fs-size-tiny); color: var(--fs-text-secondary); font-variant-numeric: tabular-nums; }
.kind-list {
list-style: none; margin: 0; padding: 0;
display: grid; grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr));
gap: var(--fs-space-1) var(--fs-space-3);
}
.kind-cell { display: flex; flex-direction: column; }
.kind-label { display: inline-flex; align-items: center; gap: var(--fs-space-1); font-size: var(--fs-size-body-sm); cursor: pointer; }
.kind-label input:focus-visible { outline: none; box-shadow: var(--fs-focus-ring); }
.door-reset { align-self: flex-start; }
</style>
<style src="@/assets/moments-shared.css" />
+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)]
+21
View File
@@ -367,6 +367,27 @@ def _default_payload_budget(request):
yield
@pytest.fixture(autouse=True)
def _default_record_kinds(request):
"""Stub the settings read behind the kind×moment table.
Both record searches read the user's kinds per door
(`record_kinds.kinds_for`); stubbed to the shipped default so a unit test
of a door needs no database. The integration lane, where the table's own
tests live, reads the real setting.
"""
if request.node.get_closest_marker("integration"):
yield
return
from grimoire.services import record_kinds
async def _default(_user_id, door):
return record_kinds.DOORS[door].default
with patch.object(record_kinds, "kinds_for", AsyncMock(side_effect=_default)):
yield
@pytest.fixture(autouse=True)
def _ungated_doors(request):
"""Leave the plugin doors' cue-swap gate off unless a test asks for it.
+93
View File
@@ -0,0 +1,93 @@
"""Real-Postgres tests for the kind×moment table (`record_kinds`): the
shipped defaults, a user's change and its reset, the refusals, the SQL clause
matching exactly the kinds named, and each cell's evidence from the ledger."""
from datetime import datetime, timezone
import pytest
from sqlalchemy import delete, select
from grimoire.models import async_session
from grimoire.models.note import Note
from grimoire.models.record_delivery import RecordDelivery
from grimoire.models.setting import Setting
from grimoire.services import record_kinds
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
async def _user(name: str = "record_kinds_owner") -> int:
async with async_session() as s:
uid = (await ensure_user(s, name)).id
await s.execute(delete(Setting).where(
Setting.user_id == uid, Setting.key == record_kinds.SETTING_KEY))
await s.execute(delete(RecordDelivery).where(RecordDelivery.user_id == uid))
await s.commit()
return uid
async def test_a_door_follows_its_default_until_the_user_changes_it():
uid = await _user()
assert await record_kinds.kinds_for(uid, "work.change") == record_kinds.DOORS["work.change"].default
await record_kinds.set_kinds(uid, "work.change", ["snippet", "task:issue"])
assert await record_kinds.kinds_for(uid, "work.change") == {"snippet", "task:issue"}
# Another door is untouched.
assert await record_kinds.kinds_for(uid, "message") == frozenset(record_kinds.KINDS)
table = await record_kinds.set_kinds(uid, "work.change", None)
row = next(d for d in table["doors"] if d["door"] == "work.change")
assert row["changed"] is False and row["kinds"] == row["default"]
async def test_setting_the_default_stores_no_change():
uid = await _user()
default = sorted(record_kinds.DOORS["work.change"].default)
table = await record_kinds.set_kinds(uid, "work.change", default)
assert not any(d["changed"] for d in table["doors"])
async def test_an_unknown_door_or_kind_is_refused_and_nothing_is_stored():
uid = await _user()
with pytest.raises(ValueError, match="unknown door"):
await record_kinds.set_kinds(uid, "work.nowhere", ["snippet"])
with pytest.raises(ValueError, match="unknown kind"):
await record_kinds.set_kinds(uid, "message", ["snippet", "rule"])
assert await record_kinds.kinds_for(uid, "message") == frozenset(record_kinds.KINDS)
async def test_the_clause_matches_exactly_the_kinds_named():
uid = await _user()
async with async_session() as s:
made = {
"snippet": Note(user_id=uid, title="s", note_type="snippet"),
"note": Note(user_id=uid, title="n", note_type="note"),
"task:issue": Note(user_id=uid, title="i", status="todo", task_kind="issue"),
"task:work": Note(user_id=uid, title="w", status="todo", task_kind="work"),
}
s.add_all(made.values())
await s.commit()
ids = {k: n.id for k, n in made.items()}
for kinds in (["snippet", "task:issue"], ["note"], ["task:work"], []):
got = set((await s.execute(
select(Note.id).where(Note.id.in_(ids.values()), record_kinds.kinds_clause(kinds))
)).scalars())
assert got == {ids[k] for k in kinds}, kinds
async def test_each_cell_carries_the_lines_its_door_pushed_and_the_opens():
uid = await _user()
async with async_session() as s:
s.add_all([
RecordDelivery(user_id=uid, session_id="s", note_id=1, kind="snippet", way="pushed",
source="write_path_semantic", plugin="p",
opened_at=datetime.now(timezone.utc)),
RecordDelivery(user_id=uid, session_id="s", note_id=2, kind="snippet", way="pushed",
source="write_path_semantic", plugin="p"),
RecordDelivery(user_id=uid, session_id="s", note_id=3, kind="task:issue", way="pushed",
source="auto_inject", plugin="p"),
])
await s.commit()
table = await record_kinds.table(uid, days=7)
cells = {d["door"]: d["evidence"] for d in table["doors"]}
assert cells["work.change"] == {"snippet": {"delivered": 2, "opened": 1}}
assert cells["message"] == {"task:issue": {"delivered": 1, "opened": 0}}
assert table["evidence_failed"] is False
+5 -1
View File
@@ -91,14 +91,18 @@ async def test_the_tool_returns_the_catalog_with_this_installs_actions():
from grimoire.mcp.tools import moments as tool
by_moment = {"actions": {"work.change": []}, "removed_defaults": []}
table = {"doors": [{"door": "message", "kinds": ["snippet"]}]}
with patch.object(tool, "current_user_id", lambda: 7), \
patch.object(tool.actions_svc, "actions_by_moment",
AsyncMock(return_value=by_moment)) as read:
AsyncMock(return_value=by_moment)) as read, \
patch.object(tool.record_kinds_svc, "table", AsyncMock(return_value=table)) as kinds:
out = await tool.list_moments()
read.assert_awaited_once_with(7)
kinds.assert_awaited_once_with(7)
assert out["moments"] == moments.catalog()["moments"]
assert out["actions"] == by_moment["actions"]
assert out["removed_defaults"] == []
assert out["record_kinds"] == table
def test_the_tools_are_registered_and_classified():
+38 -8
View File
@@ -267,11 +267,41 @@ def test_the_pipelines_fan_out_sites_declare_every_notes_source():
"grimoire/services/plugin_context.py::record_surfaced(source=arm)"]
def test_the_filters_say_which_kinds_and_whose_records():
assert rp.note_search_filters(rp.AUTO_INJECT) == {
"include_global_kinds": True, "scope": "browse",
}
assert rp.note_search_filters(rp.WRITE_PATH) == {
"note_type": ("snippet", "note", LESSON_NOTE_TYPE), "task_kind": "issue",
"include_global_kinds": True, "scope": "browse",
}
def test_the_filters_say_whose_records_and_the_table_says_which_kinds():
for arm in (rp.AUTO_INJECT, rp.WRITE_PATH):
assert rp.note_search_filters(arm) == {"include_global_kinds": True, "scope": "browse"}
assert rp.AUTO_INJECT.door == "message" and rp.WRITE_PATH.door == "work.change"
@pytest.mark.asyncio
async def test_an_arm_searches_only_the_kinds_its_door_allows():
# The shipped defaults: the message door considers every kind, so its
# search is unfiltered; the write path narrows to its row.
_r, _io_, calls = await _run(rp.AUTO_INJECT, lambda kw: [])
assert calls[0]["record_kinds"] is None
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [])
assert calls[0]["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
# A user's own row replaces the default.
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [], kinds=frozenset({"snippet"}))
assert calls[0]["record_kinds"] == ["snippet"]
@pytest.mark.asyncio
async def test_a_door_with_every_kind_off_searches_nothing_and_logs_nothing():
result, io, calls = await _run(rp.AUTO_INJECT, lambda kw: [], kinds=frozenset())
assert calls == [] and result.menu == []
io.record_retrieval.assert_not_called()
@pytest.mark.asyncio
async def test_a_slot_whose_kind_the_door_turned_off_is_not_reserved():
main = [_note(1, 0.70), _note(2, 0.69), _note(3, 0.68)]
reuse = [_note(9, 0.60, note_type="snippet")]
lesson = [_note(42, 0.58, note_type=LESSON_NOTE_TYPE)]
result, _io_, calls = await _run(
rp.AUTO_INJECT, _routed(main, reuse, lesson), budget=3,
kinds=frozenset({"note", "process"}),
)
# The reuse slot narrows to processes; the lesson slot does not run.
assert [c.get("note_type") for c in calls] == [None, ("process",)]
assert "lesson_slot" not in result.slot_ids
+1 -1
View File
@@ -51,7 +51,7 @@ async def test_an_empty_verdict_list_is_refused():
# ── the re-run replays the arm ───────────────────────────────────────────
_FILTERS = ("note_type", "task_kind", "include_global_kinds", "scope")
_FILTERS = ("note_type", "task_kind", "record_kinds", "include_global_kinds", "scope")
@pytest.mark.asyncio
+1
View File
@@ -42,6 +42,7 @@ def test_every_endpoint_is_reachable_on_the_app():
"/api/retrieval/surfaces/<surface>",
"/api/retrieval/adherence",
"/api/retrieval/record-reach",
"/api/retrieval/record-kinds",
"/api/retrieval/gate",
"/api/retrieval/tuning-history",
"/api/retrieval/moments",