From 6cb61cdf8420db6e6c346fcadf1afbd2b5f5f729 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sat, 28 Nov 2026 12:05:12 -0500 Subject: [PATCH 01/10] licence(7023): the Claude Code plugin is MIT; the server stays AGPL-3.0-only The operator settled the split on 2026-11-09. The server is AGPL-3.0-only. The plugin is a client adapter that people install into their own tooling, so it is MIT. plugin/ now carries its own LICENSE, the manifest declares MIT, and the README's Licence section names both. Plugin version minted 2026.11.28.1705. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 ++ plugin/.claude-plugin/plugin.json | 4 ++-- plugin/LICENSE | 21 +++++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 plugin/LICENSE diff --git a/README.md b/README.md index 33de81b8..ce8c7111 100644 --- a/README.md +++ b/README.md @@ -148,3 +148,5 @@ docker compose -f docker-compose.dev.yml up --build ## 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. + +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. diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 0ab4aef7..aa155d37 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,11 +1,11 @@ { "name": "grimoire", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.11.27.1932", + "version": "2026.11.28.1705", "author": { "name": "Bryan Van Deusen" }, - "license": "AGPL-3.0-only", + "license": "MIT", "mcpServers": { "grimoire": { "type": "http", diff --git a/plugin/LICENSE b/plugin/LICENSE new file mode 100644 index 00000000..a61408b1 --- /dev/null +++ b/plugin/LICENSE @@ -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. -- 2.54.0 From efba891f5e5de4680061b675bfbb6913233772d7 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sat, 28 Nov 2026 16:10:00 -0500 Subject: [PATCH 02/10] perf(8190): the exact search reads vectors from the row and text only for the winners Step 1 of milestone 669 "Knowledge reaches every project, work stays in its own: a fast exact search, cross-project recall ranked and labelled", for #6834 "auto_inject p90 latency has climbed since 10-23". A search with no project in scope took about 1 s, because it ranked about 26k chunks exactly. Two costs on that path, neither of which changes a result: - pgvector's vector type defaults to EXTERNAL storage, and a chunk row (about 1.5 KB of vector plus its text) is over the 2 KB toast threshold, so every vector sat in TOAST and each distance paid a lookup (151k buffer hits for 26k rows). Migration 0139 sets STORAGE MAIN on the four embedding tables and rewrites the existing rows once. - The materialized scope carried every chunk's text beside its distance and spilled the sort to disk. It now carries the id, chunk index and distance, and the text is joined back for the rows that survive the cut. Measured on the live corpus: 1,151 ms as before, 393 ms with the text out of the scope, before the storage change. The HNSW index stays out of the ranking. With pgvector 0.8's iterative scan it returned 7 to 60 of the true 144 nearest chunks under a narrow scope, at every setting tried. Co-Authored-By: Claude Opus 5.5 --- .../versions/0139_embedding_vectors_inline.py | 42 +++++++++++ src/grimoire/models/embedding.py | 4 +- src/grimoire/services/embeddings.py | 69 ++++++++++++++----- tests/test_integration_search_scope.py | 20 ++++++ tests/test_search_scope_shape.py | 46 ++++++++++++- 5 files changed, 161 insertions(+), 20 deletions(-) create mode 100644 alembic/versions/0139_embedding_vectors_inline.py diff --git a/alembic/versions/0139_embedding_vectors_inline.py b/alembic/versions/0139_embedding_vectors_inline.py new file mode 100644 index 00000000..a705e9bc --- /dev/null +++ b/alembic/versions/0139_embedding_vectors_inline.py @@ -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") diff --git a/src/grimoire/models/embedding.py b/src/grimoire/models/embedding.py index f3dc5c71..bf732cad 100644 --- a/src/grimoire/models/embedding.py +++ b/src/grimoire/models/embedding.py @@ -10,7 +10,9 @@ from grimoire.models import Base # 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 # 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 diff --git a/src/grimoire/services/embeddings.py b/src/grimoire/services/embeddings.py index a5495ca9..f38607ce 100644 --- a/src/grimoire/services/embeddings.py +++ b/src/grimoire/services/embeddings.py @@ -22,6 +22,7 @@ from contextvars import ContextVar from typing import TYPE_CHECKING from sqlalchemy import and_, delete, func, or_, select +from sqlalchemy.orm import aliased from grimoire.models import async_session from grimoire.models.embedding import NoteEmbedding, RuleEmbedding @@ -861,43 +862,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 # order a materialized CTE, so the ranking over it is exact. # -# What exact costs is one distance per in-scope chunk. Rules, milestones and -# Systems are hundreds of chunks. Notes are the big corpus, but the hook arms -# that run on every prompt are project-scoped, so the pass is over one -# project's chunks rather than the whole table; `retrieval_logs.duration_ms` -# on those arms is where that claim is checked. If it ever -# stops holding, pgvector 0.8's `hnsw.iterative_scan` keeps the index and is -# the next step — gated on the extension version, because an unknown `hnsw.*` -# setting errors and these searches would read that error as "nothing found". +# The index is not a faster way to the same answer. pgvector 0.8's +# `hnsw.iterative_scan` keeps walking the graph until enough rows pass the +# filter, but under a narrow scope (one small project and the lessons) it +# returns a different set: 7 to 60 of the true 144 nearest chunks, in strict +# and relaxed order alike and at an `ef_search` of 200 or 1000. Only a broad +# scope comes back right. So the ranking stays exact everywhere. +# +# 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): """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. - 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( record_key.label("record_id"), distance.label("distance"), embedding_model.chunk_index.label("chunk_index"), - embedding_model.chunk_text.label("chunk_text"), ).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 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 moves onto this without its callers or its mocks noticing. """ scoped = scoped_chunks.cte(name).prefix_with("MATERIALIZED") - return ( - select(record_model, scoped.c.distance, scoped.c.chunk_index, scoped.c.chunk_text) - .join(scoped, scoped.c.record_id == record_model.id) + nearest = ( + select(scoped.c.record_id, scoped.c.distance, scoped.c.chunk_index) .order_by(scoped.c.distance) .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) ) @@ -1116,7 +1142,9 @@ async def semantic_search_notes( # bar is applied after the collapse, where the rejected scores can # still be seen. 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()) except Exception: logger.warning("Failed to query note embeddings", exc_info=True) @@ -1635,7 +1663,8 @@ async def semantic_search_rules( rows = (await session.execute( # Overfetch so collapsing chunks to their best row still fills # 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) )).all() except Exception: @@ -1838,7 +1867,9 @@ async def semantic_search_milestones( ) async with async_session() as session: 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) )).all() except Exception: @@ -2010,7 +2041,9 @@ async def semantic_search_systems( ) async with async_session() as session: 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) )).all() except Exception: diff --git a/tests/test_integration_search_scope.py b/tests/test_integration_search_scope.py index a96b551a..eb42b6cc 100644 --- a/tests/test_integration_search_scope.py +++ b/tests/test_integration_search_scope.py @@ -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 finally: 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 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", + } diff --git a/tests/test_search_scope_shape.py b/tests/test_search_scope_shape.py index b3a517c0..34b27041 100644 --- a/tests/test_search_scope_shape.py +++ b/tests/test_search_scope_shape.py @@ -81,7 +81,8 @@ def test_the_scope_is_materialized_and_the_order_is_over_it(): .where(Note.user_id == 1) ) 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(), ) # 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. cte_body = sql.split("AS MATERIALIZED", 1)[1].split("SELECT notes", 1)[0] 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)) -- 2.54.0 From deb991b2ccc1418dadce000b23b3e88449d50403 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sat, 28 Nov 2026 16:15:53 -0500 Subject: [PATCH 03/10] test(8190): read attstorage as text; asyncpg returns the one-byte "char" type as bytes Co-Authored-By: Claude Opus 5.5 --- tests/test_integration_search_scope.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_integration_search_scope.py b/tests/test_integration_search_scope.py index eb42b6cc..7e1aa643 100644 --- a/tests/test_integration_search_scope.py +++ b/tests/test_integration_search_scope.py @@ -198,7 +198,7 @@ async def test_every_embedding_table_keeps_its_vectors_inline(): async with async_session() as s: rows = (await s.execute(text( - "SELECT c.relname, a.attstorage FROM pg_attribute a " + "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", -- 2.54.0 From 163d32859fbfdf5efe3afe73481622b58a866749 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sat, 28 Nov 2026 16:15:53 -0500 Subject: [PATCH 04/10] fix(8192): a gated arm's declines include the calls its cue gate withheld #8192 "The cannot_decline warning reads the result count from before the cue gate, so a gated arm can never show a decline", step 3 of milestone 669. auto_inject logs its ranked results before the cue gate decides, so a call the gate silenced still reads as a hit, and cannot_decline fired on an arm whose gate withholds most calls (since 11-23, gate_kept = 0 on 55 of 69, 40 of 44 and 71 of 84 calls a day, with result_count never 0). The readout gains a `gate` block per source (gated_calls, declined_by_gate), null where no row carried a gate decision, and cannot_decline counts zero_result_calls plus declined_by_gate. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/mcp/tools/search.py | 10 ++++- src/grimoire/services/retrieval_telemetry.py | 46 +++++++++++++++++--- tests/test_retrieval_warnings.py | 25 +++++++++++ tests/test_services_retrieval_telemetry.py | 31 ++++++++++--- 4 files changed, 99 insertions(+), 13 deletions(-) diff --git a/src/grimoire/mcp/tools/search.py b/src/grimoire/mcp/tools/search.py index be29efbc..4b256de2 100644 --- a/src/grimoire/mcp/tools/search.py +++ b/src/grimoire/mcp/tools/search.py @@ -439,6 +439,12 @@ async def retrieval_telemetry( Read a null as "unknown", never as a zero: an artifact read as a 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 `retrieval_logs` cannot be indexed at: `surfaced` (ranked surfacings — a 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 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 - 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 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. diff --git a/src/grimoire/services/retrieval_telemetry.py b/src/grimoire/services/retrieval_telemetry.py index 058e25bc..ae7e8769 100644 --- a/src/grimoire/services/retrieval_telemetry.py +++ b/src/grimoire/services/retrieval_telemetry.py @@ -332,7 +332,8 @@ def _bucket(rows: list) -> dict: """A score readout a human can act on, from one aggregate row.""" (calls, zero, p10, p50, p90, lo, hi, avg_n, dur, 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 { "calls": int(calls or 0), # 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), } ), + # 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), "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 # `_bucket` unpacks — calls, zero, p10, p50, p90, min, max, avg_n, # 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, # and rendering it as 0.0 would state one. _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): @@ -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 # 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 # alarm. Asked surfaces are exempt: a search returning a list every # 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 # is structurally zero, and this warning would fire on a LOGGING # 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 ( calls >= min_calls - and (b.get("zero_result_calls") or 0) == 0 + and declines == 0 and point is not None and point.kind == UNBIDDEN and point.logs_unconditionally ): out.append(_warn( "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"Check that it applies its floor at all before reading any " f"score below as evidence.", source=name, calls=calls, zero_result_calls=0, + **({"declined_by_gate": 0} if gate else {}), )) # ── Band hugs its floor ────────────────────────────────────────── @@ -1181,6 +1207,14 @@ async def retrieval_summary( ((RetrievalLog.result_count == 0) & (RetrievalLog.suppressed_count > 0), 1), 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): 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.9).within_group(miss_score.asc()), func.max(miss_score), + func.sum(gated).label("gated"), + func.sum(gate_declined).label("gate_declined"), ) .where( RetrievalLog.created_at >= since, diff --git a/tests/test_retrieval_warnings.py b/tests/test_retrieval_warnings.py index 04889bb2..6feb728c 100644 --- a/tests/test_retrieval_warnings.py +++ b/tests/test_retrieval_warnings.py @@ -97,6 +97,31 @@ def test_an_arm_that_does_decline_is_not_flagged() -> None: 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: """A structurally-zero decline count is a logging bug, not a floor. diff --git a/tests/test_services_retrieval_telemetry.py b/tests/test_services_retrieval_telemetry.py index 239524a8..5c434221 100644 --- a/tests/test_services_retrieval_telemetry.py +++ b/tests/test_services_retrieval_telemetry.py @@ -103,13 +103,14 @@ def test_the_readout_reports_unmeasured_suppression_as_none(): from grimoire.services.retrieval_telemetry import _bucket # 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, - 0, 0, 0, 0, None, None, None]) + 0, 0, 0, 0, None, None, None, 0, 0]) assert unmeasured["suppression"] is None 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"] == { "measured_calls": 35, "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 # 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, - 0, 0, 0, 0, None, None, None]) + 0, 0, 0, 0, None, None, None, 0, 0]) 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, - 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"] == { "measured_calls": 114, "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(): """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 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 = { k for k, v in b.items() if isinstance(v, int) and not isinstance(v, bool) -- 2.54.0 From 30aa5cf1c612c0b74fc64fbece9aafd6f096ae6f Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sat, 28 Nov 2026 17:20:31 -0500 Subject: [PATCH 05/10] feat(8191): knowledge reaches a session from every project, ranked below its own and labelled A per-kind reach beside the kind-by-moment table (setting record_reach, default snippet/note/process/lesson) widens the passive note arms and their slots to the user's other projects. A record from elsewhere gives up 0.05 before the floor and the ranking, and its line names the project. Work kinds stay in their project, the visibility clause is unchanged, and an explicit project search still means that project. Settings > Moments edits the reach. Co-Authored-By: Claude Opus 5.5 --- frontend/src/api/moments.ts | 13 ++ frontend/src/components/RecordKinds.vue | 54 ++++++- src/grimoire/mcp/tools/moments.py | 7 +- src/grimoire/routes/retrieval.py | 20 +++ src/grimoire/services/embeddings.py | 41 +++++- src/grimoire/services/plugin_context.py | 46 +++++- src/grimoire/services/record_kinds.py | 59 ++++++++ src/grimoire/services/retrieval_pipeline.py | 22 ++- src/grimoire/services/retrieval_review.py | 6 + tests/conftest.py | 11 +- tests/test_integration_cross_project.py | 147 ++++++++++++++++++++ tests/test_integration_record_kinds.py | 43 +++++- tests/test_note_pipeline.py | 29 ++++ tests/test_retrieval_review.py | 6 +- 14 files changed, 491 insertions(+), 13 deletions(-) create mode 100644 tests/test_integration_cross_project.py diff --git a/frontend/src/api/moments.ts b/frontend/src/api/moments.ts index b4628a8c..dd9c7778 100644 --- a/frontend/src/api/moments.ts +++ b/frontend/src/api/moments.ts @@ -297,9 +297,17 @@ export interface RecordKindsDoor { evidence: Record; } +/** Which kinds a door may offer from the user's other projects. */ +export interface RecordKindsReach { + kinds: string[]; + default: string[]; + changed: boolean; +} + export interface RecordKindsTable { days: number; evidence_failed: boolean; + reach: RecordKindsReach; kinds: { kind: string; label: string }[]; doors: RecordKindsDoor[]; } @@ -313,6 +321,11 @@ export function setRecordKinds(door: string, kinds: string[] | null): Promise { + return apiPut("/api/retrieval/record-kinds/reach", { kinds }); +} + /** How a record arrived in front of a session. */ export type RecordWay = "pushed" | "pointed" | "asked" | "direct"; diff --git a/frontend/src/components/RecordKinds.vue b/frontend/src/components/RecordKinds.vue index 0f61a4c1..bca811d9 100644 --- a/frontend/src/components/RecordKinds.vue +++ b/frontend/src/components/RecordKinds.vue @@ -1,7 +1,7 @@