Files
FabledGrimoire/tests/test_integration_cross_project.py
T
bvandeusenandClaude Opus 5.5 30aa5cf1c6
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
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 <noreply@anthropic.com>
2026-11-28 17:20:31 -05:00

148 lines
6.6 KiB
Python

"""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"])