Records reach work: the record ledger and the kind×moment table (milestone 642, steps 1 and 3) #230
@@ -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")
|
||||
@@ -279,6 +279,33 @@ export interface AdherencePayload {
|
||||
by_moment: MomentAdherenceRow[];
|
||||
}
|
||||
|
||||
/** 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}`);
|
||||
|
||||
@@ -4,9 +4,10 @@ import { useMomentsStore } from "@/stores/moments";
|
||||
import MomentProposals from "@/components/MomentProposals.vue";
|
||||
import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
|
||||
import WeightProposals from "@/components/WeightProposals.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 +49,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 +143,7 @@ async function addMapping() {
|
||||
|
||||
onMounted(async () => {
|
||||
await store.load(true);
|
||||
await loadAdherence();
|
||||
await Promise.all([loadAdherence(), loadReach()]);
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -156,6 +171,7 @@ onMounted(async () => {
|
||||
<MomentProposals />
|
||||
<WeightProposals />
|
||||
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
|
||||
<RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" />
|
||||
|
||||
<ul class="moment-list">
|
||||
<li v-for="m in catalog" :key="m.name" class="moment-row">
|
||||
|
||||
@@ -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,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"
|
||||
},
|
||||
|
||||
Executable
+74
@@ -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
|
||||
@@ -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": [
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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():
|
||||
|
||||
@@ -21,6 +21,7 @@ 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 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 +259,19 @@ async def adherence_route():
|
||||
))
|
||||
|
||||
|
||||
@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():
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,270 @@
|
||||
"""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.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")
|
||||
|
||||
|
||||
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."""
|
||||
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(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)
|
||||
@@ -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 ─────────────────────────────────────────────────────
|
||||
#
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -41,6 +41,7 @@ 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/gate",
|
||||
"/api/retrieval/tuning-history",
|
||||
"/api/retrieval/moments",
|
||||
|
||||
Reference in New Issue
Block a user