feat(8191): knowledge reaches a session from every project, ranked below its own and labelled
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 2m0s
CI & Build / Build & push image (push) Canceled after 0s
CI & Build / integration (push) Canceled after 2m7s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 2m0s
CI & Build / Build & push image (push) Canceled after 0s
CI & Build / integration (push) Canceled after 2m7s
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 <noreply@anthropic.com>
This commit is contained in:
+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