Skip to content

Commit 4bd7e7f

Browse files
cdeustclaude
andauthored
Inject only the session's project and global memories (#604) (#606)
* fix(hooks): inject only the session's project and global memories (#604) session_start and auto_recall queried memories with no project predicate, so a session under one project received the hot and protected memories of every project the store held. The PostgreSQL recall function already scoped by directory_context; the two hooks bypassed that column entirely. Both hooks now apply one rule, shared across the PostgreSQL and SQLite paths (mcp_server/shared/project_scope.py, ADR-1080): a memory injects when it is global, or its directory_context is the session's project root or an ancestor of it. An empty directory_context is not a wildcard. The project root comes from CLAUDE_PROJECT_ROOT or the hook event's cwd; when neither resolves, the hook logs it and restricts injection to global memories, never everything. Team decisions stay global by design and are unaffected. The recall tool is untouched. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Cz7A6goxVzfKL9NT7k4zDH * fix(hooks): push project predicate into the query, before LIMIT (#604) Review of 7f27b41 found the predicate ran in Python after the SQL LIMIT: a store with more out-of-project rows above the heat floor than the LIMIT allowed let those foreign rows consume the candidate window, starving the project's own rows out of the banner entirely. That is the reporter's own situation (#604), and the acceptance criteria only held in a three-row fixture. The predicate now runs inside the query, before ORDER BY/LIMIT, on both backends. mcp_server/shared/project_scope.py's project_ancestors feeds a new directory_ancestors parameter on get_hot_memories and search_fts (both stores, default None, every other caller unaffected), built into SQL via the new pg_scope_clause.py / sqlite_scope_clause.py. The two hooks' own raw SQL (auto_recall._recall_memories, session_start._fetch_anchors/_fetch_hot_memories) carry the same predicate directly. project_ancestors had its own bug, caught by the new starvation tests running against real SQL: it included an empty-string "ancestor" for any leading-slash root, which the old Python-side memory_matches_project never surfaced (a separate empty-directory_context guard ran first) but which a query built straight from the list would have matched against every empty-directory_context row. tests_py/integration/test_cold_start.py seeded a memory with an empty directory_context and no is_global, expecting injection under the old behaviour; updated to the new rule and the CHANGELOG/ADR now name the migration consequence for stores with such rows. test_sqlite_hook_paths.py and test_auto_recall.py split their scoping coverage into test_sqlite_hook_scope.py / test_auto_recall_scope.py to clear the craftsmanship file-size cap after the added regression tests. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01Cz7A6goxVzfKL9NT7k4zDH --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
1 parent 84c0a3b commit 4bd7e7f

21 files changed

Lines changed: 1244 additions & 100 deletions

