Fast exact search, cross-project knowledge, delivered rulings, short MCP instructions #236
@@ -297,9 +297,17 @@ export interface RecordKindsDoor {
|
||||
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 {
|
||||
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<Re
|
||||
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. */
|
||||
export type RecordWay = "pushed" | "pointed" | "asked" | "direct";
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
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";
|
||||
|
||||
/**
|
||||
@@ -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
|
||||
* 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.
|
||||
*
|
||||
* 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 }>();
|
||||
|
||||
@@ -44,6 +48,26 @@ function toggle(row: RecordKindsDoor, kind: string, on: boolean) {
|
||||
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 {
|
||||
const c = row.evidence[kind];
|
||||
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.
|
||||
</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
|
||||
v-for="row in table.doors" :key="row.door" class="door"
|
||||
:disabled="saving === row.door"
|
||||
|
||||
@@ -50,8 +50,11 @@ async def list_moments() -> dict:
|
||||
search fires (`message`, the operator's message, and the catalog moments
|
||||
that have one), the kinds of record it may consider, the shipped default,
|
||||
and each kind's lines shown and opened there. A kind left out is never
|
||||
pushed at that point; search for it yourself when you need it. The
|
||||
operator changes the table in Settings › Moments.
|
||||
pushed at that point; search for it yourself when you need it. Its
|
||||
`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()
|
||||
out = moments_svc.catalog()
|
||||
|
||||
@@ -294,6 +294,26 @@ async def set_record_kinds_route():
|
||||
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"])
|
||||
@login_required
|
||||
async def record_reach_route():
|
||||
|
||||
@@ -184,6 +184,19 @@ def _cosine_similarity(a: list[float], b: list[float]) -> float:
|
||||
# name, and a superseded record is demoted, never hidden.
|
||||
_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
|
||||
# headroom is far more than a 0.05 penalty can move anything through in a corpus
|
||||
# whose neighbours sit ~0.01-0.02 apart.
|
||||
@@ -944,9 +957,18 @@ async def semantic_search_notes(
|
||||
system_id: int | None = None,
|
||||
report: dict | None = None,
|
||||
record_kinds: Sequence[str] | None = None,
|
||||
cross_kinds: Sequence[str] | None = None,
|
||||
) -> list[tuple[float, Note]]:
|
||||
"""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`: `snippet`, `task:issue`, …), the vocabulary the
|
||||
injected arms filter by. It composes with every other filter.
|
||||
@@ -1063,10 +1085,17 @@ async def semantic_search_notes(
|
||||
stmt = stmt.where(Note.project_id.is_(None))
|
||||
elif project_id is not None:
|
||||
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, Note.note_type.in_(GLOBAL_NOTE_TYPES)
|
||||
)
|
||||
if include_global_kinds:
|
||||
# Family canon crosses the project
|
||||
# line the same way a lesson does, but only to a project
|
||||
# on one of the idea's platforms: the canon ideas reaching
|
||||
@@ -1175,6 +1204,16 @@ async def semantic_search_notes(
|
||||
"index": int(chunk_index),
|
||||
"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
|
||||
# filter because a call that returns nothing is exactly when it matters.
|
||||
if report is not None:
|
||||
|
||||
@@ -708,6 +708,7 @@ async def build_autoinject_hint(
|
||||
user_id=user_id, query=q, project_id=project_id,
|
||||
seen=frozenset(already), named=frozenset(named_ids),
|
||||
kinds=await record_kinds.kinds_for(user_id, rp.AUTO_INJECT.door),
|
||||
reach=await record_kinds.reach_for(user_id),
|
||||
),
|
||||
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}
|
||||
| {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:
|
||||
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 "
|
||||
"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:])
|
||||
|
||||
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),
|
||||
seen=nid in already, stale=nid in stale, score=score,
|
||||
shared_by=f"{who}, treat as a suggestion" if who else "",
|
||||
under=passage,
|
||||
under=passage, origin=origins.get(nid, ""),
|
||||
)
|
||||
lines.extend(entry)
|
||||
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:
|
||||
"""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."""
|
||||
@@ -1520,6 +1559,7 @@ async def build_write_path_hint(
|
||||
seen=frozenset(excluded), in_menu=frozenset(seen),
|
||||
still_scored=frozenset(pulled),
|
||||
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(),
|
||||
)
|
||||
@@ -1529,6 +1569,7 @@ async def build_write_path_hint(
|
||||
int(note.id): float(score) for score, note in result.answered
|
||||
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:
|
||||
# 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
|
||||
@@ -1547,6 +1588,9 @@ async def build_write_path_hint(
|
||||
# have to work out whether they mean the same thing.
|
||||
if int(note.id) in excluded:
|
||||
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((
|
||||
marker,
|
||||
{
|
||||
|
||||
@@ -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
|
||||
confirmed for it (`lesson_situations`), and any record when the work names
|
||||
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
|
||||
|
||||
@@ -87,6 +103,11 @@ LABELS: dict[str, str] = {
|
||||
}
|
||||
|
||||
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"
|
||||
WORK_CHANGE = "work.change"
|
||||
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)
|
||||
|
||||
|
||||
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:
|
||||
"""`{door: {kind: {"delivered", "opened"}}}` from the record ledger: the
|
||||
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."""
|
||||
stored = await _stored(user_id)
|
||||
evidence = await _evidence(user_id, days)
|
||||
reach = await reach_for(user_id)
|
||||
return {
|
||||
"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,
|
||||
"kinds": [{"kind": k, "label": LABELS[k]} for k in KINDS],
|
||||
"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)
|
||||
await set_setting(user_id, SETTING_KEY, json.dumps(stored))
|
||||
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)
|
||||
|
||||
@@ -1048,7 +1048,7 @@ def _menu_seen_line(note_id: int, kind: str, name: str) -> str:
|
||||
def menu_entry(
|
||||
note_id: int, *, kind: str, name: str, systems: list[str] | 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]:
|
||||
"""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 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.
|
||||
|
||||
`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:
|
||||
line = _menu_seen_line(note_id, kind, name)
|
||||
@@ -1073,6 +1077,8 @@ def menu_entry(
|
||||
line += f" ({score:.2f})"
|
||||
if stale:
|
||||
line += " — SUPERSEDED, a later record covers this; check that first"
|
||||
if origin:
|
||||
line += f" — from {origin}"
|
||||
if shared_by:
|
||||
line += f" — shared by {shared_by}"
|
||||
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
|
||||
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
|
||||
class NoteResult:
|
||||
@@ -1344,6 +1360,9 @@ async def _reserve_note_slot(
|
||||
"exclude_ids": set(on_menu),
|
||||
# KIND-FILTERED, so the slot can only be spent on what it is for.
|
||||
"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:
|
||||
kwargs["include_global_kinds"] = True
|
||||
@@ -1450,6 +1469,7 @@ async def run_note_arm(
|
||||
"project_id": moment.project_id or None,
|
||||
**note_search_filters(arm), "report": report,
|
||||
"record_kinds": record_kinds.search_kinds(allowed),
|
||||
"cross_kinds": moment.cross_kinds(),
|
||||
}
|
||||
if arm.withholds:
|
||||
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
|
||||
# made before a change is re-run against the current row.
|
||||
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 = {}
|
||||
hits = await semantic_search_notes(
|
||||
user_id, row.query or "",
|
||||
@@ -179,6 +184,7 @@ async def _rerun_notes(
|
||||
project_id=row.project_id or None,
|
||||
**rp.note_search_filters(rp.AUTO_INJECT),
|
||||
record_kinds=record_kinds.search_kinds(kinds),
|
||||
cross_kinds=reach,
|
||||
report=rep,
|
||||
)
|
||||
postdated = [int(n.id) for _s, n in hits if _after(n.created_at, row.created_at)]
|
||||
|
||||
+7
-4
@@ -371,9 +371,10 @@ def _default_record_kinds(request):
|
||||
"""Stub the settings read behind the kind×moment table.
|
||||
|
||||
Both record searches read the user's kinds per door
|
||||
(`record_kinds.kinds_for`); stubbed to the shipped default so a unit test
|
||||
of a door needs no database. The integration lane, where the table's own
|
||||
tests live, reads the real setting.
|
||||
(`record_kinds.kinds_for`) and the kinds they take from other projects
|
||||
(`record_kinds.reach_for`); both stubbed to the shipped default so a unit
|
||||
test of a door needs no database. The integration lane, where the table's
|
||||
own tests live, reads the real setting.
|
||||
"""
|
||||
if request.node.get_closest_marker("integration"):
|
||||
yield
|
||||
@@ -383,7 +384,9 @@ def _default_record_kinds(request):
|
||||
async def _default(_user_id, door):
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -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"])
|
||||
@@ -20,7 +20,8 @@ async def _user(name: str = "record_kinds_owner") -> int:
|
||||
async with async_session() as s:
|
||||
uid = (await ensure_user(s, name)).id
|
||||
await s.execute(delete(Setting).where(
|
||||
Setting.user_id == uid, Setting.key == record_kinds.SETTING_KEY))
|
||||
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.commit()
|
||||
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["message"] == {"task:issue": {"delivered": 1, "opened": 0}}
|
||||
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) == []
|
||||
|
||||
@@ -296,6 +296,35 @@ async def test_an_arm_searches_only_the_kinds_its_door_allows():
|
||||
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
|
||||
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())
|
||||
|
||||
@@ -51,7 +51,9 @@ async def test_an_empty_verdict_list_is_refused():
|
||||
# ── 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
|
||||
@@ -87,7 +89,7 @@ async def test_the_re_run_searches_the_way_the_arm_does():
|
||||
await review._rerun(1, row, 3)
|
||||
|
||||
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}"
|
||||
)
|
||||
assert {k: rerun_kw[k] for k in _FILTERS if k in rerun_kw} == arm
|
||||
|
||||
Reference in New Issue
Block a user