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

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:
2026-11-28 17:20:31 -05:00
co-authored by Claude Opus 5.5
parent 163d32859f
commit 30aa5cf1c6
14 changed files with 491 additions and 13 deletions
+5 -2
View File
@@ -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()
+20
View File
@@ -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():
+40 -1
View File
@@ -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:
+45 -1
View File
@@ -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,
{
+59
View File
@@ -56,6 +56,22 @@ the file it is recorded at, an issue through the file or area it names and
when a task in its area is taken up, a lesson through the situation
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)
+21 -1
View File
@@ -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)]