‎CHANGELOG.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,27 @@ adheres to [Semantic Versioning](https://semver.org/).
6666

6767
### Fixed
6868

69+
- **Session-start and per-prompt injection stay inside the session's project
70+
(#604).** `auto_recall` and `session_start` queried memories with no
71+
project predicate, so a session under one project received the hot and
72+
protected memories of every other project the store held. Both hooks now
73+
apply one rule, shared across the PostgreSQL and SQLite paths
74+
(`mcp_server/shared/project_scope.py`, ADR-1080): a memory is injected
75+
when it is global, or its `directory_context` is the session's project
76+
root or an ancestor of it. An empty `directory_context` is not a
77+
wildcard. The project root comes from `CLAUDE_PROJECT_ROOT` or the hook
78+
event's `cwd`; when neither is available the hook logs that it could not
79+
resolve one and injects globals only, never everything. The predicate
80+
runs inside the query, before the existing heat-ordered `LIMIT`, on both
81+
backends: applied after the fetch instead, foreign-project rows above
82+
the heat floor would consume the limited candidate window and starve a
83+
project's own rows out of it. Team decisions stay global by design and
84+
are unaffected. The `recall` tool's own behaviour is unchanged.
85+
Migration consequence: a memory written before this fix with an empty
86+
`directory_context` and `is_global = FALSE` stops being injected by
87+
these two hooks on both backends; it stays reachable through the
88+
`recall` tool and can be re-scoped or promoted to global.
89+
6990
- **Claude and direct MCP startup honour the same saved backend (#600).** A
7091
saved SQLite selection was honoured by the Claude launcher while direct
7192
console/module startup could select a reachable PostgreSQL server, sending
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<!-- Generated by Cortex wiki_reindex from wiki/adr/cortex/1080-inject-only-the-sessions-project-and-global-memories-in-session-hooks.md; ADR-1080. Read-only mirror: edit the canonical wiki page. -->
2+
3+
---
4+
created: 2026-09-17T09:22:42Z
5+
kind: adr
6+
number: 1080
7+
status: accepted
8+
tags: [hooks, memory-scoping, session-start, auto-recall]
9+
title: Inject only the session's project and global memories in session hooks
10+
---
11+
# ADR-1080: Inject only the session's project and global memories in session hooks
12+
13+
## Status
14+
15+
accepted
16+
17+
## Context
18+
19+
`auto_recall` (per-prompt injection) and `session_start` (session banner)
20+
queried memories with no project predicate on either storage backend. A
21+
session started under one project received the hot and protected memories
22+
of every project the store held, observed directly (#604) and confirmed by
23+
an outside review of Cortex. The store already carries a
24+
`directory_context` column on every memory and the PostgreSQL `recall`
25+
function already scopes by it; the two hooks bypassed that column
26+
entirely.
27+
28+
A first version of this fix applied the predicate after the fetch, in
29+
Python, over rows a heat-ordered `LIMIT` had already truncated. Review
30+
against a store with more out-of-project rows above the heat floor than
31+
the `LIMIT` allowed showed the fix's own failure mode: the foreign rows
32+
consumed the candidate window and the project's own row never reached the
33+
banner. That version is documented here only as the reason the predicate
34+
belongs in the query, not as the shipped design.
35+
36+
## Decision
37+
38+
A memory is injected into a session only when it is global, or its
39+
`directory_context` equals the session's project root, or its
40+
`directory_context` is an ancestor of the session's project root. An
41+
empty `directory_context` is not a wildcard for every project. Team
42+
decisions stay global by design and are unaffected.
43+
44+
The session's project root comes from the `CLAUDE_PROJECT_ROOT`
45+
environment override when set, otherwise from the hook event's `cwd`
46+
field. When neither is available the hook logs that it could not resolve
47+
a project root and restricts injection to global memories, never
48+
everything.
49+
50+
The predicate runs inside the query, before `ORDER BY`/`LIMIT`, on both
51+
backends. `mcp_server/shared/project_scope.py` computes
52+
`project_ancestors(project_root)`, a pure ordered list from the project
53+
root up (empty when the root is unresolved); every query call site turns
54+
that list into `(is_global OR directory_context IN/ANY(...))` before its
55+
own limit, so the limit is spent only on candidates the caller can use.
56+
PostgreSQL's own `is_protected DESC, rank DESC` / `heat_base DESC`
57+
ordering after the predicate is unchanged. `mcp_server/infrastructure/
58+
pg_scope_clause.py` and `sqlite_scope_clause.py` build that fragment and
59+
its bind params once per backend, used by `get_hot_memories` and
60+
`search_fts` (both stores, an added `directory_ancestors` parameter
61+
defaulting to `None` for every other existing caller) and by the hooks'
62+
own raw SQL (`session_start._fetch_anchors`, `_fetch_hot_memories`,
63+
`auto_recall._recall_memories`). The PostgreSQL hook queries keep a
64+
post-fetch `memory_matches_project` check as a second, redundant layer;
65+
the SQLite path and `auto_recall._recall_memories` on PostgreSQL rely on
66+
the query predicate alone.
67+
68+
Two quirks, observed in review, neither blocking: a `directory_context`
69+
of `"/"` normalizes to `""` in `project_ancestors`/the comparison and
70+
therefore matches nothing, not everything (`_normalize_path` strips the
71+
trailing separator and an all-separator path degrades to the empty
72+
string, which `project_ancestors` explicitly excludes so it can never
73+
appear as a match target). The comparison is case-sensitive: a
74+
`directory_context` recorded as `/Users/X` does not match a session
75+
whose root resolves to `/users/x`.
76+
77+
## Consequences
78+
79+
Positive: a session under one project no longer sees another project's
80+
hot or protected memories, including when the store holds more
81+
out-of-project rows above the heat floor than a hook's own `LIMIT`
82+
allows. The failure mode when a project root cannot be resolved degrades
83+
to global-only injection instead of silent leakage.
84+
85+
Negative: memories written before this fix with an empty
86+
`directory_context` and no `is_global` flag stop being injected by both
87+
hooks, on both backends, until re-scoped or promoted to global; they
88+
remain reachable through the `recall` tool, which this change does not
89+
touch. `get_hot_memories` and `search_fts` gained an optional parameter
90+
on both backends; every other caller passes nothing and is unaffected.

‎mcp_server/hooks/auto_recall.py‎

Lines changed: 55 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
)
5151
from mcp_server.hooks._telemetry import observe_hook
5252
from mcp_server.shared.freshness import provenance_suffix
53+
from mcp_server.shared.project_scope import project_ancestors, resolve_project_root
5354

5455
_LOG_PREFIX = "[cortex-auto-recall]"
5556
_DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://localhost:5432/cortex")
@@ -119,17 +120,21 @@ def _connect():
119120
return None
120121

121122

122-
def _recall_memories(conn, query: str) -> list[dict]:
123+
def _recall_memories(conn, query: str, project_root: str | None = None) -> list[dict]:
123124
"""Fast FTS-based recall against PG. No embedding model needed.
124125
125126
Uses plainto_tsquery for natural language matching against the
126127
content_tsv tsvector column. Combined with heat filter to surface
127128
important memories.
128129
129130
Each result keeps the memory ``id`` — the injection receipt (T2)
130-
records exactly which memories entered the context.
131+
records exactly which memories entered the context. The project
132+
predicate runs inside the query, before ORDER BY/LIMIT: pushed to the
133+
output it would let foreign-project rows outrank and starve the
134+
project's own rows out of the LIMIT window (issue #604 follow-up).
131135
"""
132136
results = []
137+
ancestors = project_ancestors(project_root)
133138

134139
# source: ADR-0485
135140
try:
@@ -149,11 +154,12 @@ def _recall_memories(conn, query: str) -> list[dict]:
149154
AND effective_heat(m, NOW()) >= %s
150155
AND NOT m.is_benchmark
151156
AND m.superseded_by_id IS NULL
157+
AND (m.is_global = TRUE OR m.directory_context = ANY(%s::TEXT[]))
152158
ORDER BY m.is_protected DESC, rank DESC, effective_heat(m, NOW()) DESC
153159
LIMIT %s
154160
"""
155161
),
156-
(query[:200], _MIN_HEAT, _MAX_MEMORIES + 2),
162+
(query[:200], _MIN_HEAT, ancestors, _MAX_MEMORIES + 2),
157163
).fetchall()
158164

159165
for r in rows:
@@ -204,51 +210,69 @@ def _fts_query_from_prompt(query: str) -> str:
204210
return " OR ".join(f'"{t}"' for t in terms)
205211

206212

207-
def _recall_memories_sqlite(store, query: str) -> list[dict]:
213+
def _sqlite_result_entry(memory_id: int, m: dict, heat: float) -> dict:
214+
"""One ``_recall_memories_sqlite`` result row, in the PG-path shape."""
215+
return {
216+
"id": memory_id,
217+
"content": m.get("content", ""),
218+
"heat": heat,
219+
"domain": m.get("domain", "") or "",
220+
"agent": m.get("agent_context", "") or "",
221+
"protected": bool(m.get("is_protected")),
222+
"created_at": m.get("created_at"),
223+
"source_attribution": m.get("source_attribution", ""),
224+
"is_stale": bool(m.get("is_stale")),
225+
}
226+
227+
228+
def _recall_memories_sqlite(
229+
store, query: str, project_root: str | None = None
230+
) -> list[dict]:
208231
"""FTS-based recall through the SQLite store — no embedding load.
209232
210233
Mirror of the PG ``_recall_memories`` contract: FTS prefilter +
211-
heat floor, protected-first ordering, benchmark rows excluded.
212-
``search_fts`` already restricts to supersession chain heads and
213-
non-stale rows (current_memories join) and returns [] on any FTS5
214-
error.
234+
heat floor, protected-first ordering, benchmark rows excluded. The
235+
project predicate runs inside ``search_fts`` itself, before its own
236+
LIMIT (issue #604 follow-up) -- a post-fetch filter here would let
237+
foreign-project rows starve the project's own rows out of the
238+
already-truncated pool. ``search_fts`` already restricts to
239+
supersession chain heads and non-stale rows (current_memories join)
240+
and returns [] on any FTS5 error.
215241
"""
216242
fts_query = _fts_query_from_prompt(query[:200])
217243
if not fts_query:
218244
return []
245+
ancestors = project_ancestors(project_root)
246+
hits = store.search_fts(
247+
fts_query, limit=_MAX_MEMORIES + 2, directory_ancestors=ancestors
248+
)
219249
results = []
220-
for memory_id, _score in store.search_fts(fts_query, limit=_MAX_MEMORIES + 2):
250+
for memory_id, _score in hits:
221251
m = store.get_memory(memory_id)
222252
if not m or m.get("is_benchmark"):
223253
continue
224254
heat = float(m.get("heat") or 0.0)
225255
if heat < _MIN_HEAT:
226256
continue
227-
results.append(
228-
{
229-
"id": memory_id,
230-
"content": m.get("content", ""),
231-
"heat": heat,
232-
"domain": m.get("domain", "") or "",
233-
"agent": m.get("agent_context", "") or "",
234-
"protected": bool(m.get("is_protected")),
235-
"created_at": m.get("created_at"),
236-
"source_attribution": m.get("source_attribution", ""),
237-
"is_stale": bool(m.get("is_stale")),
238-
}
239-
)
257+
results.append(_sqlite_result_entry(memory_id, m, heat))
240258
# source: ADR-0485
241259
results.sort(key=lambda m: not m["protected"])
242260
return results[:_MAX_MEMORIES]
243261

244262

245263
def _process_event_sqlite(event: dict[str, Any], query: str) -> None:
246264
"""Inject relevant memories from the SQLite store; exit 0 always."""
265+
project_root = resolve_project_root(event, os.environ)
266+
if project_root is None:
267+
_log(
268+
"project root unresolved (no CLAUDE_PROJECT_ROOT, no event cwd), "
269+
"restricting to global memories"
270+
)
247271
try:
248272
from mcp_server.infrastructure.memory_store import get_shared_store # noqa: PLC0415 — hook latency boundary: the per-event hook process defers the handler/store stack (hook boot ~0.05 s vs ~0.6 s registry import, measured 2026-07-28)
249273

250274
store = get_shared_store()
251-
memories = _recall_memories_sqlite(store, query)
275+
memories = _recall_memories_sqlite(store, query, project_root)
252276
except Exception as exc: # noqa: BLE001 — hook boundary — failure is logged to the hook log; the hook stays non-fatal
253277
_log(f"sqlite recall failed (non-fatal): {exc}")
254278
sys.exit(0)
@@ -358,8 +382,15 @@ def process_event(event: dict[str, Any]) -> None:
358382
if conn is None:
359383
sys.exit(0)
360384

385+
project_root = resolve_project_root(event, os.environ)
386+
if project_root is None:
387+
_log(
388+
"project root unresolved (no CLAUDE_PROJECT_ROOT, no event cwd), "
389+
"restricting to global memories"
390+
)
391+
361392
try:
362-
memories = _recall_memories(conn, query)
393+
memories = _recall_memories(conn, query, project_root)
363394
if not memories:
364395
sys.exit(0)
365396

0 commit comments

Comments
 (0)