Skip to content

Commit 63e3f2c

Browse files
authored
Merge pull request DeusData#632 from halindrome/feat/subagent-cmm-startup-hook
feat(install): inject CMM code-discovery reminder into Claude subagents
2 parents 7824e50 + 5255939 commit 63e3f2c

3 files changed

Lines changed: 204 additions & 14 deletions

File tree

‎src/cli/cli.c‎

Lines changed: 126 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1795,9 +1795,15 @@ static const char *const cmm_gemini_old_matchers[] = {
17951795
NULL,
17961796
};
17971797

1798-
/* Check if a hook array entry is ours (current matcher or a known old one). */
1798+
/* Check if a hook array entry is ours (current matcher or a known old one).
1799+
* When require_command_substr is non-NULL, the matcher match is not sufficient:
1800+
* the entry must ALSO carry a hooks[].command containing that substring. This
1801+
* disambiguates our entry from a user's own hook that happens to share the same
1802+
* matcher (notably "*", which a user is likely to pick for a catch-all hook), so
1803+
* upsert/remove never clobber a foreign entry. NULL preserves matcher-only
1804+
* matching for callers whose matcher is already CMM-specific (e.g. "startup"). */
17991805
static bool is_cmm_hook_entry(yyjson_mut_val *entry, const char *matcher_str,
1800-
const char *const *old_matchers) {
1806+
const char *const *old_matchers, const char *require_command_substr) {
18011807
yyjson_mut_val *matcher = yyjson_mut_obj_get(entry, "matcher");
18021808
if (!matcher || !yyjson_mut_is_str(matcher)) {
18031809
return false;
@@ -1806,16 +1812,36 @@ static bool is_cmm_hook_entry(yyjson_mut_val *entry, const char *matcher_str,
18061812
if (!val) {
18071813
return false;
18081814
}
1809-
if (strcmp(val, matcher_str) == 0) {
1810-
return true;
1811-
}
1815+
bool matcher_ok = strcmp(val, matcher_str) == 0;
18121816
/* Also match old versions for backwards-compatible upgrade */
1813-
for (int i = 0; old_matchers && old_matchers[i]; i++) {
1817+
for (int i = 0; !matcher_ok && old_matchers && old_matchers[i]; i++) {
18141818
if (strcmp(val, old_matchers[i]) == 0) {
1815-
return true;
1819+
matcher_ok = true;
18161820
}
18171821
}
1818-
return false;
1822+
if (!matcher_ok) {
1823+
return false;
1824+
}
1825+
if (require_command_substr) {
1826+
yyjson_mut_val *hooks = yyjson_mut_obj_get(entry, "hooks");
1827+
if (!hooks || !yyjson_mut_is_arr(hooks)) {
1828+
return false;
1829+
}
1830+
size_t idx;
1831+
size_t max;
1832+
yyjson_mut_val *h;
1833+
yyjson_mut_arr_foreach(hooks, idx, max, h) {
1834+
yyjson_mut_val *cmd = yyjson_mut_obj_get(h, "command");
1835+
if (cmd && yyjson_mut_is_str(cmd)) {
1836+
const char *cs = yyjson_mut_get_str(cmd);
1837+
if (cs && strstr(cs, require_command_substr)) {
1838+
return true;
1839+
}
1840+
}
1841+
}
1842+
return false;
1843+
}
1844+
return true;
18191845
}
18201846

18211847
/* Generic hook upsert for both Claude Code and Gemini CLI */
@@ -1825,8 +1851,10 @@ typedef struct {
18251851
const char *hook_event;
18261852
const char *matcher_str;
18271853
const char *command_str;
1828-
const char *const *old_matchers; /* NULL-terminated; may be NULL */
1829-
int timeout_sec; /* >0 adds "timeout" to the hook entry */
1854+
const char *const *old_matchers; /* NULL-terminated; may be NULL */
1855+
int timeout_sec; /* >0 adds "timeout" to the hook entry */
1856+
const char *match_command_substr; /* non-NULL: also require this in the
1857+
* entry command to claim ownership */
18301858
} hooks_upsert_args_t;
18311859
static int upsert_hooks_json(hooks_upsert_args_t args) {
18321860
const char *settings_path = args.settings_path;
@@ -1876,7 +1904,7 @@ static int upsert_hooks_json(hooks_upsert_args_t args) {
18761904
size_t max;
18771905
yyjson_mut_val *item;
18781906
yyjson_mut_arr_foreach(event_arr, idx, max, item) {
1879-
if (is_cmm_hook_entry(item, matcher_str, old_matchers)) {
1907+
if (is_cmm_hook_entry(item, matcher_str, old_matchers, args.match_command_substr)) {
18801908
yyjson_mut_arr_remove(event_arr, idx);
18811909
break;
18821910
}
@@ -1909,7 +1937,9 @@ typedef struct {
19091937
const char *settings_path;
19101938
const char *hook_event;
19111939
const char *matcher_str;
1912-
const char *const *old_matchers; /* NULL-terminated; may be NULL */
1940+
const char *const *old_matchers; /* NULL-terminated; may be NULL */
1941+
const char *match_command_substr; /* non-NULL: also require this in the
1942+
* entry command to claim ownership */
19131943
} hooks_remove_args_t;
19141944
static int remove_hooks_json(hooks_remove_args_t args) {
19151945
const char *settings_path = args.settings_path;
@@ -1950,7 +1980,7 @@ static int remove_hooks_json(hooks_remove_args_t args) {
19501980
size_t max;
19511981
yyjson_mut_val *item;
19521982
yyjson_mut_arr_foreach(event_arr, idx, max, item) {
1953-
if (is_cmm_hook_entry(item, matcher_str, old_matchers)) {
1983+
if (is_cmm_hook_entry(item, matcher_str, old_matchers, args.match_command_substr)) {
19541984
yyjson_mut_arr_remove(event_arr, idx);
19551985
break;
19561986
}
@@ -2121,6 +2151,82 @@ static int cbm_remove_session_hooks(const char *settings_path) {
21212151
return rc;
21222152
}
21232153

2154+
/* SubagentStart hook: subagents spawned via the Agent tool do NOT fire
2155+
* SessionStart, so the SessionStart reminder above never reaches them. This
2156+
* hook is their equivalent. Unlike SessionStart (where plain stdout is injected
2157+
* as context), SubagentStart injects context only via a JSON object on stdout:
2158+
* {"hookSpecificOutput":{"hookEventName":"SubagentStart","additionalContext":"…"}}
2159+
* The text is a leaner variant of the SessionStart protocol: it omits the
2160+
* "run index_repository first" step, since the parent session has already
2161+
* indexed the project. Matcher "*" fires for every agent type. */
2162+
#define CMM_SUBAGENT_REMINDER_SCRIPT "cbm-subagent-reminder"
2163+
2164+
static void cbm_install_subagent_reminder_script(const char *home) {
2165+
if (!home) {
2166+
return;
2167+
}
2168+
char config_dir[CLI_BUF_1K];
2169+
cbm_claude_config_dir(home, config_dir, sizeof(config_dir));
2170+
if (!config_dir[0]) {
2171+
return;
2172+
}
2173+
char hooks_dir[CLI_BUF_1K];
2174+
snprintf(hooks_dir, sizeof(hooks_dir), "%s/hooks", config_dir);
2175+
cbm_mkdir_p(hooks_dir, CLI_OCTAL_PERM);
2176+
2177+
char script_path[CLI_BUF_1K];
2178+
snprintf(script_path, sizeof(script_path), "%s/" CMM_SUBAGENT_REMINDER_SCRIPT, hooks_dir);
2179+
2180+
FILE *f = fopen(script_path, "w");
2181+
if (!f) {
2182+
return;
2183+
}
2184+
/* The additionalContext value is a single line with no embedded quotes,
2185+
* backslashes, or newlines, so the JSON below is valid as written — no
2186+
* runtime escaping (and no python3/jq dependency) is required. */
2187+
(void)fprintf(f,
2188+
"#!/bin/bash\n"
2189+
"# SubagentStart hook: tell subagents to use codebase-memory-mcp tools.\n"
2190+
"# Installed by codebase-memory-mcp. Fires when any subagent is spawned.\n"
2191+
"# SubagentStart injects context via JSON additionalContext, not plain stdout.\n"
2192+
"cat << 'REMINDER'\n"
2193+
"{\"hookSpecificOutput\":{\"hookEventName\":\"SubagentStart\","
2194+
"\"additionalContext\":\"Code discovery: prefer codebase-memory-mcp tools "
2195+
"(search_graph, trace_path, get_code_snippet, query_graph, get_architecture, "
2196+
"search_code) over grep/file-read for navigating code. Use Grep/Glob/Read for "
2197+
"text, configs, and non-code files.\"}}\n"
2198+
"REMINDER\n");
2199+
#ifndef _WIN32
2200+
fchmod(fileno(f), CLI_OCTAL_PERM);
2201+
#endif
2202+
(void)fclose(f);
2203+
#ifdef _WIN32
2204+
chmod(script_path, CLI_OCTAL_PERM);
2205+
#endif
2206+
}
2207+
2208+
int cbm_upsert_claude_subagent_hooks(const char *settings_path) {
2209+
char command[CLI_BUF_1K];
2210+
cbm_resolve_hook_command(CMM_SUBAGENT_REMINDER_SCRIPT, command, sizeof(command));
2211+
/* matcher "*" is the natural choice a user would also pick for their own
2212+
* catch-all SubagentStart hook, so claim ownership by command too — never
2213+
* clobber or remove a foreign "*" entry. */
2214+
return upsert_hooks_json(
2215+
(hooks_upsert_args_t){.settings_path = settings_path,
2216+
.hook_event = "SubagentStart",
2217+
.matcher_str = "*",
2218+
.command_str = command,
2219+
.match_command_substr = CMM_SUBAGENT_REMINDER_SCRIPT});
2220+
}
2221+
2222+
int cbm_remove_claude_subagent_hooks(const char *settings_path) {
2223+
return remove_hooks_json(
2224+
(hooks_remove_args_t){.settings_path = settings_path,
2225+
.hook_event = "SubagentStart",
2226+
.matcher_str = "*",
2227+
.match_command_substr = CMM_SUBAGENT_REMINDER_SCRIPT});
2228+
}
2229+
21242230
/* Matcher excludes read_file for consistency with the Claude fix: the hook
21252231
* is an advisory reminder, not a gate over the agent's file reads. */
21262232
#define GEMINI_HOOK_MATCHER "google_search|grep_search"
@@ -3116,6 +3222,8 @@ static void install_claude_code_config(const char *home, const char *binary_path
31163222
plan_record("Claude Code", "hook", p);
31173223
snprintf(p, sizeof(p), "%s/hooks/%s", config_dir, CMM_SESSION_REMINDER_SCRIPT);
31183224
plan_record("Claude Code", "hook", p);
3225+
snprintf(p, sizeof(p), "%s/hooks/%s", config_dir, CMM_SUBAGENT_REMINDER_SCRIPT);
3226+
plan_record("Claude Code", "hook", p);
31193227
return;
31203228
}
31213229

@@ -3149,9 +3257,12 @@ static void install_claude_code_config(const char *home, const char *binary_path
31493257
cbm_install_hook_gate_script(home, binary_path);
31503258
cbm_install_session_reminder_script(home);
31513259
cbm_upsert_session_hooks(settings_path);
3260+
cbm_install_subagent_reminder_script(home);
3261+
cbm_upsert_claude_subagent_hooks(settings_path);
31523262
}
31533263
printf(" hooks: PreToolUse (Grep/Glob search-graph augmenter, non-blocking)\n");
31543264
printf(" hooks: SessionStart (MCP usage reminder on startup/resume/clear/compact)\n");
3265+
printf(" hooks: SubagentStart (MCP usage reminder for subagents)\n");
31553266

31563267
/* Migration nudge: when CLAUDE_CONFIG_DIR is set and a legacy ~/.claude tree
31573268
* still exists, mention it so users can clean up stale artifacts. */
@@ -3774,8 +3885,9 @@ static void uninstall_claude_code(const char *home, bool dry_run) {
37743885
if (!dry_run) {
37753886
cbm_remove_claude_hooks(settings_path);
37763887
cbm_remove_session_hooks(settings_path);
3888+
cbm_remove_claude_subagent_hooks(settings_path);
37773889
}
3778-
printf(" removed PreToolUse + SessionStart hooks\n");
3890+
printf(" removed PreToolUse + SessionStart + SubagentStart hooks\n");
37793891
}
37803892

37813893
/* Remove MCP + instructions for a generic agent. */

‎src/cli/cli.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,13 @@ int cbm_remove_codex_hooks(const char *config_path);
213213
int cbm_upsert_gemini_session_hooks(const char *settings_path);
214214
int cbm_remove_gemini_session_hooks(const char *settings_path);
215215

216+
/* Install/remove a Claude Code SubagentStart reminder hook in settings.json.
217+
* Subagents spawned via the Agent tool do not fire SessionStart, so this is the
218+
* channel that gives them the same code-discovery guidance. Non-blocking; the
219+
* hook injects context via JSON additionalContext. Returns 0 on success. */
220+
int cbm_upsert_claude_subagent_hooks(const char *settings_path);
221+
int cbm_remove_claude_subagent_hooks(const char *settings_path);
222+
216223
/* ── PATH management ──────────────────────────────────────────── */
217224

218225
/* Append an export PATH line to the given rc file.

‎tests/test_cli.c‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1750,6 +1750,75 @@ TEST(cli_gemini_session_hook_parity) {
17501750
PASS();
17511751
}
17521752

1753+
/* Claude SubagentStart reminder: subagents spawned via the Agent tool do not
1754+
* fire SessionStart, so this hook is their code-discovery channel. Verify the
1755+
* install shape, idempotent re-install, and clean removal. */
1756+
TEST(cli_claude_subagent_hook) {
1757+
char tmpdir[256];
1758+
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-subhook-XXXXXX");
1759+
if (!cbm_mkdtemp(tmpdir))
1760+
FAIL("cbm_mkdtemp failed");
1761+
1762+
char cfg[512];
1763+
snprintf(cfg, sizeof(cfg), "%s/settings.json", tmpdir);
1764+
1765+
ASSERT_EQ(cbm_upsert_claude_subagent_hooks(cfg), 0);
1766+
const char *d = read_test_file(cfg);
1767+
ASSERT_NOT_NULL(d);
1768+
ASSERT(strstr(d, "SubagentStart") != NULL);
1769+
ASSERT(strstr(d, "\"*\"") != NULL); /* match-all matcher */
1770+
ASSERT(strstr(d, "cbm-subagent-reminder") != NULL); /* points at the hook script */
1771+
1772+
/* Idempotent: a second upsert must not duplicate our entry. */
1773+
ASSERT_EQ(cbm_upsert_claude_subagent_hooks(cfg), 0);
1774+
d = read_test_file(cfg);
1775+
ASSERT_NOT_NULL(d);
1776+
int count = 0;
1777+
for (const char *p = d; (p = strstr(p, "cbm-subagent-reminder")) != NULL; p++)
1778+
count++;
1779+
ASSERT_EQ(count, 1);
1780+
1781+
ASSERT_EQ(cbm_remove_claude_subagent_hooks(cfg), 0);
1782+
d = read_test_file(cfg);
1783+
ASSERT_NULL(strstr(d, "SubagentStart"));
1784+
1785+
test_rmdir_r(tmpdir);
1786+
PASS();
1787+
}
1788+
1789+
/* A user's own catch-all ("*") SubagentStart hook must survive CMM install and
1790+
* uninstall: ownership is keyed on the command, not just the "*" matcher. */
1791+
TEST(cli_claude_subagent_hook_preserves_user_entry) {
1792+
char tmpdir[256];
1793+
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-subuser-XXXXXX");
1794+
if (!cbm_mkdtemp(tmpdir))
1795+
FAIL("cbm_mkdtemp failed");
1796+
1797+
char cfg[512];
1798+
snprintf(cfg, sizeof(cfg), "%s/settings.json", tmpdir);
1799+
/* Pre-existing user SubagentStart hook, also matcher "*", different command. */
1800+
write_test_file(
1801+
cfg, "{\"hooks\":{\"SubagentStart\":[{\"matcher\":\"*\","
1802+
"\"hooks\":[{\"type\":\"command\",\"command\":\"echo user-subagent-hook\"}]}]}}");
1803+
1804+
/* Install CMM's hook: the user's "*" entry must remain, ours added alongside. */
1805+
ASSERT_EQ(cbm_upsert_claude_subagent_hooks(cfg), 0);
1806+
const char *d = read_test_file(cfg);
1807+
ASSERT_NOT_NULL(d);
1808+
ASSERT(strstr(d, "echo user-subagent-hook") != NULL); /* user's hook untouched */
1809+
ASSERT(strstr(d, "cbm-subagent-reminder") != NULL); /* ours added */
1810+
1811+
/* Remove CMM's hook: the user's entry must still be intact, ours gone. */
1812+
ASSERT_EQ(cbm_remove_claude_subagent_hooks(cfg), 0);
1813+
d = read_test_file(cfg);
1814+
ASSERT_NOT_NULL(d);
1815+
ASSERT(strstr(d, "echo user-subagent-hook") != NULL); /* user's hook preserved */
1816+
ASSERT_NULL(strstr(d, "cbm-subagent-reminder")); /* only ours removed */
1817+
1818+
test_rmdir_r(tmpdir);
1819+
PASS();
1820+
}
1821+
17531822
TEST(cli_detect_agents_finds_gemini) {
17541823
char tmpdir[256];
17551824
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-detect-XXXXXX");
@@ -2831,6 +2900,8 @@ SUITE(cli) {
28312900
RUN_TEST(cli_install_plan_receipt_no_mutation_issue388);
28322901
RUN_TEST(cli_codex_session_hook_issue330);
28332902
RUN_TEST(cli_gemini_session_hook_parity);
2903+
RUN_TEST(cli_claude_subagent_hook);
2904+
RUN_TEST(cli_claude_subagent_hook_preserves_user_entry);
28342905
RUN_TEST(cli_detect_agents_finds_gemini);
28352906
RUN_TEST(cli_detect_agents_finds_zed);
28362907
RUN_TEST(cli_detect_agents_finds_antigravity);

0 commit comments

Comments
 (0)