Fast exact search, cross-project knowledge, delivered rulings, short MCP instructions #236

Merged
bvandeusen merged 10 commits from dev into main 2026-11-28 18:24:23 -05:00
39 changed files with 967 additions and 119 deletions
+2
View File
@@ -148,3 +148,5 @@ docker compose -f docker-compose.dev.yml up --build
## Licence ## Licence
Fabled Grimoire is free software under the [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). If you run a modified version for other people over a network, the licence requires you to offer them its source. Fabled Grimoire is free software under the [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). If you run a modified version for other people over a network, the licence requires you to offer them its source.
The Claude Code plugin in [`plugin/`](plugin/) is a separate work under the [MIT License](plugin/LICENSE) (`MIT`), so you can adapt it inside your own tooling freely.
@@ -0,0 +1,42 @@
"""embedding vectors stored inline, not in TOAST
Revision ID: 0139
Revises: 0138
Create Date: 2026-11-28
Every semantic search ranks its in-scope chunks exactly, one distance per
chunk (see embeddings._rank_scoped). pgvector's `vector` type defaults to
EXTERNAL storage, and a chunk row (a 384-dimension vector, about 1.5 KB, plus
the chunk's text) is over Postgres's 2 KB toast threshold, so the vector was
moved out of line and every distance paid a TOAST lookup: several buffer
reads per chunk, on every search.
`STORAGE MAIN` keeps the vector in the row. When a row is still too wide, the
chunk text (EXTENDED) is compressed or moved out instead, which costs nothing
on the ranking path: the text is read only for the rows a search returns.
A storage change applies to rows written after it, so the existing rows are
rewritten once. Casting through `real[]` produces a fresh value, which the
row is stored with under the new setting; assigning the column to itself
would keep the old out-of-line pointer.
"""
from alembic import op
revision = "0139"
down_revision = "0138"
branch_labels = None
depends_on = None
TABLES = ("note_embeddings", "rule_embeddings", "milestone_embeddings", "system_embeddings")
def upgrade() -> None:
for table in TABLES:
op.execute(f"ALTER TABLE {table} ALTER COLUMN embedding SET STORAGE MAIN")
op.execute(f"UPDATE {table} SET embedding = embedding::real[]::vector")
def downgrade() -> None:
# Rows already inline stay inline; new rows follow the type's default.
for table in TABLES:
op.execute(f"ALTER TABLE {table} ALTER COLUMN embedding SET STORAGE EXTERNAL")
+13
View File
@@ -297,9 +297,17 @@ export interface RecordKindsDoor {
evidence: Record<string, WayCounts>; evidence: Record<string, WayCounts>;
} }
/** Which kinds a door may offer from the user's other projects. */
export interface RecordKindsReach {
kinds: string[];
default: string[];
changed: boolean;
}
export interface RecordKindsTable { export interface RecordKindsTable {
days: number; days: number;
evidence_failed: boolean; evidence_failed: boolean;
reach: RecordKindsReach;
kinds: { kind: string; label: string }[]; kinds: { kind: string; label: string }[];
doors: RecordKindsDoor[]; doors: RecordKindsDoor[];
} }
@@ -313,6 +321,11 @@ export function setRecordKinds(door: string, kinds: string[] | null): Promise<Re
return apiPut("/api/retrieval/record-kinds", { door, kinds }); return apiPut("/api/retrieval/record-kinds", { door, kinds });
} }
/** `kinds: null` puts the reach back to its shipped default. */
export function setRecordKindsReach(kinds: string[] | null): Promise<RecordKindsTable> {
return apiPut("/api/retrieval/record-kinds/reach", { kinds });
}
/** How a record arrived in front of a session. */ /** How a record arrived in front of a session. */
export type RecordWay = "pushed" | "pointed" | "asked" | "direct"; export type RecordWay = "pushed" | "pointed" | "asked" | "direct";
+6
View File
@@ -21,6 +21,12 @@ export interface System {
* everything under it. Empty means the area has not named its files. * everything under it. Empty means the area has not named its files.
*/ */
path_patterns: string[]; path_patterns: string[];
/**
* How many rulings the description carries. With no `path_patterns`,
* none of them is delivered: rulings reach a session when a command or
* edit touches the area's files. Present on the list read only.
*/
ruling_count?: number;
open_issue_count: number; open_issue_count: number;
/** /**
* How often this area's rulings were shown to a session because its files * How often this area's rulings were shown to a session because its files
+53 -1
View File
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref } from "vue"; import { onMounted, ref } from "vue";
import { apiErrorMessage } from "@/api/client"; import { apiErrorMessage } from "@/api/client";
import { getRecordKinds, setRecordKinds } from "@/api/moments"; import { getRecordKinds, setRecordKinds, setRecordKindsReach } from "@/api/moments";
import type { RecordKindsDoor, RecordKindsTable } from "@/api/moments"; import type { RecordKindsDoor, RecordKindsTable } from "@/api/moments";
/** /**
@@ -10,6 +10,10 @@ import type { RecordKindsDoor, RecordKindsTable } from "@/api/moments";
* there; a session can still search for it. Each box shows the lines that * 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 * 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. * against its own evidence. A change saves as soon as it is made.
*
* Above the doors: which kinds may also come from the user's other projects.
* Knowledge crosses by default and work stays in its project; a record from
* elsewhere ranks a little below this project's own and says where it is from.
*/ */
const props = defineProps<{ days: number }>(); const props = defineProps<{ days: number }>();
@@ -44,6 +48,26 @@ function toggle(row: RecordKindsDoor, kind: string, on: boolean) {
void save(row.door, next); void save(row.door, next);
} }
const REACH = "reach";
async function saveReach(kinds: string[] | null) {
saving.value = REACH;
saveError.value = "";
try {
table.value = await setRecordKindsReach(kinds);
} catch (e) {
saveError.value = apiErrorMessage(e, "The change could not be saved.");
} finally {
saving.value = null;
}
}
function toggleReach(kind: string, on: boolean) {
if (!table.value) return;
const now = table.value.reach.kinds;
void saveReach(on ? [...now, kind] : now.filter((k) => k !== kind));
}
function evidenceText(row: RecordKindsDoor, kind: string): string { function evidenceText(row: RecordKindsDoor, kind: string): string {
const c = row.evidence[kind]; const c = row.evidence[kind];
return c ? `${c.opened} of ${c.delivered} opened` : "none shown"; return c ? `${c.opened} of ${c.delivered} opened` : "none shown";
@@ -70,6 +94,34 @@ onMounted(load);
The counts could not be read, so they are missing below, not zero. The counts could not be read, so they are missing below, not zero.
</p> </p>
<p v-if="saveError" class="error-msg" role="alert">{{ saveError }}</p> <p v-if="saveError" class="error-msg" role="alert">{{ saveError }}</p>
<fieldset class="door" :disabled="saving === REACH">
<legend class="door-head">
<span class="door-label">Also from your other projects</span>
<span class="door-fires">at every point below, while a session works in a project</span>
<span v-if="!table.reach.changed" class="door-default">shipped default</span>
</legend>
<p class="field-hint">
A ticked kind is offered from any project you can see, not only the one the session is in.
Such a record has to be a little closer to be shown, ranks below an equally close one from
the session's project, and its line names the project it came from. An unticked kind is
offered only from the session's own project. A search the session runs itself, for one
project, still means that project.
</p>
<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="table.reach.kinds.includes(k.kind)"
@change="toggleReach(k.kind, ($event.target as HTMLInputElement).checked)"
/>
{{ k.label }}
</label>
</li>
</ul>
<button v-if="table.reach.changed" type="button" class="btn-text door-reset" @click="saveReach(null)">
Back to the shipped default
</button>
</fieldset>
<fieldset <fieldset
v-for="row in table.doors" :key="row.door" class="door" v-for="row in table.doors" :key="row.door" class="door"
:disabled="saving === row.door" :disabled="saving === row.door"
@@ -80,6 +80,11 @@ function rulingsShown(system: System): number {
return system.usage?.surfaced_count ?? 0; return system.usage?.surfaced_count ?? 0;
} }
/** Rulings with no files to deliver them on: none reaches a session. */
function rulingsUndelivered(system: System): boolean {
return (system.ruling_count ?? 0) > 0 && system.path_patterns.length === 0;
}
function rulingsTitle(system: System): string { function rulingsTitle(system: System): string {
const u = system.usage; const u = system.usage;
if (!u) return ""; if (!u) return "";
@@ -498,6 +503,12 @@ async function confirmDelete() {
>rulings shown {{ rulingsShown(system) }}×</span> >rulings shown {{ rulingsShown(system) }}×</span>
</div> </div>
<p v-if="system.description" class="system-description">{{ system.description }}</p> <p v-if="system.description" class="system-description">{{ system.description }}</p>
<p v-if="rulingsUndelivered(system)" class="system-undelivered">
<span class="usage-tag usage-dead">rulings not delivered</span>
{{ system.ruling_count === 1 ? "Its ruling reaches" : `Its ${system.ruling_count} rulings reach` }}
no session: a ruling is shown when a session touches the area's files, and this area names none.
<button type="button" class="btn-text" @click="startEdit(system)">Name its files</button>
</p>
<ul v-if="system.path_patterns.length" class="system-paths" aria-label="Files"> <ul v-if="system.path_patterns.length" class="system-paths" aria-label="Files">
<li v-for="pattern in system.path_patterns" :key="pattern" class="system-path">{{ pattern }}</li> <li v-for="pattern in system.path_patterns" :key="pattern" class="system-path">{{ pattern }}</li>
</ul> </ul>
@@ -700,6 +711,12 @@ async function confirmDelete() {
.system-form-actions { display: flex; gap: 0.4rem; } .system-form-actions { display: flex; gap: 0.4rem; }
.system-paths-input { font-family: var(--fs-font-mono); font-size: 0.8rem; } .system-paths-input { font-family: var(--fs-font-mono); font-size: 0.8rem; }
.system-undelivered {
margin: var(--fs-space-2) 0 0;
font-size: var(--fs-size-body-sm);
color: var(--fs-text-secondary);
}
/* The area's files. Mono because they are paths to be read /* The area's files. Mono because they are paths to be read
character for character; small because they qualify the card, not lead it. */ character for character; small because they qualify the card, not lead it. */
.system-paths { .system-paths {
+2 -2
View File
@@ -1,11 +1,11 @@
{ {
"name": "grimoire", "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).", "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.27.1932", "version": "2026.11.28.2315",
"author": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
"license": "AGPL-3.0-only", "license": "MIT",
"mcpServers": { "mcpServers": {
"grimoire": { "grimoire": {
"type": "http", "type": "http",
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Bryan Van Deusen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1 -1
View File
@@ -14,7 +14,7 @@ another one means adding files, not moving or rewriting any.
| Piece | Where | What it is | | Piece | Where | What it is |
|---|---|---| |---|---|---|
| **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. | | **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. |
| **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — the workflow across tools (≤1,600 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. | | **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — only what no response or skill delivers: enter the project, ask before a consequential act, search before building, the force of each record kind (≤800 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. |
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule set to hold or — when the turn closed a task — for missing completion sections). | | **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule set to hold or — when the turn closed a task — for missing completion sections). |
| **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. | | **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. |
+4 -4
View File
@@ -55,10 +55,10 @@ Two constraints on *how* that's achieved:
`project_id` so results stay scoped. `project_id` so results stay scoped.
**Code tells you what a thing does, not what was wanted.** A limit, a **Code tells you what a thing does, not what was wanted.** A limit, a
default or a fallback found by reading the work is a past session's choice default or a filter found in the work is a past session's choice until a
until a record says the operator made it. Before presenting one as a record says the operator made it. Before relying on one or changing it,
safeguard or a known cost, read the `Rulings` on the System it belongs to; read the `Rulings` on its System; none speaking to it means unconfirmed,
when none speaks to it, call it unconfirmed rather than settled. and a change that would undo what a ruling says it is for goes to them.
2. **Rules are binding, and they reach you by retrieval.** No call loads the 2. **Rules are binding, and they reach you by retrieval.** No call loads the
operator's rules and no standing set is handed to a session. A rule arrives operator's rules and no standing set is handed to a session. A rule arrives
@@ -145,10 +145,29 @@ one line each — the statement, who decided, when, and the record it came from:
Rulings Rulings
- Failed work is retried until it succeeds; no attempt limit. (Operator, 2026-09-19, #1234; restated 2026-10-02, #1290) - Failed work is retried until it succeeds; no attempt limit. (Operator, 2026-09-19, #1234; restated 2026-10-02, #1290)
**A ruling about a constraint says what it is for, and what it is not for.** A
filter, a gate or a default outlives the reason it was made, and a later session
widens or narrows it by reading the code, which shows what it does and never
why. "Searches stay in their project" reads as a rule about every record; "a
search keeps other projects' open work out — it is not there to keep knowledge
in" can be re-judged when the reason changes. Write the *for* and the *not for*:
- The project filter keeps other projects' open work out of a session — not knowledge, which crosses with a label. (Operator, 2026-11-28, #1300)
The description arrives with every record filed under that System, so a ruling The description arrives with every record filed under that System, so a ruling
there reaches each session working in the area without having to win a search. there reaches each session working in the area without having to win a search.
Once the System names its files (`path_patterns`), its rulings also arrive with **Name the System's files** (`path_patterns`, globs from the repo root) so its
the first command or edit in a session that touches them. rulings also arrive with the first command or edit in a session that touches
them. That is the delivery that reaches someone changing the code; a System with
rulings and no files reaches nobody that way, and `enter_project` names it under
`rulings_undelivered`.
**The comment at the constraint names its ruling.** The code is where the next
change starts, and a reader there may have no Grimoire at all: give the reason
in the comment as a present-tense fact, and name the System and the ruling it
comes from, so the reason is one lookup away and the comment is not the only
copy.
A quote inside a work log does not: it surfaces only when a query happens to A quote inside a work log does not: it surfaces only when a query happens to
match it, and the passage that matches is usually the prose around it — often a match it, and the passage that matches is usually the prose around it — often a
session's *reading* of the ruling rather than the ruling. session's *reading* of the ruling rather than the ruling.
+23 -32
View File
@@ -29,42 +29,33 @@ from quart import Quart
# not: a tool's own contract (its description carries it), and stance — who # not: a tool's own contract (its description carries it), and stance — who
# judges, how to report, what a missed rule means. Those fire mid-work, not at # judges, how to report, what a missed rule means. Those fire mid-work, not at
# the start; the skills state them and in-band responses (`placement`, # the start; the skills state them and in-band responses (`placement`,
# `report_back`) cue them at the moment they apply. A new topic gets a line # `report_back`) cue them at the moment they apply.
# here only if it is a session-start practice.
# #
# BUDGET: at most 1,600 characters (test_instructions_fit_the_fold). Claude # ONLY WHAT NOTHING ELSE DELIVERS. A practice a response enforces (the
# Code injects only the first ~2,048 characters of a server's instructions and # duplicate gate, the unassigned-id refusal, `existing_milestone`,
# cuts the rest mid-word, and other clients differ, so nothing load-bearing may # `systems_hint`, the design-system block) or a skill states in full has no
# sit past the fold. A block pressed against the cap is being used as a # line here. What is left is what a client with no skills and no hooks would
# rulebook. # otherwise never be told: enter the project, ask before a consequential act,
# search before building, the force of each record kind, and that responses
# say what to do next. A new topic earns a line only if it is one of those.
#
# BUDGET: at most 800 characters (test_instructions_fit_the_fold). Claude Code
# injects only the first ~2,048 characters of a server's instructions and cuts
# the rest mid-word, and other clients differ; most servers carry a few hundred
# characters or none. A block near the cap is being used as a rulebook.
_INSTRUCTIONS = """ _INSTRUCTIONS = """
Grimoire is the operator's system of record, and yours: recall before acting, Grimoire is the user's system of record. Recall before acting, record as you
record as you go, keep one copy here, not in local memory. Each go, and keep one copy here rather than in local memory.
practice is stated in full in a skill or a tool description.
- Start with enter_project(id): the project, open work, Systems, design - Start with enter_project(id).
system. `inception`: ask what it inherits, then decide_project_inception. - Rules arrive when your work matches one; silence means nothing matched.
`family`: shared ideas to answer (family-canon skill). Before a consequential act, ask what_might_apply("what you are about to
- Rules are not preloaded; one arrives when your work matches it or reaches do"). Rules bind; preferences guide and you keep them current; lessons
a moment it is mounted on (list_moments; mount rules about WHEN). Before a inform.
consequential act, what_might_apply("what you are about to do"); - Search before building, scoped with the project_id.
search(content_type="rule") reads one you suspect. Silence means nothing - Responses say what to do next; follow them.
matched, not none. Rules bind; preferences guide and you keep them current;
lessons inform.
- Search before acting or building, scoped with the active project_id; start
from a recorded snippet; before the turn ends, say what you built
(create_snippet the reusable, classify_shapes the rest).
- Work is tasks (a fix is kind="issue"): in_progress on start, add_task_log as
you go, done on finish; tag system_ids.
- A plan is a milestone: find the existing one
(search(content_type="milestone")) before start_planning.
- IDs exist only once a create returns them; records citing each other go
through create_records, writing {{ref:N}} for the Nth.
- In UI work the design system binds: resolve_design_system before
writing a value.
Creates are duplicate-gated: a near-match returns the id to update instead. The using-grimoire skill, where installed, has each practice in full.
shared:true records are another user's suggestion, not settled practice.
""" """
+5 -2
View File
@@ -50,8 +50,11 @@ async def list_moments() -> dict:
search fires (`message`, the operator's message, and the catalog moments search fires (`message`, the operator's message, and the catalog moments
that have one), the kinds of record it may consider, the shipped default, 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 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 pushed at that point; search for it yourself when you need it. Its
operator changes the table in Settings › Moments. `reach` lists the kinds that may also come from the operator's other
projects (knowledge by default, never open work): such a line ends
`from <project>`, so weigh it as experience from that project rather than
a fact about this one. The operator changes the table in Settings › Moments.
""" """
uid = current_user_id() uid = current_user_id()
out = moments_svc.catalog() out = moments_svc.catalog()
+26
View File
@@ -128,6 +128,12 @@ async def enter_project(project_id: int) -> dict:
create it with create_system rather than leaving the area unmodelled. Read create it with create_system rather than leaving the area unmodelled. Read
a subsystem's accumulated records with list_system_records. Each is id and name; get_system has the charter. a subsystem's accumulated records with list_system_records. Each is id and name; get_system has the charter.
`rulings_undelivered`, present only when it applies, lists Systems that
carry rulings but name no files. A ruling reaches a session when a
command or edit touches its System's files, so these rulings reach
nobody. Name each area's files with
`update_system(id, path_patterns=[...])`, globs from the repo root.
`platforms` is what the project is built on or ships as `platforms` is what the project is built on or ships as
— Android app, container image, Go, … — each with how it is known — Android app, container image, Go, … — each with how it is known
(`declared` by a person, `detected` from a bound repo). They decide which (`declared` by a person, `detected` from a bound repo). They decide which
@@ -281,6 +287,7 @@ async def enter_project(project_id: int) -> dict:
}, },
"pattern_coverage": coverage_svc.coverage_line(coverage) if coverage else None, "pattern_coverage": coverage_svc.coverage_line(coverage) if coverage else None,
"systems": [{"id": s.id, "name": s.name} for s in systems], "systems": [{"id": s.id, "name": s.name} for s in systems],
**_rulings_undelivered(systems),
"platforms": platforms, "platforms": platforms,
"design_system": design_system, "design_system": design_system,
"milestone_summary": milestone_summary, "milestone_summary": milestone_summary,
@@ -366,6 +373,25 @@ async def get_project(project_id: int) -> dict:
return data return data
def _rulings_undelivered(systems) -> dict:
"""`{"rulings_undelivered": {...}}` when some System's rulings reach no
session, else nothing: the key is absent, not empty, so its presence is
the signal."""
from grimoire.services import system_rulings
missing = system_rulings.undelivered(systems)
if not missing:
return {}
return {"rulings_undelivered": {
"systems": missing,
"why": (
"A System's rulings are shown when a command or edit touches its "
"files. These name no files, so their rulings reach no session."
),
"fix": "update_system(id, path_patterns=[...]) with the area's files as globs from the repo root",
}}
def _inception_choices(design_system_id, seed_systems, platforms=None) -> dict | None: def _inception_choices(design_system_id, seed_systems, platforms=None) -> dict | None:
"""The tool args → an inception choices object, or None when no inception """The tool args → an inception choices object, or None when no inception
arg was given at all (a bare create stays undecided and enter_project arg was given at all (a bare create stays undecided and enter_project
+9 -1
View File
@@ -439,6 +439,12 @@ async def retrieval_telemetry(
Read a null as "unknown", never as a zero: an artifact read as a Read a null as "unknown", never as a zero: an artifact read as a
measurement mis-scopes the surface. measurement mis-scopes the surface.
`gate` is the cue gate's share, on an arm that has one: `gated_calls`
carried a gate decision and `declined_by_gate` returned ranked results
the gate then withheld. Such an arm logs `result_count` before the gate
decides, so its declines are `zero_result_calls` plus `declined_by_gate`.
`null` when no row in the window carried a gate decision.
`usage` — NOTES ONLY, from `note_usage_events`, at the per-note grain `usage` — NOTES ONLY, from `note_usage_events`, at the per-note grain
`retrieval_logs` cannot be indexed at: `surfaced` (ranked surfacings — a `retrieval_logs` cannot be indexed at: `surfaced` (ranked surfacings — a
scored surface CHOSE the record), `ambient` (the rest), `pulled` split into scored surface CHOSE the record), `ambient` (the rest), `pulled` split into
@@ -614,7 +620,9 @@ async def retrieval_telemetry(
Only ever raised for unbidden arms known to log unconditionally: a Only ever raised for unbidden arms known to log unconditionally: a
search returning a list every time is doing its job, and an arm whose search returning a list every time is doing its job, and an arm whose
zeros were never written would flag a LOGGING bug while pointing you at zeros were never written would flag a LOGGING bug while pointing you at
a threshold. a threshold. A gated arm's declines include the calls its cue gate
withheld (`gate.declined_by_gate`), since it logs its ranked results
before the gate decides.
- `band_hugs_floor` — the weakest tenth of what an arm returns sits on - `band_hugs_floor` — the weakest tenth of what an arm returns sits on
its floor. The bar is doing the selecting and the score is not, so its floor. The bar is doing the selecting and the score is not, so
moving that floor changes how MUCH you get, not how good it is. moving that floor changes how MUCH you get, not how good it is.
+3 -1
View File
@@ -10,7 +10,9 @@ from grimoire.models import Base
# native pgvector `vector(384)` (see migration 0067) so similarity is ranked in # native pgvector `vector(384)` (see migration 0067) so similarity is ranked in
# Postgres by `<=>` rather than by a full-table Python cosine scan. The semantic # Postgres by `<=>` rather than by a full-table Python cosine scan. The semantic
# searches rank the CALLER'S in-scope chunks exactly rather than through the # searches rank the CALLER'S in-scope chunks exactly rather than through the
# HNSW index, which ranks before it filters (see embeddings._rank_scoped). # HNSW index, which ranks before it filters (see embeddings._rank_scoped). The
# column is stored inline (`STORAGE MAIN`, migration 0139), so that exact pass
# reads each vector from its row rather than from TOAST.
EMBEDDING_DIM = 384 EMBEDDING_DIM = 384
+20
View File
@@ -294,6 +294,26 @@ async def set_record_kinds_route():
return jsonify({"error": str(e)}), 400 return jsonify({"error": str(e)}), 400
@retrieval_bp.route("/record-kinds/reach", methods=["PUT"])
@login_required
async def set_record_kinds_reach_route():
"""Set which kinds may be offered from the user's other projects. Body:
`{"kinds": [...]}`, or `{"kinds": null}` for the shipped default.
Answers with the whole table."""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict) or "kinds" not in data:
return jsonify({"error": "kinds is required (a list of kinds, or null)"}), 400
kinds = data["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_reach(get_current_user_id(), kinds))
except ValueError as e:
return jsonify({"error": str(e)}), 400
@retrieval_bp.route("/record-reach", methods=["GET"]) @retrieval_bp.route("/record-reach", methods=["GET"])
@login_required @login_required
async def record_reach_route(): async def record_reach_route():
+4
View File
@@ -11,6 +11,7 @@ from grimoire.services import systems as systems_svc
from grimoire.services.access import can_write_project from grimoire.services.access import can_write_project
from grimoire.services.projects import get_project_for_user from grimoire.services.projects import get_project_for_user
from grimoire.services import system_usage as system_usage_svc from grimoire.services import system_usage as system_usage_svc
from grimoire.services import system_rulings
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -52,6 +53,9 @@ async def list_systems_route(project_id: int):
d = s.to_dict() d = s.to_dict()
d["open_issue_count"] = counts.get(s.id, 0) d["open_issue_count"] = counts.get(s.id, 0)
d["usage"] = usage.get(s.id, system_usage_svc.empty_system_usage()) d["usage"] = usage.get(s.id, system_usage_svc.empty_system_usage())
# Read beside the patterns: rulings and no files means none of them
# is ever delivered (`system_rulings.undelivered`).
d["ruling_count"] = len(system_rulings.parse_rulings(s.description))
out.append(d) out.append(d)
return jsonify({"systems": out}) return jsonify({"systems": out})
+99 -24
View File
@@ -22,6 +22,7 @@ from contextvars import ContextVar
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from sqlalchemy import and_, delete, func, or_, select from sqlalchemy import and_, delete, func, or_, select
from sqlalchemy.orm import aliased
from grimoire.models import async_session from grimoire.models import async_session
from grimoire.models.embedding import NoteEmbedding, RuleEmbedding from grimoire.models.embedding import NoteEmbedding, RuleEmbedding
@@ -183,6 +184,19 @@ def _cosine_similarity(a: list[float], b: list[float]) -> float:
# name, and a superseded record is demoted, never hidden. # name, and a superseded record is demoted, never hidden.
_SUPERSESSION_PENALTY = 0.05 _SUPERSESSION_PENALTY = 0.05
# What a record from another of the user's projects gives up against one from
# the project being worked in (`cross_kinds` on `semantic_search_notes`).
#
# Taken off the score BEFORE the floor, unlike supersession: a record from
# elsewhere has to be that much closer to be offered at all, as well as
# ranking below an equally close one from here. Offered at the same bar, a
# corpus of many projects would fill every menu with near-misses from
# unrelated work, which is what keeping searches in their project was first
# for. The size is the supersession penalty's: enough to settle a near-tie in
# favour of the work's own project, small enough that a record from elsewhere
# that answers clearly still reaches it.
_CROSS_PROJECT_PENALTY = 0.05
# Candidates fetched per requested result when a re-rank follows. Three ranks of # Candidates fetched per requested result when a re-rank follows. Three ranks of
# headroom is far more than a 0.05 penalty can move anything through in a corpus # headroom is far more than a 0.05 penalty can move anything through in a corpus
# whose neighbours sit ~0.01-0.02 apart. # whose neighbours sit ~0.01-0.02 apart.
@@ -861,43 +875,68 @@ def record_best_chunk(report: dict | None, chunks: dict[int, dict]) -> None:
# a MATERIALIZED CTE with the distance computed inside it; the index cannot # a MATERIALIZED CTE with the distance computed inside it; the index cannot
# order a materialized CTE, so the ranking over it is exact. # order a materialized CTE, so the ranking over it is exact.
# #
# What exact costs is one distance per in-scope chunk. Rules, milestones and # The index is not a faster way to the same answer. pgvector 0.8's
# Systems are hundreds of chunks. Notes are the big corpus, but the hook arms # `hnsw.iterative_scan` keeps walking the graph until enough rows pass the
# that run on every prompt are project-scoped, so the pass is over one # filter, but under a narrow scope (one small project and the lessons) it
# project's chunks rather than the whole table; `retrieval_logs.duration_ms` # returns a different set: 7 to 60 of the true 144 nearest chunks, in strict
# on those arms is where that claim is checked. If it ever # and relaxed order alike and at an `ef_search` of 200 or 1000. Only a broad
# stops holding, pgvector 0.8's `hnsw.iterative_scan` keeps the index and is # scope comes back right. So the ranking stays exact everywhere.
# the next step — gated on the extension version, because an unknown `hnsw.*` #
# setting errors and these searches would read that error as "nothing found". # What exact costs is one distance per in-scope chunk, and two things keep
# that cheap on a corpus of tens of thousands of chunks:
#
# - The vector is stored inline (`STORAGE MAIN`, migration 0139). pgvector's
# type defaults to EXTERNAL, and a chunk row (a 1.5 KB vector plus its text)
# is over the 2 KB toast threshold, so every vector was moved out of line
# and each distance paid a TOAST lookup.
# - The scope carries the record id, the chunk index and the distance, never
# the chunk text. The text of every in-scope chunk materialized beside the
# distance spills to disk on a whole-corpus scope, so `_rank_scoped` joins
# it back only for the rows that survive the cut.
def _scoped_chunks(embedding_model, record_key, distance): def _scoped_chunks(embedding_model, record_key, distance):
"""A select over an embedding table's chunks, each with its distance — the """A select over an embedding table's chunks, each with its distance — the
caller joins its record and adds its scope, and `_rank_scoped` orders it. caller joins its record and adds its scope, and `_rank_scoped` orders it.
The columns are labelled so every search's CTE carries the same four. The columns are labelled so every search's CTE carries the same three. The
chunk text is not one of them: `_rank_scoped` reads it for the winners.
""" """
return select( return select(
record_key.label("record_id"), record_key.label("record_id"),
distance.label("distance"), distance.label("distance"),
embedding_model.chunk_index.label("chunk_index"), embedding_model.chunk_index.label("chunk_index"),
embedding_model.chunk_text.label("chunk_text"),
).select_from(embedding_model) ).select_from(embedding_model)
def _rank_scoped(record_model, scoped_chunks, *, name: str, limit: int): def _rank_scoped(record_model, scoped_chunks, *, embedding_model, record_key,
name: str, limit: int):
"""(record, distance, chunk_index, chunk_text) rows, nearest first, drawn """(record, distance, chunk_index, chunk_text) rows, nearest first, drawn
ONLY from the in-scope chunks — exactly, never through the index. ONLY from the in-scope chunks — exactly, never through the index.
The nearest `limit` chunks are cut first, over the distances alone; only
then is each survivor's text read back from `embedding_model` by its key
(`record_key`, `chunk_index`), so a broad scope never carries every
chunk's text through the sort.
The row shape is what each search's collapse already unpacks, so a search The row shape is what each search's collapse already unpacks, so a search
moves onto this without its callers or its mocks noticing. moves onto this without its callers or its mocks noticing.
""" """
scoped = scoped_chunks.cte(name).prefix_with("MATERIALIZED") scoped = scoped_chunks.cte(name).prefix_with("MATERIALIZED")
return ( nearest = (
select(record_model, scoped.c.distance, scoped.c.chunk_index, scoped.c.chunk_text) select(scoped.c.record_id, scoped.c.distance, scoped.c.chunk_index)
.join(scoped, scoped.c.record_id == record_model.id)
.order_by(scoped.c.distance) .order_by(scoped.c.distance)
.limit(limit) .limit(limit)
.subquery(f"{name}_nearest")
)
text_of = aliased(embedding_model, name=f"{name}_text")
text_key = getattr(text_of, record_key.key)
return (
select(record_model, nearest.c.distance, nearest.c.chunk_index, text_of.chunk_text)
.join(nearest, nearest.c.record_id == record_model.id)
.join(text_of, and_(text_key == nearest.c.record_id,
text_of.chunk_index == nearest.c.chunk_index))
.order_by(nearest.c.distance)
) )
@@ -918,9 +957,18 @@ async def semantic_search_notes(
system_id: int | None = None, system_id: int | None = None,
report: dict | None = None, report: dict | None = None,
record_kinds: Sequence[str] | None = None, record_kinds: Sequence[str] | None = None,
cross_kinds: Sequence[str] | None = None,
) -> list[tuple[float, Note]]: ) -> list[tuple[float, Note]]:
"""Return up to *limit* (score, note) pairs most relevant to *query*. """Return up to *limit* (score, note) pairs most relevant to *query*.
`cross_kinds` (kind×moment vocabulary) are the kinds a project-scoped
search also takes from the caller's OTHER projects: knowledge reaching
the work wherever it was learned (`record_kinds.reach_for`). Given, it
replaces the GLOBAL_NOTE_TYPES carve-out (a lesson crosses when the list
says so), and every record from outside `project_id` gives up
`_CROSS_PROJECT_PENALTY` before the floor and the ranking. None leaves
the project filter as it is; it means nothing without `project_id`.
`record_kinds` narrows to the kinds of the kind×moment table `record_kinds` narrows to the kinds of the kind×moment table
(`record_kinds`: `snippet`, `task:issue`, …), the vocabulary the (`record_kinds`: `snippet`, `task:issue`, …), the vocabulary the
injected arms filter by. It composes with every other filter. injected arms filter by. It composes with every other filter.
@@ -958,12 +1006,11 @@ async def semantic_search_notes(
only: a caller that also passes `note_type` still gets exactly the kinds it only: a caller that also passes `note_type` still gets exactly the kinds it
asked for, so narrowing to snippets does not quietly acquire lessons. asked for, so narrowing to snippets does not quietly acquire lessons.
Off by default, because two callers depend on the project filter holding. Off by default, because the near-duplicate gate depends on the project
The near-duplicate gate compares a record only against its own project on filter holding: it compares a record only against its own project on
purpose, and a globally-visible kind would let a lesson block an unrelated purpose, and a globally-visible kind would let a lesson block an unrelated
note's create on a project its author never touched. Ordinary note recall note's create on a project its author never touched. The passive arms
is project-scoped for the same reason — the point of the carve-out is that widen the filter by the user's reach instead (`cross_kinds`).
ONE kind escapes, not that scoping is weaker.
`scope` ("own" | "browse" | "read", see access.notes_visibility_clause) `scope` ("own" | "browse" | "read", see access.notes_visibility_clause)
decides how far this may see. It exists because this one function serves decides how far this may see. It exists because this one function serves
@@ -1036,11 +1083,22 @@ async def semantic_search_notes(
if orphan_only: if orphan_only:
stmt = stmt.where(Note.project_id.is_(None)) stmt = stmt.where(Note.project_id.is_(None))
elif project_id is not None: elif project_id is not None:
# The project filter keeps other projects' open WORK out of a
# session; it is not there to keep knowledge in, which crosses
# through `cross_kinds` (ruling "Knowledge crosses projects;
# work stays in its own" on System "Retrieval & recall").
in_project = Note.project_id == project_id in_project = Note.project_id == project_id
if include_global_kinds: if cross_kinds is not None:
# Which kinds cross is the caller's (the user's reach);
# whose records they are stays the visibility clause's.
if cross_kinds:
from grimoire.services.record_kinds import kinds_clause
in_project = or_(in_project, kinds_clause(cross_kinds))
elif include_global_kinds:
in_project = or_( in_project = or_(
in_project, Note.note_type.in_(GLOBAL_NOTE_TYPES) in_project, Note.note_type.in_(GLOBAL_NOTE_TYPES)
) )
if include_global_kinds:
# Family canon crosses the project # Family canon crosses the project
# line the same way a lesson does, but only to a project # line the same way a lesson does, but only to a project
# on one of the idea's platforms: the canon ideas reaching # on one of the idea's platforms: the canon ideas reaching
@@ -1116,7 +1174,9 @@ async def semantic_search_notes(
# bar is applied after the collapse, where the rejected scores can # bar is applied after the collapse, where the rejected scores can
# still be seen. # still be seen.
rows = list((await session.execute( rows = list((await session.execute(
_rank_scoped(Note, stmt, name="scoped_note_chunks", limit=fetch) _rank_scoped(Note, stmt, embedding_model=NoteEmbedding,
record_key=NoteEmbedding.note_id,
name="scoped_note_chunks", limit=fetch)
)).all()) )).all())
except Exception: except Exception:
logger.warning("Failed to query note embeddings", exc_info=True) logger.warning("Failed to query note embeddings", exc_info=True)
@@ -1147,6 +1207,16 @@ async def semantic_search_notes(
"index": int(chunk_index), "index": int(chunk_index),
"text": chunk_text or "", "text": chunk_text or "",
} }
# A record from another project gives up its penalty here, before the
# floor and the report, so the best score reported is one the bar could
# actually have accepted. The sort is stable: equal scores keep the
# distance order.
if cross_kinds is not None and project_id is not None:
scored = [
(score - _CROSS_PROJECT_PENALTY if note.project_id != project_id else score, note)
for score, note in scored
]
scored.sort(key=lambda pair: pair[0], reverse=True)
# The best score anything reached, bar or no bar. Recorded BEFORE the # The best score anything reached, bar or no bar. Recorded BEFORE the
# filter because a call that returns nothing is exactly when it matters. # filter because a call that returns nothing is exactly when it matters.
if report is not None: if report is not None:
@@ -1635,7 +1705,8 @@ async def semantic_search_rules(
rows = (await session.execute( rows = (await session.execute(
# Overfetch so collapsing chunks to their best row still fills # Overfetch so collapsing chunks to their best row still fills
# the page — the same reason the note search overfetches. # the page — the same reason the note search overfetches.
_rank_scoped(Rule, scoped, name="scoped_rule_chunks", _rank_scoped(Rule, scoped, embedding_model=RuleEmbedding,
record_key=RuleEmbedding.rule_id, name="scoped_rule_chunks",
limit=limit * _CHUNK_OVERFETCH) limit=limit * _CHUNK_OVERFETCH)
)).all() )).all()
except Exception: except Exception:
@@ -1838,7 +1909,9 @@ async def semantic_search_milestones(
) )
async with async_session() as session: async with async_session() as session:
rows = (await session.execute( rows = (await session.execute(
_rank_scoped(Milestone, scoped, name="scoped_milestone_chunks", _rank_scoped(Milestone, scoped, embedding_model=MilestoneEmbedding,
record_key=MilestoneEmbedding.milestone_id,
name="scoped_milestone_chunks",
limit=limit * _CHUNK_OVERFETCH) limit=limit * _CHUNK_OVERFETCH)
)).all() )).all()
except Exception: except Exception:
@@ -2010,7 +2083,9 @@ async def semantic_search_systems(
) )
async with async_session() as session: async with async_session() as session:
rows = (await session.execute( rows = (await session.execute(
_rank_scoped(System, scoped, name="scoped_system_chunks", _rank_scoped(System, scoped, embedding_model=SystemEmbedding,
record_key=SystemEmbedding.system_id,
name="scoped_system_chunks",
limit=limit * _CHUNK_OVERFETCH) limit=limit * _CHUNK_OVERFETCH)
)).all() )).all()
except Exception: except Exception:
+45 -1
View File
@@ -708,6 +708,7 @@ async def build_autoinject_hint(
user_id=user_id, query=q, project_id=project_id, user_id=user_id, query=q, project_id=project_id,
seen=frozenset(already), named=frozenset(named_ids), seen=frozenset(already), named=frozenset(named_ids),
kinds=await record_kinds.kinds_for(user_id, rp.AUTO_INJECT.door), kinds=await record_kinds.kinds_for(user_id, rp.AUTO_INJECT.door),
reach=await record_kinds.reach_for(user_id),
), ),
floor=cfg["threshold"], budget=cfg["top_k"], io=_note_io(), floor=cfg["threshold"], budget=cfg["top_k"], io=_note_io(),
) )
@@ -730,6 +731,7 @@ async def build_autoinject_hint(
{i for i in named_ids if i not in already} {i for i in named_ids if i not in already}
| {int(n.id) for _s, n in kept if int(n.id) not in already} | {int(n.id) for _s, n in kept if int(n.id) not in already}
) )
origins = await _origins([n for _s, n in kept], project_id)
def _shared_by(note) -> str: def _shared_by(note) -> str:
if note.user_id == user_id: if note.user_id == user_id:
@@ -809,6 +811,13 @@ async def build_autoinject_hint(
"what you are doing and use your judgement — a lesson is not a " "what you are doing and use your judgement — a lesson is not a "
"rule and binds nothing." "rule and binds nothing."
) )
# Said once, for the reason the lesson sentence is: one meaning for every
# line that carries the marker, and no sentence at all when none does.
if origins:
lines.append(
"> A line ending `from <project>` was recorded in another of your "
"projects: experience to weigh here, not a fact about this one."
)
kept_header = "\n".join(lines[head_at:]) kept_header = "\n".join(lines[head_at:])
for score, note in kept: for score, note in kept:
@@ -832,7 +841,7 @@ async def build_autoinject_hint(
nid, kind=_record_kind(note), name=name, systems=systems.get(nid), nid, kind=_record_kind(note), name=name, systems=systems.get(nid),
seen=nid in already, stale=nid in stale, score=score, seen=nid in already, stale=nid in stale, score=score,
shared_by=f"{who}, treat as a suggestion" if who else "", shared_by=f"{who}, treat as a suggestion" if who else "",
under=passage, under=passage, origin=origins.get(nid, ""),
) )
lines.extend(entry) lines.extend(entry)
parts.append(hook_payload.Part( parts.append(hook_payload.Part(
@@ -868,6 +877,36 @@ async def build_autoinject_hint(
} }
async def _origins(notes, project_id: int | None) -> dict[int, str]:
"""{note id: project title} for the records here from a project other
than the session's. Empty with no session project, where every record is
from elsewhere and the label would say nothing; a record in no project
carries none. Fails open to no labels: a missing label costs a hint, a
raised error would cost the menu."""
if not project_id:
return {}
away = {
int(n.id): pid for n in notes
if isinstance(pid := getattr(n, "project_id", None), int) and pid != project_id
}
if not away:
return {}
from sqlalchemy import select
from grimoire.models import async_session
from grimoire.models.project import Project
try:
async with async_session() as session:
titles = dict((await session.execute(
select(Project.id, Project.title).where(Project.id.in_(set(away.values())))
)).all())
except Exception:
logger.warning("project titles for the menu could not be read", exc_info=True)
return {}
return {nid: titles[pid] for nid, pid in away.items() if pid in titles}
def _note_io() -> rp.NoteIO: def _note_io() -> rp.NoteIO:
"""The ranker and recorders the notes arms report to, read at call time — """The ranker and recorders the notes arms report to, read at call time —
`_rule_io`'s reason: whatever this module's names are when the arm runs.""" `_rule_io`'s reason: whatever this module's names are when the arm runs."""
@@ -1520,6 +1559,7 @@ async def build_write_path_hint(
seen=frozenset(excluded), in_menu=frozenset(seen), seen=frozenset(excluded), in_menu=frozenset(seen),
still_scored=frozenset(pulled), still_scored=frozenset(pulled),
kinds=await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door), kinds=await record_kinds.kinds_for(user_id, rp.WRITE_PATH.door),
reach=await record_kinds.reach_for(user_id),
), ),
floor=cfg["threshold"], budget=remaining, io=_note_io(), floor=cfg["threshold"], budget=remaining, io=_note_io(),
) )
@@ -1529,6 +1569,7 @@ async def build_write_path_hint(
int(note.id): float(score) for score, note in result.answered int(note.id): float(score) for score, note in result.answered
if int(note.id) in pulled if int(note.id) in pulled
} }
wp_origins = await _origins([n for _s, n in result.menu], project_id)
for score, note in result.menu: for score, note in result.menu:
# Name the kind unless it's a snippet — the menu's default and # Name the kind unless it's a snippet — the menu's default and
# the header's default reading. An issue or a dev-log offered # the header's default reading. An issue or a dev-log offered
@@ -1547,6 +1588,9 @@ async def build_write_path_hint(
# have to work out whether they mean the same thing. # have to work out whether they mean the same thing.
if int(note.id) in excluded: if int(note.id) in excluded:
marker += " · seen" marker += " · seen"
# A record from another project says which, as on the prompt menu.
if int(note.id) in wp_origins:
marker += f" · from {wp_origins[int(note.id)]}"
scored.append(( scored.append((
marker, marker,
{ {
+59
View File
@@ -56,6 +56,22 @@ the file it is recorded at, an issue through the file or area it names and
when a task in its area is taken up, a lesson through the situation when a task in its area is taken up, a lesson through the situation
confirmed for it (`lesson_situations`), and any record when the work names confirmed for it (`lesson_situations`), and any record when the work names
its id. its id.
WHERE A RECORD MAY COME FROM
A door's search runs in the session's project, and each kind declares
whether a record of that kind from another of the user's projects may be
offered there too (setting `record_reach`, shipped default `REACH_DEFAULT`).
Knowledge crosses: a snippet, a note, a process or a lesson says how
something works or what was learned, and that holds wherever it was
written. Work does not: an open task, a spike or a plan is about its own
project, and offered elsewhere it reads as work to do here. A record from
another project ranks a little below an equally close one from this project,
has to be that much closer to be offered at all, and its line names the
project it came from (`embeddings.semantic_search_notes`, `cross_kinds`).
Who may see a record is a separate boundary (`access.notes_visibility_clause`)
and reach never widens it. A search the session asks for itself, scoped to
a project, still means that project.
""" """
from __future__ import annotations from __future__ import annotations
@@ -87,6 +103,11 @@ LABELS: dict[str, str] = {
} }
SETTING_KEY = "record_kinds" SETTING_KEY = "record_kinds"
REACH_SETTING_KEY = "record_reach"
# The kinds a door may offer from the user's other projects: knowledge, not
# work. See WHERE A RECORD MAY COME FROM.
REACH_DEFAULT: frozenset[str] = frozenset({"snippet", "note", "process", "lesson"})
MESSAGE = "message" MESSAGE = "message"
WORK_CHANGE = "work.change" WORK_CHANGE = "work.change"
WORK_CHANGE_SIMILAR = "work.change.similar" WORK_CHANGE_SIMILAR = "work.change.similar"
@@ -254,6 +275,19 @@ async def kinds_for(user_id: int, door: str) -> frozenset[str]:
return (await _stored(user_id)).get(door, spec.default) return (await _stored(user_id)).get(door, spec.default)
async def reach_for(user_id: int) -> frozenset[str]:
"""The kinds this user's doors may offer from their other projects: their
change, or the shipped default."""
from grimoire.services.settings import get_setting
try:
raw = json.loads(await get_setting(user_id, REACH_SETTING_KEY, "null") or "null")
except Exception: # noqa: BLE001 - a bad stored value falls back to the default
logger.debug("record reach setting unreadable", exc_info=True)
return REACH_DEFAULT
return clean(raw) if isinstance(raw, list) else REACH_DEFAULT
async def _evidence(user_id: int, days: int) -> dict[str, dict[str, dict]] | None: async def _evidence(user_id: int, days: int) -> dict[str, dict[str, dict]] | None:
"""`{door: {kind: {"delivered", "opened"}}}` from the record ledger: the """`{door: {kind: {"delivered", "opened"}}}` from the record ledger: the
lines each door pushed of each kind, and how many were opened. None when lines each door pushed of each kind, and how many were opened. None when
@@ -281,8 +315,14 @@ async def table(user_id: int, days: int = 30) -> dict:
last `days`, for the settings view and the MCP readout.""" last `days`, for the settings view and the MCP readout."""
stored = await _stored(user_id) stored = await _stored(user_id)
evidence = await _evidence(user_id, days) evidence = await _evidence(user_id, days)
reach = await reach_for(user_id)
return { return {
"days": days, "days": days,
"reach": {
"kinds": sorted(reach, key=KINDS.index),
"default": sorted(REACH_DEFAULT, key=KINDS.index),
"changed": reach != REACH_DEFAULT,
},
"evidence_failed": evidence is None, "evidence_failed": evidence is None,
"kinds": [{"kind": k, "label": LABELS[k]} for k in KINDS], "kinds": [{"kind": k, "label": LABELS[k]} for k in KINDS],
"doors": [ "doors": [
@@ -324,3 +364,22 @@ async def set_kinds(user_id: int, door: str, kinds: list[str] | None) -> dict:
stored[door] = sorted(set(kinds), key=KINDS.index) stored[door] = sorted(set(kinds), key=KINDS.index)
await set_setting(user_id, SETTING_KEY, json.dumps(stored)) await set_setting(user_id, SETTING_KEY, json.dumps(stored))
return await table(user_id) return await table(user_id)
async def set_reach(user_id: int, kinds: list[str] | None) -> dict:
"""Set which kinds may be offered from the user's other projects, or put
it back to the shipped default with None. Refuses an unknown kind, and a
set equal to the default is stored as no change, as `set_kinds` does."""
from grimoire.services.settings import delete_setting, set_setting
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)}")
if kinds is None or frozenset(kinds) == REACH_DEFAULT:
await delete_setting(user_id, REACH_SETTING_KEY)
else:
await set_setting(
user_id, REACH_SETTING_KEY, json.dumps(sorted(set(kinds), key=KINDS.index)),
)
return await table(user_id)
+21 -1
View File
@@ -1048,7 +1048,7 @@ def _menu_seen_line(note_id: int, kind: str, name: str) -> str:
def menu_entry( def menu_entry(
note_id: int, *, kind: str, name: str, systems: list[str] | None = None, note_id: int, *, kind: str, name: str, systems: list[str] | None = None,
seen: bool = False, stale: bool = False, score: float | None = None, seen: bool = False, stale: bool = False, score: float | None = None,
shared_by: str = "", under: str = "", shared_by: str = "", under: str = "", origin: str = "",
) -> list[str]: ) -> list[str]:
"""One record on a notes menu: its line, and what sits under it. """One record on a notes menu: its line, and what sits under it.
@@ -1064,6 +1064,10 @@ def menu_entry(
A superseded record is DEMOTED, not removed, so one can still reach A superseded record is DEMOTED, not removed, so one can still reach
a menu, and when it does the reader has to be told: an agent handed stale a menu, and when it does the reader has to be told: an agent handed stale
material with nothing marking it acts on it with full confidence. material with nothing marking it acts on it with full confidence.
`origin` is the project a record from elsewhere came from. Unlabelled, a
note about another project's code reads as a fact about this one; named,
it reads as experience to weigh.
""" """
if seen: if seen:
line = _menu_seen_line(note_id, kind, name) line = _menu_seen_line(note_id, kind, name)
@@ -1073,6 +1077,8 @@ def menu_entry(
line += f" ({score:.2f})" line += f" ({score:.2f})"
if stale: if stale:
line += " — SUPERSEDED, a later record covers this; check that first" line += " — SUPERSEDED, a later record covers this; check that first"
if origin:
line += f" — from {origin}"
if shared_by: if shared_by:
line += f" — shared by {shared_by}" line += f" — shared by {shared_by}"
return [line, f"> ↳ {under}"] if under else [line] return [line, f"> ↳ {under}"] if under else [line]
@@ -1254,6 +1260,16 @@ class NoteMoment:
is the door's shipped default; an empty set means the arm searches is the door's shipped default; an empty set means the arm searches
nothing.""" nothing."""
reach: frozenset[str] | None = None
"""The kinds this user takes from their other projects
(`record_kinds.reach_for`). None is the shipped default."""
def cross_kinds(self) -> list[str]:
"""What the search is given as `cross_kinds`: one spelling for the
arm, its slots and the review re-run of a call."""
reach = self.reach if self.reach is not None else record_kinds.REACH_DEFAULT
return sorted(reach, key=record_kinds.KINDS.index)
@dataclass @dataclass
class NoteResult: class NoteResult:
@@ -1344,6 +1360,9 @@ async def _reserve_note_slot(
"exclude_ids": set(on_menu), "exclude_ids": set(on_menu),
# KIND-FILTERED, so the slot can only be spent on what it is for. # KIND-FILTERED, so the slot can only be spent on what it is for.
"note_type": kinds, "scope": arm.scope, "report": report, "note_type": kinds, "scope": arm.scope, "report": report,
# The slot draws from the same projects as the arm above it: a
# reusable snippet from another project is the reuse case.
"cross_kinds": moment.cross_kinds(),
} }
if slot.include_global_kinds: if slot.include_global_kinds:
kwargs["include_global_kinds"] = True kwargs["include_global_kinds"] = True
@@ -1450,6 +1469,7 @@ async def run_note_arm(
"project_id": moment.project_id or None, "project_id": moment.project_id or None,
**note_search_filters(arm), "report": report, **note_search_filters(arm), "report": report,
"record_kinds": record_kinds.search_kinds(allowed), "record_kinds": record_kinds.search_kinds(allowed),
"cross_kinds": moment.cross_kinds(),
} }
if arm.withholds: if arm.withholds:
kwargs["exclude_ids"] = set(moment.in_menu - scored) kwargs["exclude_ids"] = set(moment.in_menu - scored)
@@ -171,6 +171,11 @@ async def _rerun_notes(
# The kinds the door considers NOW: the table keeps no history, so a call # 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. # made before a change is re-run against the current row.
kinds = await record_kinds.kinds_for(user_id, rp.AUTO_INJECT.door) kinds = await record_kinds.kinds_for(user_id, rp.AUTO_INJECT.door)
# The projects it draws from, by the same rule and the same spelling.
reach = rp.NoteMoment(
user_id=user_id, query="", project_id=None,
reach=await record_kinds.reach_for(user_id),
).cross_kinds()
rep: dict = {} rep: dict = {}
hits = await semantic_search_notes( hits = await semantic_search_notes(
user_id, row.query or "", user_id, row.query or "",
@@ -179,6 +184,7 @@ async def _rerun_notes(
project_id=row.project_id or None, project_id=row.project_id or None,
**rp.note_search_filters(rp.AUTO_INJECT), **rp.note_search_filters(rp.AUTO_INJECT),
record_kinds=record_kinds.search_kinds(kinds), record_kinds=record_kinds.search_kinds(kinds),
cross_kinds=reach,
report=rep, report=rep,
) )
postdated = [int(n.id) for _s, n in hits if _after(n.created_at, row.created_at)] postdated = [int(n.id) for _s, n in hits if _after(n.created_at, row.created_at)]
+41 -5
View File
@@ -332,7 +332,8 @@ def _bucket(rows: list) -> dict:
"""A score readout a human can act on, from one aggregate row.""" """A score readout a human can act on, from one aggregate row."""
(calls, zero, p10, p50, p90, lo, hi, avg_n, dur, (calls, zero, p10, p50, p90, lo, hi, avg_n, dur,
measured, supp_calls, supp_zero, measured, supp_calls, supp_zero,
miss_calls, miss_p50, miss_p90, miss_max) = rows miss_calls, miss_p50, miss_p90, miss_max,
gated, gate_declined) = rows
return { return {
"calls": int(calls or 0), "calls": int(calls or 0),
# A call that returned nothing is not a low-scoring call — it is a # A call that returned nothing is not a low-scoring call — it is a
@@ -388,6 +389,21 @@ def _bucket(rows: list) -> dict:
"max": _round(miss_max), "max": _round(miss_max),
} }
), ),
# WHAT THE CUE GATE TURNED AWAY. A gated arm logs its ranked results
# before the gate decides, so its `result_count` is what cleared the
# floor, and a call the gate silenced still reads as a hit there.
# `declined_by_gate` counts those calls, which returned something
# from the ranker and were withheld by the gate; a gated arm's
# declines are these plus `zero_result_calls`.
#
# None when no row in the window carried a gate decision: an ungated
# arm, or rows older than the gate.
"gate": (
None if not int(gated or 0) else {
"gated_calls": int(gated or 0),
"declined_by_gate": int(gate_declined or 0),
}
),
"avg_result_count": _round(avg_n), "avg_result_count": _round(avg_n),
"p90_duration_ms": _round(dur, 1), "p90_duration_ms": _round(dur, 1),
} }
@@ -397,11 +413,11 @@ def _bucket(rows: list) -> dict:
# the window: nothing counted, nothing scored. Positional, matching the SELECT # the window: nothing counted, nothing scored. Positional, matching the SELECT
# `_bucket` unpacks — calls, zero, p10, p50, p90, min, max, avg_n, # `_bucket` unpacks — calls, zero, p10, p50, p90, min, max, avg_n,
# dur, measured, supp_calls, supp_zero, miss_calls, miss_p50, miss_p90, # dur, measured, supp_calls, supp_zero, miss_calls, miss_p50, miss_p90,
# miss_max. The counts are 0 because zero calls is a real observation; # miss_max, gated, gate_declined. The counts are 0 because zero calls is a real observation;
# everything else is None because a distribution nobody sampled has no value, # everything else is None because a distribution nobody sampled has no value,
# and rendering it as 0.0 would state one. # and rendering it as 0.0 would state one.
_NO_ROWS_IN_WINDOW = [0, 0, None, None, None, None, None, None, None, _NO_ROWS_IN_WINDOW = [0, 0, None, None, None, None, None, None, None,
0, 0, 0, 0, None, None, None] 0, 0, 0, 0, None, None, None, 0, 0]
def _round(v, places: int = 4): def _round(v, places: int = 4):
@@ -591,6 +607,12 @@ def _compute_warnings(sources: dict, usage: dict, rule_usage: dict,
# it is stuck — either its bar is beneath everything or it is not # it is stuck — either its bar is beneath everything or it is not
# applying one. # applying one.
# #
# A gated arm stays quiet in two places: the floor, which shows as a
# zero-result call, and the cue gate after it, which logs the ranked
# results and then withholds them (`gate.declined_by_gate`). Both are
# declines; counting the first alone flags an arm whose gate is
# silencing most of its calls.
#
# THREE GUARDS BEFORE TRUSTING THIS, and each prevents a false # THREE GUARDS BEFORE TRUSTING THIS, and each prevents a false
# alarm. Asked surfaces are exempt: a search returning a list every # alarm. Asked surfaces are exempt: a search returning a list every
# time is a search doing its job, and flagging `mcp_search` would # time is a search doing its job, and flagging `mcp_search` would
@@ -600,20 +622,24 @@ def _compute_warnings(sources: dict, usage: dict, rule_usage: dict,
# exempt: an arm that records only its hits has a decline count that # exempt: an arm that records only its hits has a decline count that
# is structurally zero, and this warning would fire on a LOGGING # is structurally zero, and this warning would fire on a LOGGING
# defect while pointing the reader at the threshold. # defect while pointing the reader at the threshold.
gate = b.get("gate") or {}
declines = (b.get("zero_result_calls") or 0) + (gate.get("declined_by_gate") or 0)
if ( if (
calls >= min_calls calls >= min_calls
and (b.get("zero_result_calls") or 0) == 0 and declines == 0
and point is not None and point is not None
and point.kind == UNBIDDEN and point.kind == UNBIDDEN
and point.logs_unconditionally and point.logs_unconditionally
): ):
out.append(_warn( out.append(_warn(
"cannot_decline", "cannot_decline",
f"{calls} calls, 0 of them returned nothing. An arm that fires " f"{calls} calls, 0 of them returned nothing"
f"{' or were withheld by its cue gate' if gate else ''}. An arm that fires "
f"unasked has to be able to say nothing; this one never has. " f"unasked has to be able to say nothing; this one never has. "
f"Check that it applies its floor at all before reading any " f"Check that it applies its floor at all before reading any "
f"score below as evidence.", f"score below as evidence.",
source=name, calls=calls, zero_result_calls=0, source=name, calls=calls, zero_result_calls=0,
**({"declined_by_gate": 0} if gate else {}),
)) ))
# ── Band hugs its floor ────────────────────────────────────────── # ── Band hugs its floor ──────────────────────────────────────────
@@ -1181,6 +1207,14 @@ async def retrieval_summary(
((RetrievalLog.result_count == 0) & (RetrievalLog.suppressed_count > 0), 1), ((RetrievalLog.result_count == 0) & (RetrievalLog.suppressed_count > 0), 1),
else_=0, else_=0,
) )
# A gate decision is on the row only for a gated arm. A call the gate
# silenced after the ranker returned something: `result_count > 0`, so it
# is never also one of the zero-result calls above.
gated = case((RetrievalLog.gate_kept.isnot(None), 1), else_=0)
gate_declined = case(
((RetrievalLog.gate_kept == 0) & (RetrievalLog.result_count > 0), 1),
else_=0,
)
def pct(p: float): def pct(p: float):
return func.percentile_cont(p).within_group(RetrievalLog.top_score.asc()) return func.percentile_cont(p).within_group(RetrievalLog.top_score.asc())
@@ -1216,6 +1250,8 @@ async def retrieval_summary(
func.percentile_cont(0.5).within_group(miss_score.asc()), func.percentile_cont(0.5).within_group(miss_score.asc()),
func.percentile_cont(0.9).within_group(miss_score.asc()), func.percentile_cont(0.9).within_group(miss_score.asc()),
func.max(miss_score), func.max(miss_score),
func.sum(gated).label("gated"),
func.sum(gate_declined).label("gate_declined"),
) )
.where( .where(
RetrievalLog.created_at >= since, RetrievalLog.created_at >= since,
+19
View File
@@ -74,6 +74,25 @@ def parse_rulings(description: str | None) -> list[str]:
return out return out
def undelivered(systems) -> list[dict]:
"""The Systems whose rulings reach no session: they carry rulings and
name no files, so nothing a session touches falls under them.
Delivery is by `path_patterns` alone, so such a System's rulings are
never shown on an edit or a command, and nothing else says so. A System
without rulings has nothing to deliver and is not listed. One entry per
System: `{"id", "name", "rulings"}`, rulings being how many.
"""
out = []
for system in systems:
if system.path_patterns:
continue
count = len(parse_rulings(system.description))
if count:
out.append({"id": int(system.id), "name": system.name, "rulings": count})
return out
def _relative(token: str, root: str, cwd_rel: str) -> str: def _relative(token: str, root: str, cwd_rel: str) -> str:
"""`token` as a repo-relative path, or "" when it is not one.""" """`token` as a repo-relative path, or "" when it is not one."""
if token.startswith("/"): if token.startswith("/"):
+7 -4
View File
@@ -371,9 +371,10 @@ def _default_record_kinds(request):
"""Stub the settings read behind the kind×moment table. """Stub the settings read behind the kind×moment table.
Both record searches read the user's kinds per door Both record searches read the user's kinds per door
(`record_kinds.kinds_for`); stubbed to the shipped default so a unit test (`record_kinds.kinds_for`) and the kinds they take from other projects
of a door needs no database. The integration lane, where the table's own (`record_kinds.reach_for`); both stubbed to the shipped default so a unit
tests live, reads the real setting. 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"): if request.node.get_closest_marker("integration"):
yield yield
@@ -383,7 +384,9 @@ def _default_record_kinds(request):
async def _default(_user_id, door): async def _default(_user_id, door):
return record_kinds.DOORS[door].default return record_kinds.DOORS[door].default
with patch.object(record_kinds, "kinds_for", AsyncMock(side_effect=_default)): with patch.object(record_kinds, "kinds_for", AsyncMock(side_effect=_default)), \
patch.object(record_kinds, "reach_for",
AsyncMock(return_value=record_kinds.REACH_DEFAULT)):
yield yield
+2 -3
View File
@@ -87,9 +87,8 @@ def test_the_plugin_names_the_skill_it_ships():
# --- the pointers --------------------------------------------------------------------- # --- the pointers ---------------------------------------------------------------------
def test_every_surface_that_meets_family_canon_points_at_the_skill(): def test_every_surface_that_meets_family_canon_points_at_the_skill():
server = (ROOT / "src" / "grimoire" / "mcp" / "server.py").read_text() # Not the MCP instructions: `enter_project` returns the `family` key with
index = re.search(r'_INSTRUCTIONS = """(.*?)"""', server, re.S).group(1) # its own text, which is where a session meets family canon.
assert "family-canon" in index and "`family`" in index
for module, tool in (("notes", "create_note"), ("snippets", "create_snippet"), for module, tool in (("notes", "create_note"), ("snippets", "create_snippet"),
("shapes", "classify_shapes")): ("shapes", "classify_shapes")):
assert "family-canon" in tool_doc(f"grimoire.mcp.tools.{module}", tool), tool assert "family-canon" in tool_doc(f"grimoire.mcp.tools.{module}", tool), tool
+22 -19
View File
@@ -22,12 +22,15 @@ WHAT IT PINS
(the index, the adapter's static text and commands, the live context, the (the index, the adapter's static text and commands, the live context, the
other skills). A topic legitimately stated in two places at two different other skills). A topic legitimately stated in two places at two different
moments declares that in `shared_with`, with the reason beside it. moments declares that in `shared_with`, with the reason beside it.
3. THE INDEX NAMES THE SESSION-START REFLEXES. `_INSTRUCTIONS` is the one 3. THE INDEX NAMES WHAT NOTHING ELSE DELIVERS. `_INSTRUCTIONS` is the one
surface every MCP client receives, so each reflex it indexes keeps its surface every MCP client receives, so a topic it indexes keeps its `index`
`index` markers there — a one-line pointer, not a copy. Only session-start markers there — a one-line pointer, not a copy. Only the practices a client
practices carry `index`: judging, reporting and the missed-rule route fire with no skills and no hooks would otherwise never meet carry `index`:
mid-work, so they stay out of the index (the skills and the in-band entering the project, asking before a consequential act, searching before
responses carry them at the moment they apply). building, and the force of each record kind. A practice a response enforces
(the duplicate gate, the unassigned-id refusal, `existing_milestone`,
`systems_hint`, the design-system block) or that fires mid-work carries no
`index`: the response or the skill delivers it at the moment it applies.
WHAT IT CANNOT SEE WHAT IT CANNOT SEE
@@ -133,7 +136,7 @@ TOPICS: tuple[Topic, ...] = (
index=("enter_project",)), index=("enter_project",)),
Topic("rules are retrieved; ask before a consequential act", U, ('content_type="rule"', "nothing matched"), Topic("rules are retrieved; ask before a consequential act", U, ('content_type="rule"', "nothing matched"),
"an empty session is not evidence of an empty rulebook", "an empty session is not evidence of an empty rulebook",
index=('content_type="rule"', "nothing matched")), index=("nothing matched",)),
Topic("rules bind, preferences guide and are kept current", U, ("preference", "update_preference"), Topic("rules bind, preferences guide and are kept current", U, ("preference", "update_preference"),
"updating one mid-work is the normal case rather than an interruption of it", "updating one mid-work is the normal case rather than an interruption of it",
index=("preferences guide",)), index=("preferences guide",)),
@@ -170,11 +173,11 @@ TOPICS: tuple[Topic, ...] = (
Topic("stay inside the active project's scope", U, ("stay inside the active project", "cross-project"), Topic("stay inside the active project's scope", U, ("stay inside the active project", "cross-project"),
"stay inside the active project's scope", index=("project_id",)), "stay inside the active project's scope", index=("project_id",)),
Topic("record as you go; honest status; fixes are issues", U, ("add_task_log", "in_progress", 'kind="issue"'), Topic("record as you go; honest status; fixes are issues", U, ("add_task_log", "in_progress", 'kind="issue"'),
"fixes are issues, not work-logs", index=("add_task_log", 'kind="issue"')), "fixes are issues, not work-logs"),
Topic("an id exists only once a create returns it", U, ("exists only once a create", "{{ref:"), Topic("an id exists only once a create returns it", U, ("exists only once a create", "{{ref:"),
"exists only once a create call returns it", index=("create_records", "{{ref:n}}")), "exists only once a create call returns it"),
Topic("tag records to systems as you write", U, ("system_ids", "create_system"), Topic("tag records to systems as you write", U, ("system_ids", "create_system"),
"would someone investigating that subsystem want this record", index=("system_ids",)), "would someone investigating that subsystem want this record"),
Topic("answer the systems_hint at the moment of work", U, ("systems_hint",), Topic("answer the systems_hint at the moment of work", U, ("systems_hint",),
"treat it as the tagging question asked at the moment of work"), "treat it as the tagging question asked at the moment of work"),
Topic("a retrieved rule outranks a default habit", U, ("outranks a default habit",), Topic("a retrieved rule outranks a default habit", U, ("outranks a default habit",),
@@ -186,11 +189,11 @@ TOPICS: tuple[Topic, ...] = (
("hand off", "claims it for this session"), ("hand off", "claims it for this session"),
"write down what the next session needs"), "write down what the next session needs"),
Topic("the project's design system binds ui", U, ("resolve_design_system",), Topic("the project's design system binds ui", U, ("resolve_design_system",),
"building ui: the project's design system binds", index=("resolve_design_system",)), "building ui: the project's design system binds"),
Topic("name the record, never just its number", U, ("name the record",), Topic("name the record, never just its number", U, ("name the record",),
"a bare id reads as complete to you and as homework to them"), "a bare id reads as complete to you and as homework to them"),
Topic("project inception is a decision", U, ("decide_project_inception",), Topic("project inception is a decision", U, ("decide_project_inception",),
"starting a project: decide what it inherits", index=("decide_project_inception",)), "starting a project: decide what it inherits"),
Topic("where a new rule goes, and its trigger", U, ("create_project_rule", "when_to_apply"), Topic("where a new rule goes, and its trigger", U, ("create_project_rule", "when_to_apply"),
"whichever home it gets"), "whichever home it gets"),
Topic("a rule vs the other entities", U, ("standing instruction",), "first ask whether it's a rule at all"), Topic("a rule vs the other entities", U, ("standing instruction",), "first ask whether it's a rule at all"),
@@ -200,7 +203,7 @@ TOPICS: tuple[Topic, ...] = (
Topic("rules mounted on a moment arrive by lookup; correct a misfire in-session", U, Topic("rules mounted on a moment arrive by lookup; correct a misfire in-session", U,
("list_moments", "map_action", "unmap_action", "judge_rule_moments"), ("list_moments", "map_action", "unmap_action", "judge_rule_moments"),
"it belongs in the session that noticed, not on a settings page", "it belongs in the session that noticed, not on a settings page",
index=("list_moments", "moment")), ),
Topic("a new rule about when gets its moments as it is written", U, Topic("a new rule about when gets its moments as it is written", U,
("moments=[...]", "create_process(moments="), ("moments=[...]", "create_process(moments="),
"then ask when it applies, as well as what it is about"), "then ask when it applies, as well as what it is about"),
@@ -247,16 +250,16 @@ TOPICS: tuple[Topic, ...] = (
"which files are which area is your call"), "which files are which area is your call"),
# ── process arcs — owned by their skills ── # ── process arcs — owned by their skills ──
Topic("plan in a milestone, steps created together", "skill:writing-plans", ("start_planning", "{{ref:"), Topic("plan in a milestone, steps created together", "skill:writing-plans", ("start_planning", "{{ref:"),
"a milestone earns its place when the work has an arc", index=("start_planning",)), "a milestone earns its place when the work has an arc"),
# Without this, a session opens a second plan beside the roadmap milestone # Without this, a session opens a second plan beside the roadmap milestone
# that already covers the work. # that already covers the work.
Topic("find the existing plan before making one", "skill:writing-plans", Topic("find the existing plan before making one", "skill:writing-plans",
('content_type="milestone"', "unplanned_milestones", "existing_milestone"), ('content_type="milestone"', "unplanned_milestones", "existing_milestone"),
"when an active milestone already covers the work, the plan is that milestone", "when an active milestone already covers the work, the plan is that milestone",
index=('search(content_type="milestone")',)), ),
Topic("reuse recorded shapes; record at first build", "skill:reusing-code", Topic("reuse recorded shapes; record at first build", "skill:reusing-code",
("create_snippet", "when_to_use", "first build", "second copy"), ("create_snippet", "when_to_use", "first build", "second copy"),
"prior art offered beside a write is not noise", index=("create_snippet",)), "prior art offered beside a write is not noise"),
# The writer judges what it wrote, at the end of the turn, # The writer judges what it wrote, at the end of the turn,
# asked by the plugin's Stop hook — the moment the knowledge exists. # asked by the plugin's Stop hook — the moment the knowledge exists.
Topic("judge what you wrote before the turn ends", "skill:reusing-code", Topic("judge what you wrote before the turn ends", "skill:reusing-code",
@@ -304,7 +307,7 @@ TOPICS: tuple[Topic, ...] = (
"skill:family-canon", "skill:family-canon",
("family_hint", "get_family_adoption", "resolve_family_conflict", "precedent"), ("family_hint", "get_family_adoption", "resolve_family_conflict", "precedent"),
"write the reason so a session in another project can tell whether the same fact holds there", "write the reason so a session in another project can tell whether the same fact holds there",
index=("family-canon",)), ),
# ── per-tool contracts and in-band behaviour — owned by the server ── # ── per-tool contracts and in-band behaviour — owned by the server ──
Topic("closing a task cues the report", "docstrings", ("report_back",), "reporting this to the operator?"), Topic("closing a task cues the report", "docstrings", ("report_back",), "reporting this to the operator?"),
# The agent is the judge. Two topics, not one, because they fire # The agent is the judge. Two topics, not one, because they fire
@@ -329,9 +332,9 @@ TOPICS: tuple[Topic, ...] = (
"it simply stops competing with this one"), "it simply stops competing with this one"),
Topic("deletes are recoverable from the trash", "docstrings", ("deleted_batch_id",), "deleted_batch_id"), Topic("deletes are recoverable from the trash", "docstrings", ("deleted_batch_id",), "deleted_batch_id"),
Topic("creates are duplicate-gated", "docstrings", ("near-duplicate",), "bypass the near-duplicate gate", Topic("creates are duplicate-gated", "docstrings", ("near-duplicate",), "bypass the near-duplicate gate",
index=("duplicate-gated",)), ),
Topic("shared records are another user's suggestion", "docstrings", ("shared: true",), Topic("shared records are another user's suggestion", "docstrings", ("shared: true",),
"belongs to another user", index=("shared:true",)), "belongs to another user"),
Topic("stored processes are followed as written", "docstrings", ("get_process",), "follow the returned body"), Topic("stored processes are followed as written", "docstrings", ("get_process",), "follow the returned body"),
Topic("a project is never guessed", "docstrings", ("never guessing a project",), "never guessing a project"), Topic("a project is never guessed", "docstrings", ("never guessing a project",), "never guessing a project"),
Topic("an unbound repo gets a bind hint", "live", ("bind_repo",), "isn't mapped to a grimoire project"), Topic("an unbound repo gets a bind hint", "live", ("bind_repo",), "isn't mapped to a grimoire project"),
+5 -5
View File
@@ -51,11 +51,11 @@ def _instructions_text() -> str:
# Claude Code injects only the first ~2,048 characters of an MCP server's # Claude Code injects only the first ~2,048 characters of an MCP server's
# instructions and silently cuts the rest mid-word, so guidance past the cap # instructions and silently cuts the rest mid-word, so guidance past the cap
# never reaches a session. The budget is set below the cap, not at it: the # never reaches a session. The budget sits far below the cap: most servers
# field runs ~600–1,600 characters, and # carry a few hundred characters or none, and the block holds only what no
# a block pressed against 2,048 is being used for depth that belongs in a # response or skill delivers, so a block growing toward the cap is carrying
# skill. # depth that belongs in a skill.
INSTRUCTIONS_BUDGET = 1600 INSTRUCTIONS_BUDGET = 800
def test_instructions_fit_the_fold(): def test_instructions_fit_the_fold():
+147
View File
@@ -0,0 +1,147 @@
"""Real-Postgres: knowledge reaches a session from the user's other projects,
work stays in its own, and nobody else's unshared records cross at all.
A project-scoped search given `cross_kinds` (the user's reach,
`record_kinds.reach_for`) also takes those kinds from every other project the
caller may see. A record from elsewhere gives up a fixed penalty before the
floor and the ranking, so it ranks below an equally close record from the
session's project and needs to be that much closer to be offered at all.
Rows are inserted directly with one hand-made vector each and the embedder is
stubbed, so every record is exactly as close as every other and only the
scope and the penalty separate them.
"""
import traceback
import uuid
from unittest.mock import AsyncMock, patch
import pytest
from grimoire.models import async_session
from grimoire.models.embedding import NoteEmbedding
from grimoire.models.note import Note
from grimoire.services import embeddings as emb
from grimoire.services.record_kinds import REACH_DEFAULT
from tests.test_integration_search_scope import (
MINE_VEC, QUERY_VEC, _chunk, _cleanup, _people,
)
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine", "_no_embedding")]
# Cosine 0.8 to the query, for every record (MINE_VEC).
SCORE = 0.8
REACH = sorted(REACH_DEFAULT)
async def _search(user_id: int, project_id: int, **kw) -> list[tuple[float, int]]:
"""(score, id) pairs, best first. The search fails open, so a swallowed
traceback is captured and named in the failure instead of reading as an
empty result."""
raised: list[str] = []
with patch("grimoire.services.embeddings.get_embedding",
AsyncMock(return_value=QUERY_VEC)), \
patch("grimoire.services.embeddings.logger") as log:
log.warning.side_effect = lambda *_a, **_k: raised.append(traceback.format_exc())
hits = await emb.semantic_search_notes(
user_id, "anything", limit=10, project_id=project_id, scope="browse",
demote_superseded=False, **kw,
)
assert not raised, "the search raised:\n" + "\n".join(raised)
return [(round(score, 4), int(note.id)) for score, note in hits]
async def _corpus(tag: str) -> dict:
"""The reader's two projects and a stranger's, one equally close record
in each, and an open task in the reader's other project."""
reader, crowd, here, elsewhere, theirs = await _people(tag)
async with async_session() as s:
here_note = Note(user_id=reader, project_id=here, title="here", body="here")
away_note = Note(user_id=reader, project_id=elsewhere, title="away", body="away")
away_task = Note(user_id=reader, project_id=elsewhere, title="away task",
body="open work", status="todo", task_kind="work")
stranger = Note(user_id=crowd, project_id=theirs, title="stranger", body="theirs")
s.add_all([here_note, away_note, away_task, stranger])
await s.flush()
for n in (here_note, away_note, away_task, stranger):
s.add(_chunk(NoteEmbedding, "note_id", n.id, MINE_VEC, user_id=n.user_id))
await s.commit()
return {
"reader": reader, "crowd": crowd, "here": here,
"here_note": here_note.id, "away_note": away_note.id,
"away_task": away_task.id, "stranger": stranger.id,
}
@pytest.mark.asyncio
async def test_knowledge_from_another_project_reaches_the_session_below_its_own():
c = await _corpus(uuid.uuid4().hex[:8])
try:
hits = await _search(c["reader"], c["here"], threshold=0.5, cross_kinds=REACH)
# The session's own record first at its full score; the note from the
# other project after it, at the score less the penalty.
assert hits == [
(SCORE, c["here_note"]),
(round(SCORE - emb._CROSS_PROJECT_PENALTY, 4), c["away_note"]),
]
finally:
await _cleanup(c["reader"], c["crowd"])
@pytest.mark.asyncio
async def test_without_the_reach_the_search_keeps_to_its_project():
"""The project-only clause the reach widens: the same corpus, no
`cross_kinds`, and the other project's note is not reached. Without this
the test above could pass on a search that never filtered by project."""
c = await _corpus(uuid.uuid4().hex[:8])
try:
assert await _search(c["reader"], c["here"], threshold=0.5) == [(SCORE, c["here_note"])]
finally:
await _cleanup(c["reader"], c["crowd"])
@pytest.mark.asyncio
async def test_work_and_strangers_records_do_not_cross():
c = await _corpus(uuid.uuid4().hex[:8])
try:
found = {i for _s, i in await _search(c["reader"], c["here"], threshold=0.5,
cross_kinds=REACH)}
assert c["away_task"] not in found, "an open task crossed from another project"
assert c["stranger"] not in found, "another user's unshared note crossed"
# Work crosses only where the reach says so, which is what makes the
# first assertion about the reach rather than about tasks.
found = {i for _s, i in await _search(c["reader"], c["here"], threshold=0.5,
cross_kinds=[*REACH, "task:work"])}
assert c["away_task"] in found and c["stranger"] not in found
finally:
await _cleanup(c["reader"], c["crowd"])
@pytest.mark.asyncio
async def test_a_record_from_elsewhere_clears_a_floor_its_penalty_higher():
"""At a bar between the two scores, the session's own record is offered
and the equally close one from elsewhere is not."""
c = await _corpus(uuid.uuid4().hex[:8])
try:
bar = SCORE - emb._CROSS_PROJECT_PENALTY / 2
hits = await _search(c["reader"], c["here"], threshold=bar, cross_kinds=REACH)
assert hits == [(SCORE, c["here_note"])]
finally:
await _cleanup(c["reader"], c["crowd"])
@pytest.mark.asyncio
async def test_a_line_from_elsewhere_is_labelled_with_its_project_and_one_from_here_is_not():
from grimoire.models.project import Project
from grimoire.services.plugin_context import _origins
c = await _corpus(uuid.uuid4().hex[:8])
try:
async with async_session() as s:
notes = [await s.get(Note, c["here_note"]), await s.get(Note, c["away_note"])]
away_title = (await s.get(Project, notes[1].project_id)).title
assert await _origins(notes, c["here"]) == {c["away_note"]: away_title}
# With no project bound every record is from elsewhere, and a label
# on every line would say nothing.
assert await _origins(notes, None) == {}
finally:
await _cleanup(c["reader"], c["crowd"])
+42 -1
View File
@@ -20,7 +20,8 @@ async def _user(name: str = "record_kinds_owner") -> int:
async with async_session() as s: async with async_session() as s:
uid = (await ensure_user(s, name)).id uid = (await ensure_user(s, name)).id
await s.execute(delete(Setting).where( await s.execute(delete(Setting).where(
Setting.user_id == uid, Setting.key == record_kinds.SETTING_KEY)) Setting.user_id == uid,
Setting.key.in_([record_kinds.SETTING_KEY, record_kinds.REACH_SETTING_KEY])))
await s.execute(delete(RecordDelivery).where(RecordDelivery.user_id == uid)) await s.execute(delete(RecordDelivery).where(RecordDelivery.user_id == uid))
await s.commit() await s.commit()
return uid return uid
@@ -94,3 +95,43 @@ async def test_each_cell_carries_the_lines_its_door_pushed_and_the_opens():
assert cells["work.change"] == {} assert cells["work.change"] == {}
assert cells["message"] == {"task:issue": {"delivered": 1, "opened": 0}} assert cells["message"] == {"task:issue": {"delivered": 1, "opened": 0}}
assert table["evidence_failed"] is False assert table["evidence_failed"] is False
async def _reach_rows(uid: int) -> list[str]:
async with async_session() as s:
return list((await s.execute(select(Setting.value).where(
Setting.user_id == uid, Setting.key == record_kinds.REACH_SETTING_KEY,
))).scalars())
async def test_the_reach_follows_its_default_until_the_user_changes_it():
uid = await _user("record_reach_owner")
assert await record_kinds.reach_for(uid) == record_kinds.REACH_DEFAULT
# Knowledge crosses by default; no task kind does.
assert not any(k.startswith(record_kinds.TASK_PREFIX) for k in record_kinds.REACH_DEFAULT)
table = await record_kinds.set_reach(uid, ["snippet", "task:issue"])
assert table["reach"] == {
"kinds": ["snippet", "task:issue"],
"default": sorted(record_kinds.REACH_DEFAULT, key=record_kinds.KINDS.index),
"changed": True,
}
assert await record_kinds.reach_for(uid) == {"snippet", "task:issue"}
# Nothing crossing is a real setting, not a reset.
await record_kinds.set_reach(uid, [])
assert await record_kinds.reach_for(uid) == frozenset()
table = await record_kinds.set_reach(uid, None)
assert table["reach"]["changed"] is False
assert await _reach_rows(uid) == []
async def test_a_reach_equal_to_the_default_stores_no_change():
uid = await _user("record_reach_owner")
await record_kinds.set_reach(uid, sorted(record_kinds.REACH_DEFAULT))
assert await _reach_rows(uid) == []
async def test_an_unknown_kind_in_the_reach_is_refused_and_nothing_is_stored():
uid = await _user("record_reach_owner")
with pytest.raises(ValueError, match="unknown kind"):
await record_kinds.set_reach(uid, ["snippet", "dossier"])
assert await _reach_rows(uid) == []
+20
View File
@@ -187,3 +187,23 @@ async def test_a_system_is_found_behind_another_users_nearer_charters():
assert mine_id not in found and len(found) == 10 assert mine_id not in found and len(found) == 10
finally: finally:
await _cleanup(reader, crowd) await _cleanup(reader, crowd)
@pytest.mark.asyncio
async def test_every_embedding_table_keeps_its_vectors_inline():
"""The ranking computes one distance per in-scope chunk, so a vector moved
out of line into TOAST costs a lookup per chunk on every search.
pgvector's type defaults to EXTERNAL storage; migration 0139 sets MAIN."""
from sqlalchemy import text
async with async_session() as s:
rows = (await s.execute(text(
"SELECT c.relname, a.attstorage::text FROM pg_attribute a "
"JOIN pg_class c ON c.oid = a.attrelid "
"WHERE a.attname = 'embedding' AND c.relname = ANY(:tables)"
), {"tables": ["note_embeddings", "rule_embeddings",
"milestone_embeddings", "system_embeddings"]})).all()
assert dict(rows) == {
"note_embeddings": "m", "rule_embeddings": "m",
"milestone_embeddings": "m", "system_embeddings": "m",
}
+29
View File
@@ -296,6 +296,35 @@ async def test_an_arm_searches_only_the_kinds_its_door_allows():
assert calls[0]["record_kinds"] == ["snippet"] assert calls[0]["record_kinds"] == ["snippet"]
@pytest.mark.asyncio
async def test_the_arm_and_its_slots_take_the_users_reach_from_other_projects():
main = [_note(1, 0.70)]
reuse = [_note(9, 0.60, note_type="snippet")]
lesson = [_note(42, 0.58, note_type=LESSON_NOTE_TYPE)]
default = sorted(record_kinds.REACH_DEFAULT, key=record_kinds.KINDS.index)
_r, _io_, calls = await _run(
rp.AUTO_INJECT, _routed(main, reuse, lesson), kinds=EVERY_KIND,
)
# Unset, the shipped default, and every search of the call the same.
assert len(calls) == 3 and all(c["cross_kinds"] == default for c in calls)
_r, _io_, calls = await _run(
rp.AUTO_INJECT, _routed(main, reuse, lesson), kinds=EVERY_KIND,
reach=frozenset({"note"}),
)
assert all(c["cross_kinds"] == ["note"] for c in calls)
# Nothing crossing is passed as nothing, not as "no preference".
_r, _io_, calls = await _run(rp.WRITE_PATH, lambda kw: [], reach=frozenset())
assert calls[0]["cross_kinds"] == []
def test_a_line_from_another_project_names_it():
line = rp.menu_entry(7, kind="note", name="How the cache warms", score=0.71,
origin="Another project")
assert line[0].endswith("(0.71) — from Another project")
# A record from the session's own project carries no origin.
assert "from" not in rp.menu_entry(7, kind="note", name="How the cache warms")[0]
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_a_door_with_every_kind_off_searches_nothing_and_logs_nothing(): 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()) result, io, calls = await _run(rp.AUTO_INJECT, lambda kw: [], kinds=frozenset())
+4 -2
View File
@@ -51,7 +51,9 @@ async def test_an_empty_verdict_list_is_refused():
# ── the re-run replays the arm ─────────────────────────────────────────── # ── the re-run replays the arm ───────────────────────────────────────────
_FILTERS = ("note_type", "task_kind", "record_kinds", "include_global_kinds", "scope") _FILTERS = (
"note_type", "task_kind", "record_kinds", "include_global_kinds", "scope", "cross_kinds",
)
@pytest.mark.asyncio @pytest.mark.asyncio
@@ -87,7 +89,7 @@ async def test_the_re_run_searches_the_way_the_arm_does():
await review._rerun(1, row, 3) await review._rerun(1, row, 3)
arm = {k: arm_kw[k] for k in _FILTERS if k in arm_kw} arm = {k: arm_kw[k] for k in _FILTERS if k in arm_kw}
assert "scope" in arm and "include_global_kinds" in arm, ( assert {"scope", "include_global_kinds", "cross_kinds"} <= set(arm), (
f"the arm no longer passes its visibility filters: {arm_kw}" f"the arm no longer passes its visibility filters: {arm_kw}"
) )
assert {k: rerun_kw[k] for k in _FILTERS if k in rerun_kw} == arm assert {k: rerun_kw[k] for k in _FILTERS if k in rerun_kw} == arm
+25
View File
@@ -97,6 +97,31 @@ def test_an_arm_that_does_decline_is_not_flagged() -> None:
assert "cannot_decline" not in codes(ws) assert "cannot_decline" not in codes(ws)
def test_a_gated_arm_whose_gate_declines_is_not_flagged() -> None:
"""A gated arm logs its ranked results before the cue gate decides, so a
call the gate silenced still reads as a hit in `zero_result_calls`. Those
withheld calls are declines too."""
gated = src(calls=300, zero_result_calls=0,
gate={"gated_calls": 300, "declined_by_gate": 240})
assert "cannot_decline" not in codes(warn({"auto_inject": gated}))
def test_counting_zero_results_alone_would_flag_that_arm() -> None:
"""The same arm with its gate block dropped, which is how the check read it
before: the warning fires, so the test above is not passing by accident."""
assert "cannot_decline" in codes(
warn({"auto_inject": src(calls=300, zero_result_calls=0)}))
def test_a_gated_arm_that_never_declines_anywhere_is_flagged() -> None:
gated = src(calls=300, zero_result_calls=0,
gate={"gated_calls": 300, "declined_by_gate": 0})
ws = warn({"auto_inject": gated})
w = next(w for w in ws if w["code"] == "cannot_decline")
assert w["numbers"] == {"calls": 300, "zero_result_calls": 0, "declined_by_gate": 0}
assert "cue gate" in w["detail"]
def test_an_arm_not_known_to_log_unconditionally_is_exempt(monkeypatch) -> None: def test_an_arm_not_known_to_log_unconditionally_is_exempt(monkeypatch) -> None:
"""A structurally-zero decline count is a logging bug, not a floor. """A structurally-zero decline count is a logging bug, not a floor.
+1
View File
@@ -44,6 +44,7 @@ def test_every_endpoint_is_reachable_on_the_app():
"/api/retrieval/record-reach", "/api/retrieval/record-reach",
"/api/retrieval/gate-stops", "/api/retrieval/gate-stops",
"/api/retrieval/record-kinds", "/api/retrieval/record-kinds",
"/api/retrieval/record-kinds/reach",
"/api/retrieval/gate", "/api/retrieval/gate",
"/api/retrieval/tuning-history", "/api/retrieval/tuning-history",
"/api/retrieval/moments", "/api/retrieval/moments",
+45 -1
View File
@@ -81,7 +81,8 @@ def test_the_scope_is_materialized_and_the_order_is_over_it():
.where(Note.user_id == 1) .where(Note.user_id == 1)
) )
sql = compiled_sql( sql = compiled_sql(
emb._rank_scoped(Note, scoped, name="scoped_x", limit=5), emb._rank_scoped(Note, scoped, embedding_model=NoteEmbedding,
record_key=NoteEmbedding.note_id, name="scoped_x", limit=5),
dialect=postgresql.dialect(), dialect=postgresql.dialect(),
) )
# MATERIALIZED is what keeps the planner from inlining the CTE and walking # MATERIALIZED is what keeps the planner from inlining the CTE and walking
@@ -92,3 +93,46 @@ def test_the_scope_is_materialized_and_the_order_is_over_it():
# The scope sits inside the CTE, where the ranking draws from. # The scope sits inside the CTE, where the ranking draws from.
cte_body = sql.split("AS MATERIALIZED", 1)[1].split("SELECT notes", 1)[0] cte_body = sql.split("AS MATERIALIZED", 1)[1].split("SELECT notes", 1)[0]
assert "notes.user_id" in cte_body assert "notes.user_id" in cte_body
def _ranked_sql(scoped) -> str:
return compiled_sql(
emb._rank_scoped(Note, scoped, embedding_model=NoteEmbedding,
record_key=NoteEmbedding.note_id, name="scoped_x", limit=5),
dialect=postgresql.dialect(),
)
def _scope_body(sql: str) -> str:
"""The materialized scope's own SELECT, up to where the ranking reads it."""
return sql.split("AS MATERIALIZED", 1)[1].split("SELECT notes", 1)[0]
def _mine(scoped):
return scoped.join(Note, NoteEmbedding.note_id == Note.id).where(Note.user_id == 1)
def test_the_scope_carries_distances_and_the_text_is_read_for_the_winners_only():
"""Every in-scope chunk's text materialized beside its distance spills the
sort to disk on a whole-corpus scope (about 1 s on tens of thousands of
chunks), so the scope holds ids and distances, the cut happens over those,
and the text is joined back for the rows that survived it."""
distance = NoteEmbedding.embedding.cosine_distance(NoteEmbedding.embedding)
sql = _ranked_sql(_mine(emb._scoped_chunks(NoteEmbedding, NoteEmbedding.note_id, distance)))
assert "chunk_text" not in _scope_body(sql), "the materialized scope carries the chunk text"
# The cut sits inside the subquery the text is joined onto, so the join
# reads at most `limit` rows of text.
nearest = sql.split(") AS scoped_x_nearest", 1)[0].rsplit("FROM scoped_x", 1)[1]
assert "LIMIT 5" in nearest
assert "scoped_x_text.chunk_text" in sql
assert "scoped_x_text.chunk_index = scoped_x_nearest.chunk_index" in sql
def test_a_scope_that_carries_the_text_is_caught():
"""Replay the guard against the shape it replaced: a scope that labels the
chunk text beside the distance."""
distance = NoteEmbedding.embedding.cosine_distance(NoteEmbedding.embedding)
old = _mine(emb._scoped_chunks(NoteEmbedding, NoteEmbedding.note_id, distance)
.add_columns(NoteEmbedding.chunk_text.label("chunk_text")))
assert "chunk_text" in _scope_body(_ranked_sql(old))
+24 -7
View File
@@ -103,13 +103,14 @@ def test_the_readout_reports_unmeasured_suppression_as_none():
from grimoire.services.retrieval_telemetry import _bucket from grimoire.services.retrieval_telemetry import _bucket
# calls, zero, p10, p50, p90, min, max, avg_n, dur, # calls, zero, p10, p50, p90, min, max, avg_n, dur,
# measured, supp_calls, supp_zero, miss_calls, miss_p50, miss_p90, miss_max # measured, supp_calls, supp_zero, miss_calls, miss_p50, miss_p90, miss_max,
# gated, gate_declined
unmeasured = _bucket([326, 114, 0.6, 0.68, 0.77, 0.55, 0.85, 1.7, 130.9, unmeasured = _bucket([326, 114, 0.6, 0.68, 0.77, 0.55, 0.85, 1.7, 130.9,
0, 0, 0, 0, None, None, None]) 0, 0, 0, 0, None, None, None, 0, 0])
assert unmeasured["suppression"] is None assert unmeasured["suppression"] is None
measured = _bucket([35, 34, 0.75, 0.75, 0.75, 0.75, 0.75, 0.03, 51.9, measured = _bucket([35, 34, 0.75, 0.75, 0.75, 0.75, 0.75, 0.03, 51.9,
35, 9, 9, 0, None, None, None]) 35, 9, 9, 0, None, None, None, 0, 0])
assert measured["suppression"] == { assert measured["suppression"] == {
"measured_calls": 35, "measured_calls": 35,
"calls_with_suppression": 9, "calls_with_suppression": 9,
@@ -1124,13 +1125,14 @@ def test_the_readout_reports_unmeasured_near_misses_as_none():
from grimoire.services.retrieval_telemetry import _bucket from grimoire.services.retrieval_telemetry import _bucket
# calls, zero, p10, p50, p90, min, max, avg_n, dur, # calls, zero, p10, p50, p90, min, max, avg_n, dur,
# measured, supp_calls, supp_zero, miss_calls, miss_p50, miss_p90, miss_max # measured, supp_calls, supp_zero, miss_calls, miss_p50, miss_p90, miss_max,
# gated, gate_declined
none_measured = _bucket([326, 114, 0.6, 0.68, 0.77, 0.55, 0.85, 1.7, 130.9, none_measured = _bucket([326, 114, 0.6, 0.68, 0.77, 0.55, 0.85, 1.7, 130.9,
0, 0, 0, 0, None, None, None]) 0, 0, 0, 0, None, None, None, 0, 0])
assert none_measured["near_misses"] is None assert none_measured["near_misses"] is None
measured = _bucket([326, 114, 0.6, 0.68, 0.77, 0.55, 0.85, 1.7, 130.9, measured = _bucket([326, 114, 0.6, 0.68, 0.77, 0.55, 0.85, 1.7, 130.9,
0, 0, 0, 114, 0.61, 0.7104, 0.7189]) 0, 0, 0, 114, 0.61, 0.7104, 0.7189, 0, 0])
assert measured["near_misses"] == { assert measured["near_misses"] == {
"measured_calls": 114, "measured_calls": 114,
"p50": 0.61, "p50": 0.61,
@@ -1139,6 +1141,21 @@ def test_the_readout_reports_unmeasured_near_misses_as_none():
} }
def test_the_readout_reports_the_cue_gate_only_where_rows_carried_one():
"""An ungated arm, or a window older than the gate, has no gate block:
a zeroed one would claim the gate declined nothing."""
from grimoire.services.retrieval_telemetry import _bucket
ungated = _bucket([326, 0, 0.6, 0.68, 0.77, 0.55, 0.85, 3.9, 130.9,
0, 0, 0, 0, None, None, None, 0, 0])
assert ungated["gate"] is None
gated = _bucket([69, 0, 0.77, 0.8, 0.86, 0.7, 0.9, 3.9, 1065.0,
0, 0, 0, 0, None, None, None, 69, 55])
assert gated["gate"] == {"gated_calls": 69, "declined_by_gate": 55}
assert gated["zero_result_calls"] == 0
def test_the_readout_carries_no_field_derivable_from_its_neighbours(): def test_the_readout_carries_no_field_derivable_from_its_neighbours():
"""No readout field is a sum of the two beside it. """No readout field is a sum of the two beside it.
@@ -1150,7 +1167,7 @@ def test_the_readout_carries_no_field_derivable_from_its_neighbours():
from grimoire.services.retrieval_telemetry import _bucket from grimoire.services.retrieval_telemetry import _bucket
b = _bucket([326, 114, 0.6, 0.68, 0.77, 0.55, 0.85, 1.7, 130.9, b = _bucket([326, 114, 0.6, 0.68, 0.77, 0.55, 0.85, 1.7, 130.9,
0, 0, 0, 114, 0.61, 0.71, 0.72]) 0, 0, 0, 114, 0.61, 0.71, 0.72, 0, 0])
derivable = { derivable = {
k for k, v in b.items() k for k, v in b.items()
if isinstance(v, int) and not isinstance(v, bool) if isinstance(v, int) and not isinstance(v, bool)
+32
View File
@@ -239,3 +239,35 @@ async def test_a_write_with_no_prior_art_still_carries_its_areas_rulings():
args, kwargs = rulings.call_args args, kwargs = rulings.call_args
assert args[2] == ["src/a.py"] assert args[2] == ["src/a.py"]
assert kwargs["seen"] == [9] and kwargs["source"] == "rulings_write_path" assert kwargs["seen"] == [9] and kwargs["source"] == "rulings_write_path"
# ── a System whose rulings reach nobody ───────────────────────────────────
def _area(sid, *, description, patterns):
return SimpleNamespace(id=sid, name=f"Area {sid}", description=description,
path_patterns=patterns)
RULED = "What it does.\n\n## Rulings\n\n- **One decision** (operator, a date).\n- **Another.**\n"
def test_a_system_with_rulings_and_no_files_is_named_as_undelivered():
systems = [
_area(1, description=RULED, patterns=[]),
# Files named: its rulings are delivered on them.
_area(2, description=RULED, patterns=["src/area/**"]),
# No rulings: nothing to deliver, so nothing to flag.
_area(3, description="What it does.", patterns=[]),
]
assert sr.undelivered(systems) == [{"id": 1, "name": "Area 1", "rulings": 2}]
def test_enter_project_carries_the_flag_only_when_a_system_needs_it():
from grimoire.mcp.tools.projects import _rulings_undelivered
flagged = _rulings_undelivered([_area(1, description=RULED, patterns=[])])
assert flagged["rulings_undelivered"]["systems"] == [{"id": 1, "name": "Area 1", "rulings": 2}]
assert "update_system" in flagged["rulings_undelivered"]["fix"]
# Absent, not empty, when every ruled System names its files.
assert _rulings_undelivered([_area(2, description=RULED, patterns=["src/**"])]) == {}