Skip to content

Commit 7f27b41

Browse files
cdeustclaude
andcommitted
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
1 parent bba138a commit 7f27b41

12 files changed

Lines changed: 756 additions & 64 deletions

‎CHANGELOG.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,20 @@ adheres to [Semantic Versioning](https://semver.org/).
5353

5454
### Fixed
5555

56+
- **Session-start and per-prompt injection stay inside the session's project
57+
(#604).** `auto_recall` and `session_start` queried memories with no
58+
project predicate, so a session under one project received the hot and
59+
protected memories of every other project the store held. Both hooks now
60+
apply one rule, shared across the PostgreSQL and SQLite paths
61+
(`mcp_server/shared/project_scope.py`, ADR-1080): a memory is injected
62+
when it is global, or its `directory_context` is the session's project
63+
root or an ancestor of it. An empty `directory_context` is not a
64+
wildcard. The project root comes from `CLAUDE_PROJECT_ROOT` or the hook
65+
event's `cwd`; when neither is available the hook logs that it could not
66+
resolve one and injects globals only, never everything. Team decisions
67+
stay global by design and are unaffected. The `recall` tool's own
68+
behaviour is unchanged.
69+
5670
- **Claude and direct MCP startup honour the same saved backend (#600).** A
5771
saved SQLite selection was honoured by the Claude launcher while direct
5872
console/module startup could select a reachable PostgreSQL server, sending
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
## Decision
29+
30+
A memory is injected into a session only when it is global, or its
31+
`directory_context` equals the session's project root, or its
32+
`directory_context` is an ancestor of the session's project root. An
33+
empty `directory_context` is not a wildcard for every project. Team
34+
decisions stay global by design and are unaffected.
35+
36+
The session's project root comes from the `CLAUDE_PROJECT_ROOT`
37+
environment override when set, otherwise from the hook event's `cwd`
38+
field. When neither is available the hook logs that it could not resolve
39+
a project root and restricts injection to global memories, never
40+
everything.
41+
42+
The rule is one pure function, `memory_matches_project` in
43+
`mcp_server/shared/project_scope.py`, with a companion
44+
`resolve_project_root` and `project_ancestors`. Both hooks and both
45+
storage backends call it: the PostgreSQL queries fetch `directory_context`
46+
and `is_global` alongside their existing columns and filter the returned
47+
rows in Python; the SQLite store rows already carry both columns, so the
48+
same filter applies directly. No SQL predicate is duplicated across the
49+
four call sites, and no store schema or generic store method changed.
50+
51+
## Consequences
52+
53+
Positive: a session under one project no longer sees another project's
54+
hot or protected memories. The failure mode when a project root cannot be
55+
resolved degrades to global-only injection instead of silent leakage.
56+
57+
Negative: memories written before this fix with an empty
58+
`directory_context` and no `is_global` flag stop being injected by these
59+
two hooks until re-scoped or promoted to global; they remain reachable
60+
through the `recall` tool, which this change does not touch.

‎mcp_server/hooks/auto_recall.py‎

Lines changed: 35 additions & 6 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 memory_matches_project, resolve_project_root
5354

5455
_LOG_PREFIX = "[cortex-auto-recall]"
5556
_DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://localhost:5432/cortex")
@@ -119,15 +120,18 @@ 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. Rows outside
132+
``project_root`` (and not global) are dropped after the fetch, the
133+
same ``memory_matches_project`` rule the SQLite path and session_start
134+
apply (issue #604).
131135
"""
132136
results = []
133137

@@ -141,6 +145,7 @@ def _recall_memories(conn, query: str) -> list[dict]:
141145
effective_heat(m, NOW()) AS heat,
142146
m.domain, m.agent_context, m.is_protected,
143147
m.created_at, m.source_attribution, m.is_stale,
148+
m.directory_context, m.is_global,
144149
ts_rank_cd(m.content_tsv, q) AS rank
145150
FROM memories m
146151
JOIN current_memories cm ON cm.id = m.id,
@@ -157,6 +162,10 @@ def _recall_memories(conn, query: str) -> list[dict]:
157162
).fetchall()
158163

159164
for r in rows:
165+
if not memory_matches_project(
166+
r.get("directory_context"), bool(r.get("is_global")), project_root
167+
):
168+
continue
160169
results.append(
161170
{
162171
"id": r["id"],
@@ -204,11 +213,14 @@ def _fts_query_from_prompt(query: str) -> str:
204213
return " OR ".join(f'"{t}"' for t in terms)
205214

206215

207-
def _recall_memories_sqlite(store, query: str) -> list[dict]:
216+
def _recall_memories_sqlite(
217+
store, query: str, project_root: str | None = None
218+
) -> list[dict]:
208219
"""FTS-based recall through the SQLite store — no embedding load.
209220
210221
Mirror of the PG ``_recall_memories`` contract: FTS prefilter +
211-
heat floor, protected-first ordering, benchmark rows excluded.
222+
heat floor, protected-first ordering, benchmark rows excluded, and
223+
the same ``memory_matches_project`` scoping (issue #604).
212224
``search_fts`` already restricts to supersession chain heads and
213225
non-stale rows (current_memories join) and returns [] on any FTS5
214226
error.
@@ -221,6 +233,10 @@ def _recall_memories_sqlite(store, query: str) -> list[dict]:
221233
m = store.get_memory(memory_id)
222234
if not m or m.get("is_benchmark"):
223235
continue
236+
if not memory_matches_project(
237+
m.get("directory_context"), bool(m.get("is_global")), project_root
238+
):
239+
continue
224240
heat = float(m.get("heat") or 0.0)
225241
if heat < _MIN_HEAT:
226242
continue
@@ -244,11 +260,17 @@ def _recall_memories_sqlite(store, query: str) -> list[dict]:
244260

245261
def _process_event_sqlite(event: dict[str, Any], query: str) -> None:
246262
"""Inject relevant memories from the SQLite store; exit 0 always."""
263+
project_root = resolve_project_root(event, os.environ)
264+
if project_root is None:
265+
_log(
266+
"project root unresolved (no CLAUDE_PROJECT_ROOT, no event cwd), "
267+
"restricting to global memories"
268+
)
247269
try:
248270
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)
249271

250272
store = get_shared_store()
251-
memories = _recall_memories_sqlite(store, query)
273+
memories = _recall_memories_sqlite(store, query, project_root)
252274
except Exception as exc: # noqa: BLE001 — hook boundary — failure is logged to the hook log; the hook stays non-fatal
253275
_log(f"sqlite recall failed (non-fatal): {exc}")
254276
sys.exit(0)
@@ -358,8 +380,15 @@ def process_event(event: dict[str, Any]) -> None:
358380
if conn is None:
359381
sys.exit(0)
360382

383+
project_root = resolve_project_root(event, os.environ)
384+
if project_root is None:
385+
_log(
386+
"project root unresolved (no CLAUDE_PROJECT_ROOT, no event cwd), "
387+
"restricting to global memories"
388+
)
389+
361390
try:
362-
memories = _recall_memories(conn, query)
391+
memories = _recall_memories(conn, query, project_root)
363392
if not memories:
364393
sys.exit(0)
365394

‎mcp_server/hooks/session_start.py‎

Lines changed: 62 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
from mcp_server.shared.freshness import provenance_suffix
3333
from mcp_server.shared.platform import python_executable
3434
from mcp_server.shared.log_rotation import methodology_log_path, open_rotating_log
35+
from mcp_server.shared.project_scope import memory_matches_project, resolve_project_root
3536
import sqlite3
3637
import asyncio
3738
from datetime import datetime as _dt, timezone as _tz
@@ -142,14 +143,16 @@ def _connect_pg():
142143
# ── Memory fetching ──────────────────────────────────────────────────────
143144

144145

145-
def _fetch_anchors(conn) -> list[dict]:
146-
"""Fetch anchored memories (is_protected with _anchor tag).
146+
def _fetch_anchors(conn, project_root: str | None = None) -> list[dict]:
147+
"""Fetch anchored memories (is_protected with _anchor tag) scoped to
148+
project_root or global (issue #604).
147149
148150
source: ADR-0498"""
149151
try:
150152
rows = conn.execute(
151153
# source: ADR-0498
152154
"SELECT m.id, m.content, m.tags, m.domain, m.is_global, "
155+
"m.directory_context, "
153156
"m.created_at, m.source_attribution, m.is_stale "
154157
# source: ADR-0498
155158
"FROM memories m JOIN current_memories cm ON cm.id = m.id "
@@ -169,6 +172,10 @@ def _fetch_anchors(conn) -> list[dict]:
169172

170173
anchors = []
171174
for r in rows:
175+
if not memory_matches_project(
176+
r.get("directory_context"), bool(r.get("is_global")), project_root
177+
):
178+
continue
172179
tags = r.get("tags") or []
173180
if isinstance(tags, str):
174181
try:
@@ -239,8 +246,11 @@ def _fetch_team_decisions(conn, exclude_ids: set) -> list[dict]:
239246
return decisions[:3] # Keep injection compact
240247

241248

242-
def _fetch_hot_memories(conn, exclude_ids: set) -> list[dict]:
243-
"""Fetch high-heat memories, excluding anchors.
249+
def _fetch_hot_memories(
250+
conn, exclude_ids: set, project_root: str | None = None
251+
) -> list[dict]:
252+
"""Fetch high-heat memories, excluding anchors, scoped to project_root
253+
or global (issue #604).
244254
245255
Tier exclusion: auto-captured tool noise and block-replica snapshots
246256
must not appear in the session-start banner — they poison the injected
@@ -250,6 +260,7 @@ def _fetch_hot_memories(conn, exclude_ids: set) -> list[dict]:
250260
try:
251261
rows = conn.execute(
252262
"SELECT id, content, domain, heat_base AS heat, tags, is_global, "
263+
"directory_context, "
253264
"created_at, source_attribution, is_stale "
254265
# current_memories: hot-pool content injected into the session
255266
# banner — supersession chain heads only.
@@ -271,19 +282,24 @@ def _fetch_hot_memories(conn, exclude_ids: set) -> list[dict]:
271282

272283
hot = []
273284
for r in rows:
274-
if r["id"] not in exclude_ids:
275-
hot.append(
276-
{
277-
"id": r["id"],
278-
"content": r.get("content", ""),
279-
"domain": r.get("domain", ""),
280-
"heat": r.get("heat", 0.0),
281-
"is_global": bool(r.get("is_global", False)),
282-
"created_at": r.get("created_at"),
283-
"source_attribution": r.get("source_attribution", ""),
284-
"is_stale": bool(r.get("is_stale")),
285-
}
286-
)
285+
if r["id"] in exclude_ids:
286+
continue
287+
if not memory_matches_project(
288+
r.get("directory_context"), bool(r.get("is_global")), project_root
289+
):
290+
continue
291+
hot.append(
292+
{
293+
"id": r["id"],
294+
"content": r.get("content", ""),
295+
"domain": r.get("domain", ""),
296+
"heat": r.get("heat", 0.0),
297+
"is_global": bool(r.get("is_global", False)),
298+
"created_at": r.get("created_at"),
299+
"source_attribution": r.get("source_attribution", ""),
300+
"is_stale": bool(r.get("is_stale")),
301+
}
302+
)
287303
return hot[:_HOT_LIMIT]
288304

289305

@@ -1030,12 +1046,15 @@ def _backend_is_sqlite() -> bool:
10301046
return False
10311047

10321048

1033-
def _partition_banner_rows(rows: list[dict]) -> tuple[list[dict], list[dict]]:
1049+
def _partition_banner_rows(
1050+
rows: list[dict], project_root: str | None = None
1051+
) -> tuple[list[dict], list[dict]]:
10341052
"""Split hot rows into (anchors, hot) with the PG path's exclusions.
10351053
10361054
Mirrors _fetch_anchors/_fetch_hot_memories: tier-1 noise tags are
1037-
dropped, protected ``_anchor``-tagged rows become anchors, the rest
1038-
are hot-pool entries. Supersession exclusion already happened
1055+
dropped, rows outside project_root (and not global) are dropped
1056+
(issue #604), protected ``_anchor``-tagged rows become anchors, the
1057+
rest are hot-pool entries. Supersession exclusion already happened
10391058
upstream (``get_hot_memories(heads_only=True)`` routes through the
10401059
``current_memories`` view).
10411060
"""
@@ -1045,6 +1064,10 @@ def _partition_banner_rows(rows: list[dict]) -> tuple[list[dict], list[dict]]:
10451064
tags = [t for t in (r.get("tags") or []) if isinstance(t, str)]
10461065
if _SQLITE_NOISE_TAGS & set(tags):
10471066
continue
1067+
if not memory_matches_project(
1068+
r.get("directory_context"), bool(r.get("is_global")), project_root
1069+
):
1070+
continue
10481071
entry = {
10491072
"id": r["id"],
10501073
"content": r.get("content", ""),
@@ -1062,7 +1085,9 @@ def _partition_banner_rows(rows: list[dict]) -> tuple[list[dict], list[dict]]:
10621085
return anchors[:_ANCHOR_LIMIT], hot[:_HOT_LIMIT]
10631086

10641087

1065-
def _sqlite_banner_rows(store) -> tuple[list[dict], list[dict], dict | None]:
1088+
def _sqlite_banner_rows(
1089+
store, project_root: str | None = None
1090+
) -> tuple[list[dict], list[dict], dict | None]:
10661091
"""Fetch (anchors, hot, checkpoint) from the SQLite store, tolerantly."""
10671092
try:
10681093
rows = store.get_hot_memories(
@@ -1071,7 +1096,7 @@ def _sqlite_banner_rows(store) -> tuple[list[dict], list[dict], dict | None]:
10711096
except Exception as exc: # noqa: BLE001 — hook boundary — failure is logged to the hook log; the hook stays non-fatal
10721097
_log(f"SQLite hot-memory fetch failed (non-fatal): {exc}")
10731098
rows = []
1074-
anchors, hot = _partition_banner_rows(rows)
1099+
anchors, hot = _partition_banner_rows(rows, project_root)
10751100
try:
10761101
checkpoint = _checkpoint_from_row(store.get_active_checkpoint())
10771102
except Exception as exc: # noqa: BLE001 — hook boundary; failure is logged to the hook log, the banner degrades
@@ -1082,6 +1107,12 @@ def _sqlite_banner_rows(store) -> tuple[list[dict], list[dict], dict | None]:
10821107

10831108
def _sqlite_context(event: dict) -> None:
10841109
"""Build and print the SessionStart banner on the SQLite backend."""
1110+
project_root = resolve_project_root(event, os.environ)
1111+
if project_root is None:
1112+
_log(
1113+
"project root unresolved (no CLAUDE_PROJECT_ROOT, no event cwd), "
1114+
"restricting to global memories"
1115+
)
10851116
try:
10861117
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)
10871118

@@ -1101,7 +1132,7 @@ def _sqlite_context(event: dict) -> None:
11011132
print(msg)
11021133
return
11031134

1104-
anchors, hot, checkpoint = _sqlite_banner_rows(store)
1135+
anchors, hot, checkpoint = _sqlite_banner_rows(store, project_root)
11051136
receipt_id = None
11061137
payload = [{"memory_id": m["id"]} for m in (*anchors, *hot)]
11071138
if payload:
@@ -1195,9 +1226,15 @@ def main() -> None:
11951226
return
11961227

11971228
# Normal flow — fetch and inject context
1198-
anchors = _fetch_anchors(conn)
1229+
project_root = resolve_project_root(event, os.environ)
1230+
if project_root is None:
1231+
_log(
1232+
"project root unresolved (no CLAUDE_PROJECT_ROOT, no event cwd), "
1233+
"restricting to global memories"
1234+
)
1235+
anchors = _fetch_anchors(conn, project_root)
11991236
anchor_ids = {a["id"] for a in anchors}
1200-
hot = _fetch_hot_memories(conn, anchor_ids)
1237+
hot = _fetch_hot_memories(conn, anchor_ids, project_root)
12011238
team_decisions = _fetch_team_decisions(conn, anchor_ids)
12021239
checkpoint = _fetch_checkpoint(conn)
12031240
pending_curations = _count_pending_curations(conn)

0 commit comments

Comments
 (0)