Skip to content

Commit ea892c5

Browse files
authored
Merge pull request DeusData#2817 from DeusData/feat/drift-reminder-hook
feat(cli): note when a Claude Code session keeps searching without the graph
2 parents 820cd02 + 8fd93a2 commit ea892c5

5 files changed

Lines changed: 407 additions & 17 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ overwrite user-modified agents.
694694

695695
| Agent | Activation | MCP config | Durable context / augmentation |
696696
|-------|------------|------------|--------------------------------|
697-
| Claude Code | Detected | `~/.claude.json` | Skill + three exact-tool graph agents; `SessionStart`, `SubagentStart`, non-blocking `PreToolUse` for `Grep`/`Glob`/`Bash`, and post-`Read` coverage |
697+
| Claude Code | Detected | `~/.claude.json` | Skill + three exact-tool graph agents; `SessionStart`, `SubagentStart`, non-blocking `PreToolUse` for `Grep`/`Glob`/`Bash`, post-`Read` coverage, and a drift note after repeated searches without a graph call |
698698
| Codex CLI | Detected | `$CODEX_HOME/config.toml` | Managed `AGENTS.md` activation pointer, skill, three read-only agents; `SessionStart` + `SubagentStart`, `PreToolUse` graph lookup for `Bash` searches |
699699
| Gemini CLI | Detected | `.gemini/settings.json` | `GEMINI.md`, three explicit read/graph-tool subagents; `BeforeTool`, `AfterTool` `read_file` coverage, and `SessionStart` |
700700
| Zed | Detected | platform `settings.json` (JSONC) | `AGENTS.md` + shared skill |
@@ -755,7 +755,10 @@ the requested tool call. Codex CLI's `PreToolUse` on `Bash` gives its shell
755755
searches the same context. GitHub Copilot CLI and VS Code's Copilot runtime get
756756
it after the search: their `preToolUse` can only decide permissions, so a
757757
`PostToolUse` entry for `Bash`, `Grep` and `Glob` appends the graph symbols to
758-
the tool result.
758+
the tool result. In Claude Code, once a session has run three searches with no
759+
codebase-memory-mcp tool call, the next augmentation adds one line saying so;
760+
the next note comes after six searches, then twelve. Claude's `PostToolUse`
761+
entry also matches the graph tools, and a graph tool call resets the count.
759762

760763
Claude Code, Codex CLI, Qwen Code, GitHub Copilot CLI, and VS Code's Copilot
761764
runtime receive paired session/subagent context where the vendor exposes a

‎scripts/smoke-test.sh‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1697,22 +1697,24 @@ echo "OK 8c-i: Claude exact-tool graph subagent"
16971697

16981698
# 8d: Claude Code hooks keep search augmentation and read-coverage reporting
16991699
# separate: PreToolUse matches exactly Grep|Glob|Bash, while PostToolUse matches
1700-
# exactly Read. Neither hook may grow a Search or catch-all matcher.
1700+
# exactly Read plus the graph tools, whose calls reset the drift note. Neither
1701+
# hook may grow a Search or catch-all matcher.
17011702
if ! cat "$FAKE_HOME/.claude/settings.json" 2>/dev/null | python3 -c "
17021703
import json, sys
17031704
d = json.load(sys.stdin)
17041705
all_hooks = d.get('hooks', {})
17051706
pre = all_hooks.get('PreToolUse', [])
17061707
post = all_hooks.get('PostToolUse', [])
17071708
ok = (any(h.get('matcher') == 'Grep|Glob|Bash' for h in pre) and
1708-
any(h.get('matcher') == 'Read' for h in post))
1709-
bad = any('Search' in str(h.get('matcher', '')) for h in pre + post)
1709+
any(h.get('matcher') == 'Read|mcp__.*codebase-memory-mcp__.*' for h in post))
1710+
bad = any('Search' in str(h.get('matcher', '')) or h.get('matcher', '') in ('', '*')
1711+
for h in pre + post)
17101712
sys.exit(0 if (ok and not bad) else 1)
17111713
" 2>/dev/null; then
17121714
echo "FAIL 8d: Claude search/read hook matchers are not exact"
17131715
exit 1
17141716
fi
1715-
echo "OK 8d: Claude Code PreToolUse Grep|Glob|Bash + PostToolUse Read"
1717+
echo "OK 8d: Claude Code PreToolUse Grep|Glob|Bash + PostToolUse Read and graph tools"
17161718

