Merge pull request 'Records reach work: the record ledger and the kind×moment table (milestone 642, steps 1 and 3)' (#230) from dev into main
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Successful in 2m6s
CI & Build / integration (push) Successful in 2m2s
CI & Build / Build & push image (push) Successful in 17s

This commit was merged in pull request #230.
This commit is contained in:
2026-11-24 14:40:00 -05:00
36 changed files with 1602 additions and 51 deletions
@@ -0,0 +1,44 @@
"""record deliveries: each non-rule record put in front of a session, and whether it was opened
Revision ID: 0136
Revises: 0135
Create Date: 2026-11-24
The note-side twin of `rule_deliveries`. A row per record a hook pushed, a
search the session ran returned, or the session opened with nothing
delivering it first, so opens can be told apart by the way the record
arrived.
"""
import sqlalchemy as sa
from alembic import op
revision = "0136"
down_revision = "0135"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"record_deliveries",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("user_id", sa.BigInteger(), nullable=False),
sa.Column("session_id", sa.Text(), nullable=False),
sa.Column("note_id", sa.BigInteger(), nullable=False),
sa.Column("kind", sa.Text(), nullable=False),
sa.Column("way", sa.Text(), nullable=False),
sa.Column("source", sa.Text(), nullable=False),
sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.Column("opened_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("plugin", sa.Text(), nullable=True),
)
op.create_index("ix_record_deliveries_session_note", "record_deliveries",
["user_id", "session_id", "note_id", "delivered_at"])
op.create_index("ix_record_deliveries_delivered_at", "record_deliveries", ["delivered_at"])
def downgrade() -> None:
op.drop_index("ix_record_deliveries_delivered_at", table_name="record_deliveries")
op.drop_index("ix_record_deliveries_session_note", table_name="record_deliveries")
op.drop_table("record_deliveries")
+59 -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,64 @@ 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";
export interface WayCounts {
delivered: number;
opened: number;
}
export interface RecordReachKind {
/** `snippet`, `note`, `lesson`, `process`, or `task:<kind>`. */
kind: string;
ways: Record<RecordWay, WayCounts>;
sources: { way: RecordWay; source: string; delivered: number; opened: number }[];
}
export interface RecordReachPayload {
days: number;
sessions: number;
totals: Record<RecordWay, WayCounts>;
by_kind: RecordReachKind[];
}
/** How non-rule records reached sessions: pushed, asked for, or opened directly. */
export function getRecordReach(days = 30): Promise<RecordReachPayload> {
return apiGet(`/api/retrieval/record-reach?days=${days}`);
}
/** Whether the rules in force at each moment were followed there. */
export function getAdherence(days = 30): Promise<AdherencePayload> {
return apiGet(`/api/retrieval/adherence?days=${days}`);
+21 -3
View File
@@ -4,9 +4,11 @@ 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 } from "@/api/moments";
import type { AdherencePayload, MomentAction, MomentAdherenceRow, MomentUsage } from "@/api/moments";
import { getAdherence, getRecordReach } from "@/api/moments";
import type { AdherencePayload, MomentAction, MomentAdherenceRow, MomentUsage, RecordReachPayload } from "@/api/moments";
import { fmtDate } from "@/utils/dateFormat";
/**
@@ -48,6 +50,20 @@ async function loadAdherence() {
}
}
// How records other than rules reach sessions, read on its own for the same
// reason as adherence.
const reach = ref<RecordReachPayload | null>(null);
const reachFailed = ref(false);
async function loadReach() {
try {
reach.value = await getRecordReach(days.value);
reachFailed.value = false;
} catch {
reachFailed.value = true;
}
}
function followed(moment: string): MomentAdherenceRow | null {
return adherence.value?.by_moment.find((m) => m.at === moment) ?? null;
}
@@ -128,7 +144,7 @@ async function addMapping() {
onMounted(async () => {
await store.load(true);
await loadAdherence();
await Promise.all([loadAdherence(), loadReach()]);
});
</script>
@@ -156,6 +172,8 @@ onMounted(async () => {
<MomentProposals />
<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" />
+115
View File
@@ -0,0 +1,115 @@
<script setup lang="ts">
import { computed } from "vue";
import type { RecordReachPayload, RecordWay, WayCounts } from "@/api/moments";
/**
* How records other than rules reached sessions: shown by a hook, found by a
* search the session ran itself, or opened with nothing showing them first —
* and how many were opened each way. It says, per kind, whether a record is
* found by being pushed or by being asked for. One row per kind; open a row
* for the doors behind it.
*/
const props = defineProps<{
data: RecordReachPayload | null;
failed: boolean;
}>();
const emit = defineEmits<{ retry: [] }>();
const rows = computed(() => props.data?.by_kind ?? []);
const KIND_LABELS: Record<string, string> = {
snippet: "Snippets",
note: "Notes",
lesson: "Lessons",
process: "Processes",
"task:issue": "Issues",
"task:work": "Work tasks",
"task:spike": "Spikes",
};
function kindLabel(kind: string): string {
return KIND_LABELS[kind] ?? kind;
}
// Each way in reading order. A direct open is opened by definition, so it
// shows one number; the others show how many of those delivered were opened.
const WAYS: [RecordWay, string][] = [
["pushed", "shown by a hook"],
["asked", "from its own search"],
["direct", "opened unshown"],
];
function wayText(way: RecordWay, c: WayCounts): string {
return way === "direct" ? `${c.opened}` : `${c.opened} of ${c.delivered}`;
}
</script>
<template>
<section class="reach" aria-labelledby="reach-title">
<h3 id="reach-title" class="sub-title">How records reach the work</h3>
<p v-if="failed" class="error-msg">
Record reach could not be loaded.
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
</p>
<p v-else-if="!data" class="empty-msg">Loading record reach…</p>
<p v-else-if="!rows.length" class="empty-msg">
No record reached a session in the last {{ data.days }} days from a plugin that reports opens.
</p>
<template v-else>
<p class="field-hint">
Records opened, out of those delivered, over the last {{ data.days }} days across
{{ data.sessions }} sessions: shown by a hook, returned by a search the session ran,
or opened with nothing showing them first.
</p>
<div class="reach-totals">
<span v-for="[way, label] in WAYS" :key="way">
{{ label }} {{ wayText(way, data.totals[way]) }}
</span>
</div>
<ul class="reach-list">
<li v-for="r in rows" :key="r.kind" class="reach-kind">
<details>
<summary class="reach-row">
<span class="reach-title">{{ kindLabel(r.kind) }}</span>
<span class="reach-counts">
<span v-for="[way, label] in WAYS" :key="way" :class="{ 'way-none': !r.ways[way].delivered }">
{{ label }} {{ wayText(way, r.ways[way]) }}
</span>
</span>
</summary>
<ul class="reach-sources">
<li v-for="s in r.sources" :key="`${s.way}:${s.source}`" class="reach-row">
<code class="moment-name">{{ s.source }}</code>
<span class="reach-counts">
<span>{{ s.way === "direct" ? `${s.opened} opened` : `${s.opened} of ${s.delivered} opened` }}</span>
</span>
</li>
</ul>
</details>
</li>
</ul>
</template>
</section>
</template>
<style scoped>
.reach { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.reach-totals,
.reach-counts {
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2);
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary);
font-variant-numeric: tabular-nums;
}
.reach-counts { margin-left: auto; justify-content: flex-end; }
.reach-list,
.reach-sources { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
.reach-sources { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
.reach-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.reach-kind summary { cursor: pointer; }
.reach-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
/* A way that delivered nothing for this kind is a gap, not a zero to read. */
.way-none { color: var(--fs-text-tertiary); }
</style>
<style src="@/assets/moments-shared.css" />
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.11.23.2305",
"version": "2026.11.24.1827",
"author": {
"name": "Bryan Van Deusen"
},
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Grimoire — tell the server this session opened a record, or ran a search.
#
# WHAT THIS ANSWERS
#
# A hook puts records in front of a session (prior art, the notes menu); the
# session also searches for records itself, and opens others it reached on
# its own (an id in a task log, a record the operator named). The server
# records what each hook pushed against the session. This reports the other
# half, from the tool calls themselves:
#
# - `get_note`, `get_task`, `get_snippet`, `get_lesson`, `get_process` — the
# record was opened. The server stamps the delivery it followed, or records
# a direct open when nothing delivered it first.
# - `search` — the session asked. The server reads what that call returned
# from its own log and records those results against the session, so an
# open that follows counts as one reached by asking.
#
# Together they say, per kind of record, how much a session is shown, how
# much it asks for, how much it reaches on its own, and what it opens.
#
# A tool call happened or it did not, and the harness reports it either way:
# this asks the session nothing.
#
# EXIT 0, ALWAYS, silent on outage. This is bookkeeping; a failure here must
# never turn a successful tool call into a hook error.
set -uo pipefail
# shellcheck source=plugin/hooks/grimoire_defs.sh
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
event=$(cat 2>/dev/null || true)
[ -n "$event" ] || exit 0
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
[ -n "$session_id" ] || exit 0
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
command -v curl >/dev/null 2>&1 || exit 0
grimoire_config || exit 0
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
post() {
printf '%s' "$2" | curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/$1" >/dev/null 2>&1 || true
}
case "$tool_name" in
*__search)
q=$(grimoire_json_pick "$event_flat" '.tool_input.q')
[ -n "$q" ] || exit 0
q_esc=$(printf '%s' "$q" | grimoire_json_escape) || exit 0
post record-searched "$(printf '{"session_id":"%s","q":"%s"}' "$sid_esc" "$q_esc")"
;;
*)
# Each getter names its id differently; read whichever is present. A
# process opened by name rather than id is left unrecorded.
note_id=""
for field in note_id task_id snippet_id lesson_id name_or_id; do
note_id=$(grimoire_json_pick "$event_flat" ".tool_input.${field}")
[ -n "$note_id" ] && break
done
case "$note_id" in
''|*[!0-9]*) exit 0 ;;
esac
post record-opened "$(printf '{"session_id":"%s","note_id":%s}' "$sid_esc" "$note_id")"
;;
esac
exit 0
+9
View File
@@ -81,6 +81,15 @@
}
]
},
{
"matcher": "mcp__.*__(get_note|get_task|get_snippet|get_lesson|get_process|search)",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_record_read.sh\""
}
]
},
{
"matcher": "mcp__.*__(rule_outcome|rule_misfired)",
"hooks": [
+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
+9
View File
@@ -528,6 +528,15 @@ async def retrieval_telemetry(
a ratio of opens would read near zero on an arm that is working.
`system_usage_failed: true` means its read broke and the zeros mean nothing.
`record_reach` — how every non-rule record reached a session, from
`record_deliveries`: per kind (`snippet`, `note`, `lesson`, `task:issue`,
…), each way it arrived — `pushed` by a hook, `asked` (a result of a
`search` the session ran itself), `direct` (opened with nothing
delivering it first) — with `delivered` and `opened`, and per door in
`sources`. It is the readout that says whether a kind is found by being
pushed or by being asked for, which `usage` cannot: a pull there does not
say which door led to it. Counts only sessions whose plugin reports opens.
`judged` — whether the lines RELATED, from `retrieval_judgments`:
per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`)
on a sample of logged menus, `within_budget` against `beyond_budget` and
+1
View File
@@ -62,6 +62,7 @@ from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401
from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401
from grimoire.models.rule_adherence import RuleAdherence # noqa: E402, F401
from grimoire.models.record_delivery import RecordDelivery # noqa: E402, F401
from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401
from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
+78
View File
@@ -0,0 +1,78 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, Index, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import iso
# How a record came to be in front of the session.
PUSHED = "pushed" # a hook put it there unasked (auto-inject, the write path, a slot)
ASKED = "asked" # it was a result of a search the session ran itself
DIRECT = "direct" # it was opened with nothing delivering it first in the session
WAYS = (PUSHED, ASKED, DIRECT)
class RecordDelivery(Base):
"""One record put in front of one session, and whether it was opened.
The note-side twin of `rule_deliveries`, for every record kind that is not
a rule (note, snippet, issue, work task, lesson, process). It answers what
`note_usage_events` cannot: a pull there does not say which door led to
it, so "was this note opened because a hook pushed it, because the session
searched for it, or because the session went to it on its own" has no
answer. Here each line is a row against its session, and the open is
stamped on the row it followed.
`way` says how the record arrived (`pushed`, `asked`, `direct`). `source`
is the door: the hook arm (`auto_inject`, `write_path_semantic`,
`write_path_place`, `lesson_slot`, …), `mcp_search` for a search the
session ran, or `direct`. `kind` is the record's kind when it was
delivered (`snippet`, `note`, `lesson`, `process`, `task:issue`,
`task:work`, …), kept on the row so the readout needs no join and survives
the record's deletion.
A `direct` row is written when a session opens a record that nothing
delivered to it within the open window — found through a cross-reference,
a task's own id, the operator naming it. It is delivered and opened at the
same instant, and it is the measure of records a session reaches without
being shown them.
FK-free on `note_id` and `user_id`, like the other telemetry tables, and
pruned after `rule_deliveries.RETAIN_DAYS`.
"""
__tablename__ = "record_deliveries"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
session_id: Mapped[str] = mapped_column(Text, nullable=False)
note_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
kind: Mapped[str] = mapped_column(Text, nullable=False)
way: Mapped[str] = mapped_column(Text, nullable=False)
source: Mapped[str] = mapped_column(Text, nullable=False)
delivered_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = (
# Stamping an open: this session's latest delivery of this record.
Index("ix_record_deliveries_session_note", "user_id", "session_id", "note_id", "delivered_at"),
Index("ix_record_deliveries_delivered_at", "delivered_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"session_id": self.session_id,
"note_id": self.note_id,
"kind": self.kind,
"way": self.way,
"source": self.source,
"delivered_at": iso(self.delivered_at),
"opened_at": iso(self.opened_at),
"plugin": self.plugin,
}
+51 -1
View File
@@ -22,6 +22,7 @@ from grimoire.services import reply_shapes as reply_shapes_svc
from grimoire.services import repo_bindings as repo_bindings_svc
from grimoire.services import rule_adherence as rule_adherence_svc
from grimoire.services import report_check as report_check_svc
from grimoire.services import record_deliveries as record_deliveries_svc
from grimoire.services import rule_deliveries as rule_deliveries_svc
from grimoire.services import rule_moment_judgments as judgments_svc
from grimoire.services import shape_check as shape_check_svc
@@ -60,12 +61,14 @@ async def _bind_delivery_session() -> None:
@plugin_bp.after_request
async def _flush_deliveries(response):
"""Write any rule deliveries a door rendered without fitting a payload.
"""Write any rule and record deliveries a door rendered without fitting a
payload.
A door that fits its payload (`hook_payload.fit`) has already written the
lines it kept and dropped the rest, so this finds nothing left for it.
"""
rule_deliveries_svc.flush()
record_deliveries_svc.flush()
return response
@@ -459,6 +462,53 @@ async def rule_opened():
))
@plugin_bp.post("/record-opened")
@login_required
async def record_opened():
"""A session opened a record (a note, snippet, task, lesson or process).
Body: `{"session_id", "note_id"}`, posted by the plugin after a `get_note`,
`get_task`, `get_snippet`, `get_lesson` or `get_process` call. The open is
stamped on this session's latest delivery of the record; with none, it
is recorded as `direct`, a record reached without being shown. Answers
`{"way"}`: how the open was counted, or "" when it was not.
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
return jsonify({"way": ""})
try:
note_id = int(data.get("note_id") or 0)
except (TypeError, ValueError):
note_id = 0
if note_id <= 0:
return jsonify({"way": ""})
way = await record_deliveries_svc.mark_opened(
g.user.id, str(data.get("session_id") or ""), note_id,
plugin=rule_deliveries_svc.current_plugin(),
)
return jsonify({"way": way})
@plugin_bp.post("/record-searched")
@login_required
async def record_searched():
"""A session ran `search` itself.
Body: `{"session_id", "q"}`, posted by the plugin after the call. The
results that call returned, read from the server's own log of it, are
recorded against the session as `asked`, so an open that follows counts
as one the session reached by asking. Answers `{"recorded"}`.
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
return jsonify({"recorded": 0})
recorded = await record_deliveries_svc.from_search(
g.user.id, str(data.get("session_id") or ""), str(data.get("q") or ""),
plugin=rule_deliveries_svc.current_plugin(),
)
return jsonify({"recorded": recorded})
@plugin_bp.post("/rule-verdict")
@login_required
async def rule_verdict():
+48
View File
@@ -21,6 +21,8 @@ from grimoire.auth import get_current_user_id, login_required
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
@@ -258,6 +260,52 @@ 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():
"""How non-rule records reached this user's sessions: per kind, pushed by
a hook, returned by the session's own search, or opened directly, and how
many were opened each way. `?days=` sets the window (default 30)."""
try:
days = int(request.args.get("days") or 30)
except ValueError:
return jsonify({"error": "days must be a whole number"}), 400
return jsonify(await record_deliveries_svc.summary(get_current_user_id(), days=days))
@retrieval_bp.route("/weights/proposals", methods=["GET"])
@login_required
async def weight_proposals_route():
+2
View File
@@ -199,6 +199,8 @@ _NOT_INCLUDED = [
# Adherence verdicts on those deliveries, keyed by the same session ids
# and pruned with them.
"rule_adherence",
# The same per-session ledger for every other record kind.
"record_deliveries",
# Verdicts on retrieval_logs rows, so they go where their subject
# goes: a restore that carried a judgment of a call it did not carry would
# leave a verdict on nothing. A sample, re-takeable by the review pass.
+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
+4 -2
View File
@@ -120,11 +120,13 @@ def assemble(parts, budget: int) -> Fitted:
async def fit(user_id: int, parts) -> Fitted:
"""Assemble under this user's budget and record the rule lines delivered."""
from grimoire.services import rule_deliveries
"""Assemble under this user's budget and record the rule and record lines
delivered."""
from grimoire.services import record_deliveries, rule_deliveries
fitted = assemble(list(parts), await payload_budget(user_id))
rule_deliveries.flush(set(fitted.ids(RULE)))
record_deliveries.flush(set(fitted.ids(NOTE)))
return fitted
+9
View File
@@ -136,6 +136,15 @@ def record_surfaced(
logger.debug("note usage payload build failed", exc_info=True)
return
_schedule(rows)
# The same lines, against the session a plugin door is delivering to. A
# synced skill is not a line in front of the session, so it is left out.
if source not in _NOT_A_LINE:
from grimoire.services import record_deliveries
record_deliveries.record(user_id, note_ids, source)
# Surfacing sources that put nothing in front of the session as a line.
_NOT_A_LINE = frozenset({"process_skill_sync"})
def record_pulled(
+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(),
)
+264
View File
@@ -0,0 +1,264 @@
"""Each non-rule record put in front of a session, how it got there, and
whether the session opened it.
One table (`record_deliveries`), the note-side twin of `rule_deliveries`, and
four calls:
- `record` — from `note_usage.record_surfaced`, every record a plugin door
pushed to a bound session. Within a request the rows wait until the door's
payload is fitted, and `flush` writes only those whose line made it in
(`hook_payload.fit`), exactly as rule lines are kept.
- `from_search` — the session ran `search` itself; the plugin reports it and
the results that call returned are recorded as `asked`.
- `mark_opened` — the session opened a record. The latest unopened delivery
of it in the session gets the stamp. With nothing delivering it first, a
`direct` row is written, delivered and opened at once: the record was
reached without being shown.
- `summary` — per kind, how records arrived (`pushed`, `asked`, `direct`),
by door, and how many were opened.
Only rows from a plugin that reports its version count in the readout: an
older plugin does not report opens, so its rows would read as never opened.
"""
from __future__ import annotations
import logging
from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from sqlalchemy import case, delete, func, select, tuple_, update
from grimoire.models import async_session
from grimoire.models.note import Note
from grimoire.models.record_delivery import ASKED, DIRECT, PUSHED, RecordDelivery
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__)
# A search the plugin reports is matched to the call the server logged within
# this long before; the report follows the call by a second or two, so a
# longer window only adds the chance of matching an older identical query.
SEARCH_MATCH_WINDOW = timedelta(minutes=3)
SEARCH_SOURCE = "mcp_search"
DIRECT_SOURCE = "direct"
# Rows a bound request rendered, written by `flush`. Reset per request by
# `rule_deliveries.bind_session`, so the two ledgers share one binding.
_pending: ContextVar[list | None] = ContextVar("record_delivery_pending", default=None)
def reset() -> None:
_pending.set([])
def record(user_id: int | None, note_ids, source: str) -> None:
"""Record records a hook pushed to the bound session. A no-op outside a
plugin request, since an open could never be tied back to it."""
sid = rule_deliveries.current_session()
if not sid or not user_id:
return
try:
rows = [{"user_id": int(user_id), "session_id": sid, "note_id": int(n),
"way": PUSHED, "source": source, "plugin": rule_deliveries.current_plugin()}
for n in dict.fromkeys(note_ids or [])]
except Exception: # noqa: BLE001 - observation never breaks the observed
logger.debug("record delivery payload build failed", exc_info=True)
return
pending = _pending.get()
if pending is not None:
pending.extend(rows)
elif rows:
spawn(_insert(rows), site="record_delivery_write")
def flush(kept: set[int] | None = None) -> None:
"""Write this request's buffered rows: those for records in `kept`, or all
of them when `kept` is None. A record whose line the payload left out was
never shown, so its row is dropped."""
rows = _pending.get()
if not rows:
return
_pending.set([])
if kept is not None:
rows = [r for r in rows if r["note_id"] in kept]
if rows:
spawn(_insert(rows), site="record_delivery_write")
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."""
rows = (await session.execute(
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_of(t, s, k) for i, t, s, k in rows}
async def _insert(rows: list[dict]) -> None:
"""Write rows, each with its record's kind. An id that is not a record (a
rule id in a mixed list, a deleted note) is dropped. A record the session
already opened within the open window is stamped opened as it is
written, as `rule_deliveries` does: it reached a reader who has it."""
now = datetime.now(timezone.utc)
async with async_session() as session:
kinds: dict[tuple[int, int], str] = {}
for uid in {r["user_id"] for r in rows}:
found = await _kinds(session, uid, {r["note_id"] for r in rows if r["user_id"] == uid})
kinds.update({(uid, nid): k for nid, k in found.items()})
rows = [{**r, "kind": kinds[(r["user_id"], r["note_id"])]}
for r in rows if (r["user_id"], r["note_id"]) in kinds]
if not rows:
return
keys = list({(r["user_id"], r["session_id"], r["note_id"]) for r in rows})
read = {tuple(k) for k in (await session.execute(
select(RecordDelivery.user_id, RecordDelivery.session_id, RecordDelivery.note_id)
.where(
tuple_(RecordDelivery.user_id, RecordDelivery.session_id, RecordDelivery.note_id).in_(keys),
RecordDelivery.opened_at >= now - rule_deliveries.OPEN_WINDOW,
)
.distinct()
)).all()}
for r in rows:
if (r["user_id"], r["session_id"], r["note_id"]) in read:
r["opened_at"] = now
session.add_all(RecordDelivery(**r) for r in rows)
await session.commit()
async def from_search(user_id: int, session_id: str | None, query: str, plugin: str | None = None) -> int:
"""Record the results of a search this session ran itself, as `asked`.
The MCP call does not know its session; the plugin does, and reports the
query after the call. The server's own log of that call
(`retrieval_logs`, source `mcp_search`) holds what it returned, so the
report is matched to the latest logged call with the same query in
`SEARCH_MATCH_WINDOW`. Returns how many records were recorded.
"""
sid = rule_deliveries.clean_session(session_id)
if not sid or not (query or "").strip():
return 0
since = datetime.now(timezone.utc) - SEARCH_MATCH_WINDOW
async with async_session() as session:
result_ids = (await session.execute(
select(RetrievalLog.result_ids)
.where(RetrievalLog.user_id == user_id, RetrievalLog.source == SEARCH_SOURCE,
RetrievalLog.query == query, RetrievalLog.created_at >= since)
.order_by(RetrievalLog.created_at.desc(), RetrievalLog.id.desc())
.limit(1)
)).scalar_one_or_none()
ids = [int(h["id"]) for h in (result_ids or []) if isinstance(h, dict) and str(h.get("id", "")).isdigit()]
if not ids:
return 0
rows = [{"user_id": int(user_id), "session_id": sid, "note_id": n, "way": ASKED,
"source": SEARCH_SOURCE, "plugin": plugin} for n in dict.fromkeys(ids)]
await _insert(rows)
return len(rows)
async def mark_opened(user_id: int, session_id: str | None, note_id: int, plugin: str | None = None) -> str:
"""Stamp this session's latest unopened delivery of the record, within the
open window. With none, write a `direct` row: the session reached the
record without being shown it. Returns the way the open is counted
under, or "" when nothing was recorded."""
sid = rule_deliveries.clean_session(session_id)
if not sid or not note_id:
return ""
now = datetime.now(timezone.utc)
async with async_session() as session:
latest = (await session.execute(
select(RecordDelivery.id, RecordDelivery.way)
.where(
RecordDelivery.user_id == user_id,
RecordDelivery.session_id == sid,
RecordDelivery.note_id == int(note_id),
RecordDelivery.opened_at.is_(None),
RecordDelivery.delivered_at >= now - rule_deliveries.OPEN_WINDOW,
)
.order_by(RecordDelivery.delivered_at.desc(), RecordDelivery.id.desc())
.limit(1)
)).first()
if latest is not None:
await session.execute(
update(RecordDelivery).where(RecordDelivery.id == latest[0]).values(opened_at=now)
)
await session.commit()
return str(latest[1])
kinds = await _kinds(session, int(user_id), {int(note_id)})
if int(note_id) not in kinds:
return ""
already = (await session.execute(
select(RecordDelivery.id).where(
RecordDelivery.user_id == user_id, RecordDelivery.session_id == sid,
RecordDelivery.note_id == int(note_id),
RecordDelivery.opened_at >= now - rule_deliveries.OPEN_WINDOW,
).limit(1)
)).scalar_one_or_none()
if already is not None:
# Read again: the first open was counted where it happened.
return ""
session.add(RecordDelivery(
user_id=int(user_id), session_id=sid, note_id=int(note_id), kind=kinds[int(note_id)],
way=DIRECT, source=DIRECT_SOURCE, delivered_at=now, opened_at=now, plugin=plugin,
))
await session.commit()
return DIRECT
async def summary(user_id: int, days: int = 30) -> dict:
"""How records reached this user's sessions over the last `days`.
Per kind: `delivered` and `opened` rows for each way a record arrived
(`pushed` by a hook, `asked` through the session's own search, `direct`
when it was opened with nothing delivering it), and per door. A `direct`
row is always opened; it is counted so the readout shows how much a
session reaches without being shown.
"""
days = max(1, min(int(days or 30), rule_deliveries.RETAIN_DAYS))
since = datetime.now(timezone.utc) - timedelta(days=days)
async with async_session() as session:
rows = (await session.execute(
select(
RecordDelivery.kind, RecordDelivery.way, RecordDelivery.source,
func.count(RecordDelivery.id),
func.sum(case((RecordDelivery.opened_at.is_not(None), 1), else_=0)),
func.count(func.distinct(RecordDelivery.session_id)),
)
.where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since,
RecordDelivery.plugin.is_not(None))
.group_by(RecordDelivery.kind, RecordDelivery.way, RecordDelivery.source)
)).all()
sessions = (await session.execute(
select(func.count(func.distinct(RecordDelivery.session_id)))
.where(RecordDelivery.user_id == user_id, RecordDelivery.delivered_at >= since,
RecordDelivery.plugin.is_not(None))
)).scalar_one()
def zero() -> dict:
return {w: {"delivered": 0, "opened": 0} for w in (PUSHED, ASKED, DIRECT)}
kinds: dict[str, dict] = {}
totals = zero()
for kind, way, source, delivered, opened, _sessions in rows:
slot = kinds.setdefault(kind, {"kind": kind, "ways": zero(), "sources": []})
for bucket in (slot["ways"], totals):
bucket[way]["delivered"] += int(delivered)
bucket[way]["opened"] += int(opened or 0)
slot["sources"].append({"way": way, "source": source,
"delivered": int(delivered), "opened": int(opened or 0)})
for slot in kinds.values():
slot["sources"].sort(key=lambda s: (-s["delivered"], s["source"]))
by_kind = sorted(kinds.values(),
key=lambda k: (-sum(w["delivered"] for w in k["ways"].values()), k["kind"]))
return {"days": days, "sessions": int(sessions or 0), "totals": totals, "by_kind": by_kind}
async def prune(cutoff: datetime) -> int:
async with async_session() as session:
result = await session.execute(delete(RecordDelivery).where(RecordDelivery.delivered_at < cutoff))
await session.commit()
return int(result.rowcount or 0)
+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)]
@@ -1718,6 +1718,17 @@ async def retrieval_summary(
out["rule_usage"] = rule_usage
out["system_usage"] = await _system_usage(user_id, since)
out["moment_usage"] = await moment_usage(user_id, since)
# How each non-rule record reached a session: pushed by a hook, returned
# by a search the session ran, or opened with nothing delivering it — and
# how many were opened each way. Its own guard, so a failure flags itself.
try:
from grimoire.services import record_deliveries
out["record_reach"] = (await record_deliveries.summary(user_id, days=days)
if user_id else None)
except Exception:
logger.exception("record reach read failed")
out["record_reach"] = None
out["record_reach_failed"] = True
# ── Judged lines ─────────────────────────────────────────────────────
#
+13 -2
View File
@@ -64,6 +64,9 @@ def bind_session(session_id: str | None, plugin: str | None = None) -> None:
_session.set(clean_session(session_id))
_plugin.set(_UNSAFE.sub("_", (plugin or "").strip())[:_PLUGIN_MAX])
_pending.set([])
# The record ledger delivers to the same session, under the same binding.
from grimoire.services import record_deliveries
record_deliveries.reset()
def flush(kept: set[int] | None = None) -> None:
@@ -91,6 +94,11 @@ def current_session() -> str:
return _session.get()
def current_plugin() -> str | None:
"""The plugin version that sent this request, or None when it sent none."""
return _plugin.get() or None
def clean_session(session_id: str | None) -> str:
# The plugin's own filename-safe form of the id, so a hook that sends the
# raw id and one that sends the safe one name the same session.
@@ -252,8 +260,9 @@ async def retired(user_id: int, rule_ids: list[int]) -> set[int]:
async def prune(retain_days: int = RETAIN_DAYS) -> int:
"""Delete deliveries older than `retain_days`, and the adherence verdicts
on them (`rule_adherence`), which mean nothing without their delivery."""
"""Delete deliveries older than `retain_days`, the adherence verdicts on
them (`rule_adherence`), which mean nothing without their delivery, and
the record deliveries of the same age (`record_deliveries`)."""
from grimoire.services import rule_adherence
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
@@ -263,6 +272,8 @@ async def prune(retain_days: int = RETAIN_DAYS) -> int:
)
await session.commit()
await rule_adherence.prune(cutoff)
from grimoire.services import record_deliveries
await record_deliveries.prune(cutoff)
return int(result.rowcount or 0)
+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.
+140
View File
@@ -0,0 +1,140 @@
"""Real-Postgres tests for `record_deliveries`: every non-rule record put in
front of a session, the way it arrived (pushed, asked, direct), and the open
stamped on the delivery it followed."""
from datetime import datetime, timedelta, 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.retrieval_log import RetrievalLog
from grimoire.services import background, note_usage, record_deliveries, rule_deliveries
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
PLUGIN = "2026.11.24.1900"
async def _setup(name: str = "record_delivery_owner") -> tuple[int, dict[str, int]]:
"""A user with one record of each kind the readout tells apart."""
async with async_session() as s:
user = await ensure_user(s, name)
uid = user.id
await s.execute(delete(RecordDelivery).where(RecordDelivery.user_id == uid))
await s.execute(delete(RetrievalLog).where(RetrievalLog.user_id == uid))
notes = {
"snippet": Note(user_id=uid, title="a snippet", note_type="snippet"),
"note": Note(user_id=uid, title="a note", note_type="note"),
"issue": Note(user_id=uid, title="an issue", status="todo", task_kind="issue"),
"lesson": Note(user_id=uid, title="a lesson", note_type="lesson"),
}
s.add_all(notes.values())
await s.commit()
return uid, {k: n.id for k, n in notes.items()}
async def _rows(uid: int) -> list[RecordDelivery]:
async with async_session() as s:
return list((await s.execute(
select(RecordDelivery).where(RecordDelivery.user_id == uid).order_by(RecordDelivery.id)
)).scalars().all())
async def _push(uid, sid, ids, source="write_path_semantic", kept=None):
"""What a plugin door does: bind the session, surface, fit, flush."""
rule_deliveries.bind_session(sid, PLUGIN)
try:
note_usage.record_surfaced(user_id=uid, note_ids=ids, source=source)
record_deliveries.flush(kept)
await background.drain()
finally:
rule_deliveries.bind_session("")
async def test_a_pushed_line_is_recorded_with_its_kind_only_when_the_payload_kept_it():
uid, n = await _setup()
await _push(uid, "s-1", [n["snippet"], n["issue"], n["lesson"]], kept={n["snippet"], n["issue"]})
rows = await _rows(uid)
assert [(r.note_id, r.kind, r.way, r.source, r.plugin) for r in rows] == [
(n["snippet"], "snippet", "pushed", "write_path_semantic", PLUGIN),
(n["issue"], "task:issue", "pushed", "write_path_semantic", PLUGIN),
]
async def test_nothing_is_recorded_outside_a_session_or_for_a_synced_skill():
uid, n = await _setup()
note_usage.record_surfaced(user_id=uid, note_ids=[n["note"]], source="auto_inject")
await _push(uid, "s-1", [n["note"]], source="process_skill_sync")
await background.drain()
assert await _rows(uid) == []
async def test_a_record_the_reader_cannot_read_is_not_recorded():
uid, _n = await _setup()
_other, theirs = await _setup("record_delivery_stranger")
await _push(uid, "s-1", [theirs["note"]])
assert await _rows(uid) == []
assert await record_deliveries.mark_opened(uid, "s-1", theirs["note"]) == ""
async def test_an_open_is_stamped_on_the_delivery_it_followed_and_otherwise_counts_as_direct():
uid, n = await _setup()
await _push(uid, "s-1", [n["snippet"]])
assert await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN) == "pushed"
# Nothing delivered the note to this session: reached on its own.
assert await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN) == "direct"
# Opened again: the first open was already counted.
assert await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN) == ""
rows = {(r.note_id, r.way): r.opened_at is not None for r in await _rows(uid)}
assert rows == {(n["snippet"], "pushed"): True, (n["note"], "direct"): True}
async def test_a_search_the_session_ran_records_its_results_as_asked():
uid, n = await _setup()
async with async_session() as s:
s.add(RetrievalLog(user_id=uid, source="mcp_search", query="how is the lock released",
result_count=2,
result_ids=[{"id": n["issue"], "score": 0.8, "rank": 1},
{"id": n["note"], "score": 0.7, "rank": 2}]))
s.add(RetrievalLog(user_id=uid, source="mcp_search", query="something else", result_count=1,
result_ids=[{"id": n["lesson"], "score": 0.9, "rank": 1}]))
await s.commit()
assert await record_deliveries.from_search(uid, "s-1", "how is the lock released", PLUGIN) == 2
assert await record_deliveries.from_search(uid, "s-1", "never searched", PLUGIN) == 0
assert await record_deliveries.mark_opened(uid, "s-1", n["issue"], PLUGIN) == "asked"
assert sorted((r.note_id, r.way) for r in await _rows(uid)) == sorted(
[(n["issue"], "asked"), (n["note"], "asked")])
async def test_a_record_already_opened_in_the_session_counts_as_opened_when_pushed_again():
uid, n = await _setup()
assert await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN) == "direct"
await _push(uid, "s-1", [n["snippet"]])
await _push(uid, "s-2", [n["snippet"]])
later = {r.session_id: r.opened_at is not None for r in await _rows(uid) if r.way == "pushed"}
assert later == {"s-1": True, "s-2": False}
async def test_the_readout_counts_each_way_per_kind_from_plugins_that_report_opens():
uid, n = await _setup()
await _push(uid, "s-1", [n["snippet"], n["issue"]])
await record_deliveries.mark_opened(uid, "s-1", n["snippet"], PLUGIN)
await record_deliveries.mark_opened(uid, "s-1", n["note"], PLUGIN)
# A row from a plugin that never reports opens says nothing about them.
async with async_session() as s:
s.add(RecordDelivery(user_id=uid, session_id="old", note_id=n["lesson"], kind="lesson",
way="pushed", source="write_path_semantic", plugin=None,
delivered_at=datetime.now(timezone.utc) - timedelta(minutes=1)))
await s.commit()
out = await record_deliveries.summary(uid, days=7)
kinds = {k["kind"]: k["ways"] for k in out["by_kind"]}
assert kinds["snippet"]["pushed"] == {"delivered": 1, "opened": 1}
assert kinds["task:issue"]["pushed"] == {"delivered": 1, "opened": 0}
assert kinds["note"]["direct"] == {"delivered": 1, "opened": 1}
assert "lesson" not in kinds
assert out["totals"]["pushed"] == {"delivered": 2, "opened": 1}
assert out["sessions"] == 1
+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
+3 -3
View File
@@ -101,10 +101,10 @@ async def test_the_write_path_asks_for_lessons_at_all():
await pc.build_write_path_hint(1, "src/ui/Badge.vue", code="x" * 400)
kw = search.await_args.kwargs
assert LESSON_NOTE_TYPE in kw["note_type"]
# The kinds it already carried must survive the addition — a tuple rewritten
assert LESSON_NOTE_TYPE in kw["record_kinds"]
# The kinds it already carried must survive the addition — a set rewritten
# rather than extended would trade one unreachable kind for another.
assert {"snippet", "note"} <= set(kw["note_type"])
assert {"snippet", "note"} <= set(kw["record_kinds"])
assert kw["include_global_kinds"] is True
+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
+59
View File
@@ -0,0 +1,59 @@
"""`grimoire_record_read.sh`, run for real through bash with a stand-in `curl`:
an opened record and a search the session ran are reported to the server
with the session, and the hook is registered on exactly those tools."""
from __future__ import annotations
import json
import re
from tests.test_rule_moment_signal_hooks import HOOKS, _run, sandbox # noqa: F401 - fixture
ROOT = HOOKS.parents[1]
def _sent(tmp) -> tuple[str, dict | None]:
log = (tmp / "curl.log").read_text() if (tmp / "curl.log").exists() else ""
body = (tmp / "curl.body").read_text() if (tmp / "curl.body").exists() else ""
return log, (json.loads(body) if body else None)
def test_an_opened_record_is_reported_with_its_session(sandbox): # noqa: F811
tmp, env = sandbox
_run("grimoire_record_read.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__get_task", "tool_input": {"task_id": 42}},
env)
log, body = _sent(tmp)
assert "/api/plugin/record-opened" in log
assert body == {"session_id": "s1", "note_id": 42}
def test_a_search_is_reported_with_its_query(sandbox): # noqa: F811
tmp, env = sandbox
_run("grimoire_record_read.sh",
{"session_id": "s1", "tool_name": "mcp__plugin_grimoire_grimoire__search",
"tool_input": {"q": 'why does "the lock" stick', "content_type": "issue"}},
env)
log, body = _sent(tmp)
assert "/api/plugin/record-searched" in log
assert body == {"session_id": "s1", "q": 'why does "the lock" stick'}
def test_a_process_opened_by_name_is_not_reported(sandbox): # noqa: F811
tmp, env = sandbox
_run("grimoire_record_read.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__get_process",
"tool_input": {"name_or_id": "Drift Audit"}},
env)
assert _sent(tmp) == ("", None)
def test_the_hook_runs_after_every_record_getter_and_search_and_nothing_else():
hooks = json.loads((ROOT / "plugin" / "hooks" / "hooks.json").read_text())["hooks"]["PostToolUse"]
matchers = [e["matcher"] for e in hooks
if any("grimoire_record_read.sh" in h["command"] for h in e["hooks"])]
assert len(matchers) == 1
runs = re.compile(f"^(?:{matchers[0]})$")
for tool in ("get_note", "get_task", "get_snippet", "get_lesson", "get_process", "search"):
assert runs.match(f"mcp__plugin_grimoire_grimoire__{tool}"), tool
for tool in ("get_rule", "search_rules", "update_task", "get_milestone"):
assert not runs.match(f"mcp__plugin_grimoire_grimoire__{tool}"), tool
+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
+2
View File
@@ -41,6 +41,8 @@ def test_every_endpoint_is_reachable_on_the_app():
"/api/retrieval/surfaces",
"/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",
+1 -2
View File
@@ -483,10 +483,9 @@ async def test_write_path_semantic_arm_asks_for_experience_not_just_snippets():
)
kw = search.await_args.kwargs
assert kw["note_type"] == ("snippet", "note", LESSON_NOTE_TYPE)
# An open to-do resembling the code answers nothing; an ISSUE carries a root
# cause and a NOTE carries durable knowledge. Only the todo is excluded.
assert kw["task_kind"] == "issue"
assert kw["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
# Telemetry must not claim this was a notes-only retrieval any more.
assert rec.call_args.kwargs["is_task"] is None
+1 -2
View File
@@ -255,8 +255,7 @@ async def test_semantic_arm_is_snippet_only_and_browse_scoped():
# code shape. What
# stays out is the open to-do list, which resembles the code and answers
# nothing.
assert kwargs["note_type"] == ("snippet", "note", "lesson")
assert kwargs["task_kind"] == "issue"
assert kwargs["record_kinds"] == ["lesson", "note", "snippet", "task:issue"]
# Nobody asked for this, so it must not reach a one-to-one direct share.
assert kwargs["scope"] == "browse"