17171719
# 8e: Claude Code shim script — must be non-blocking augmenter, not a gate.
17181720
# #929: Windows installs a .cmd script (extensionless bash shims triggered the

‎src/cli/cli.c‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4661,7 +4661,10 @@ static int cbm_remove_grok_mcp_owned(const char *binary_path, const char *config
46614661
/* Search augmentation runs before Grep/Glob/Bash; exact coverage context runs after
46624662
* Read. Both adapters are context-only and fail open. */
46634663
#define CMM_HOOK_SEARCH_MATCHER "Grep|Glob|Bash"
4664-
#define CMM_HOOK_READ_MATCHER "Read"
4664+
/* The PostToolUse entry also matches the graph tools (mcp__<server>__<tool>,
4665+
* or mcp__plugin_<plugin>_<server>__<tool>), whose calls reset the drift
4666+
* reminder's search count (#509). */
4667+
#define CMM_HOOK_READ_MATCHER "Read|mcp__.*codebase-memory-mcp__.*"
46654668
/* Basename only; the full command path is resolved at install time via
46664669
* cbm_resolve_hook_command so $CLAUDE_CONFIG_DIR is honored. */
46674670
#ifdef _WIN32
@@ -4682,6 +4685,11 @@ static const char *const cmm_claude_exec_args[] = {"hook-augment"};
46824685
/* Old matcher values from previous versions — recognized during upgrade so
46834686
* upsert/remove can clean them up before inserting the current matcher.
46844687
* Per-agent lists (no shared global): each caller passes its own. */
4688+
/* Installs up to v0.12 matched only Read in PostToolUse. */
4689+
static const char *const cmm_claude_old_read_matchers[] = {
4690+
"Read",
4691+
NULL,
4692+
};
46854693
static const char *const cmm_claude_old_matchers[] = {
46864694
"Grep|Glob|Read|Search",
46874695
"Grep|Glob|Read",
@@ -5459,7 +5467,7 @@ static int cbm_upsert_claude_hooks_with_binary(const char *settings_path, const
54595467
if (cbm_remove_previous_claude_exec_hook(settings_path, "PreToolUse", CMM_HOOK_SEARCH_MATCHER,
54605468
cmm_claude_old_matchers, binary_path) != CLI_OK ||
54615469
cbm_remove_previous_claude_exec_hook(settings_path, "PostToolUse", CMM_HOOK_READ_MATCHER,
5462-
NULL, binary_path) != CLI_OK) {
5470+
cmm_claude_old_read_matchers, binary_path) != CLI_OK) {
54635471
return CLI_ERR;
54645472
}
54655473
int search_result = upsert_hooks_json((hooks_upsert_args_t){
@@ -5478,6 +5486,7 @@ static int cbm_upsert_claude_hooks_with_binary(const char *settings_path, const
54785486
.settings_path = settings_path,
54795487
.hook_event = "PostToolUse",
54805488
.matcher_str = CMM_HOOK_READ_MATCHER,
5489+
.old_matchers = cmm_claude_old_read_matchers,
54815490
.command_str = command,
54825491
.command_args = command_args,
54835492
.command_arg_count = command_arg_count,
@@ -5532,6 +5541,7 @@ static int cbm_remove_claude_hooks_with_binary(const char *settings_path, const
55325541
.settings_path = settings_path,
55335542
.hook_event = "PostToolUse",
55345543
.matcher_str = CMM_HOOK_READ_MATCHER,
5544+
.old_matchers = cmm_claude_old_read_matchers,
55355545
.old_commands = old_commands,
55365546
.match_command_exact = command,
55375547
.match_args = command_args,

‎src/cli/hook_augment.c‎

Lines changed: 142 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
#include "yyjson/yyjson.h"
2727

2828
#include <ctype.h>
29+
#include <limits.h>
30+
#include <stdatomic.h>
2931
#include <stdbool.h>
3032
#include <stdint.h>
3133
#include <stdio.h>
@@ -1414,6 +1416,129 @@ static void ha_tool_call_free(ha_tool_call_t *call) {
14141416
call->input = NULL;
14151417
}
14161418

1419+
/* Drift reminder (#509). A Claude Code session that keeps searching with Grep,
1420+
* Glob or Bash and makes no codebase-memory-mcp tool call gets one factual line
1421+
* on its next augmentation once HA_DRIFT_FIRST searches have run; the threshold
1422+
* then doubles (3, 6, 12, ...), and a graph tool call resets the session. The
1423+
* managed PostToolUse hook matches the graph tools for that reset. The state
1424+
* lives in the process that runs hook requests, which is the daemon, keyed by
1425+
* the payload's session_id in a bounded table that evicts the least recently
1426+
* used session. Codex sends the same event payload, with a turn_id, but has no
1427+
* reset hook, so its sessions are not tracked. */
1428+
enum {
1429+
HA_DRIFT_SESSIONS = 64,
1430+
HA_DRIFT_FIRST = 3,
1431+
HA_DRIFT_SESSION_MAX = 128,
1432+
};
1433+
1434+
typedef struct {
1435+
char session[HA_DRIFT_SESSION_MAX + 1];
1436+
unsigned searches;
1437+
unsigned threshold;
1438+
uint64_t used;
1439+
} ha_drift_slot_t;
1440+
1441+
static ha_drift_slot_t g_ha_drift[HA_DRIFT_SESSIONS];
1442+
static uint64_t g_ha_drift_clock;
1443+
static atomic_flag g_ha_drift_spin = ATOMIC_FLAG_INIT;
1444+
1445+
static void ha_drift_lock(void) {
1446+
while (atomic_flag_test_and_set_explicit(&g_ha_drift_spin, memory_order_acquire)) {}
1447+
}
1448+
1449+
static void ha_drift_unlock(void) {
1450+
atomic_flag_clear_explicit(&g_ha_drift_spin, memory_order_release);
1451+
}
1452+
1453+
static const char *ha_drift_session(yyjson_val *root, ha_lifecycle_dialect_t dialect) {
1454+
if (dialect != HA_DIALECT_EVENT || !root || yyjson_obj_get(root, "turn_id")) {
1455+
return NULL;
1456+
}
1457+
const char *session = ha_obj_str(root, "session_id");
1458+
size_t length = session ? strlen(session) : 0U;
1459+
if (length == 0U || length > HA_DRIFT_SESSION_MAX) {
1460+
return NULL;
1461+
}
1462+
for (size_t i = 0U; i < length; i++) {
1463+
unsigned char ch = (unsigned char)session[i];
1464+
if (!isalnum(ch) && ch != '-' && ch != '_' && ch != '.') {
1465+
return NULL;
1466+
}
1467+
}
1468+
return session;
1469+
}
1470+
1471+
/* Claude names MCP tools mcp__<server>__<tool>, and a plugin's servers
1472+
* mcp__plugin_<plugin>_<server>__<tool>. */
1473+
static bool ha_is_graph_tool(const char *tool) {
1474+
return tool && strncmp(tool, "mcp__", 5) == 0 && strstr(tool, "codebase-memory-mcp__");
1475+
}
1476+
1477+
/* The caller holds the lock. An unknown session takes an empty slot, or else
1478+
* the least recently used one. */
1479+
static ha_drift_slot_t *ha_drift_find(const char *session, bool create) {
1480+
ha_drift_slot_t *victim = NULL;
1481+
for (size_t i = 0U; i < HA_DRIFT_SESSIONS; i++) {
1482+
ha_drift_slot_t *slot = &g_ha_drift[i];
1483+
if (slot->session[0] && strcmp(slot->session, session) == 0) {
1484+
slot->used = ++g_ha_drift_clock;
1485+
return slot;
1486+
}
1487+
if (!victim || (victim->session[0] && (!slot->session[0] || slot->used < victim->used))) {
1488+
victim = slot;
1489+
}
1490+
}
1491+
if (!create) {
1492+
return NULL;
1493+
}
1494+
snprintf(victim->session, sizeof(victim->session), "%s", session);
1495+
victim->searches = 0U;
1496+
victim->threshold = HA_DRIFT_FIRST;
1497+
victim->used = ++g_ha_drift_clock;
1498+
return victim;
1499+
}
1500+
1501+
static void ha_drift_reset(const char *session) {
1502+
ha_drift_lock();
1503+
ha_drift_slot_t *slot = ha_drift_find(session, false);
1504+
if (slot) {
1505+
memset(slot, 0, sizeof(*slot));
1506+
}
1507+
ha_drift_unlock();
1508+
}
1509+
1510+
/* Counts one search. The reminder is due when the count has reached the
1511+
* threshold and this search has an augmentation to carry it; delivering it
1512+
* raises the threshold past the count by doubling. */
1513+
static bool ha_drift_note_search(const char *session, bool augmented, unsigned *searches) {
1514+
ha_drift_lock();
1515+
ha_drift_slot_t *slot = ha_drift_find(session, true);
1516+
if (slot->searches < UINT_MAX) {
1517+
slot->searches++;
1518+
}
1519+
bool due = augmented && slot->searches >= slot->threshold;
1520+
while (due && slot->threshold <= slot->searches && slot->threshold <= UINT_MAX / 2U) {
1521+
slot->threshold *= 2U;
1522+
}
1523+
*searches = slot->searches;
1524+
ha_drift_unlock();
1525+
return due;
1526+
}
1527+
1528+
/* Writes the context followed by the drift line into out. Returns false when
1529+
* they do not fit, and the caller then sends the context alone. The context is
1530+
* at most 4096 bytes plus the follow-up line, so HA_DRIFT_CONTEXT_CAP fits it. */
1531+
enum { HA_DRIFT_CONTEXT_CAP = 5120 };
1532+
1533+
static bool ha_drift_context(char *out, size_t out_size, const char *context, unsigned searches) {
1534+
int written = snprintf(out, out_size,
1535+
"%s\n[codebase-memory] This session has run %u searches since its last "
1536+
"codebase-memory-mcp tool call. Questions about callers, callees, call "
1537+
"paths and definitions are one graph call each.",
1538+
context, searches);
1539+
return written > 0 && (size_t)written < out_size;
1540+
}
1541+
14171542
static bool ha_tool_event_supported(ha_lifecycle_dialect_t dialect, const char *event,
14181543
const char *tool, bool *coverage) {
14191544
if (coverage) {
@@ -1752,6 +1877,13 @@ static char *ha_process(cbm_mcp_server_t *srv, const char *input_json, const cha
17521877
ha_tool_call_read(root, forced_event, dialect, &call);
17531878
const char *event = call.event;
17541879
const char *tool = call.tool;
1880+
const char *session = ha_drift_session(root, dialect);
1881+
if (session && event && strcmp(event, "PostToolUse") == 0 && ha_is_graph_tool(tool)) {
1882+
ha_drift_reset(session);
1883+
ha_tool_call_free(&call);
1884+
yyjson_doc_free(doc);
1885+
return NULL;
1886+
}
17551887
bool coverage = false;
17561888
if (!ha_tool_event_supported(dialect, event, tool, &coverage)) {
17571889
ha_tool_call_free(&call);
@@ -1809,10 +1941,17 @@ static char *ha_process(cbm_mcp_server_t *srv, const char *input_json, const cha
18091941
}
18101942

18111943
char *ctx = ha_resolve_and_query(srv, cwd, token);
1944+
unsigned searches = 0U;
1945+
char drift_context[HA_DRIFT_CONTEXT_CAP];
1946+
const char *text = ctx;
1947+
if (session && ha_drift_note_search(session, ctx != NULL, &searches) &&
1948+
ha_drift_context(drift_context, sizeof(drift_context), ctx, searches)) {
1949+
text = drift_context;
1950+
}
18121951
char *output = NULL;
1813-
if (ctx) {
1814-
output = dialect == HA_DIALECT_COPILOT ? ha_build_copilot_json(ctx)
1815-
: ha_build_event_json(event, ctx);
1952+
if (text) {
1953+
output = dialect == HA_DIALECT_COPILOT ? ha_build_copilot_json(text)
1954+
: ha_build_event_json(event, text);
18161955
}
18171956
free(ctx);
18181957
yyjson_doc_free(doc);

0 commit comments

Comments
 (0)