From ed78ff056e89da814ff5ae05da6fb32b7e10c0db Mon Sep 17 00:00:00 2001 From: lorenzozanee Date: Sun, 20 Sep 2026 16:44:10 +0800 Subject: [PATCH 01/32] fix(install): reject Android portable binary Signed-off-by: lorenzozanee --- install.sh | 11 ++++++++ tests/test-install-android-guard.sh | 41 +++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100755 tests/test-install-android-guard.sh diff --git a/install.sh b/install.sh index 9f4b4ec99..01ab6c378 100755 --- a/install.sh +++ b/install.sh @@ -148,8 +148,19 @@ detect_arch() { esac } +is_android() { + [ "$(uname -o 2>/dev/null || true)" = "Android" ] \ + || [ -n "${TERMUX_VERSION:-}" ] \ + || [[ "${PREFIX:-}" == /data/data/com.termux/* ]] +} + OS=$(detect_os) ARCH=$(detect_arch) +if [ "$OS" = "linux" ] && is_android; then + echo "error: Android/Termux is not supported by the Linux portable binary." >&2 + echo "Build from source with scripts/build.sh in Termux or use a supported Linux host." >&2 + exit 1 +fi echo "codebase-memory-mcp installer" echo " os: $OS" diff --git a/tests/test-install-android-guard.sh b/tests/test-install-android-guard.sh new file mode 100755 index 000000000..6b3a383a2 --- /dev/null +++ b/tests/test-install-android-guard.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +mkdir -p "$WORK/bin" "$WORK/home" +cat >"$WORK/bin/uname" <<'EOF' +case "$1" in + -s) printf '%s\n' Linux ;; + -m) printf '%s\n' aarch64 ;; + -o) printf '%s\n' Android ;; + *) exit 1 ;; +esac +EOF +cat >"$WORK/bin/curl" <<'EOF' +printf 'curl must not run for Android/Termux\n' >&2 +exit 99 +EOF +chmod +x "$WORK/bin/uname" "$WORK/bin/curl" + +set +e +output=$(PATH="$WORK/bin:$PATH" HOME="$WORK/home" bash "$ROOT/install.sh" --skip-config 2>&1) +rc=$? +set -e + +if [ "$rc" -eq 0 ]; then + printf 'FAIL: installer accepted Android/Termux\n' >&2 + exit 1 +fi +if ! grep -Fq 'Android/Termux' <<<"$output"; then + printf 'FAIL: missing Android/Termux guidance\n%s\n' "$output" >&2 + exit 1 +fi +if grep -Fq 'curl must not run' <<<"$output"; then + printf 'FAIL: installer downloaded before rejecting Android/Termux\n' >&2 + exit 1 +fi + +printf 'PASS: Android/Termux is rejected before download\n' From 0d2f840c8ed2695db206acbcad1ad1c36a1f3958 Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 4 Aug 2026 07:22:01 -0400 Subject: [PATCH 02/32] feat(config): add ignore_worktrees to skip linked git worktrees Agents that use `git worktree add` to run parallel branches end up with one indexed project per worktree. Each is a near-duplicate of the main checkout, so the cache fills with redundant graphs and project pickers get noisy. Add an opt-in `ignore_worktrees` config key. When enabled, a linked worktree is left alone: - auto-index on connect skips it (logged as autoindex.skip) - the daemon's background auto-index skips it - explicit index_repository refuses with an actionable message naming both ways forward (index_worktree=true, or turn the key off) - the hook-augment "not indexed" guidance stops telling the agent to run index_repository in a directory where it would only be refused Detection is git plumbing, no subprocess: /.git must be a regular file holding a "gitdir:" pointer AND that gitdir must contain a `commondir` file. The commondir check is what separates a linked worktree from a submodule, whose .git is also a gitlink file but whose gitdir has no commondir. The main checkout of a repo that has worktrees is never affected. Defaults to false, so behaviour is unchanged unless the key is set. Signed-off-by: Nohj --- README.md | 3 + docs/CONFIGURATION.md | 30 ++++ src/cli/cli.c | 1 + src/cli/cli.h | 4 +- src/cli/hook_augment.c | 20 ++- src/daemon/application.c | 6 + src/git/git_context.c | 60 ++++++++ src/git/git_context.h | 12 ++ src/mcp/mcp.c | 36 ++++- src/mcp/mcp_internal.h | 5 + tests/test_cli.c | 22 ++- tests/test_git_context.c | 114 +++++++++++++++ tests/test_mcp.c | 292 +++++++++++++++++++++++++++++++++++++++ 13 files changed, 597 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 66b50fe08..3a9b2137d 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,8 @@ Watcher registration is controlled separately by `auto_watch` (default `true`). To turn the watcher off entirely, set `config set watcher_enabled false` (default `true`): the background poll thread never starts and no project is registered, while `auto_index` and manual `index_repository` keep working. Unlike `auto_watch` — which is consulted per session — `watcher_enabled` is read once when the background daemon starts, so run `codebase-memory-mcp daemon stop` after changing it; reconnecting your MCP client alone will not restart the daemon. See [docs/CONFIGURATION.md](docs/CONFIGURATION.md#2-cli-managed-runtime-settings). +Linked git worktrees are indexed as their own projects by default. Set `config set ignore_worktrees true` to skip them on the automatic paths — useful when short-lived `git worktree add` checkouts would otherwise each leave behind a permanent index of the same repository. An explicit `index_repository` call on a worktree is then refused unless you pass `index_worktree=true`. See [docs/CONFIGURATION.md](docs/CONFIGURATION.md#ignore_worktrees). + ### Keeping Up to Date **Updates run from the install script on every platform, not from inside the running binary.** `codebase-memory-mcp update` validates your flags and then prints the exact command to run: @@ -735,6 +737,7 @@ codebase-memory-mcp config list # show all settings codebase-memory-mcp config set auto_index true # auto-index on session start codebase-memory-mcp config set auto_index_limit 50000 # max files for auto-index codebase-memory-mcp config set auto_watch false # don't register background git watcher (default: true) +codebase-memory-mcp config set ignore_worktrees true # skip linked git worktrees when auto-indexing (default: false) codebase-memory-mcp config set watcher_enabled false # stop the watcher thread entirely (default: true) codebase-memory-mcp config set index_max_files 250000 # optional per-index source-file limit codebase-memory-mcp config set index_max_source_mb 16384 # optional per-index source-size limit diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 038256976..4c27e7f57 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -87,6 +87,7 @@ Current keys: |---|---|---| | `auto_index` | `false` | Automatically index new projects when an MCP session starts. | | `auto_index_limit` | `50000` | Maximum file count allowed for automatic indexing of a new project. | +| `ignore_worktrees` | `false` | Skip linked git worktrees (`git worktree add`) when indexing automatically. | | `auto_watch` | `true` | Register the session's project with the background git watcher on connect. Set `false` to keep a session from registering its project (the watcher still runs for other projects). | | `watcher_enabled` | `true` | Master switch for the background watcher subsystem. Set `false` to stop the watcher from starting at all — no poll thread and no project registration. Reindex manually with `index_repository` when disabled. | | `index_max_files` | `off` | Optional maximum number of accepted source files in one discovery run. | @@ -126,6 +127,35 @@ and preserves any previously serving database. See [Index resource limits](INDEX_RESOURCE_LIMITS.md) for counting, validation, and error-response details. +### `ignore_worktrees` + +Every indexed project is registered under its own absolute root path, so each +linked worktree becomes a separate permanent index. On machines that create many +short-lived worktrees, the automatic paths (`auto_index`, and the session hook's +"index this project first" guidance) turn every throwaway checkout into another +stored index of what is largely the same repository. + +Enable the key to keep those checkouts out of the index: + +```bash +codebase-memory-mcp config set ignore_worktrees true +``` + +With it enabled: + +- automatic indexing skips a session whose root is a linked worktree; +- the `hook-augment` context says the worktree is unindexed on purpose instead + of telling the agent to run `index_repository`; +- an explicit `index_repository` call on a linked worktree is refused, and names + both ways forward — pass `index_worktree=true` for that one call, or turn the + key back off. + +The main checkout of the same repository is unaffected, as are ordinary clones +and submodules. Detection is git plumbing only: a linked worktree's `.git` is a +file pointing at a gitdir that contains a `commondir` entry. + +The default is `false`, so indexing behavior is unchanged unless you opt in. + ## 3. UI Settings The optional built-in graph UI stores its settings in: diff --git a/src/cli/cli.c b/src/cli/cli.c index b59a894a6..13c678943 100644 --- a/src/cli/cli.c +++ b/src/cli/cli.c @@ -7442,6 +7442,7 @@ static const config_key_def_t CONFIG_KEYS[] = { {CBM_CONFIG_AUTO_INDEX, "false", "Enable auto-indexing on MCP session start"}, {CBM_CONFIG_AUTO_INDEX_LIMIT, "50000", "Max files for auto-indexing new projects"}, {CBM_CONFIG_AUTO_WATCH, "true", "Register background git watcher on session connect"}, + {CBM_CONFIG_IGNORE_WORKTREES, "false", "Skip linked git worktrees when indexing automatically"}, {CBM_CONFIG_WATCHER_ENABLED, "true", "Run the background watcher thread (auto-reindex); false to disable"}, {CBM_CONFIG_UI_LANG, "auto", "Pin graph UI language: en, zh, or auto"}, diff --git a/src/cli/cli.h b/src/cli/cli.h index cf7f6fa44..ada71ab01 100644 --- a/src/cli/cli.h +++ b/src/cli/cli.h @@ -250,7 +250,8 @@ bool cbm_hook_augment_invocation_supported_for_testing(const char *dialect, const char *forced_event); bool cbm_hook_path_contains_for_testing(const char *root, const char *candidate, bool case_insensitive); -const char *cbm_hook_no_project_index_guidance_for_testing(const char *event); +const char *cbm_hook_no_project_index_guidance_for_testing(const char *event, + bool worktree_ignored); bool cbm_hook_augment_parse_bash_pattern_for_testing(const char *cmd, char *out, size_t out_sz); bool cbm_mcp_command_path_probe_safe_for_testing(const char *command, bool windows); void cbm_set_mcp_command_path_probe_counter_for_testing(int *counter); @@ -431,6 +432,7 @@ bool cbm_config_load_index_policy(cbm_config_t *cfg, cbm_index_resource_policy_t #define CBM_CONFIG_AUTO_INDEX "auto_index" #define CBM_CONFIG_AUTO_INDEX_LIMIT "auto_index_limit" #define CBM_CONFIG_AUTO_WATCH "auto_watch" +#define CBM_CONFIG_IGNORE_WORKTREES "ignore_worktrees" #define CBM_CONFIG_UI_LANG "ui-lang" #define CBM_CONFIG_WATCHER_ENABLED "watcher_enabled" /* #1558: the graph UI's loopback listener. Stored in the UI config file rather diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index f8909c365..1043b48cd 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -21,7 +21,9 @@ #include "foundation/constants.h" #include "foundation/mem.h" #include "foundation/platform.h" +#include "git/git_context.h" #include "mcp/mcp.h" +#include "mcp/mcp_internal.h" #include "pipeline/pipeline.h" #include "yyjson/yyjson.h" @@ -1440,7 +1442,14 @@ static const char *ha_active_tier(yyjson_val *root, const char *event) { return "Tier 2 verification"; } -static const char *ha_no_project_index_guidance(const char *event) { +static const char *ha_no_project_index_guidance(const char *event, bool worktree_ignored) { + /* ignore_worktrees is on and this cwd is a linked worktree: indexing it is + * deliberately disabled, so telling the agent to run index_repository would + * only produce a refusal. Point at the setting instead. */ + if (worktree_ignored) { + return "This is a linked git worktree and ignore_worktrees is enabled, so it is not " + "indexed on purpose; do not run index_repository here."; + } return event && strcmp(event, "SubagentStart") == 0 ? "Ask the parent agent to run index_repository before structural exploration; " "do not attempt graph mutation." @@ -1472,6 +1481,8 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root } const char *cwd = ha_normalized_cwd_with_server(root, srv, cwd_buffer, sizeof(cwd_buffer)); char *project = srv && cwd ? ha_resolve_indexed_project(srv, cwd) : NULL; + bool worktree_ignored = !project && srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && + cbm_git_is_linked_worktree(cwd); cbm_mcp_server_free(owned_server); char context[2048]; @@ -1505,7 +1516,7 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root "and file reads for literals, configs, non-code files, and verification.", scope, safe_project, tier); } else { - const char *index_guidance = ha_no_project_index_guidance(event); + const char *index_guidance = ha_no_project_index_guidance(event, worktree_ignored); snprintf(context, sizeof(context), "[codebase-memory] %s context: no indexed graph project matched this working " "directory. %s Once indexed, " @@ -1624,8 +1635,9 @@ bool cbm_hook_path_contains_for_testing(const char *root, const char *candidate, return ha_path_contains_mode(root, candidate, case_insensitive); } -const char *cbm_hook_no_project_index_guidance_for_testing(const char *event) { - return ha_no_project_index_guidance(event); +const char *cbm_hook_no_project_index_guidance_for_testing(const char *event, + bool worktree_ignored) { + return ha_no_project_index_guidance(event, worktree_ignored); } bool cbm_hook_augment_parse_bash_pattern_for_testing(const char *cmd, char *out, size_t out_sz) { diff --git a/src/daemon/application.c b/src/daemon/application.c index 748b8bb75..8a79ecd5d 100644 --- a/src/daemon/application.c +++ b/src/daemon/application.c @@ -15,6 +15,7 @@ #include "foundation/sha256.h" #include "foundation/subprocess.h" #include "foundation/workspace.h" +#include "git/git_context.h" #include "mcp/index_supervisor.h" #include "mcp/mcp.h" #include "mcp/mcp_internal.h" @@ -2071,6 +2072,11 @@ static void application_background_initialize_impl(cbm_daemon_application_sessio !application_session_workspace_allowed(session, "auto_index_discovery")) { auto_index_candidate = false; } + if (auto_index_candidate && cbm_mcp_ignore_worktrees_enabled(session->mcp) && + cbm_git_is_linked_worktree(root_path)) { + cbm_log_info("daemon.autoindex.skipped", "project", project, "reason", "linked_worktree"); + auto_index_candidate = false; + } bool within_auto_index_limit = !auto_index_candidate || cbm_mcp_auto_index_within_file_limit(root_path, auto_index_limit, &tracked_files); diff --git a/src/git/git_context.c b/src/git/git_context.c index f739c46e6..2734dc703 100644 --- a/src/git/git_context.c +++ b/src/git/git_context.c @@ -100,6 +100,66 @@ static bool path_is_absolute(const char *path) { #endif } +/* Read the "gitdir: " pointer out of a gitlink FILE at /.git. + * Returns false when .git is missing, a directory (ordinary repo), or holds no + * pointer. A relative pointer is resolved against path. */ +static bool read_gitlink_target(const char *path, char *out, size_t out_size) { + char dot_git[GIT_OUTPUT_MAX]; + int n = snprintf(dot_git, sizeof(dot_git), "%s/.git", path); + if (n < 0 || n >= (int)sizeof(dot_git)) { + return false; + } + struct stat st; + if (stat(dot_git, &st) != 0 || !S_ISREG(st.st_mode)) { + return false; + } + + FILE *f = cbm_fopen(dot_git, "r"); + if (!f) { + return false; + } + char line[GIT_OUTPUT_MAX]; + bool got = false; + while (fgets(line, sizeof(line), f)) { + trim_newlines(line); + if (strncmp(line, "gitdir:", 7) != 0) { + continue; + } + const char *value = line + 7; + while (*value == ' ' || *value == '\t') { + value++; + } + if (!value[0]) { + break; + } + int written = path_is_absolute(value) ? snprintf(out, out_size, "%s", value) + : snprintf(out, out_size, "%s/%s", path, value); + got = written > 0 && written < (int)out_size; + break; + } + fclose(f); + return got; +} + +bool cbm_git_is_linked_worktree(const char *path) { + if (!path || !path[0]) { + return false; + } + char git_dir[GIT_OUTPUT_MAX]; + if (!read_gitlink_target(path, git_dir, sizeof(git_dir))) { + return false; + } + /* Only linked worktrees carry /commondir; a submodule gitlink + * points at /.git/modules/, which does not. */ + char commondir[GIT_OUTPUT_MAX]; + int n = snprintf(commondir, sizeof(commondir), "%s/commondir", git_dir); + if (n < 0 || n >= (int)sizeof(commondir)) { + return false; + } + struct stat st; + return stat(commondir, &st) == 0 && S_ISREG(st.st_mode); +} + static char *join_root_relative(const char *root, const char *rel) { if (!root || !root[0]) { return git_strdup(rel); diff --git a/src/git/git_context.h b/src/git/git_context.h index 876309eb6..633e28018 100644 --- a/src/git/git_context.h +++ b/src/git/git_context.h @@ -19,6 +19,18 @@ typedef struct { char *base_sha; } cbm_git_context_t; +/* True when path is the root of a LINKED git worktree (`git worktree add`). + * + * Plumbing-only, no subprocess: /.git must be a regular file holding a + * "gitdir: " pointer AND that gitdir must contain a `commondir` file. + * The commondir check is what separates a linked worktree from a submodule — + * a submodule's .git is also a gitlink file, but its gitdir + * (/.git/modules/) has no commondir entry. + * + * Callers run this on every session start, so it stays fork-free; the richer + * cbm_git_context_resolve() shells out to git and is not usable on that path. */ +bool cbm_git_is_linked_worktree(const char *path); + int cbm_git_context_resolve(const char *path, cbm_git_context_t *out); void cbm_git_context_free(cbm_git_context_t *ctx); char *cbm_git_context_branch_qn(const char *project_name, const cbm_git_context_t *ctx); diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c index 75ff8e396..f27ddb9a8 100644 --- a/src/mcp/mcp.c +++ b/src/mcp/mcp.c @@ -478,7 +478,10 @@ static const tool_def_t TOOLS[] = { "\"name\":{\"type\":\"string\",\"description\":" "\"Name override; Non-ASCII bytes are encoded; unsafe characters normalized.\"}," "\"persistence\":{\"type\":\"boolean\",\"default\":false,\"description\":" - "\"Write .codebase-memory/graph.db.zst.\"}" + "\"Write .codebase-memory/graph.db.zst.\"}," + "\"index_worktree\":{\"type\":\"boolean\",\"default\":false,\"description\":" + "\"Index repo_path even when it is a linked git worktree and the " + "ignore_worktrees config key is enabled. No effect otherwise.\"}" "},\"required\":[\"repo_path\"]}"}, {"search_graph", @@ -11145,6 +11148,20 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) { return cbm_mcp_text_result(boundary_err, true); } + /* ignore_worktrees: an EXPLICIT index_repository call on a linked worktree + * is refused with the two ways forward (per-call override, or turn the + * setting off) rather than silently skipped — a silent success would be + * indistinguishable from a real index to the caller. */ + if (cbm_mcp_ignore_worktrees_enabled(srv) && !cbm_mcp_get_bool_arg(args, "index_worktree") && + cbm_git_is_linked_worktree(repo_path)) { + index_args_free(repo_path, mode_str, name_override); + return cbm_mcp_text_result( + "repo_path is a linked git worktree and ignore_worktrees is enabled. Pass " + "index_worktree=true to index it anyway, or run: codebase-memory-mcp config set " + "ignore_worktrees false", + true); + } + if (mode_str && strcmp(mode_str, "cross-repo-intelligence") == 0) { char *result = handle_cross_repo_mode(srv, repo_path, name_override, args); index_args_free(repo_path, mode_str, name_override); @@ -17569,6 +17586,17 @@ static bool auto_watch_enabled(cbm_mcp_server_t *srv) { return cbm_config_get_bool(srv->config, CBM_CONFIG_AUTO_WATCH, true); } +/* ignore_worktrees config: gates automatic indexing of LINKED git worktrees + * (default off, so existing setups keep indexing them). Users who create many + * short-lived worktrees can stop each throwaway checkout from registering a + * new permanent project with `config set ignore_worktrees true`. */ +bool cbm_mcp_ignore_worktrees_enabled(const cbm_mcp_server_t *srv) { + if (!srv || !srv->config) { + return false; /* default off */ + } + return cbm_config_get_bool(srv->config, CBM_CONFIG_IGNORE_WORKTREES, false); +} + /* Register the session project with the background watcher for ongoing * change detection — unless auto_watch is disabled. */ static void register_watcher_if_enabled(cbm_mcp_server_t *srv) { @@ -17721,6 +17749,12 @@ static void maybe_auto_index(cbm_mcp_server_t *srv) { return; } + if (cbm_mcp_ignore_worktrees_enabled(srv) && cbm_git_is_linked_worktree(srv->session_root)) { + cbm_log_info("autoindex.skip", "reason", "linked_worktree", "project", + srv->session_project); + return; + } + /* Quick tracked-file count check to avoid OOM on massive repos. */ int file_count = -1; #ifdef CBM_ENABLE_TEST_SEAMS diff --git a/src/mcp/mcp_internal.h b/src/mcp/mcp_internal.h index de170067a..8e78f9f40 100644 --- a/src/mcp/mcp_internal.h +++ b/src/mcp/mcp_internal.h @@ -63,6 +63,11 @@ const char *cbm_mcp_edge_strategy_class(const char *strategy); bool cbm_mcp_auto_index_within_file_limit(const char *root_path, int file_limit, int *file_count_out); +/* True when the `ignore_worktrees` config key is on for this server (default + * off). Callers pair it with cbm_git_is_linked_worktree() to decide whether an + * automatic index of a linked worktree should be skipped. */ +bool cbm_mcp_ignore_worktrees_enabled(const cbm_mcp_server_t *srv); + /* detect_changes seed scoping (#1363): does `node`'s line range overlap any * recorded hunk for `file`? Exposed for direct unit testing of the overlap * logic, independent of the git/subprocess/index plumbing around it. */ diff --git a/tests/test_cli.c b/tests/test_cli.c index 211ec6355..46f826d63 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -12263,14 +12263,18 @@ TEST(cli_hook_augment_subagent_tier_router_contract) { } TEST(cli_hook_augment_subagent_no_project_guidance_is_read_only) { - const char *session = cbm_hook_no_project_index_guidance_for_testing("SessionStart"); - const char *subagent = cbm_hook_no_project_index_guidance_for_testing("SubagentStart"); + const char *session = cbm_hook_no_project_index_guidance_for_testing("SessionStart", false); + const char *subagent = cbm_hook_no_project_index_guidance_for_testing("SubagentStart", false); + const char *worktree = cbm_hook_no_project_index_guidance_for_testing("SessionStart", true); ASSERT_NOT_NULL(session); ASSERT_NOT_NULL(subagent); + ASSERT_NOT_NULL(worktree); ASSERT(strstr(session, "Run index_repository") != NULL); ASSERT(strstr(subagent, "Ask the parent agent to run index_repository") != NULL); ASSERT(strstr(subagent, "do not attempt graph mutation") != NULL); ASSERT(strstr(subagent, "Run index_repository") == NULL); + ASSERT(strstr(worktree, "ignore_worktrees is enabled") != NULL); + ASSERT(strstr(worktree, "do not run index_repository") != NULL); PASS(); } @@ -15578,6 +15582,19 @@ TEST(cli_ui_config_keys_are_discoverable_and_settable_issue1558) { PASS(); } +TEST(cli_ignore_worktrees_config_key_is_discoverable) { + bool listed = false; + for (size_t i = 0; i < cbm_cli_config_key_count_for_testing(); i++) { + const char *key = cbm_cli_config_key_at_for_testing(i); + if (key && strcmp(key, CBM_CONFIG_IGNORE_WORKTREES) == 0) { + listed = true; + break; + } + } + ASSERT_TRUE(listed); + PASS(); +} + TEST(cli_skill_frontmatter_scalars_with_colons_are_quoted_issue1554) { const cbm_skill_t *sk = cbm_get_skills(); ASSERT_NOT_NULL(sk); @@ -16011,6 +16028,7 @@ SUITE(cli) { RUN_TEST(cli_update_download_failure_does_not_quiesce_sessions); RUN_TEST(cli_update_already_current_does_not_quiesce_sessions); RUN_TEST(cli_ui_config_keys_are_discoverable_and_settable_issue1558); + RUN_TEST(cli_ignore_worktrees_config_key_is_discoverable); RUN_TEST(cli_skill_frontmatter_scalars_with_colons_are_quoted_issue1554); RUN_TEST(cli_external_manager_detection_needs_positive_evidence_issue1566); RUN_TEST(cli_clients_selector_vocabulary_is_complete_and_strict_issue1558); diff --git a/tests/test_git_context.c b/tests/test_git_context.c index a384651a5..08df0dd7b 100644 --- a/tests/test_git_context.c +++ b/tests/test_git_context.c @@ -232,10 +232,124 @@ TEST(canonical_root_linked_worktree) { #endif /* _WIN32 */ } +/* ── cbm_git_is_linked_worktree ─────────────────────────────────── */ +/* Detection backing the `ignore_worktrees` config gate. The predicate must be + * TRUE only for a linked worktree (`git worktree add`) — never for the main + * checkout, a plain directory, or a submodule. The submodule case is the one a + * naive "is .git a regular file?" check gets wrong: a submodule's .git is also a + * gitlink file, and it is separated here by the absence of a `commondir` entry + * in the pointed-at gitdir. */ + +TEST(is_linked_worktree_true_for_linked_worktree) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree test not implemented for Windows"); +#else + /* th_mktempdir() returns a static buffer — copy before the second call. */ + char main_tmp[256]; + char *raw = th_mktempdir("cbm_wt_main"); + if (!raw) FAIL("th_mktempdir returned NULL"); + strncpy(main_tmp, raw, sizeof(main_tmp) - 1); + main_tmp[sizeof(main_tmp) - 1] = '\0'; + + char wt_tmp[256]; + raw = th_mktempdir("cbm_wt_linked"); + if (!raw) FAIL("th_mktempdir returned NULL"); + strncpy(wt_tmp, raw, sizeof(wt_tmp) - 1); + wt_tmp[sizeof(wt_tmp) - 1] = '\0'; + th_rmtree(wt_tmp); /* git worktree add creates it */ + + if (make_git_repo(main_tmp) != 0) { + th_rmtree(main_tmp); + SKIP_PLATFORM("git not available to init a repo"); + } + if (git_run(main_tmp, "branch wt-branch") != 0) { + th_rmtree(main_tmp); + FAIL("failed to create branch for worktree"); + } + char wt_cmd[1024]; + snprintf(wt_cmd, sizeof(wt_cmd), "worktree add \"%s\" wt-branch", wt_tmp); + if (git_run(main_tmp, wt_cmd) != 0) { + th_rmtree(wt_tmp); + th_rmtree(main_tmp); + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + + bool worktree_detected = cbm_git_is_linked_worktree(wt_tmp); + /* The MAIN checkout of the very same repo must NOT be flagged — otherwise + * enabling ignore_worktrees would stop indexing ordinary repositories. */ + bool main_detected = cbm_git_is_linked_worktree(main_tmp); + + git_run(main_tmp, "worktree prune"); + th_rmtree(main_tmp); + th_rmtree(wt_tmp); + + ASSERT(worktree_detected); + ASSERT(!main_detected); + PASS(); +#endif /* _WIN32 */ +} + +TEST(is_linked_worktree_false_for_submodule_and_nongit) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree test not implemented for Windows"); +#else + char super_tmp[256]; + char *raw = th_mktempdir("cbm_wt_super"); + if (!raw) FAIL("th_mktempdir returned NULL"); + strncpy(super_tmp, raw, sizeof(super_tmp) - 1); + super_tmp[sizeof(super_tmp) - 1] = '\0'; + + char child_tmp[256]; + raw = th_mktempdir("cbm_wt_child"); + if (!raw) FAIL("th_mktempdir returned NULL"); + strncpy(child_tmp, raw, sizeof(child_tmp) - 1); + child_tmp[sizeof(child_tmp) - 1] = '\0'; + + if (make_git_repo(super_tmp) != 0 || make_git_repo(child_tmp) != 0) { + th_rmtree(super_tmp); + th_rmtree(child_tmp); + SKIP_PLATFORM("git not available to init a repo"); + } + + /* A plain directory that is not a git repo at all. */ + char plain[1024]; + snprintf(plain, sizeof(plain), "%s/plain", super_tmp); + if (th_mkdir_p(plain) != 0) { + th_rmtree(super_tmp); + th_rmtree(child_tmp); + FAIL("failed to create plain dir"); + } + bool plain_detected = cbm_git_is_linked_worktree(plain); + + /* file:// submodules are refused by default since the CVE-2022-39253 fix. */ + char sub_cmd[1024]; + snprintf(sub_cmd, sizeof(sub_cmd), + "-c protocol.file.allow=always submodule add -q \"%s\" subm", child_tmp); + int sub_rc = git_run(super_tmp, sub_cmd); + + char subm[1024]; + snprintf(subm, sizeof(subm), "%s/subm", super_tmp); + bool submodule_detected = sub_rc == 0 && cbm_git_is_linked_worktree(subm); + + th_rmtree(super_tmp); + th_rmtree(child_tmp); + + ASSERT(!plain_detected); + if (sub_rc != 0) { + SKIP_PLATFORM("git submodule add unavailable in this environment"); + } + /* A submodule gitlink has no commondir → must not be treated as a worktree. */ + ASSERT(!submodule_detected); + PASS(); +#endif /* _WIN32 */ +} + /* ── Suite ──────────────────────────────────────────────────────── */ SUITE(git_context) { RUN_TEST(canonical_root_repo_root); RUN_TEST(canonical_root_subdir); RUN_TEST(canonical_root_linked_worktree); + RUN_TEST(is_linked_worktree_true_for_linked_worktree); + RUN_TEST(is_linked_worktree_false_for_submodule_and_nongit); } diff --git a/tests/test_mcp.c b/tests/test_mcp.c index ffa9ea3a3..787b26e2e 100644 --- a/tests/test_mcp.c +++ b/tests/test_mcp.c @@ -19278,6 +19278,291 @@ TEST(mcp_auto_watch_false_skips_watcher_on_connect) { PASS(); } +/* ═══════════════════════════════════════════════════════════════ + * ignore_worktrees — explicit index_repository on a linked worktree + * ═══════════════════════════════════════════════════════════════ */ + +/* An EXPLICIT index_repository call is refused only when ignore_worktrees is on + * AND repo_path is a linked worktree AND no per-call override was passed. The + * refusal must never fire for the MAIN checkout — that would break ordinary + * indexing for anyone enabling the key — and index_worktree=true must escape it. + * + * Default-off is the regression class the project guards hardest: with the key + * unset, a linked worktree still indexes exactly as today. + * + * Probe returns a bit set, or a negative fixture-setup code. */ +enum { + IGNORE_WT_REFUSED_WORKTREE = 1, /* expected when the key is on */ + IGNORE_WT_REFUSED_MAIN = 2, /* BUG if set */ + IGNORE_WT_REFUSED_OVERRIDE = 4, /* BUG if set */ +}; + +#ifndef _WIN32 +typedef struct { + char cache[256]; + char main_repo[512]; + char wt_repo[512]; +} ignore_wt_fixture_t; + +static void ignore_wt_fixture_cleanup(ignore_wt_fixture_t *fx) { + if (!fx) { + return; + } + if (fx->main_repo[0]) { + char prune[1024]; + snprintf(prune, sizeof(prune), "git -C \"%s\" worktree prune >/dev/null 2>&1", fx->main_repo); + (void)system(prune); + } + if (fx->cache[0]) { + th_rmtree(fx->cache); + } +} + +/* 0 = ready. -1 tmpdir, -2 mkdir, -3 git worktree fixture unavailable. */ +static int ignore_wt_fixture_setup(ignore_wt_fixture_t *fx) { + memset(fx, 0, sizeof(*fx)); + char *raw = th_mktempdir("cbm_ignorewt"); + if (!raw) { + return -1; + } + snprintf(fx->cache, sizeof(fx->cache), "%s", raw); + snprintf(fx->main_repo, sizeof(fx->main_repo), "%s/main", fx->cache); + snprintf(fx->wt_repo, sizeof(fx->wt_repo), "%s/wt", fx->cache); + if (th_mkdir_p(fx->main_repo) != 0) { + ignore_wt_fixture_cleanup(fx); + return -2; + } + + char cmd[2048]; + snprintf(cmd, sizeof(cmd), + "git -C \"%s\" init -q >/dev/null 2>&1 && " + "git -C \"%s\" config user.email t@example.com && " + "git -C \"%s\" config user.name T && touch \"%s/.keep\" && " + "git -C \"%s\" add .keep && git -C \"%s\" commit -q -m init && " + "git -C \"%s\" worktree add -q \"%s\" -b wtb", + fx->main_repo, fx->main_repo, fx->main_repo, fx->main_repo, fx->main_repo, + fx->main_repo, fx->main_repo, fx->wt_repo); + if (system(cmd) != 0) { + ignore_wt_fixture_cleanup(fx); + return -3; + } + return 0; +} + +static bool ignore_wt_refused(cbm_mcp_server_t *srv, const char *repo_path, bool override) { + char args[2048]; + snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"%s}", repo_path, + override ? ",\"index_worktree\":true" : ""); + char *result = cbm_mcp_handle_tool(srv, "index_repository", args); + bool refused = result && strstr(result, "ignore_worktrees is enabled") != NULL; + free(result); + return refused; +} + +static int ignore_worktrees_index_probe(const char *ignore_value) { + ignore_wt_fixture_t fx; + int setup = ignore_wt_fixture_setup(&fx); + if (setup < 0) { + return setup; + } + + const char *saved = getenv("CBM_CACHE_DIR"); + char *saved_copy = saved ? strdup(saved) : NULL; + cbm_setenv("CBM_CACHE_DIR", fx.cache, 1); + + int bits = -4; + cbm_config_t *cfg = cbm_config_open(fx.cache); + if (cfg) { + if (ignore_value) { + cbm_config_set(cfg, CBM_CONFIG_IGNORE_WORKTREES, ignore_value); + } + cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL); + if (srv) { + cbm_mcp_server_set_config(srv, cfg); + bits = 0; + if (ignore_wt_refused(srv, fx.wt_repo, false)) { + bits |= IGNORE_WT_REFUSED_WORKTREE; + } + if (ignore_wt_refused(srv, fx.main_repo, false)) { + bits |= IGNORE_WT_REFUSED_MAIN; + } + if (ignore_wt_refused(srv, fx.wt_repo, true)) { + bits |= IGNORE_WT_REFUSED_OVERRIDE; + } + cbm_mcp_server_free(srv); + } + cbm_config_close(cfg); + } + + restore_cache_dir(saved_copy); + free(saved_copy); + ignore_wt_fixture_cleanup(&fx); + return bits; +} + +#ifdef CBM_ENABLE_TEST_SEAMS +static void ignore_wt_count_started(void *context) { + int *calls = context; + (*calls)++; +} + +/* Drive initialize → maybe_auto_index on a linked worktree. ignore_value NULL + * leaves the key unset (default-off). The count hook fires only if auto-index + * reaches discovery, so a skip for linked_worktree must leave it at 0. */ +static int ignore_wt_autoindex_count_calls(const char *session_root, const char *ignore_value) { + char *raw = th_mktempdir("cbm_ignorewt_auto"); + if (!raw) { + return -1; + } + char cache[256]; + snprintf(cache, sizeof(cache), "%s", raw); + + const char *saved = getenv("CBM_CACHE_DIR"); + char *saved_copy = saved ? strdup(saved) : NULL; + cbm_setenv("CBM_CACHE_DIR", cache, 1); + + char old_cwd[1024]; + if (!cbm_getcwd(old_cwd, sizeof(old_cwd)) || cbm_chdir(session_root) != 0) { + restore_cache_dir(saved_copy); + free(saved_copy); + th_cleanup(cache); + return -2; + } + + int calls = -3; + cbm_config_t *cfg = cbm_config_open(cache); + cbm_mcp_server_t *srv = cfg ? cbm_mcp_server_new(NULL) : NULL; + if (srv) { + cbm_config_set(cfg, CBM_CONFIG_AUTO_INDEX, "true"); + /* Fail-closed on the actual count so this never launches an index thread. */ + cbm_config_set(cfg, CBM_CONFIG_AUTO_INDEX_LIMIT, "-1"); + if (ignore_value) { + cbm_config_set(cfg, CBM_CONFIG_IGNORE_WORKTREES, ignore_value); + } + cbm_mcp_server_set_config(srv, cfg); + calls = 0; + cbm_mcp_server_set_auto_index_count_test_hook(srv, ignore_wt_count_started, &calls); + char *response = cbm_mcp_server_handle( + srv, "{\"jsonrpc\":\"2.0\",\"id\":1430,\"method\":\"initialize\",\"params\":{}}"); + free(response); + cbm_mcp_server_free(srv); + } + if (cfg) { + cbm_config_close(cfg); + } + + (void)cbm_chdir(old_cwd); + restore_cache_dir(saved_copy); + free(saved_copy); + th_cleanup(cache); + return calls; +} +#endif /* CBM_ENABLE_TEST_SEAMS */ +#endif /* !_WIN32 */ + +TEST(mcp_ignore_worktrees_gates_explicit_index_repository) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree fixture not implemented for Windows"); +#else + int bits = ignore_worktrees_index_probe("true"); + if (bits == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (bits == -2) { + FAIL("failed to create ignore_worktrees fixture directory"); + } + if (bits < 0) { + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + /* RED before the gate existed: nothing is ever refused. */ + ASSERT((bits & IGNORE_WT_REFUSED_WORKTREE) != 0); + ASSERT((bits & IGNORE_WT_REFUSED_MAIN) == 0); + ASSERT((bits & IGNORE_WT_REFUSED_OVERRIDE) == 0); + PASS(); +#endif /* _WIN32 */ +} + +/* Default-off pin: key unset, linked worktree still indexes. The gate is + * opt-in; an unset key must be bit-for-bit today's behaviour. */ +TEST(mcp_ignore_worktrees_default_off_still_indexes_worktree) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree fixture not implemented for Windows"); +#else + int bits = ignore_worktrees_index_probe(NULL); + if (bits == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (bits == -2) { + FAIL("failed to create ignore_worktrees fixture directory"); + } + if (bits < 0) { + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + ASSERT((bits & IGNORE_WT_REFUSED_WORKTREE) == 0); + ASSERT((bits & IGNORE_WT_REFUSED_MAIN) == 0); + ASSERT((bits & IGNORE_WT_REFUSED_OVERRIDE) == 0); + PASS(); +#endif /* _WIN32 */ +} + +#ifdef CBM_ENABLE_TEST_SEAMS +TEST(mcp_ignore_worktrees_skips_auto_index_on_linked_worktree) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree fixture not implemented for Windows"); +#else + ignore_wt_fixture_t fx; + int setup = ignore_wt_fixture_setup(&fx); + if (setup == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (setup == -2) { + FAIL("failed to create ignore_worktrees fixture directory"); + } + if (setup < 0) { + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + int calls = ignore_wt_autoindex_count_calls(fx.wt_repo, "true"); + ignore_wt_fixture_cleanup(&fx); + if (calls == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (calls < 0) { + FAIL("ignore_worktrees auto-index fixture failed"); + } + ASSERT_EQ(calls, 0); + PASS(); +#endif /* _WIN32 */ +} + +TEST(mcp_ignore_worktrees_default_off_auto_index_reaches_count) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree fixture not implemented for Windows"); +#else + ignore_wt_fixture_t fx; + int setup = ignore_wt_fixture_setup(&fx); + if (setup == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (setup == -2) { + FAIL("failed to create ignore_worktrees fixture directory"); + } + if (setup < 0) { + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + int calls = ignore_wt_autoindex_count_calls(fx.wt_repo, NULL); + ignore_wt_fixture_cleanup(&fx); + if (calls == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (calls < 0) { + FAIL("ignore_worktrees auto-index fixture failed"); + } + ASSERT_EQ(calls, 1); + PASS(); +#endif /* _WIN32 */ +} +#endif /* CBM_ENABLE_TEST_SEAMS */ + /* ══════════════════════════════════════════════════════════════════ * #1466 / #713 — the auto_index_limit guard * @@ -20766,6 +21051,13 @@ SUITE(mcp) { RUN_TEST(autoindex_limit_guards_non_git_root_issue713); RUN_TEST(autoindex_limit_admits_non_git_root_under_limit_issue713); RUN_TEST(autoindex_limit_guards_git_root_issue713); + /* ignore_worktrees gate */ + RUN_TEST(mcp_ignore_worktrees_gates_explicit_index_repository); + RUN_TEST(mcp_ignore_worktrees_default_off_still_indexes_worktree); +#ifdef CBM_ENABLE_TEST_SEAMS + RUN_TEST(mcp_ignore_worktrees_skips_auto_index_on_linked_worktree); + RUN_TEST(mcp_ignore_worktrees_default_off_auto_index_reaches_count); +#endif } /* Kept separate so daemon-coordination regressions can be iterated without From 3aec07ea3705700a1eba71321f1eb76c435a4d1d Mon Sep 17 00:00:00 2001 From: Amir Fathi Date: Mon, 14 Sep 2026 14:08:49 +0000 Subject: [PATCH 03/32] fix(daemon): stop the lifetime-lock probe from dropping a held lock posix_lifetime_lock_probe opened a throwaway fd on the lock file to confirm an already-claimed lock, then closed it. fcntl(2) record locks are scoped to (process, inode), so that close silently released the real lock too, even though the reservation's own fd stayed open. Check the in-process claim before opening anything and return early; that branch only ever needed to trust the registry. Signed-off-by: Amir Fathi --- src/daemon/ipc.c | 13 +++-- tests/test_daemon_ipc.c | 104 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 4 deletions(-) diff --git a/src/daemon/ipc.c b/src/daemon/ipc.c index 3917a7a05..e3dbe0aff 100644 --- a/src/daemon/ipc.c +++ b/src/daemon/ipc.c @@ -1205,6 +1205,15 @@ static int posix_lifetime_lock_probe(const cbm_daemon_ipc_endpoint_t *endpoint, if (process_claimed < 0) { return -1; } + if (process_claimed == 1) { + /* Already held by this process per the in-process registry: trust + * that alone. Opening a throwaway fd on the lock file here and then + * closing it would release the real fcntl(2) record lock, which is + * scoped to (process, inode) rather than (fd, inode): closing any + * fd on this inode drops every lock this process holds on it, even + * one held via a different, still-open fd. */ + return endpoint_runtime_still_valid(endpoint) ? 1 : -1; + } int fd = openat(endpoint->dir_fd, lock_name, O_RDWR | O_CLOEXEC | O_NOFOLLOW); if (fd < 0) { @@ -1216,10 +1225,6 @@ static int posix_lifetime_lock_probe(const cbm_daemon_ipc_endpoint_t *endpoint, (void)close(fd); return -1; } - if (process_claimed == 1) { - bool still_private = endpoint_runtime_still_valid(endpoint); - return close(fd) == 0 && still_private ? 1 : -1; - } struct flock record_lock = { .l_type = F_WRLCK, .l_whence = SEEK_SET, diff --git a/tests/test_daemon_ipc.c b/tests/test_daemon_ipc.c index 815f630a6..ce034dd11 100644 --- a/tests/test_daemon_ipc.c +++ b/tests/test_daemon_ipc.c @@ -3365,6 +3365,109 @@ TEST(daemon_ipc_posix_lifetime_reservation_rejects_fork_inheritance) { PASS(); } +static bool ipc_test_lifetime_lock_path(char out[TEST_PATH_CAP], const char *runtime_dir, + const char *key) { + int written = runtime_dir && key + ? snprintf(out, TEST_PATH_CAP, "%s/cbm-%s.lifetime.lock", runtime_dir, key) + : -1; + return written > 0 && written < TEST_PATH_CAP; +} + +TEST(daemon_ipc_posix_lifetime_reservation_probe_does_not_drop_held_lock) { + static const char key[] = "c1c1d2d2e3e3f4f4"; + char parent[TEST_PATH_CAP] = {0}; + char runtime_dir[TEST_PATH_CAP] = {0}; + char lock_path[TEST_PATH_CAP] = {0}; + cbm_daemon_ipc_endpoint_t *endpoint = NULL; + cbm_daemon_ipc_lifetime_reservation_t *reservation = NULL; + int result_pipe[2] = {-1, -1}; + pid_t child = -1; + uint8_t child_result = 0; + int child_status = -1; + int acquired = -1; + int held_after_first_probe = -1; + int held_after_second_probe = -1; + int free_after_release = -1; + bool lock_path_ok = false; + + if (ipc_test_parent_new(parent, "probe-holds-lock")) { + endpoint = cbm_daemon_ipc_endpoint_new(key, parent); + } + if (endpoint) { + ipc_test_copy_path(runtime_dir, cbm_daemon_ipc_endpoint_runtime_dir(endpoint)); + lock_path_ok = ipc_test_lifetime_lock_path(lock_path, runtime_dir, key); + acquired = cbm_daemon_ipc_lifetime_reservation_try_acquire(endpoint, &reservation); + } + if (reservation) { + /* Two probes, matching how a real daemon polls its own reservation + * repeatedly while running. Each probe of an already-held lock used + * to open a throwaway fd on the lock file and close it. Since + * fcntl(2) record locks are scoped to (process, inode), that close + * silently released the real lock every time, regardless of the + * still-open fd the reservation itself is holding. */ + held_after_first_probe = cbm_daemon_ipc_lifetime_reservation_probe(endpoint); + held_after_second_probe = cbm_daemon_ipc_lifetime_reservation_probe(endpoint); + } + if (reservation && lock_path_ok && pipe(result_pipe) == 0) { + child = fork(); + } + if (child == 0) { + /* A genuinely independent process, not going through any of this + * codebase's APIs so it cannot inherit the parent's in-process + * claim registry: try to take the real OS-level lock directly. If + * the parent's fcntl lock survived the probes above, this fails. */ + (void)close(result_pipe[0]); + int fd = open(lock_path, O_RDWR); + struct flock record_lock = { + .l_type = F_WRLCK, + .l_whence = SEEK_SET, + .l_start = 0, + .l_len = 0, + }; + int lock_result = fd >= 0 ? fcntl(fd, F_SETLK, &record_lock) : -1; + child_result = lock_result == 0 ? 1 : 0; + if (fd >= 0) { + (void)close(fd); + } + bool reported = ipc_test_fd_write_all(result_pipe[1], &child_result, sizeof(child_result)); + (void)close(result_pipe[1]); + _exit(reported ? 0 : 1); + } + if (child > 0) { + (void)close(result_pipe[1]); + result_pipe[1] = -1; + bool received = ipc_test_fd_read_all(result_pipe[0], &child_result, sizeof(child_result)); + (void)close(result_pipe[0]); + result_pipe[0] = -1; + if (!received) { + child_result = 2; + } + while (waitpid(child, &child_status, 0) < 0 && errno == EINTR) {} + } + cbm_daemon_ipc_lifetime_reservation_release(reservation); + if (endpoint) { + free_after_release = cbm_daemon_ipc_lifetime_reservation_probe(endpoint); + } + for (size_t index = 0; index < 2; index++) { + if (result_pipe[index] >= 0) { + (void)close(result_pipe[index]); + } + } + cbm_daemon_ipc_endpoint_free(endpoint); + ipc_test_remove_tree(runtime_dir, parent); + + ASSERT_EQ(acquired, 1); + ASSERT_TRUE(lock_path_ok); + ASSERT_EQ(held_after_first_probe, 1); + ASSERT_EQ(held_after_second_probe, 1); + ASSERT_GT(child, 0); + ASSERT_TRUE(WIFEXITED(child_status)); + ASSERT_EQ(WEXITSTATUS(child_status), 0); + ASSERT_EQ(child_result, 0); + ASSERT_EQ(free_after_release, 0); + PASS(); +} + TEST(daemon_ipc_posix_child_participant_handoff_retains_legacy_bridge) { #ifdef _WIN32 PASS(); @@ -5524,6 +5627,7 @@ SUITE(daemon_ipc) { #endif RUN_TEST(daemon_ipc_posix_startup_lock_is_cross_process); RUN_TEST(daemon_ipc_posix_lifetime_reservation_rejects_fork_inheritance); + RUN_TEST(daemon_ipc_posix_lifetime_reservation_probe_does_not_drop_held_lock); RUN_TEST(daemon_ipc_posix_child_participant_handoff_retains_legacy_bridge); RUN_TEST(daemon_ipc_posix_publication_boundaries_recover_from_crash); RUN_TEST(daemon_ipc_posix_record_publication_windows_recover_from_crash); From 8bd9d37b156641ecf1c82b16b0ec0a8246e8c201 Mon Sep 17 00:00:00 2001 From: Amir Fathi Date: Sun, 27 Sep 2026 06:12:08 +0000 Subject: [PATCH 04/32] fix(daemon): stop the lifetime-lock probe from dropping a held lock posix_lifetime_lock_try_acquire opened a throwaway fd on the lock file to confirm an already-claimed lock, then closed it, in both the probe path and the try-acquire-again path. fcntl(2) record locks are scoped to (process, inode), so that close silently released the real lock too, even though the reservation's own fd stayed open. Check the in-process claim before opening anything and return early in both places; neither branch ever needed more than the registry. Also hardens the child-process verdict in the regression test: it now reports held only when open() succeeded and F_SETLK failed with EACCES or EAGAIN, so a wrong path or an unrelated errno can no longer read as a pass. Signed-off-by: Amir Fathi --- src/daemon/ipc.c | 19 ++++-- tests/test_daemon_ipc.c | 140 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 141 insertions(+), 18 deletions(-) diff --git a/src/daemon/ipc.c b/src/daemon/ipc.c index e3dbe0aff..46ed2d514 100644 --- a/src/daemon/ipc.c +++ b/src/daemon/ipc.c @@ -1182,6 +1182,13 @@ static int posix_named_shared_lock_try_acquire(const cbm_daemon_ipc_endpoint_t * return posix_named_lock_try_acquire_mode(endpoint, lock_name, true, fd_out, process_entry_out); } +/* Never open and close the lifetime lock file in a process that may already + * hold it: fcntl(2) record locks are scoped to (process, inode), so that + * close would silently release every lock this process holds on the file, + * regardless of which fd took it. This lock is fcntl rather than flock for + * exactly this reason in reverse: flock locks survive a fork, fcntl locks + * do not, and a forked child must never appear to hold its parent's + * reservation. */ static int posix_record_lock_set(int fd, short lock_type) { struct flock record_lock = { .l_type = lock_type, @@ -1262,11 +1269,13 @@ static int posix_lifetime_lock_try_acquire(const cbm_daemon_ipc_endpoint_t *endp process_lock_entry_t *process_entry = NULL; int process_result = process_lock_claim(endpoint, lock_name, &process_entry); if (process_result != 1) { - return process_result == 0 && - private_regular_file_at_is_safe(endpoint->dir_fd, lock_name, 1) && - endpoint_runtime_still_valid(endpoint) - ? 0 - : -1; + /* Already held by this process per the in-process registry: trust + * that alone, the same as the probe's early return above. Calling + * private_regular_file_at_is_safe() here would open a throwaway fd + * on the lock file and close it, releasing the real fcntl(2) record + * lock this process holds, because that lock is scoped to (process, + * inode) rather than (fd, inode). */ + return process_result == 0 && endpoint_runtime_still_valid(endpoint) ? 0 : -1; } int fd = openat(endpoint->dir_fd, lock_name, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); if (fd < 0 || !fd_set_cloexec(fd)) { diff --git a/tests/test_daemon_ipc.c b/tests/test_daemon_ipc.c index ce034dd11..b5e6c006c 100644 --- a/tests/test_daemon_ipc.c +++ b/tests/test_daemon_ipc.c @@ -3373,6 +3373,46 @@ static bool ipc_test_lifetime_lock_path(char out[TEST_PATH_CAP], const char *run return written > 0 && written < TEST_PATH_CAP; } +/* Child-process verdict on whether the lifetime lock at lock_path is held by + * someone else, going straight through open()/fcntl() rather than any of + * this codebase's APIs, so a genuinely separate process cannot inherit the + * parent's in-process claim registry. Distinguishes three outcomes instead + * of collapsing "held" and "could not even check" into the same value: + * IPC_TEST_LOCK_HELD only when open() succeeded and F_SETLK failed with + * EACCES or EAGAIN (the lock is held by another process, as expected); + * IPC_TEST_LOCK_TAKEN when F_SETLK succeeded (the lock was free, a bug); + * IPC_TEST_LOCK_ERROR for anything else (open() failed, e.g. a wrong path, + * or F_SETLK failed with an errno that says nothing about the lock's + * state), which must never be mistaken for IPC_TEST_LOCK_HELD. */ +enum { + IPC_TEST_LOCK_HELD = 0, + IPC_TEST_LOCK_TAKEN = 1, + IPC_TEST_LOCK_ERROR = 3, +}; + +static uint8_t ipc_test_lock_child_verdict(const char *lock_path) { + int fd = open(lock_path, O_RDWR); + if (fd < 0) { + return IPC_TEST_LOCK_ERROR; + } + struct flock record_lock = { + .l_type = F_WRLCK, + .l_whence = SEEK_SET, + .l_start = 0, + .l_len = 0, + }; + int lock_result; + do { + lock_result = fcntl(fd, F_SETLK, &record_lock); + } while (lock_result != 0 && errno == EINTR); + int lock_errno = errno; + (void)close(fd); + if (lock_result == 0) { + return IPC_TEST_LOCK_TAKEN; + } + return lock_errno == EACCES || lock_errno == EAGAIN ? IPC_TEST_LOCK_HELD : IPC_TEST_LOCK_ERROR; +} + TEST(daemon_ipc_posix_lifetime_reservation_probe_does_not_drop_held_lock) { static const char key[] = "c1c1d2d2e3e3f4f4"; char parent[TEST_PATH_CAP] = {0}; @@ -3417,18 +3457,7 @@ TEST(daemon_ipc_posix_lifetime_reservation_probe_does_not_drop_held_lock) { * claim registry: try to take the real OS-level lock directly. If * the parent's fcntl lock survived the probes above, this fails. */ (void)close(result_pipe[0]); - int fd = open(lock_path, O_RDWR); - struct flock record_lock = { - .l_type = F_WRLCK, - .l_whence = SEEK_SET, - .l_start = 0, - .l_len = 0, - }; - int lock_result = fd >= 0 ? fcntl(fd, F_SETLK, &record_lock) : -1; - child_result = lock_result == 0 ? 1 : 0; - if (fd >= 0) { - (void)close(fd); - } + child_result = ipc_test_lock_child_verdict(lock_path); bool reported = ipc_test_fd_write_all(result_pipe[1], &child_result, sizeof(child_result)); (void)close(result_pipe[1]); _exit(reported ? 0 : 1); @@ -3463,7 +3492,91 @@ TEST(daemon_ipc_posix_lifetime_reservation_probe_does_not_drop_held_lock) { ASSERT_GT(child, 0); ASSERT_TRUE(WIFEXITED(child_status)); ASSERT_EQ(WEXITSTATUS(child_status), 0); - ASSERT_EQ(child_result, 0); + ASSERT_EQ(child_result, IPC_TEST_LOCK_HELD); + ASSERT_EQ(free_after_release, 0); + PASS(); +} + +TEST(daemon_ipc_posix_lifetime_reservation_try_acquire_again_does_not_drop_held_lock) { + static const char key[] = "a1a1b2b2c3c3d4d4"; + char parent[TEST_PATH_CAP] = {0}; + char runtime_dir[TEST_PATH_CAP] = {0}; + char lock_path[TEST_PATH_CAP] = {0}; + cbm_daemon_ipc_endpoint_t *endpoint = NULL; + cbm_daemon_ipc_lifetime_reservation_t *reservation = NULL; + cbm_daemon_ipc_lifetime_reservation_t *second_reservation = + (cbm_daemon_ipc_lifetime_reservation_t *)(uintptr_t)1; + int result_pipe[2] = {-1, -1}; + pid_t child = -1; + uint8_t child_result = 0; + int child_status = -1; + int acquired = -1; + int reacquired = -1; + int free_after_release = -1; + bool lock_path_ok = false; + + if (ipc_test_parent_new(parent, "try-acquire-again-holds-lock")) { + endpoint = cbm_daemon_ipc_endpoint_new(key, parent); + } + if (endpoint) { + ipc_test_copy_path(runtime_dir, cbm_daemon_ipc_endpoint_runtime_dir(endpoint)); + lock_path_ok = ipc_test_lifetime_lock_path(lock_path, runtime_dir, key); + acquired = cbm_daemon_ipc_lifetime_reservation_try_acquire(endpoint, &reservation); + } + if (reservation) { + /* This process already holds the lifetime lock. Calling try_acquire + * again, still in this process, must trust the in-process registry + * alone and return 0 (already held, nothing new to hand back) + * without touching the lock file: opening and closing a second fd + * on it would drop the fcntl(2) record lock this process already + * holds, exactly the way the probe's own fast path used to. */ + reacquired = cbm_daemon_ipc_lifetime_reservation_try_acquire(endpoint, &second_reservation); + } + if (reservation && lock_path_ok && pipe(result_pipe) == 0) { + child = fork(); + } + if (child == 0) { + /* A genuinely independent process, not going through any of this + * codebase's APIs so it cannot inherit the parent's in-process + * claim registry: try to take the real OS-level lock directly. If + * the repeated try_acquire above survived, this fails. */ + (void)close(result_pipe[0]); + child_result = ipc_test_lock_child_verdict(lock_path); + bool reported = ipc_test_fd_write_all(result_pipe[1], &child_result, sizeof(child_result)); + (void)close(result_pipe[1]); + _exit(reported ? 0 : 1); + } + if (child > 0) { + (void)close(result_pipe[1]); + result_pipe[1] = -1; + bool received = ipc_test_fd_read_all(result_pipe[0], &child_result, sizeof(child_result)); + (void)close(result_pipe[0]); + result_pipe[0] = -1; + if (!received) { + child_result = 2; + } + while (waitpid(child, &child_status, 0) < 0 && errno == EINTR) {} + } + cbm_daemon_ipc_lifetime_reservation_release(reservation); + if (endpoint) { + free_after_release = cbm_daemon_ipc_lifetime_reservation_probe(endpoint); + } + for (size_t index = 0; index < 2; index++) { + if (result_pipe[index] >= 0) { + (void)close(result_pipe[index]); + } + } + cbm_daemon_ipc_endpoint_free(endpoint); + ipc_test_remove_tree(runtime_dir, parent); + + ASSERT_EQ(acquired, 1); + ASSERT_TRUE(lock_path_ok); + ASSERT_EQ(reacquired, 0); + ASSERT_TRUE(second_reservation == NULL); + ASSERT_GT(child, 0); + ASSERT_TRUE(WIFEXITED(child_status)); + ASSERT_EQ(WEXITSTATUS(child_status), 0); + ASSERT_EQ(child_result, IPC_TEST_LOCK_HELD); ASSERT_EQ(free_after_release, 0); PASS(); } @@ -5628,6 +5741,7 @@ SUITE(daemon_ipc) { RUN_TEST(daemon_ipc_posix_startup_lock_is_cross_process); RUN_TEST(daemon_ipc_posix_lifetime_reservation_rejects_fork_inheritance); RUN_TEST(daemon_ipc_posix_lifetime_reservation_probe_does_not_drop_held_lock); + RUN_TEST(daemon_ipc_posix_lifetime_reservation_try_acquire_again_does_not_drop_held_lock); RUN_TEST(daemon_ipc_posix_child_participant_handoff_retains_legacy_bridge); RUN_TEST(daemon_ipc_posix_publication_boundaries_recover_from_crash); RUN_TEST(daemon_ipc_posix_record_publication_windows_recover_from_crash); From 1c840df7495e3b71924b8efd7e3bbf53c9076abc Mon Sep 17 00:00:00 2001 From: Amir Fathi Date: Mon, 28 Sep 2026 15:05:48 +0000 Subject: [PATCH 05/32] ci: retrigger after macOS smoke runner cancellation pr-smoke (macos-14) was cancelled mid-run (operation was canceled) at an unrelated UI-server check, with all 30+ other legs green; ci-ok failed only as a consequence. Empty commit to get a fresh run. Signed-off-by: Amir Fathi From 16698e8193fa1dbb53f34f7205569495b3b5fbca Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 4 Aug 2026 07:22:01 -0400 Subject: [PATCH 06/32] feat(config): add ignore_worktrees to skip linked git worktrees Agents that use `git worktree add` to run parallel branches end up with one indexed project per worktree. Each is a near-duplicate of the main checkout, so the cache fills with redundant graphs and project pickers get noisy. Add an opt-in `ignore_worktrees` config key. When enabled, a linked worktree is left alone: - auto-index on connect skips it (logged as autoindex.skip) - the daemon's background auto-index skips it - explicit index_repository refuses with an actionable message naming both ways forward (index_worktree=true, or turn the key off) - the hook-augment "not indexed" guidance stops telling the agent to run index_repository in a directory where it would only be refused Detection is git plumbing, no subprocess: /.git must be a regular file holding a "gitdir:" pointer AND that gitdir must contain a `commondir` file. The commondir check is what separates a linked worktree from a submodule, whose .git is also a gitlink file but whose gitdir has no commondir. The main checkout of a repo that has worktrees is never affected. Defaults to false, so behaviour is unchanged unless the key is set. Signed-off-by: Nohj --- README.md | 3 + docs/CONFIGURATION.md | 30 ++++ src/cli/cli.c | 1 + src/cli/cli.h | 4 +- src/cli/hook_augment.c | 20 ++- src/daemon/application.c | 6 + src/git/git_context.c | 60 ++++++++ src/git/git_context.h | 12 ++ src/mcp/mcp.c | 36 ++++- src/mcp/mcp_internal.h | 5 + tests/test_cli.c | 22 ++- tests/test_git_context.c | 114 +++++++++++++++ tests/test_mcp.c | 292 +++++++++++++++++++++++++++++++++++++++ 13 files changed, 597 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 9c82c18ae..fb4ce7326 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,8 @@ Watcher registration is controlled separately by `auto_watch` (default `true`). To turn the watcher off entirely, set `config set watcher_enabled false` (default `true`): the background poll thread never starts and no project is registered, while `auto_index` and manual `index_repository` keep working. Unlike `auto_watch` — which is consulted per session — `watcher_enabled` is read once when the background daemon starts, so run `codebase-memory-mcp daemon stop` after changing it; reconnecting your MCP client alone will not restart the daemon. See [docs/CONFIGURATION.md](docs/CONFIGURATION.md#2-cli-managed-runtime-settings). +Linked git worktrees are indexed as their own projects by default. Set `config set ignore_worktrees true` to skip them on the automatic paths — useful when short-lived `git worktree add` checkouts would otherwise each leave behind a permanent index of the same repository. An explicit `index_repository` call on a worktree is then refused unless you pass `index_worktree=true`. See [docs/CONFIGURATION.md](docs/CONFIGURATION.md#ignore_worktrees). + ### Keeping Up to Date **Updates run from the install script on every platform, not from inside the running binary.** `codebase-memory-mcp update` validates your flags and then prints the exact command to run: @@ -735,6 +737,7 @@ codebase-memory-mcp config list # show all settings codebase-memory-mcp config set auto_index true # auto-index on session start codebase-memory-mcp config set auto_index_limit 50000 # max files for auto-index codebase-memory-mcp config set auto_watch false # don't register background git watcher (default: true) +codebase-memory-mcp config set ignore_worktrees true # skip linked git worktrees when auto-indexing (default: false) codebase-memory-mcp config set watcher_enabled false # stop the watcher thread entirely (default: true) codebase-memory-mcp config set index_max_files 250000 # optional per-index source-file limit codebase-memory-mcp config set index_max_source_mb 16384 # optional per-index source-size limit diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 038256976..4c27e7f57 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -87,6 +87,7 @@ Current keys: |---|---|---| | `auto_index` | `false` | Automatically index new projects when an MCP session starts. | | `auto_index_limit` | `50000` | Maximum file count allowed for automatic indexing of a new project. | +| `ignore_worktrees` | `false` | Skip linked git worktrees (`git worktree add`) when indexing automatically. | | `auto_watch` | `true` | Register the session's project with the background git watcher on connect. Set `false` to keep a session from registering its project (the watcher still runs for other projects). | | `watcher_enabled` | `true` | Master switch for the background watcher subsystem. Set `false` to stop the watcher from starting at all — no poll thread and no project registration. Reindex manually with `index_repository` when disabled. | | `index_max_files` | `off` | Optional maximum number of accepted source files in one discovery run. | @@ -126,6 +127,35 @@ and preserves any previously serving database. See [Index resource limits](INDEX_RESOURCE_LIMITS.md) for counting, validation, and error-response details. +### `ignore_worktrees` + +Every indexed project is registered under its own absolute root path, so each +linked worktree becomes a separate permanent index. On machines that create many +short-lived worktrees, the automatic paths (`auto_index`, and the session hook's +"index this project first" guidance) turn every throwaway checkout into another +stored index of what is largely the same repository. + +Enable the key to keep those checkouts out of the index: + +```bash +codebase-memory-mcp config set ignore_worktrees true +``` + +With it enabled: + +- automatic indexing skips a session whose root is a linked worktree; +- the `hook-augment` context says the worktree is unindexed on purpose instead + of telling the agent to run `index_repository`; +- an explicit `index_repository` call on a linked worktree is refused, and names + both ways forward — pass `index_worktree=true` for that one call, or turn the + key back off. + +The main checkout of the same repository is unaffected, as are ordinary clones +and submodules. Detection is git plumbing only: a linked worktree's `.git` is a +file pointing at a gitdir that contains a `commondir` entry. + +The default is `false`, so indexing behavior is unchanged unless you opt in. + ## 3. UI Settings The optional built-in graph UI stores its settings in: diff --git a/src/cli/cli.c b/src/cli/cli.c index 6e33759e4..08aded621 100644 --- a/src/cli/cli.c +++ b/src/cli/cli.c @@ -7442,6 +7442,7 @@ static const config_key_def_t CONFIG_KEYS[] = { {CBM_CONFIG_AUTO_INDEX, "false", "Enable auto-indexing on MCP session start"}, {CBM_CONFIG_AUTO_INDEX_LIMIT, "50000", "Max files for auto-indexing new projects"}, {CBM_CONFIG_AUTO_WATCH, "true", "Register background git watcher on session connect"}, + {CBM_CONFIG_IGNORE_WORKTREES, "false", "Skip linked git worktrees when indexing automatically"}, {CBM_CONFIG_WATCHER_ENABLED, "true", "Run the background watcher thread (auto-reindex); false to disable"}, {CBM_CONFIG_UI_LANG, "auto", "Pin graph UI language: en, zh, or auto"}, diff --git a/src/cli/cli.h b/src/cli/cli.h index 5522edef0..a6ef66618 100644 --- a/src/cli/cli.h +++ b/src/cli/cli.h @@ -262,7 +262,8 @@ bool cbm_hook_augment_invocation_supported_for_testing(const char *dialect, const char *forced_event); bool cbm_hook_path_contains_for_testing(const char *root, const char *candidate, bool case_insensitive); -const char *cbm_hook_no_project_index_guidance_for_testing(const char *event); +const char *cbm_hook_no_project_index_guidance_for_testing(const char *event, + bool worktree_ignored); bool cbm_hook_augment_parse_bash_pattern_for_testing(const char *cmd, char *out, size_t out_sz); bool cbm_mcp_command_path_probe_safe_for_testing(const char *command, bool windows); void cbm_set_mcp_command_path_probe_counter_for_testing(int *counter); @@ -443,6 +444,7 @@ bool cbm_config_load_index_policy(cbm_config_t *cfg, cbm_index_resource_policy_t #define CBM_CONFIG_AUTO_INDEX "auto_index" #define CBM_CONFIG_AUTO_INDEX_LIMIT "auto_index_limit" #define CBM_CONFIG_AUTO_WATCH "auto_watch" +#define CBM_CONFIG_IGNORE_WORKTREES "ignore_worktrees" #define CBM_CONFIG_UI_LANG "ui-lang" #define CBM_CONFIG_WATCHER_ENABLED "watcher_enabled" /* #1558: the graph UI's loopback listener. Stored in the UI config file rather diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index f8909c365..1043b48cd 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -21,7 +21,9 @@ #include "foundation/constants.h" #include "foundation/mem.h" #include "foundation/platform.h" +#include "git/git_context.h" #include "mcp/mcp.h" +#include "mcp/mcp_internal.h" #include "pipeline/pipeline.h" #include "yyjson/yyjson.h" @@ -1440,7 +1442,14 @@ static const char *ha_active_tier(yyjson_val *root, const char *event) { return "Tier 2 verification"; } -static const char *ha_no_project_index_guidance(const char *event) { +static const char *ha_no_project_index_guidance(const char *event, bool worktree_ignored) { + /* ignore_worktrees is on and this cwd is a linked worktree: indexing it is + * deliberately disabled, so telling the agent to run index_repository would + * only produce a refusal. Point at the setting instead. */ + if (worktree_ignored) { + return "This is a linked git worktree and ignore_worktrees is enabled, so it is not " + "indexed on purpose; do not run index_repository here."; + } return event && strcmp(event, "SubagentStart") == 0 ? "Ask the parent agent to run index_repository before structural exploration; " "do not attempt graph mutation." @@ -1472,6 +1481,8 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root } const char *cwd = ha_normalized_cwd_with_server(root, srv, cwd_buffer, sizeof(cwd_buffer)); char *project = srv && cwd ? ha_resolve_indexed_project(srv, cwd) : NULL; + bool worktree_ignored = !project && srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && + cbm_git_is_linked_worktree(cwd); cbm_mcp_server_free(owned_server); char context[2048]; @@ -1505,7 +1516,7 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root "and file reads for literals, configs, non-code files, and verification.", scope, safe_project, tier); } else { - const char *index_guidance = ha_no_project_index_guidance(event); + const char *index_guidance = ha_no_project_index_guidance(event, worktree_ignored); snprintf(context, sizeof(context), "[codebase-memory] %s context: no indexed graph project matched this working " "directory. %s Once indexed, " @@ -1624,8 +1635,9 @@ bool cbm_hook_path_contains_for_testing(const char *root, const char *candidate, return ha_path_contains_mode(root, candidate, case_insensitive); } -const char *cbm_hook_no_project_index_guidance_for_testing(const char *event) { - return ha_no_project_index_guidance(event); +const char *cbm_hook_no_project_index_guidance_for_testing(const char *event, + bool worktree_ignored) { + return ha_no_project_index_guidance(event, worktree_ignored); } bool cbm_hook_augment_parse_bash_pattern_for_testing(const char *cmd, char *out, size_t out_sz) { diff --git a/src/daemon/application.c b/src/daemon/application.c index 748b8bb75..8a79ecd5d 100644 --- a/src/daemon/application.c +++ b/src/daemon/application.c @@ -15,6 +15,7 @@ #include "foundation/sha256.h" #include "foundation/subprocess.h" #include "foundation/workspace.h" +#include "git/git_context.h" #include "mcp/index_supervisor.h" #include "mcp/mcp.h" #include "mcp/mcp_internal.h" @@ -2071,6 +2072,11 @@ static void application_background_initialize_impl(cbm_daemon_application_sessio !application_session_workspace_allowed(session, "auto_index_discovery")) { auto_index_candidate = false; } + if (auto_index_candidate && cbm_mcp_ignore_worktrees_enabled(session->mcp) && + cbm_git_is_linked_worktree(root_path)) { + cbm_log_info("daemon.autoindex.skipped", "project", project, "reason", "linked_worktree"); + auto_index_candidate = false; + } bool within_auto_index_limit = !auto_index_candidate || cbm_mcp_auto_index_within_file_limit(root_path, auto_index_limit, &tracked_files); diff --git a/src/git/git_context.c b/src/git/git_context.c index 47956562f..cb27c17cf 100644 --- a/src/git/git_context.c +++ b/src/git/git_context.c @@ -100,6 +100,66 @@ static bool path_is_absolute(const char *path) { #endif } +/* Read the "gitdir: " pointer out of a gitlink FILE at /.git. + * Returns false when .git is missing, a directory (ordinary repo), or holds no + * pointer. A relative pointer is resolved against path. */ +static bool read_gitlink_target(const char *path, char *out, size_t out_size) { + char dot_git[GIT_OUTPUT_MAX]; + int n = snprintf(dot_git, sizeof(dot_git), "%s/.git", path); + if (n < 0 || n >= (int)sizeof(dot_git)) { + return false; + } + struct stat st; + if (stat(dot_git, &st) != 0 || !S_ISREG(st.st_mode)) { + return false; + } + + FILE *f = cbm_fopen(dot_git, "r"); + if (!f) { + return false; + } + char line[GIT_OUTPUT_MAX]; + bool got = false; + while (fgets(line, sizeof(line), f)) { + trim_newlines(line); + if (strncmp(line, "gitdir:", 7) != 0) { + continue; + } + const char *value = line + 7; + while (*value == ' ' || *value == '\t') { + value++; + } + if (!value[0]) { + break; + } + int written = path_is_absolute(value) ? snprintf(out, out_size, "%s", value) + : snprintf(out, out_size, "%s/%s", path, value); + got = written > 0 && written < (int)out_size; + break; + } + fclose(f); + return got; +} + +bool cbm_git_is_linked_worktree(const char *path) { + if (!path || !path[0]) { + return false; + } + char git_dir[GIT_OUTPUT_MAX]; + if (!read_gitlink_target(path, git_dir, sizeof(git_dir))) { + return false; + } + /* Only linked worktrees carry /commondir; a submodule gitlink + * points at /.git/modules/, which does not. */ + char commondir[GIT_OUTPUT_MAX]; + int n = snprintf(commondir, sizeof(commondir), "%s/commondir", git_dir); + if (n < 0 || n >= (int)sizeof(commondir)) { + return false; + } + struct stat st; + return stat(commondir, &st) == 0 && S_ISREG(st.st_mode); +} + static char *join_root_relative(const char *root, const char *rel) { if (!root || !root[0]) { return git_strdup(rel); diff --git a/src/git/git_context.h b/src/git/git_context.h index 876309eb6..633e28018 100644 --- a/src/git/git_context.h +++ b/src/git/git_context.h @@ -19,6 +19,18 @@ typedef struct { char *base_sha; } cbm_git_context_t; +/* True when path is the root of a LINKED git worktree (`git worktree add`). + * + * Plumbing-only, no subprocess: /.git must be a regular file holding a + * "gitdir: " pointer AND that gitdir must contain a `commondir` file. + * The commondir check is what separates a linked worktree from a submodule — + * a submodule's .git is also a gitlink file, but its gitdir + * (/.git/modules/) has no commondir entry. + * + * Callers run this on every session start, so it stays fork-free; the richer + * cbm_git_context_resolve() shells out to git and is not usable on that path. */ +bool cbm_git_is_linked_worktree(const char *path); + int cbm_git_context_resolve(const char *path, cbm_git_context_t *out); void cbm_git_context_free(cbm_git_context_t *ctx); char *cbm_git_context_branch_qn(const char *project_name, const cbm_git_context_t *ctx); diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c index 78b8dccf9..41a63273e 100644 --- a/src/mcp/mcp.c +++ b/src/mcp/mcp.c @@ -478,7 +478,10 @@ static const tool_def_t TOOLS[] = { "\"name\":{\"type\":\"string\",\"description\":" "\"Name override; Non-ASCII bytes are encoded; unsafe characters normalized.\"}," "\"persistence\":{\"type\":\"boolean\",\"default\":false,\"description\":" - "\"Write .codebase-memory/graph.db.zst.\"}" + "\"Write .codebase-memory/graph.db.zst.\"}," + "\"index_worktree\":{\"type\":\"boolean\",\"default\":false,\"description\":" + "\"Index repo_path even when it is a linked git worktree and the " + "ignore_worktrees config key is enabled. No effect otherwise.\"}" "},\"required\":[\"repo_path\"]}"}, {"search_graph", @@ -11174,6 +11177,20 @@ static char *handle_index_repository(cbm_mcp_server_t *srv, const char *args) { return cbm_mcp_text_result(boundary_err, true); } + /* ignore_worktrees: an EXPLICIT index_repository call on a linked worktree + * is refused with the two ways forward (per-call override, or turn the + * setting off) rather than silently skipped — a silent success would be + * indistinguishable from a real index to the caller. */ + if (cbm_mcp_ignore_worktrees_enabled(srv) && !cbm_mcp_get_bool_arg(args, "index_worktree") && + cbm_git_is_linked_worktree(repo_path)) { + index_args_free(repo_path, mode_str, name_override); + return cbm_mcp_text_result( + "repo_path is a linked git worktree and ignore_worktrees is enabled. Pass " + "index_worktree=true to index it anyway, or run: codebase-memory-mcp config set " + "ignore_worktrees false", + true); + } + if (mode_str && strcmp(mode_str, "cross-repo-intelligence") == 0) { char *result = handle_cross_repo_mode(srv, repo_path, name_override, args); index_args_free(repo_path, mode_str, name_override); @@ -17613,6 +17630,17 @@ static bool auto_watch_enabled(cbm_mcp_server_t *srv) { return cbm_config_get_bool(srv->config, CBM_CONFIG_AUTO_WATCH, true); } +/* ignore_worktrees config: gates automatic indexing of LINKED git worktrees + * (default off, so existing setups keep indexing them). Users who create many + * short-lived worktrees can stop each throwaway checkout from registering a + * new permanent project with `config set ignore_worktrees true`. */ +bool cbm_mcp_ignore_worktrees_enabled(const cbm_mcp_server_t *srv) { + if (!srv || !srv->config) { + return false; /* default off */ + } + return cbm_config_get_bool(srv->config, CBM_CONFIG_IGNORE_WORKTREES, false); +} + /* Register the session project with the background watcher for ongoing * change detection — unless auto_watch is disabled. */ static void register_watcher_if_enabled(cbm_mcp_server_t *srv) { @@ -17765,6 +17793,12 @@ static void maybe_auto_index(cbm_mcp_server_t *srv) { return; } + if (cbm_mcp_ignore_worktrees_enabled(srv) && cbm_git_is_linked_worktree(srv->session_root)) { + cbm_log_info("autoindex.skip", "reason", "linked_worktree", "project", + srv->session_project); + return; + } + /* Quick tracked-file count check to avoid OOM on massive repos. */ int file_count = -1; #ifdef CBM_ENABLE_TEST_SEAMS diff --git a/src/mcp/mcp_internal.h b/src/mcp/mcp_internal.h index de170067a..8e78f9f40 100644 --- a/src/mcp/mcp_internal.h +++ b/src/mcp/mcp_internal.h @@ -63,6 +63,11 @@ const char *cbm_mcp_edge_strategy_class(const char *strategy); bool cbm_mcp_auto_index_within_file_limit(const char *root_path, int file_limit, int *file_count_out); +/* True when the `ignore_worktrees` config key is on for this server (default + * off). Callers pair it with cbm_git_is_linked_worktree() to decide whether an + * automatic index of a linked worktree should be skipped. */ +bool cbm_mcp_ignore_worktrees_enabled(const cbm_mcp_server_t *srv); + /* detect_changes seed scoping (#1363): does `node`'s line range overlap any * recorded hunk for `file`? Exposed for direct unit testing of the overlap * logic, independent of the git/subprocess/index plumbing around it. */ diff --git a/tests/test_cli.c b/tests/test_cli.c index 7cd44244e..14553ef68 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -12536,14 +12536,18 @@ TEST(cli_hook_augment_subagent_tier_router_contract) { } TEST(cli_hook_augment_subagent_no_project_guidance_is_read_only) { - const char *session = cbm_hook_no_project_index_guidance_for_testing("SessionStart"); - const char *subagent = cbm_hook_no_project_index_guidance_for_testing("SubagentStart"); + const char *session = cbm_hook_no_project_index_guidance_for_testing("SessionStart", false); + const char *subagent = cbm_hook_no_project_index_guidance_for_testing("SubagentStart", false); + const char *worktree = cbm_hook_no_project_index_guidance_for_testing("SessionStart", true); ASSERT_NOT_NULL(session); ASSERT_NOT_NULL(subagent); + ASSERT_NOT_NULL(worktree); ASSERT(strstr(session, "Run index_repository") != NULL); ASSERT(strstr(subagent, "Ask the parent agent to run index_repository") != NULL); ASSERT(strstr(subagent, "do not attempt graph mutation") != NULL); ASSERT(strstr(subagent, "Run index_repository") == NULL); + ASSERT(strstr(worktree, "ignore_worktrees is enabled") != NULL); + ASSERT(strstr(worktree, "do not run index_repository") != NULL); PASS(); } @@ -15941,6 +15945,19 @@ TEST(cli_ui_config_keys_are_discoverable_and_settable_issue1558) { PASS(); } +TEST(cli_ignore_worktrees_config_key_is_discoverable) { + bool listed = false; + for (size_t i = 0; i < cbm_cli_config_key_count_for_testing(); i++) { + const char *key = cbm_cli_config_key_at_for_testing(i); + if (key && strcmp(key, CBM_CONFIG_IGNORE_WORKTREES) == 0) { + listed = true; + break; + } + } + ASSERT_TRUE(listed); + PASS(); +} + TEST(cli_skill_frontmatter_scalars_with_colons_are_quoted_issue1554) { const cbm_skill_t *sk = cbm_get_skills(); ASSERT_NOT_NULL(sk); @@ -16374,6 +16391,7 @@ SUITE(cli) { RUN_TEST(cli_update_download_failure_does_not_quiesce_sessions); RUN_TEST(cli_update_already_current_does_not_quiesce_sessions); RUN_TEST(cli_ui_config_keys_are_discoverable_and_settable_issue1558); + RUN_TEST(cli_ignore_worktrees_config_key_is_discoverable); RUN_TEST(cli_skill_frontmatter_scalars_with_colons_are_quoted_issue1554); RUN_TEST(cli_external_manager_detection_needs_positive_evidence_issue1566); RUN_TEST(cli_clients_selector_vocabulary_is_complete_and_strict_issue1558); diff --git a/tests/test_git_context.c b/tests/test_git_context.c index cc94f1d06..894cb68aa 100644 --- a/tests/test_git_context.c +++ b/tests/test_git_context.c @@ -253,6 +253,118 @@ TEST(canonical_root_linked_worktree) { #endif /* _WIN32 */ } +/* ── cbm_git_is_linked_worktree ─────────────────────────────────── */ +/* Detection backing the `ignore_worktrees` config gate. The predicate must be + * TRUE only for a linked worktree (`git worktree add`) — never for the main + * checkout, a plain directory, or a submodule. The submodule case is the one a + * naive "is .git a regular file?" check gets wrong: a submodule's .git is also a + * gitlink file, and it is separated here by the absence of a `commondir` entry + * in the pointed-at gitdir. */ + +TEST(is_linked_worktree_true_for_linked_worktree) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree test not implemented for Windows"); +#else + /* th_mktempdir() returns a static buffer — copy before the second call. */ + char main_tmp[256]; + char *raw = th_mktempdir("cbm_wt_main"); + if (!raw) FAIL("th_mktempdir returned NULL"); + strncpy(main_tmp, raw, sizeof(main_tmp) - 1); + main_tmp[sizeof(main_tmp) - 1] = '\0'; + + char wt_tmp[256]; + raw = th_mktempdir("cbm_wt_linked"); + if (!raw) FAIL("th_mktempdir returned NULL"); + strncpy(wt_tmp, raw, sizeof(wt_tmp) - 1); + wt_tmp[sizeof(wt_tmp) - 1] = '\0'; + th_rmtree(wt_tmp); /* git worktree add creates it */ + + if (make_git_repo(main_tmp) != 0) { + th_rmtree(main_tmp); + SKIP_PLATFORM("git not available to init a repo"); + } + if (git_run(main_tmp, "branch wt-branch") != 0) { + th_rmtree(main_tmp); + FAIL("failed to create branch for worktree"); + } + char wt_cmd[1024]; + snprintf(wt_cmd, sizeof(wt_cmd), "worktree add \"%s\" wt-branch", wt_tmp); + if (git_run(main_tmp, wt_cmd) != 0) { + th_rmtree(wt_tmp); + th_rmtree(main_tmp); + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + + bool worktree_detected = cbm_git_is_linked_worktree(wt_tmp); + /* The MAIN checkout of the very same repo must NOT be flagged — otherwise + * enabling ignore_worktrees would stop indexing ordinary repositories. */ + bool main_detected = cbm_git_is_linked_worktree(main_tmp); + + git_run(main_tmp, "worktree prune"); + th_rmtree(main_tmp); + th_rmtree(wt_tmp); + + ASSERT(worktree_detected); + ASSERT(!main_detected); + PASS(); +#endif /* _WIN32 */ +} + +TEST(is_linked_worktree_false_for_submodule_and_nongit) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree test not implemented for Windows"); +#else + char super_tmp[256]; + char *raw = th_mktempdir("cbm_wt_super"); + if (!raw) FAIL("th_mktempdir returned NULL"); + strncpy(super_tmp, raw, sizeof(super_tmp) - 1); + super_tmp[sizeof(super_tmp) - 1] = '\0'; + + char child_tmp[256]; + raw = th_mktempdir("cbm_wt_child"); + if (!raw) FAIL("th_mktempdir returned NULL"); + strncpy(child_tmp, raw, sizeof(child_tmp) - 1); + child_tmp[sizeof(child_tmp) - 1] = '\0'; + + if (make_git_repo(super_tmp) != 0 || make_git_repo(child_tmp) != 0) { + th_rmtree(super_tmp); + th_rmtree(child_tmp); + SKIP_PLATFORM("git not available to init a repo"); + } + + /* A plain directory that is not a git repo at all. */ + char plain[1024]; + snprintf(plain, sizeof(plain), "%s/plain", super_tmp); + if (th_mkdir_p(plain) != 0) { + th_rmtree(super_tmp); + th_rmtree(child_tmp); + FAIL("failed to create plain dir"); + } + bool plain_detected = cbm_git_is_linked_worktree(plain); + + /* file:// submodules are refused by default since the CVE-2022-39253 fix. */ + char sub_cmd[1024]; + snprintf(sub_cmd, sizeof(sub_cmd), + "-c protocol.file.allow=always submodule add -q \"%s\" subm", child_tmp); + int sub_rc = git_run(super_tmp, sub_cmd); + + char subm[1024]; + snprintf(subm, sizeof(subm), "%s/subm", super_tmp); + bool submodule_detected = sub_rc == 0 && cbm_git_is_linked_worktree(subm); + + th_rmtree(super_tmp); + th_rmtree(child_tmp); + + ASSERT(!plain_detected); + if (sub_rc != 0) { + SKIP_PLATFORM("git submodule add unavailable in this environment"); + } + /* A submodule gitlink has no commondir → must not be treated as a worktree. */ + ASSERT(!submodule_detected); + PASS(); +#endif /* _WIN32 */ +} + /* ── Suite ──────────────────────────────────────────────────────── */ SUITE(git_context) { @@ -260,4 +372,6 @@ SUITE(git_context) { RUN_TEST(canonical_root_repo_root); RUN_TEST(canonical_root_subdir); RUN_TEST(canonical_root_linked_worktree); + RUN_TEST(is_linked_worktree_true_for_linked_worktree); + RUN_TEST(is_linked_worktree_false_for_submodule_and_nongit); } diff --git a/tests/test_mcp.c b/tests/test_mcp.c index 60649f505..b7b1335a1 100644 --- a/tests/test_mcp.c +++ b/tests/test_mcp.c @@ -19335,6 +19335,291 @@ TEST(mcp_auto_watch_false_skips_watcher_on_connect) { PASS(); } +/* ═══════════════════════════════════════════════════════════════ + * ignore_worktrees — explicit index_repository on a linked worktree + * ═══════════════════════════════════════════════════════════════ */ + +/* An EXPLICIT index_repository call is refused only when ignore_worktrees is on + * AND repo_path is a linked worktree AND no per-call override was passed. The + * refusal must never fire for the MAIN checkout — that would break ordinary + * indexing for anyone enabling the key — and index_worktree=true must escape it. + * + * Default-off is the regression class the project guards hardest: with the key + * unset, a linked worktree still indexes exactly as today. + * + * Probe returns a bit set, or a negative fixture-setup code. */ +enum { + IGNORE_WT_REFUSED_WORKTREE = 1, /* expected when the key is on */ + IGNORE_WT_REFUSED_MAIN = 2, /* BUG if set */ + IGNORE_WT_REFUSED_OVERRIDE = 4, /* BUG if set */ +}; + +#ifndef _WIN32 +typedef struct { + char cache[256]; + char main_repo[512]; + char wt_repo[512]; +} ignore_wt_fixture_t; + +static void ignore_wt_fixture_cleanup(ignore_wt_fixture_t *fx) { + if (!fx) { + return; + } + if (fx->main_repo[0]) { + char prune[1024]; + snprintf(prune, sizeof(prune), "git -C \"%s\" worktree prune >/dev/null 2>&1", fx->main_repo); + (void)system(prune); + } + if (fx->cache[0]) { + th_rmtree(fx->cache); + } +} + +/* 0 = ready. -1 tmpdir, -2 mkdir, -3 git worktree fixture unavailable. */ +static int ignore_wt_fixture_setup(ignore_wt_fixture_t *fx) { + memset(fx, 0, sizeof(*fx)); + char *raw = th_mktempdir("cbm_ignorewt"); + if (!raw) { + return -1; + } + snprintf(fx->cache, sizeof(fx->cache), "%s", raw); + snprintf(fx->main_repo, sizeof(fx->main_repo), "%s/main", fx->cache); + snprintf(fx->wt_repo, sizeof(fx->wt_repo), "%s/wt", fx->cache); + if (th_mkdir_p(fx->main_repo) != 0) { + ignore_wt_fixture_cleanup(fx); + return -2; + } + + char cmd[2048]; + snprintf(cmd, sizeof(cmd), + "git -C \"%s\" init -q >/dev/null 2>&1 && " + "git -C \"%s\" config user.email t@example.com && " + "git -C \"%s\" config user.name T && touch \"%s/.keep\" && " + "git -C \"%s\" add .keep && git -C \"%s\" commit -q -m init && " + "git -C \"%s\" worktree add -q \"%s\" -b wtb", + fx->main_repo, fx->main_repo, fx->main_repo, fx->main_repo, fx->main_repo, + fx->main_repo, fx->main_repo, fx->wt_repo); + if (system(cmd) != 0) { + ignore_wt_fixture_cleanup(fx); + return -3; + } + return 0; +} + +static bool ignore_wt_refused(cbm_mcp_server_t *srv, const char *repo_path, bool override) { + char args[2048]; + snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"%s}", repo_path, + override ? ",\"index_worktree\":true" : ""); + char *result = cbm_mcp_handle_tool(srv, "index_repository", args); + bool refused = result && strstr(result, "ignore_worktrees is enabled") != NULL; + free(result); + return refused; +} + +static int ignore_worktrees_index_probe(const char *ignore_value) { + ignore_wt_fixture_t fx; + int setup = ignore_wt_fixture_setup(&fx); + if (setup < 0) { + return setup; + } + + const char *saved = getenv("CBM_CACHE_DIR"); + char *saved_copy = saved ? strdup(saved) : NULL; + cbm_setenv("CBM_CACHE_DIR", fx.cache, 1); + + int bits = -4; + cbm_config_t *cfg = cbm_config_open(fx.cache); + if (cfg) { + if (ignore_value) { + cbm_config_set(cfg, CBM_CONFIG_IGNORE_WORKTREES, ignore_value); + } + cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL); + if (srv) { + cbm_mcp_server_set_config(srv, cfg); + bits = 0; + if (ignore_wt_refused(srv, fx.wt_repo, false)) { + bits |= IGNORE_WT_REFUSED_WORKTREE; + } + if (ignore_wt_refused(srv, fx.main_repo, false)) { + bits |= IGNORE_WT_REFUSED_MAIN; + } + if (ignore_wt_refused(srv, fx.wt_repo, true)) { + bits |= IGNORE_WT_REFUSED_OVERRIDE; + } + cbm_mcp_server_free(srv); + } + cbm_config_close(cfg); + } + + restore_cache_dir(saved_copy); + free(saved_copy); + ignore_wt_fixture_cleanup(&fx); + return bits; +} + +#ifdef CBM_ENABLE_TEST_SEAMS +static void ignore_wt_count_started(void *context) { + int *calls = context; + (*calls)++; +} + +/* Drive initialize → maybe_auto_index on a linked worktree. ignore_value NULL + * leaves the key unset (default-off). The count hook fires only if auto-index + * reaches discovery, so a skip for linked_worktree must leave it at 0. */ +static int ignore_wt_autoindex_count_calls(const char *session_root, const char *ignore_value) { + char *raw = th_mktempdir("cbm_ignorewt_auto"); + if (!raw) { + return -1; + } + char cache[256]; + snprintf(cache, sizeof(cache), "%s", raw); + + const char *saved = getenv("CBM_CACHE_DIR"); + char *saved_copy = saved ? strdup(saved) : NULL; + cbm_setenv("CBM_CACHE_DIR", cache, 1); + + char old_cwd[1024]; + if (!cbm_getcwd(old_cwd, sizeof(old_cwd)) || cbm_chdir(session_root) != 0) { + restore_cache_dir(saved_copy); + free(saved_copy); + th_cleanup(cache); + return -2; + } + + int calls = -3; + cbm_config_t *cfg = cbm_config_open(cache); + cbm_mcp_server_t *srv = cfg ? cbm_mcp_server_new(NULL) : NULL; + if (srv) { + cbm_config_set(cfg, CBM_CONFIG_AUTO_INDEX, "true"); + /* Fail-closed on the actual count so this never launches an index thread. */ + cbm_config_set(cfg, CBM_CONFIG_AUTO_INDEX_LIMIT, "-1"); + if (ignore_value) { + cbm_config_set(cfg, CBM_CONFIG_IGNORE_WORKTREES, ignore_value); + } + cbm_mcp_server_set_config(srv, cfg); + calls = 0; + cbm_mcp_server_set_auto_index_count_test_hook(srv, ignore_wt_count_started, &calls); + char *response = cbm_mcp_server_handle( + srv, "{\"jsonrpc\":\"2.0\",\"id\":1430,\"method\":\"initialize\",\"params\":{}}"); + free(response); + cbm_mcp_server_free(srv); + } + if (cfg) { + cbm_config_close(cfg); + } + + (void)cbm_chdir(old_cwd); + restore_cache_dir(saved_copy); + free(saved_copy); + th_cleanup(cache); + return calls; +} +#endif /* CBM_ENABLE_TEST_SEAMS */ +#endif /* !_WIN32 */ + +TEST(mcp_ignore_worktrees_gates_explicit_index_repository) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree fixture not implemented for Windows"); +#else + int bits = ignore_worktrees_index_probe("true"); + if (bits == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (bits == -2) { + FAIL("failed to create ignore_worktrees fixture directory"); + } + if (bits < 0) { + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + /* RED before the gate existed: nothing is ever refused. */ + ASSERT((bits & IGNORE_WT_REFUSED_WORKTREE) != 0); + ASSERT((bits & IGNORE_WT_REFUSED_MAIN) == 0); + ASSERT((bits & IGNORE_WT_REFUSED_OVERRIDE) == 0); + PASS(); +#endif /* _WIN32 */ +} + +/* Default-off pin: key unset, linked worktree still indexes. The gate is + * opt-in; an unset key must be bit-for-bit today's behaviour. */ +TEST(mcp_ignore_worktrees_default_off_still_indexes_worktree) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree fixture not implemented for Windows"); +#else + int bits = ignore_worktrees_index_probe(NULL); + if (bits == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (bits == -2) { + FAIL("failed to create ignore_worktrees fixture directory"); + } + if (bits < 0) { + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + ASSERT((bits & IGNORE_WT_REFUSED_WORKTREE) == 0); + ASSERT((bits & IGNORE_WT_REFUSED_MAIN) == 0); + ASSERT((bits & IGNORE_WT_REFUSED_OVERRIDE) == 0); + PASS(); +#endif /* _WIN32 */ +} + +#ifdef CBM_ENABLE_TEST_SEAMS +TEST(mcp_ignore_worktrees_skips_auto_index_on_linked_worktree) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree fixture not implemented for Windows"); +#else + ignore_wt_fixture_t fx; + int setup = ignore_wt_fixture_setup(&fx); + if (setup == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (setup == -2) { + FAIL("failed to create ignore_worktrees fixture directory"); + } + if (setup < 0) { + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + int calls = ignore_wt_autoindex_count_calls(fx.wt_repo, "true"); + ignore_wt_fixture_cleanup(&fx); + if (calls == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (calls < 0) { + FAIL("ignore_worktrees auto-index fixture failed"); + } + ASSERT_EQ(calls, 0); + PASS(); +#endif /* _WIN32 */ +} + +TEST(mcp_ignore_worktrees_default_off_auto_index_reaches_count) { +#ifdef _WIN32 + SKIP_PLATFORM("git worktree fixture not implemented for Windows"); +#else + ignore_wt_fixture_t fx; + int setup = ignore_wt_fixture_setup(&fx); + if (setup == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (setup == -2) { + FAIL("failed to create ignore_worktrees fixture directory"); + } + if (setup < 0) { + SKIP_PLATFORM("git worktree add unavailable (git 2.5+ required)"); + } + int calls = ignore_wt_autoindex_count_calls(fx.wt_repo, NULL); + ignore_wt_fixture_cleanup(&fx); + if (calls == -1) { + FAIL("th_mktempdir returned NULL"); + } + if (calls < 0) { + FAIL("ignore_worktrees auto-index fixture failed"); + } + ASSERT_EQ(calls, 1); + PASS(); +#endif /* _WIN32 */ +} +#endif /* CBM_ENABLE_TEST_SEAMS */ + /* ══════════════════════════════════════════════════════════════════ * #1466 / #713 — the auto_index_limit guard * @@ -20824,6 +21109,13 @@ SUITE(mcp) { RUN_TEST(autoindex_limit_guards_non_git_root_issue713); RUN_TEST(autoindex_limit_admits_non_git_root_under_limit_issue713); RUN_TEST(autoindex_limit_guards_git_root_issue713); + /* ignore_worktrees gate */ + RUN_TEST(mcp_ignore_worktrees_gates_explicit_index_repository); + RUN_TEST(mcp_ignore_worktrees_default_off_still_indexes_worktree); +#ifdef CBM_ENABLE_TEST_SEAMS + RUN_TEST(mcp_ignore_worktrees_skips_auto_index_on_linked_worktree); + RUN_TEST(mcp_ignore_worktrees_default_off_auto_index_reaches_count); +#endif } /* Kept separate so daemon-coordination regressions can be iterated without From d63d0e16d18cf46836f0d019a03726bb6a577d16 Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 03:23:24 +0000 Subject: [PATCH 07/32] fix(git): probe worktree gitlinks without stat() Upstream's Unicode path fix dropped stat() from this file because it follows symlinks and rejects non-ASCII paths on Windows. Keep ignore_worktrees detection on cbm_path_info_utf8 so the rebase does not restore that probe. Signed-off-by: Nohj --- src/git/git_context.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/git/git_context.c b/src/git/git_context.c index cb27c17cf..3a3da7acb 100644 --- a/src/git/git_context.c +++ b/src/git/git_context.c @@ -86,6 +86,14 @@ static int git_capture(const char *repo_path, const char *git_args, char **out) return *out ? 0 : CBM_NOT_FOUND; } +/* Regular file, not a directory and not a symlink. Uses the Unicode-safe + * path probe: stat() follows links and rejects non-ASCII paths on Windows, + * which upstream removed from this file in the Unicode repository-path fix. */ +static bool path_is_regular_file(const char *path) { + cbm_path_info_t info; + return cbm_path_info_utf8(path, &info) == CBM_PATH_INFO_OK && info.is_regular; +} + static bool path_is_absolute(const char *path) { if (!path || !path[0]) { return false; @@ -109,8 +117,7 @@ static bool read_gitlink_target(const char *path, char *out, size_t out_size) { if (n < 0 || n >= (int)sizeof(dot_git)) { return false; } - struct stat st; - if (stat(dot_git, &st) != 0 || !S_ISREG(st.st_mode)) { + if (!path_is_regular_file(dot_git)) { return false; } @@ -156,8 +163,7 @@ bool cbm_git_is_linked_worktree(const char *path) { if (n < 0 || n >= (int)sizeof(commondir)) { return false; } - struct stat st; - return stat(commondir, &st) == 0 && S_ISREG(st.st_mode); + return path_is_regular_file(commondir); } static char *join_root_relative(const char *root, const char *rel) { From 3bb85c8c7c3c005fc59bed0a8ee5c467d903a761 Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 03:37:57 +0000 Subject: [PATCH 08/32] fix(daemon): recheck ignore_worktrees on auto-index retry A session queued while capacity was full could still be indexed after the setting was turned on. Retry admission now applies the same linked-worktree gate as the initial path. Signed-off-by: Nohj --- src/daemon/application.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/daemon/application.c b/src/daemon/application.c index 8a79ecd5d..153bc0d81 100644 --- a/src/daemon/application.c +++ b/src/daemon/application.c @@ -1457,6 +1457,18 @@ static void application_auto_index_retry_pending_locked(cbm_daemon_application_t application_refresh_watch_locked(session); continue; } + /* ignore_worktrees can be turned on after this session was queued for + * a capacity slot. Initial admission already skips linked worktrees; + * retry must apply the same gate or the pending checkout is indexed + * once a slot opens. */ + if (cbm_mcp_ignore_worktrees_enabled(session->mcp) && + cbm_git_is_linked_worktree(root_path)) { + session->auto_index_retry_pending = false; + cbm_log_info("daemon.autoindex.skipped", "project", project, "reason", + "linked_worktree"); + application_refresh_watch_locked(session); + continue; + } char *args = application_auto_index_args(application, root_path); if (!args) { continue; From 5d5c9621eb3e94ee26ab39c26b15237fb38223df Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 10:44:02 +0000 Subject: [PATCH 09/32] fix(cli): load runtime config for the hook-augment worktree note The production hook builds its server with cbm_mcp_server_new(NULL), so ignore_worktrees stayed off and an unindexed linked worktree still told the agent to run index_repository. Attach the runtime store for that check, then drop it before return. Signed-off-by: Nohj --- src/cli/hook_augment.c | 14 ++++++++++++++ src/mcp/mcp.c | 12 ++++++++++++ src/mcp/mcp.h | 6 ++++++ tests/test_cli.c | 16 +++++++++++++++- 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index 1043b48cd..a389e487f 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -1475,14 +1475,28 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root char cwd_buffer[4096]; cbm_mcp_server_t *owned_server = NULL; + cbm_config_t *owned_config = NULL; if (!srv) { owned_server = cbm_mcp_server_new(NULL); srv = owned_server; } + /* cbm_mcp_server_new(NULL) does not attach the runtime store. The production + * hook uses that constructor, so ignore_worktrees would stay at its default + * (off) and the "not indexed" note would still tell the agent to run + * index_repository in a linked worktree the setting refuses. Load the store + * only when the caller has not already set one, then drop it before return + * so a caller-owned server is not left pointing at a closed config. */ + if (srv) { + owned_config = cbm_mcp_server_attach_runtime_config(srv); + } const char *cwd = ha_normalized_cwd_with_server(root, srv, cwd_buffer, sizeof(cwd_buffer)); char *project = srv && cwd ? ha_resolve_indexed_project(srv, cwd) : NULL; bool worktree_ignored = !project && srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && cbm_git_is_linked_worktree(cwd); + if (owned_config) { + cbm_mcp_server_set_config(srv, NULL); + cbm_config_close(owned_config); + } cbm_mcp_server_free(owned_server); char context[2048]; diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c index 41a63273e..19083feee 100644 --- a/src/mcp/mcp.c +++ b/src/mcp/mcp.c @@ -1751,6 +1751,18 @@ void cbm_mcp_server_set_config(cbm_mcp_server_t *srv, struct cbm_config *cfg) { } } +struct cbm_config *cbm_mcp_server_attach_runtime_config(cbm_mcp_server_t *srv) { + if (!srv || srv->config) { + return NULL; + } + cbm_config_t *cfg = cbm_config_open(cbm_resolve_cache_dir()); + if (!cfg) { + return NULL; + } + srv->config = cfg; + return cfg; +} + #ifdef CBM_ENABLE_TEST_SEAMS void cbm_mcp_server_set_auto_index_count_test_hook(cbm_mcp_server_t *srv, cbm_mcp_auto_index_count_test_hook_fn hook, diff --git a/src/mcp/mcp.h b/src/mcp/mcp.h index 09befb780..6fb110181 100644 --- a/src/mcp/mcp.h +++ b/src/mcp/mcp.h @@ -158,6 +158,12 @@ void cbm_mcp_server_set_watcher(cbm_mcp_server_t *srv, struct cbm_watcher *w); /* Set external config store reference (for auto_index setting). Not owned. */ void cbm_mcp_server_set_config(cbm_mcp_server_t *srv, struct cbm_config *cfg); +/* Open the runtime config and attach it when srv has none. The returned store + * is owned by the caller, who must clear it with cbm_mcp_server_set_config + * before closing. Returns NULL when a config is already set or the store + * cannot be opened. */ +struct cbm_config *cbm_mcp_server_attach_runtime_config(cbm_mcp_server_t *srv); + /* Set an explicit session context for an embedded/daemon-backed server. * session_root is copied and its project name is derived using the same naming * rule as indexing. allowed_root is copied when non-NULL; an explicit NULL diff --git a/tests/test_cli.c b/tests/test_cli.c index 14553ef68..5d7441ec4 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -10629,9 +10629,21 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}", wtdir); char *wt_out = cbm_hook_augment_lifecycle_json(input); bool deliberate = wt_out && wt_out[0] && strstr(wt_out, "no indexed graph project matched") && - !strstr(wt_out, "is indexed"); + strstr(wt_out, "Run index_repository") && + !strstr(wt_out, "ignore_worktrees is enabled") && !strstr(wt_out, "is indexed"); free(wt_out); + /* The hook must read the runtime store. With the key off the note still + * says to index; with it on, the same unindexed worktree must not. */ + cbm_config_t *cfg = cbm_config_open(cache); + bool configured = cfg && cbm_config_set(cfg, CBM_CONFIG_IGNORE_WORKTREES, "true") == 0; + cbm_config_close(cfg); + char *ignored_out = configured ? cbm_hook_augment_lifecycle_json(input) : NULL; + bool honored = ignored_out && strstr(ignored_out, "ignore_worktrees is enabled") && + strstr(ignored_out, "do not run index_repository") && + !strstr(ignored_out, "is indexed"); + free(ignored_out); + snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}", maindir); char *main_out = cbm_hook_augment_lifecycle_json(input); @@ -10647,6 +10659,8 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { if (!deliberate) FAIL("unindexed worktree must get a deliberate no-match notice, never a silent 0 bytes"); + if (!honored) + FAIL("ignore_worktrees in the runtime config must change the unindexed-worktree note"); if (!main_ok) FAIL("the indexed main checkout must still resolve in the same matrix"); PASS(); From 0071007396568b44fb331bb876084dd88a91a415 Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 10:59:57 +0000 Subject: [PATCH 10/32] fix(git): detect linked worktrees from nested directories ignore_worktrees only inspected /.git, so a session or index path inside a linked worktree still passed the gate. Walk ancestors until a git anchor, and stop at a main checkout or a submodule. Signed-off-by: Nohj --- src/git/git_context.c | 87 +++++++++++++++++++++++++++++++++++++--- src/git/git_context.h | 13 +++--- tests/test_git_context.c | 23 ++++++++++- 3 files changed, 110 insertions(+), 13 deletions(-) diff --git a/src/git/git_context.c b/src/git/git_context.c index 3a3da7acb..3fbf5b65d 100644 --- a/src/git/git_context.c +++ b/src/git/git_context.c @@ -148,22 +148,97 @@ static bool read_gitlink_target(const char *path, char *out, size_t out_size) { return got; } -bool cbm_git_is_linked_worktree(const char *path) { - if (!path || !path[0]) { - return false; +/* 1 = linked-worktree gitlink, 0 = a different git anchor (stop walking), + * -1 = no .git at this directory (keep walking). */ +static int linked_worktree_anchor(const char *path) { + char dot_git[GIT_OUTPUT_MAX]; + int n = snprintf(dot_git, sizeof(dot_git), "%s/.git", path); + if (n < 0 || n >= (int)sizeof(dot_git)) { + return 0; + } + cbm_path_info_t info; + if (cbm_path_info_utf8(dot_git, &info) != CBM_PATH_INFO_OK) { + return -1; + } + /* A directory .git is a main checkout. Anything else that is not a + * regular gitlink file (a symlink, for example) is also an anchor: + * do not follow it, and do not blame a parent worktree for this tree. */ + if (!info.is_regular) { + return 0; } char git_dir[GIT_OUTPUT_MAX]; if (!read_gitlink_target(path, git_dir, sizeof(git_dir))) { - return false; + return 0; } /* Only linked worktrees carry /commondir; a submodule gitlink * points at /.git/modules/, which does not. */ char commondir[GIT_OUTPUT_MAX]; - int n = snprintf(commondir, sizeof(commondir), "%s/commondir", git_dir); + n = snprintf(commondir, sizeof(commondir), "%s/commondir", git_dir); if (n < 0 || n >= (int)sizeof(commondir)) { + return 0; + } + return path_is_regular_file(commondir) ? 1 : 0; +} + +static bool parent_directory(char *path) { + size_t n = strlen(path); + while (n > 1 && (path[n - 1] == '/' || path[n - 1] == '\\')) { + path[--n] = '\0'; + } +#ifdef _WIN32 + if ((n == 2 && path[1] == ':') || + (n == 3 && path[1] == ':' && (path[2] == '/' || path[2] == '\\'))) { return false; } - return path_is_regular_file(commondir); +#endif + if (n <= 1) { + return false; + } + char *slash = NULL; + for (size_t i = 0; i < n; i++) { + if (path[i] == '/' || path[i] == '\\') { + slash = path + i; + } + } + if (!slash) { + return false; + } + if (slash == path) { + path[1] = '\0'; + return true; + } + *slash = '\0'; + return true; +} + +bool cbm_git_is_linked_worktree(const char *path) { + if (!path || !path[0]) { + return false; + } + char current[GIT_OUTPUT_MAX]; + int n = snprintf(current, sizeof(current), "%s", path); + if (n < 0 || n >= (int)sizeof(current)) { + return false; + } + size_t len = strlen(current); + while (len > 1 && (current[len - 1] == '/' || current[len - 1] == '\\')) { + current[--len] = '\0'; + } + /* A session cwd or index_repository path is often a subdirectory. Walk + * ancestors until a git anchor so ignore_worktrees applies to the whole + * linked checkout, not only its root. */ + for (int depth = 0; depth < 64; depth++) { + int kind = linked_worktree_anchor(current); + if (kind >= 0) { + return kind == 1; + } + char previous[GIT_OUTPUT_MAX]; + snprintf(previous, sizeof(previous), "%s", current); + if (!parent_directory(current) || strcmp(previous, current) == 0) { + return false; + } + } + return false; } static char *join_root_relative(const char *root, const char *rel) { diff --git a/src/git/git_context.h b/src/git/git_context.h index 633e28018..30f2f545a 100644 --- a/src/git/git_context.h +++ b/src/git/git_context.h @@ -19,13 +19,14 @@ typedef struct { char *base_sha; } cbm_git_context_t; -/* True when path is the root of a LINKED git worktree (`git worktree add`). +/* True when path is a LINKED git worktree (`git worktree add`) or a + * subdirectory of one. * - * Plumbing-only, no subprocess: /.git must be a regular file holding a - * "gitdir: " pointer AND that gitdir must contain a `commondir` file. - * The commondir check is what separates a linked worktree from a submodule — - * a submodule's .git is also a gitlink file, but its gitdir - * (/.git/modules/) has no commondir entry. + * Plumbing-only, no subprocess. Walk ancestors until a git anchor. A linked + * worktree's /.git is a regular file holding a "gitdir: " pointer + * AND that gitdir contains a `commondir` file. The walk stops at any other + * anchor: a main checkout (`.git` is a directory) or a submodule (gitlink + * file whose gitdir, /.git/modules/, has no commondir). * * Callers run this on every session start, so it stays fork-free; the richer * cbm_git_context_resolve() shells out to git and is not usable on that path. */ diff --git a/tests/test_git_context.c b/tests/test_git_context.c index 894cb68aa..5b3c4b779 100644 --- a/tests/test_git_context.c +++ b/tests/test_git_context.c @@ -296,16 +296,30 @@ TEST(is_linked_worktree_true_for_linked_worktree) { } bool worktree_detected = cbm_git_is_linked_worktree(wt_tmp); + /* A subdirectory has no .git of its own. The predicate must still see the + * linked worktree above it, or ignore_worktrees misses nested sessions. */ + char nested[1024]; + snprintf(nested, sizeof(nested), "%s/nested/deeper", wt_tmp); + bool nested_ok = th_mkdir_p(nested) == 0; + bool nested_detected = nested_ok && cbm_git_is_linked_worktree(nested); /* The MAIN checkout of the very same repo must NOT be flagged — otherwise * enabling ignore_worktrees would stop indexing ordinary repositories. */ bool main_detected = cbm_git_is_linked_worktree(main_tmp); + char main_nested[1024]; + snprintf(main_nested, sizeof(main_nested), "%s/src", main_tmp); + bool main_nested_ok = th_mkdir_p(main_nested) == 0; + bool main_nested_detected = main_nested_ok && cbm_git_is_linked_worktree(main_nested); git_run(main_tmp, "worktree prune"); th_rmtree(main_tmp); th_rmtree(wt_tmp); ASSERT(worktree_detected); + ASSERT(nested_ok); + ASSERT(nested_detected); ASSERT(!main_detected); + ASSERT(main_nested_ok); + ASSERT(!main_nested_detected); PASS(); #endif /* _WIN32 */ } @@ -351,6 +365,10 @@ TEST(is_linked_worktree_false_for_submodule_and_nongit) { char subm[1024]; snprintf(subm, sizeof(subm), "%s/subm", super_tmp); bool submodule_detected = sub_rc == 0 && cbm_git_is_linked_worktree(subm); + char sub_nested[1024]; + snprintf(sub_nested, sizeof(sub_nested), "%s/nested", subm); + bool sub_nested_made = sub_rc == 0 && th_mkdir_p(sub_nested) == 0; + bool sub_nested_detected = sub_nested_made && cbm_git_is_linked_worktree(sub_nested); th_rmtree(super_tmp); th_rmtree(child_tmp); @@ -359,8 +377,11 @@ TEST(is_linked_worktree_false_for_submodule_and_nongit) { if (sub_rc != 0) { SKIP_PLATFORM("git submodule add unavailable in this environment"); } - /* A submodule gitlink has no commondir → must not be treated as a worktree. */ + /* A submodule gitlink has no commondir → must not be treated as a worktree, + * including a subdirectory, which must not walk into the superproject. */ ASSERT(!submodule_detected); + ASSERT(sub_nested_made); + ASSERT(!sub_nested_detected); PASS(); #endif /* _WIN32 */ } From 47c7a07a745c143a499977f920f0f8273cdadc8f Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 11:12:54 +0000 Subject: [PATCH 11/32] fix(cli): do not treat a parent graph as a linked worktree ignore_worktrees checked the setting only after project resolution, so a linked worktree nested in an indexed checkout was reported as that parent project. Drop an ancestor match and keep an index whose root is the worktree itself. Signed-off-by: Nohj --- src/cli/hook_augment.c | 19 ++++++++++++++++--- tests/test_cli.c | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index a389e487f..b08d6ebd1 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -1490,9 +1490,22 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root owned_config = cbm_mcp_server_attach_runtime_config(srv); } const char *cwd = ha_normalized_cwd_with_server(root, srv, cwd_buffer, sizeof(cwd_buffer)); - char *project = srv && cwd ? ha_resolve_indexed_project(srv, cwd) : NULL; - bool worktree_ignored = !project && srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && - cbm_git_is_linked_worktree(cwd); + char project_root[4096]; + project_root[0] = '\0'; + char *project = srv && cwd ? ha_resolve_indexed_project_with_root(srv, cwd, project_root, + sizeof(project_root)) + : NULL; + /* ignore_worktrees refuses a linked worktree, including one nested inside an + * indexed checkout. The ancestor walk would otherwise report that parent + * graph as this cwd's project. An index whose own root is the linked + * worktree (or inside it) still counts. */ + bool ignore_linked = srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && + cbm_git_is_linked_worktree(cwd); + if (ignore_linked && project && !cbm_git_is_linked_worktree(project_root)) { + free(project); + project = NULL; + } + bool worktree_ignored = ignore_linked && !project; if (owned_config) { cbm_mcp_server_set_config(srv, NULL); cbm_config_close(owned_config); diff --git a/tests/test_cli.c b/tests/test_cli.c index 5d7441ec4..6297a64d0 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -10644,6 +10644,41 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { !strstr(ignored_out, "is indexed"); free(ignored_out); + /* A linked worktree nested inside the indexed checkout must not inherit + * that parent graph once ignore_worktrees is on. */ + char insider[512]; + snprintf(insider, sizeof(insider), "%s/inside-wt", maindir); + snprintf(cmd, sizeof(cmd), "cd \"%s\" && git worktree add -q \"%s\" -b agl7inside", maindir, + insider); + bool inside_made = configured && system(cmd) == 0; + char inside_sub[600]; + snprintf(inside_sub, sizeof(inside_sub), "%s/nested", insider); + bool inside_sub_made = inside_made && test_mkdirp(inside_sub) == 0; + snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}", + inside_sub); + char *inside_out = inside_sub_made ? cbm_hook_augment_lifecycle_json(input) : NULL; + bool inside_ignored = inside_out && strstr(inside_out, "ignore_worktrees is enabled") && + strstr(inside_out, "do not run index_repository") && + !strstr(inside_out, "is indexed") && !strstr(inside_out, main_name); + free(inside_out); + + /* Indexing that nested worktree itself must still win over the parent. */ + char *inside_name = inside_made ? cbm_project_name_from_path(insider) : NULL; + bool inside_stored = false; + if (inside_name) { + char db_inside[900]; + snprintf(db_inside, sizeof(db_inside), "%s/%s.db", cache, inside_name); + cbm_store_t *si = cbm_store_open_path(db_inside); + inside_stored = si && cbm_store_upsert_project(si, inside_name, insider) == CBM_STORE_OK; + if (si) + cbm_store_close(si); + } + char *exact_out = inside_stored ? cbm_hook_augment_lifecycle_json(input) : NULL; + bool exact_kept = exact_out && inside_name && strstr(exact_out, inside_name) && + strstr(exact_out, "is indexed") && + !strstr(exact_out, "ignore_worktrees is enabled"); + free(exact_out); + snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}", maindir); char *main_out = cbm_hook_augment_lifecycle_json(input); @@ -10652,6 +10687,7 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { restore_test_env("CBM_CACHE_DIR", saved_cache); free(main_name); + free(inside_name); snprintf(cmd, sizeof(cmd), "cd \"%s\" && git worktree remove --force \"%s\" >/dev/null 2>&1", maindir, wtdir); (void)system(cmd); @@ -10661,6 +10697,10 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { FAIL("unindexed worktree must get a deliberate no-match notice, never a silent 0 bytes"); if (!honored) FAIL("ignore_worktrees in the runtime config must change the unindexed-worktree note"); + if (!inside_ignored) + FAIL("a nested linked worktree must not inherit the indexed parent graph"); + if (!exact_kept) + FAIL("an exact index of the nested worktree must still be reported"); if (!main_ok) FAIL("the indexed main checkout must still resolve in the same matrix"); PASS(); From 51a18c7b27728534ffefd7b2c4963277a91aa176 Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 11:18:45 +0000 Subject: [PATCH 12/32] fix(cli): keep a worktree graph only for that same worktree The parent-graph drop treated any linked worktree root as a match, so an unindexed worktree nested inside an indexed one still inherited that parent. Compare the gitdir of each path's own anchor and keep the project only when both paths are that same linked worktree. Signed-off-by: Nohj --- src/cli/hook_augment.c | 7 +++---- src/git/git_context.c | 37 +++++++++++++++++++++++++++++++++++-- src/git/git_context.h | 6 ++++++ tests/test_cli.c | 21 +++++++++++++++++++++ tests/test_git_context.c | 18 ++++++++++++++++++ 5 files changed, 83 insertions(+), 6 deletions(-) diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index b08d6ebd1..d3baace47 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -1496,12 +1496,11 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root sizeof(project_root)) : NULL; /* ignore_worktrees refuses a linked worktree, including one nested inside an - * indexed checkout. The ancestor walk would otherwise report that parent - * graph as this cwd's project. An index whose own root is the linked - * worktree (or inside it) still counts. */ + * indexed checkout or inside another linked worktree. Keep a match only when + * its root belongs to this cwd's own linked worktree, not a parent graph. */ bool ignore_linked = srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && cbm_git_is_linked_worktree(cwd); - if (ignore_linked && project && !cbm_git_is_linked_worktree(project_root)) { + if (ignore_linked && project && !cbm_git_same_linked_worktree(cwd, project_root)) { free(project); project = NULL; } diff --git a/src/git/git_context.c b/src/git/git_context.c index 3fbf5b65d..8e2629cc4 100644 --- a/src/git/git_context.c +++ b/src/git/git_context.c @@ -211,7 +211,8 @@ static bool parent_directory(char *path) { return true; } -bool cbm_git_is_linked_worktree(const char *path) { +/* On a linked-worktree hit, optionally copy that anchor directory into root_out. */ +static bool walk_linked_worktree_root(const char *path, char *root_out, size_t root_out_size) { if (!path || !path[0]) { return false; } @@ -230,7 +231,16 @@ bool cbm_git_is_linked_worktree(const char *path) { for (int depth = 0; depth < 64; depth++) { int kind = linked_worktree_anchor(current); if (kind >= 0) { - return kind == 1; + if (kind != 1) { + return false; + } + if (root_out && root_out_size > 0U) { + int written = snprintf(root_out, root_out_size, "%s", current); + if (written < 0 || (size_t)written >= root_out_size) { + return false; + } + } + return true; } char previous[GIT_OUTPUT_MAX]; snprintf(previous, sizeof(previous), "%s", current); @@ -241,6 +251,29 @@ bool cbm_git_is_linked_worktree(const char *path) { return false; } +bool cbm_git_is_linked_worktree(const char *path) { + return walk_linked_worktree_root(path, NULL, 0U); +} + +bool cbm_git_same_linked_worktree(const char *a, const char *b) { + char root_a[GIT_OUTPUT_MAX]; + char root_b[GIT_OUTPUT_MAX]; + if (!walk_linked_worktree_root(a, root_a, sizeof(root_a)) || + !walk_linked_worktree_root(b, root_b, sizeof(root_b))) { + return false; + } + /* The gitdir file is unique per linked worktree. Comparing those pointers + * keeps a nested worktree from matching its parent even when both are + * linked checkouts. */ + char git_a[GIT_OUTPUT_MAX]; + char git_b[GIT_OUTPUT_MAX]; + if (!read_gitlink_target(root_a, git_a, sizeof(git_a)) || + !read_gitlink_target(root_b, git_b, sizeof(git_b))) { + return false; + } + return strcmp(git_a, git_b) == 0; +} + static char *join_root_relative(const char *root, const char *rel) { if (!root || !root[0]) { return git_strdup(rel); diff --git a/src/git/git_context.h b/src/git/git_context.h index 30f2f545a..1b9d174f1 100644 --- a/src/git/git_context.h +++ b/src/git/git_context.h @@ -32,6 +32,12 @@ typedef struct { * cbm_git_context_resolve() shells out to git and is not usable on that path. */ bool cbm_git_is_linked_worktree(const char *path); +/* True when both paths sit in the same linked worktree. Identity is the + * gitdir pointer of each path's linked-worktree anchor, so a worktree nested + * inside another does not count as that parent. False when either path is not + * inside a linked worktree. */ +bool cbm_git_same_linked_worktree(const char *a, const char *b); + int cbm_git_context_resolve(const char *path, cbm_git_context_t *out); void cbm_git_context_free(cbm_git_context_t *ctx); char *cbm_git_context_branch_qn(const char *project_name, const cbm_git_context_t *ctx); diff --git a/tests/test_cli.c b/tests/test_cli.c index 6297a64d0..e234d77df 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -10679,6 +10679,25 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { !strstr(exact_out, "ignore_worktrees is enabled"); free(exact_out); + /* An unindexed worktree nested inside that indexed worktree must not + * inherit the outer worktree's graph. */ + char child[600]; + snprintf(child, sizeof(child), "%s/child-wt", insider); + snprintf(cmd, sizeof(cmd), "cd \"%s\" && git worktree add -q \"%s\" -b agl7child", maindir, + child); + bool child_made = inside_stored && system(cmd) == 0; + char child_sub[700]; + snprintf(child_sub, sizeof(child_sub), "%s/sub", child); + bool child_sub_made = child_made && test_mkdirp(child_sub) == 0; + snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}", + child_sub); + char *child_out = child_sub_made ? cbm_hook_augment_lifecycle_json(input) : NULL; + bool child_ignored = child_out && inside_name && + strstr(child_out, "ignore_worktrees is enabled") && + strstr(child_out, "do not run index_repository") && + !strstr(child_out, "is indexed") && !strstr(child_out, inside_name); + free(child_out); + snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}", maindir); char *main_out = cbm_hook_augment_lifecycle_json(input); @@ -10701,6 +10720,8 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { FAIL("a nested linked worktree must not inherit the indexed parent graph"); if (!exact_kept) FAIL("an exact index of the nested worktree must still be reported"); + if (!child_ignored) + FAIL("a worktree nested inside an indexed worktree must not inherit that graph"); if (!main_ok) FAIL("the indexed main checkout must still resolve in the same matrix"); PASS(); diff --git a/tests/test_git_context.c b/tests/test_git_context.c index 5b3c4b779..10cab0009 100644 --- a/tests/test_git_context.c +++ b/tests/test_git_context.c @@ -309,6 +309,19 @@ TEST(is_linked_worktree_true_for_linked_worktree) { snprintf(main_nested, sizeof(main_nested), "%s/src", main_tmp); bool main_nested_ok = th_mkdir_p(main_nested) == 0; bool main_nested_detected = main_nested_ok && cbm_git_is_linked_worktree(main_nested); + /* A worktree nested inside another must not share the parent's anchor. */ + char inner[1024]; + snprintf(inner, sizeof(inner), "%s/inner-wt", wt_tmp); + char inner_cmd[1200]; + snprintf(inner_cmd, sizeof(inner_cmd), "worktree add -b inner-branch \"%s\"", inner); + bool inner_added = git_run(main_tmp, inner_cmd) == 0; + char inner_sub[1200]; + snprintf(inner_sub, sizeof(inner_sub), "%s/sub", inner); + bool inner_sub_ok = inner_added && th_mkdir_p(inner_sub) == 0; + bool same_outer = cbm_git_same_linked_worktree(nested, wt_tmp); + bool same_inner = inner_sub_ok && cbm_git_same_linked_worktree(inner_sub, inner); + bool not_parent = inner_sub_ok && !cbm_git_same_linked_worktree(inner_sub, wt_tmp); + bool not_main = !cbm_git_same_linked_worktree(nested, main_tmp); git_run(main_tmp, "worktree prune"); th_rmtree(main_tmp); @@ -320,6 +333,11 @@ TEST(is_linked_worktree_true_for_linked_worktree) { ASSERT(!main_detected); ASSERT(main_nested_ok); ASSERT(!main_nested_detected); + ASSERT(inner_added); + ASSERT(same_outer); + ASSERT(same_inner); + ASSERT(not_parent); + ASSERT(not_main); PASS(); #endif /* _WIN32 */ } From 72f1a52dc6bb898166a2998b335c0682110a5c31 Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 11:25:14 +0000 Subject: [PATCH 13/32] fix(git): identify a worktree by its canonical gitdir A 64-level walk missed a deep session path, and a relative gitdir joined onto a symlink spelling no longer matched the real project root. Walk to the filesystem root and compare canonical gitdirs. Drop the unused project resolver that failed the macOS -Werror build. Signed-off-by: Nohj --- src/cli/hook_augment.c | 4 ---- src/git/git_context.c | 14 +++++++++++--- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index d3baace47..10e7741a1 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -1002,10 +1002,6 @@ static char *ha_resolve_indexed_project_with_root(cbm_mcp_server_t *srv, const c return ha_registry_project_for_path(srv, cwd, root_out, root_out_size); } -static char *ha_resolve_indexed_project(cbm_mcp_server_t *srv, const char *cwd) { - return ha_resolve_indexed_project_with_root(srv, cwd, NULL, 0U); -} - static const char *ha_hook_event_name(yyjson_val *root) { const char *event = ha_obj_str(root, "hook_event_name"); return event ? event : ha_obj_str(root, "hookEventName"); diff --git a/src/git/git_context.c b/src/git/git_context.c index 8e2629cc4..a63d3385e 100644 --- a/src/git/git_context.c +++ b/src/git/git_context.c @@ -228,7 +228,9 @@ static bool walk_linked_worktree_root(const char *path, char *root_out, size_t r /* A session cwd or index_repository path is often a subdirectory. Walk * ancestors until a git anchor so ignore_worktrees applies to the whole * linked checkout, not only its root. */ - for (int depth = 0; depth < 64; depth++) { + /* Bound is the path itself: each step drops one component and stops at + * the filesystem root. A fixed depth would miss a deep session cwd. */ + for (;;) { int kind = linked_worktree_anchor(current); if (kind >= 0) { if (kind != 1) { @@ -248,7 +250,6 @@ static bool walk_linked_worktree_root(const char *path, char *root_out, size_t r return false; } } - return false; } bool cbm_git_is_linked_worktree(const char *path) { @@ -271,7 +272,14 @@ bool cbm_git_same_linked_worktree(const char *a, const char *b) { !read_gitlink_target(root_b, git_b, sizeof(git_b))) { return false; } - return strcmp(git_a, git_b) == 0; + /* A relative gitdir is joined onto the walked path. Canonicalize both so + * a symlink spelling of the cwd still matches the real project root. + * Fall back to the raw string when the gitdir does not exist. */ + char norm_a[GIT_OUTPUT_MAX]; + char norm_b[GIT_OUTPUT_MAX]; + const char *left = cbm_canonical_path(git_a, norm_a, sizeof(norm_a)) ? norm_a : git_a; + const char *right = cbm_canonical_path(git_b, norm_b, sizeof(norm_b)) ? norm_b : git_b; + return strcmp(left, right) == 0; } static char *join_root_relative(const char *root, const char *rel) { From 394faaacfbec823e3d138407bb21ad46869f9022 Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 11:35:29 +0000 Subject: [PATCH 14/32] fix(cli): canonicalize cwd before the worktree gate A symlink into a linked worktree has no .git on its lexical path, so the hook told the agent to run index_repository. That call canonicalizes first and then refuses. Resolve the cwd before project lookup and the ignore_worktrees checks. Signed-off-by: Nohj --- src/cli/hook_augment.c | 8 ++++++++ tests/test_cli.c | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index 10e7741a1..3de1691aa 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -1486,6 +1486,14 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root owned_config = cbm_mcp_server_attach_runtime_config(srv); } const char *cwd = ha_normalized_cwd_with_server(root, srv, cwd_buffer, sizeof(cwd_buffer)); + /* A symlink alias has no .git of its own, and walking its lexical parents + * leaves the linked worktree. index_repository canonicalizes before the + * same gate, so the hook must too or it tells the agent to index a path + * the setting will refuse. */ + char canonical_cwd[4096]; + if (cwd && ha_canonical_path(cwd, canonical_cwd, sizeof(canonical_cwd))) { + cwd = canonical_cwd; + } char project_root[4096]; project_root[0] = '\0'; char *project = srv && cwd ? ha_resolve_indexed_project_with_root(srv, cwd, project_root, diff --git a/tests/test_cli.c b/tests/test_cli.c index e234d77df..27883c5c8 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -10644,6 +10644,22 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { !strstr(ignored_out, "is indexed"); free(ignored_out); + /* A symlink to a directory inside that worktree has no lexical .git. + * The hook must still follow the real path and honor ignore_worktrees. */ + char alias_target[600]; + snprintf(alias_target, sizeof(alias_target), "%s/nested", wtdir); + bool alias_target_ok = test_mkdirp(alias_target) == 0; + char alias[512]; + snprintf(alias, sizeof(alias), "%s/wt-alias", tmpdir); + bool alias_made = alias_target_ok && symlink(alias_target, alias) == 0; + snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}", + alias); + char *alias_out = alias_made ? cbm_hook_augment_lifecycle_json(input) : NULL; + bool alias_ignored = alias_out && strstr(alias_out, "ignore_worktrees is enabled") && + strstr(alias_out, "do not run index_repository") && + !strstr(alias_out, "Run index_repository"); + free(alias_out); + /* A linked worktree nested inside the indexed checkout must not inherit * that parent graph once ignore_worktrees is on. */ char insider[512]; @@ -10716,6 +10732,8 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { FAIL("unindexed worktree must get a deliberate no-match notice, never a silent 0 bytes"); if (!honored) FAIL("ignore_worktrees in the runtime config must change the unindexed-worktree note"); + if (!alias_ignored) + FAIL("a symlink into an ignored worktree must not recommend index_repository"); if (!inside_ignored) FAIL("a nested linked worktree must not inherit the indexed parent graph"); if (!exact_kept) From 3bab06134bdf1401e568884e1e624c464522635e Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 12:00:58 +0000 Subject: [PATCH 15/32] style(cli): break the worktree gate assignment for clang-format The ignore_linked initializer exceeded the formatter's assignment break. Lint treats that as an error, so the line now matches .clang-format. Signed-off-by: Nohj --- src/cli/hook_augment.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index 3de1691aa..342a7bd61 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -1502,8 +1502,8 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root /* ignore_worktrees refuses a linked worktree, including one nested inside an * indexed checkout or inside another linked worktree. Keep a match only when * its root belongs to this cwd's own linked worktree, not a parent graph. */ - bool ignore_linked = srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && - cbm_git_is_linked_worktree(cwd); + bool ignore_linked = + srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && cbm_git_is_linked_worktree(cwd); if (ignore_linked && project && !cbm_git_same_linked_worktree(cwd, project_root)) { free(project); project = NULL; From b21c8ccb6ec37b53d026984278bd795db5f3abc1 Mon Sep 17 00:00:00 2001 From: Nohj Date: Tue, 29 Sep 2026 12:19:57 +0000 Subject: [PATCH 16/32] fix(cli): drop a parent worktree graph without a new free The memory-core ratchet rejects another raw free() in the hook. Keep the parent name until the existing free(project) and skip it when the match is a different worktree. Signed-off-by: Nohj --- src/cli/hook_augment.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index 342a7bd61..384ba8467 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -1504,11 +1504,11 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root * its root belongs to this cwd's own linked worktree, not a parent graph. */ bool ignore_linked = srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && cbm_git_is_linked_worktree(cwd); - if (ignore_linked && project && !cbm_git_same_linked_worktree(cwd, project_root)) { - free(project); - project = NULL; - } - bool worktree_ignored = ignore_linked && !project; + /* Drop a parent graph without a second free(): this file's raw free count + * is ratcheted, and the single free(project) below still releases it. */ + bool drop_ancestor = + ignore_linked && project && !cbm_git_same_linked_worktree(cwd, project_root); + bool worktree_ignored = ignore_linked && (!project || drop_ancestor); if (owned_config) { cbm_mcp_server_set_config(srv, NULL); cbm_config_close(owned_config); @@ -1531,7 +1531,7 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root scope = "Compaction"; } const char *tier = ha_active_tier(root, event); - if (project) { + if (project && !drop_ancestor) { char safe_project[HA_METADATA_CAP]; ha_sanitize_metadata(project, safe_project, sizeof(safe_project)); snprintf(context, sizeof(context), From b2e143371115d43d3518ef962e296cda4dd4ddef Mon Sep 17 00:00:00 2001 From: Nohj Date: Wed, 30 Sep 2026 19:30:37 -0400 Subject: [PATCH 17/32] Fix portable stat declarations for worktree detection Signed-off-by: Nohj --- src/git/git_context.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/git/git_context.c b/src/git/git_context.c index 38802e5aa..640befd6c 100644 --- a/src/git/git_context.c +++ b/src/git/git_context.c @@ -10,6 +10,7 @@ #include #include #include +#include enum { GIT_CMD_MAX = 1024, From 470500eaae0b25c69772ba5dca1b01a7554c9637 Mon Sep 17 00:00:00 2001 From: Nohj Date: Wed, 30 Sep 2026 19:55:35 -0400 Subject: [PATCH 18/32] Restore runtime config attachment for hook augmentation Signed-off-by: Nohj --- src/mcp/mcp.c | 11 +++++++++++ tests/test_mcp.c | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c index cccff1838..c45ec6de8 100644 --- a/src/mcp/mcp.c +++ b/src/mcp/mcp.c @@ -1849,6 +1849,17 @@ void cbm_mcp_server_set_config(cbm_mcp_server_t *srv, struct cbm_config *cfg) { } } +struct cbm_config *cbm_mcp_server_attach_runtime_config(cbm_mcp_server_t *srv) { + if (!srv || srv->config) { + return NULL; + } + cbm_config_t *config = cbm_config_open(cbm_resolve_cache_dir()); + if (config) { + cbm_mcp_server_set_config(srv, config); + } + return config; +} + #ifdef CBM_ENABLE_TEST_SEAMS void cbm_mcp_server_set_auto_index_count_test_hook(cbm_mcp_server_t *srv, cbm_mcp_auto_index_count_test_hook_fn hook, diff --git a/tests/test_mcp.c b/tests/test_mcp.c index a03c1731a..8eab275a2 100644 --- a/tests/test_mcp.c +++ b/tests/test_mcp.c @@ -1202,6 +1202,41 @@ TEST(mcp_initialize_response) { PASS(); } +TEST(mcp_attach_runtime_config_respects_caller_ownership) { + char *cache = th_mktempdir("cbm_mcp_runtime_config"); + ASSERT_NOT_NULL(cache); + const char *saved = getenv("CBM_CACHE_DIR"); + char *saved_copy = saved ? strdup(saved) : NULL; + cbm_setenv("CBM_CACHE_DIR", cache, 1); + + cbm_config_t *config = cbm_config_open(cache); + cbm_mcp_server_t *server = cbm_mcp_server_new(NULL); + bool stored = config && cbm_config_set(config, CBM_CONFIG_IGNORE_WORKTREES, "true") == 0; + bool default_off = server && !cbm_mcp_ignore_worktrees_enabled(server); + cbm_config_t *attached = server ? cbm_mcp_server_attach_runtime_config(server) : NULL; + bool enabled = attached && cbm_mcp_ignore_worktrees_enabled(server); + bool not_replaced = server && cbm_mcp_server_attach_runtime_config(server) == NULL; + if (server) { + cbm_mcp_server_set_config(server, config); + } + cbm_config_close(attached); + bool caller_config_kept = server && cbm_mcp_server_attach_runtime_config(server) == NULL && + cbm_mcp_ignore_worktrees_enabled(server); + cbm_mcp_server_free(server); + cbm_config_close(config); + restore_cache_dir(saved_copy); + free(saved_copy); + int removed = th_rmtree(cache); + + ASSERT(stored); + ASSERT(default_off); + ASSERT(enabled); + ASSERT(not_replaced); + ASSERT(caller_config_kept); + ASSERT_EQ(removed, 0); + PASS(); +} + TEST(mcp_tools_list) { char *json = cbm_mcp_tools_list(); ASSERT_NOT_NULL(json); @@ -21147,6 +21182,7 @@ SUITE(mcp) { /* MCP protocol helpers */ RUN_TEST(mcp_initialize_response); + RUN_TEST(mcp_attach_runtime_config_respects_caller_ownership); RUN_TEST(mcp_tools_list); RUN_TEST(mcp_tools_help_list_matches_registry); RUN_TEST(mcp_tools_list_latest_metadata); From adc2764a3eff3791cc5692ec7e997887a1f6df3f Mon Sep 17 00:00:00 2001 From: Nohj Date: Wed, 30 Sep 2026 20:32:09 -0400 Subject: [PATCH 19/32] Fix C++ sanitizer runtime linkage in fuzz build Signed-off-by: Nohj --- Makefile.cbm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile.cbm b/Makefile.cbm index ab5c89db7..b2a655505 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -1381,10 +1381,10 @@ fuzz: CC=$(FUZZ_CC) CXX=$(FUZZ_CXX) SANITIZE="$(FUZZ_SANITIZE)" $(BUILD_DIR)/cbm-fuzz: $(FUZZ_SRC) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) - $(CC) $(CFLAGS_TEST) -fsanitize=fuzzer -o $@ \ + $(CXX) $(CFLAGS_TEST) -x c -fsanitize=fuzzer -o $@ \ $(FUZZ_SRC) $(PROD_SRCS) \ $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ - $(OBJS_VENDORED_TEST) \ + -x none $(OBJS_VENDORED_TEST) \ $(LDFLAGS_TEST) # Path-sensitive memory analysis: leak paths, null derefs, uninitialized reads. From 9588007b16a07c3a85980ceb980e21cd8102c17a Mon Sep 17 00:00:00 2001 From: Nohj Date: Wed, 30 Sep 2026 21:45:52 -0400 Subject: [PATCH 20/32] Free partial Cypher patterns after parse errors Signed-off-by: Nohj --- src/cypher/cypher.c | 27 ++++++++++++++++++--------- tests/test_cypher.c | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/cypher/cypher.c b/src/cypher/cypher.c index 7c7a2f987..42ecb93c5 100644 --- a/src/cypher/cypher.c +++ b/src/cypher/cypher.c @@ -1862,6 +1862,8 @@ static int parse_return(parser_t *p, cbm_return_clause_t **out) { return parse_return_or_with(p, out, false); } +static void free_pattern(cbm_pattern_t *pat); + /* Parse a single MATCH pattern into pat */ static int parse_match_pattern(parser_t *p, cbm_pattern_t *pat) { memset(pat, 0, sizeof(*pat)); @@ -1870,31 +1872,38 @@ static int parse_match_pattern(parser_t *p, cbm_pattern_t *pat) { pat->nodes = malloc(node_cap * sizeof(cbm_node_pattern_t)); pat->rels = calloc(rel_cap, sizeof(cbm_rel_pattern_t)); - if (parse_node(p, &pat->nodes[0]) < 0) { - return CBM_NOT_FOUND; - } + /* Count the slot before parsing so even partially filled nodes and + * relationships are released when a malformed pattern is rejected. */ pat->node_count = SKIP_ONE; + if (parse_node(p, &pat->nodes[0]) < 0) { + goto fail; + } while (check(p, TOK_DASH) || check(p, TOK_LT)) { if (pat->rel_count >= rel_cap) { rel_cap *= PAIR_LEN; pat->rels = safe_realloc(pat->rels, rel_cap * sizeof(cbm_rel_pattern_t)); } - if (parse_rel(p, &pat->rels[pat->rel_count]) < 0) { - return CBM_NOT_FOUND; - } pat->rel_count++; + if (parse_rel(p, &pat->rels[pat->rel_count - SKIP_ONE]) < 0) { + goto fail; + } if (pat->node_count >= node_cap) { node_cap *= PAIR_LEN; pat->nodes = safe_realloc(pat->nodes, node_cap * sizeof(cbm_node_pattern_t)); } - if (parse_node(p, &pat->nodes[pat->node_count]) < 0) { - return CBM_NOT_FOUND; - } pat->node_count++; + if (parse_node(p, &pat->nodes[pat->node_count - SKIP_ONE]) < 0) { + goto fail; + } } return 0; + +fail: + free_pattern(pat); + memset(pat, 0, sizeof(*pat)); + return CBM_NOT_FOUND; } /* Parse UNWIND [...] AS var clause into query */ diff --git a/tests/test_cypher.c b/tests/test_cypher.c index 7c251bd9b..5d198a0ef 100644 --- a/tests/test_cypher.c +++ b/tests/test_cypher.c @@ -274,6 +274,24 @@ TEST(cypher_parse_accepts_single_with_clause) { PASS(); } +TEST(cypher_parse_rejects_partial_patterns) { + const char *queries[] = { + "MATCH p = (a:Class)-[:INHERITS*1..3]->(b:Class) RETURN a.name, length(p)", + "MATCH (a)-[:CALLS]->(b) MATCH (c)-[:CALLS*]-> RETURN a.name", + "MATCH (a)-[:CALLS|]->(b)", + }; + for (size_t i = 0; i < sizeof(queries) / sizeof(queries[0]); i++) { + cbm_query_t *q = NULL; + char *err = NULL; + int rc = cbm_cypher_parse(queries[i], &q, &err); + ASSERT_NEQ(rc, 0); + ASSERT_NULL(q); + ASSERT_NOT_NULL(err); + free(err); + } + PASS(); +} + TEST(cypher_parse_relationship_outbound) { cbm_query_t *q = NULL; char *err = NULL; @@ -4842,6 +4860,7 @@ SUITE(cypher) { RUN_TEST(cypher_parse_rejects_trailing_tokens); RUN_TEST(cypher_parse_rejects_second_with_clause); RUN_TEST(cypher_parse_accepts_single_with_clause); + RUN_TEST(cypher_parse_rejects_partial_patterns); RUN_TEST(cypher_parse_relationship_outbound); RUN_TEST(cypher_parse_relationship_inbound); RUN_TEST(cypher_parse_relationship_any); From 62479ff9fce0f8a052b0eab29a5499ca48b93bec Mon Sep 17 00:00:00 2001 From: Nohj Date: Wed, 30 Sep 2026 22:38:59 -0400 Subject: [PATCH 21/32] Isolate Git context probes from inherited repository environment Signed-off-by: Nohj --- src/git/git_context.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/git/git_context.c b/src/git/git_context.c index a63d3385e..6986be4aa 100644 --- a/src/git/git_context.c +++ b/src/git/git_context.c @@ -65,7 +65,9 @@ static int git_capture(const char *repo_path, const char *git_args, char **out) return CBM_NOT_FOUND; } - FILE *fp = cbm_popen(cmd, "r"); + /* A hook or editor may export GIT_DIR/GIT_WORK_TREE for another repo. + * Isolate this child so git -C selects repo_path rather than that repo. */ + FILE *fp = cbm_popen_git(cmd); if (!fp) { return CBM_NOT_FOUND; } From fa331ed5e6b4294a0ed9bbd6b6f2bb6c98302d85 Mon Sep 17 00:00:00 2001 From: Petteri Ponsimaa Date: Wed, 21 Oct 2026 10:00:23 +0300 Subject: [PATCH 22/32] feat(extraction): route Next.js App Router handlers app/**/route.{ts,js} files produced 0 Route nodes, so cross-repo intelligence found no edges into a Next.js backend (#759). cbm_extract_nextjs_routes fills route_path/route_method on the existing Function definition for each exported HTTP-verb handler. It adds no pass and no synthetic definitions; the route-node pass builds the Route and HANDLES edge as it does for other frameworks. CBM_SEMANTIC_INDEX_VERSION goes from 9 to 10 so existing indexes re-extract once. Fixes #759 Signed-off-by: Petteri Ponsimaa --- Makefile.cbm | 1 + internal/cbm/cbm.c | 3 + internal/cbm/cbm.h | 5 + internal/cbm/extract_nextjs.c | 272 ++++++++++++++++++++ src/pipeline/pipeline_internal.h | 9 +- tests/test_extraction.c | 173 +++++++++++++ tests/test_pipeline.c | 422 +++++++++++++++++++++++++++++++ 7 files changed, 883 insertions(+), 2 deletions(-) create mode 100644 internal/cbm/extract_nextjs.c diff --git a/Makefile.cbm b/Makefile.cbm index 3b93146f1..631290d69 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -397,6 +397,7 @@ EXTRACTION_SRCS = \ $(CBM_DIR)/diagram.c \ $(CBM_DIR)/route_path.c \ $(CBM_DIR)/openapi.c \ + $(CBM_DIR)/extract_nextjs.c \ $(CBM_DIR)/sql_values.c \ $(CBM_DIR)/helpers.c \ $(CBM_DIR)/cpp_branch_views.c \ diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c index 23b871dbc..50dd97568 100644 --- a/internal/cbm/cbm.c +++ b/internal/cbm/cbm.c @@ -3902,6 +3902,9 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C // OpenAPI operations as Routes (self-gated: API description documents). cbm_extract_openapi(&ctx); + // Next.js App Router handlers' routes (self-gated: app/**/route.ts and route.js). + cbm_extract_nextjs_routes(&ctx); + // K8s / Kustomize semantic pass (additional structured extraction for YAML-based infra files). if (ctx.language == CBM_LANG_KUSTOMIZE || ctx.language == CBM_LANG_K8S) { cbm_extract_k8s(&ctx); diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index ade41fea5..12b8c1acd 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -1389,6 +1389,11 @@ void cbm_extract_diagram_file(CBMExtractCtx *ctx); * or JSON files whose root says `openapi` or `swagger`. */ void cbm_extract_openapi(CBMExtractCtx *ctx); +/* Next.js App Router route handlers (extract_nextjs.c): the HTTP verb Functions + * a route file exports carry the route path its directories name. Self-gated: + * TS / JS route.ts and route.js under app/ or src/app/. */ +void cbm_extract_nextjs_routes(CBMExtractCtx *ctx); + /* Canonicalize route-path parameter placeholders (":id", "{id}", "", * "${...}") to a single "{}" token so that client call sites, server handlers * and OpenAPI operations rendezvous on the same Route QN regardless of diff --git a/internal/cbm/extract_nextjs.c b/internal/cbm/extract_nextjs.c new file mode 100644 index 000000000..eea270fa7 --- /dev/null +++ b/internal/cbm/extract_nextjs.c @@ -0,0 +1,272 @@ +/* + * extract_nextjs.c -- Next.js App Router route handlers (#759): an HTTP verb a + * route file (`app/.../route.ts` or `route.js`, the app directory at the root + * or under src/) exports serves the path its directories name. + * + * The handler is the Function definition extraction already made for the + * export: this fills its route_path / route_method, so its Route node and + * HANDLES edge come from the route pass exactly as a decorator route's do, on + * a full and on an incremental index alike. The path is spelled as SvelteKit's + * (sveltekit_route_path, pass_route_nodes.c): `[id]` is `:id`, `[...slug]` is + * `*slug` and a `(group)` directory adds no segment. + * + * A directory this cannot spell makes the file no route at all: an optional + * catch-all (`[[...slug]]`), a private folder (`_lib`), a parallel slot + * (`@modal`), an intercepting route (`(.)photo`), a malformed bracket, or a + * path that does not fit route_path. A handler is a Function of this file: + * `export [async] function GET`, `export const GET = [async] (...) => ...`, + * or `export { GET }` of such a declaration. A renamed + * (`export { handler as GET }`), re-exported, destructured or wrapped + * (`export const GET = auth(handler)`) handler, or a `function` expression + * bound to a const, has no Function of its own here and is not routed. Each + * file is judged alone: a src/app/ route file is routed even where a root + * app/ directory makes Next.js ignore src/app/. + */ +#include "cbm.h" +#include "foundation/arena.h" +#include "helpers.h" +#include "tree_sitter/api.h" +#include "foundation/constants.h" +#include +#include +#include + +enum { + NX_PATH_MAX = CBM_SZ_256, /* the route pass rebuilds a Route from this much */ + NX_REST_LEN = 3, /* "..." */ +}; + +/* The path of a route file below its app directory, NULL for any other file. */ +static const char *nx_app_relative(const char *rel_path) { + const char *base = rel_path ? strrchr(rel_path, '/') : NULL; + if (!base || (strcmp(base, "/route.ts") != 0 && strcmp(base, "/route.js") != 0)) { + return NULL; + } + if (strncmp(rel_path, "app/", strlen("app/")) == 0) { + return rel_path + strlen("app/"); + } + if (strncmp(rel_path, "src/app/", strlen("src/app/")) == 0) { + return rel_path + strlen("src/app/"); + } + return NULL; +} + +static bool nx_has_any(const char *s, size_t n, const char *chars) { + for (size_t i = 0; i < n; i++) { + if (strchr(chars, s[i])) { + return true; + } + } + return false; +} + +/* Append directory segment seg (n bytes) to the route path out[*len]. False + * when the segment cannot be spelled or the path would not fit. */ +static bool nx_append_segment(char *out, size_t *len, const char *seg, size_t n) { + if (n == 0 || seg[0] == '_' || seg[0] == '@') { + return false; + } + if (seg[0] == '(') { + /* A route group adds nothing; `(.)x`, `(..)x` and `(...)x` intercept. */ + return n > PAIR_LEN && seg[n - SKIP_ONE] == ')' && seg[SKIP_ONE] != '.' && + !nx_has_any(seg + SKIP_ONE, n - PAIR_LEN, "()"); + } + char marker = '\0'; + if (seg[0] == '[') { + if (seg[n - SKIP_ONE] != ']') { + return false; + } + marker = ':'; + seg += SKIP_ONE; + n -= PAIR_LEN; + if (n >= NX_REST_LEN && strncmp(seg, "...", NX_REST_LEN) == 0) { + marker = '*'; + seg += NX_REST_LEN; + n -= NX_REST_LEN; + } + if (n == 0 || nx_has_any(seg, n, "[].")) { + return false; + } + } else if (nx_has_any(seg, n, "[]")) { + return false; + } + size_t need = SKIP_ONE + (marker ? SKIP_ONE : 0) + n; + if (*len + need >= NX_PATH_MAX) { + return false; + } + out[(*len)++] = '/'; + if (marker) { + out[(*len)++] = marker; + } + memcpy(out + *len, seg, n); + *len += n; + out[*len] = '\0'; + return true; +} + +/* The route path of the file being extracted, in the arena; NULL for none. */ +static const char *nx_route_path(CBMExtractCtx *ctx) { + const char *seg = nx_app_relative(ctx->rel_path); + if (!seg) { + return NULL; + } + const char *base = strrchr(ctx->rel_path, '/'); + char path[NX_PATH_MAX] = "/"; + size_t len = 0; + while (seg < base) { + const char *end = strchr(seg, '/'); + if (!nx_append_segment(path, &len, seg, (size_t)(end - seg))) { + return NULL; + } + seg = end + SKIP_ONE; + } + return cbm_arena_strdup(ctx->arena, path); +} + +static bool nx_is_method(const char *name) { + static const char *const methods[] = {"GET", "POST", "PUT", "PATCH", + "DELETE", "HEAD", "OPTIONS"}; + for (size_t i = 0; i < sizeof(methods) / sizeof(methods[0]); i++) { + if (strcmp(name, methods[i]) == 0) { + return true; + } + } + return false; +} + +static bool nx_is(TSNode n, const char *type) { + return !ts_node_is_null(n) && strcmp(ts_node_type(n), type) == 0; +} + +/* Does a node carry the anonymous keyword child kw (`default`, `type`)? */ +static bool nx_has_keyword(TSNode n, const char *kw) { + uint32_t count = ts_node_child_count(n); + for (uint32_t i = 0; i < count; i++) { + TSNode c = ts_node_child(n, i); + if (!ts_node_is_named(c) && strcmp(ts_node_type(c), kw) == 0) { + return true; + } + } + return false; +} + +/* The name of a declarator whose value is an arrow function, the Function + * extraction names after the binding (`GET = () => ...`); a null node for any + * other declarator. */ +static TSNode nx_arrow_binding(TSNode declarator) { + TSNode value = ts_node_child_by_field_name(declarator, TS_FIELD("value")); + TSNode name = ts_node_child_by_field_name(declarator, TS_FIELD("name")); + if (!nx_is(name, "identifier") || !nx_is(value, "arrow_function")) { + return (TSNode){0}; + } + return name; +} + +/* Route the Function definition named by name_node, declared inside decl. */ +static void nx_route_handler(CBMExtractCtx *ctx, TSNode decl, TSNode name_node, const char *path) { + const char *name = cbm_node_text(ctx->arena, name_node, ctx->source); + if (!name || !nx_is_method(name)) { + return; + } + const char *qn = + cbm_fqn_compute_source_lang(ctx->arena, ctx->project, ctx->rel_path, name, ctx->language); + uint32_t first = ts_node_start_point(decl).row + TS_LINE_OFFSET; + uint32_t last = ts_node_end_point(decl).row + TS_LINE_OFFSET; + for (int i = 0; qn && i < ctx->result->defs.count; i++) { + CBMDefinition *def = &ctx->result->defs.items[i]; + if (!def->route_path && def->label && def->qualified_name && + strcmp(def->label, "Function") == 0 && strcmp(def->qualified_name, qn) == 0 && + def->start_line >= first && def->end_line <= last) { + def->route_path = path; + def->route_method = name; + return; + } + } +} + +/* Does the name node, if any, spell want? Any name does when want is NULL. */ +static bool nx_wanted(CBMExtractCtx *ctx, TSNode name, const char *want) { + if (ts_node_is_null(name)) { + return false; + } + const char *text = want ? cbm_node_text(ctx->arena, name, ctx->source) : NULL; + return !want || (text && strcmp(text, want) == 0); +} + +/* Route the handlers a top-level declaration (function or const) defines. + * Only names equal to want are considered when want is set. */ +static void nx_route_declaration(CBMExtractCtx *ctx, TSNode decl, const char *path, + const char *want) { + if (nx_is(decl, "function_declaration")) { + TSNode name = ts_node_child_by_field_name(decl, TS_FIELD("name")); + if (nx_wanted(ctx, name, want)) { + nx_route_handler(ctx, decl, name, path); + } + return; + } + if (!nx_is(decl, "lexical_declaration") && !nx_is(decl, "variable_declaration")) { + return; + } + uint32_t count = ts_node_named_child_count(decl); + for (uint32_t i = 0; i < count; i++) { + TSNode declarator = ts_node_named_child(decl, i); + TSNode name = + nx_is(declarator, "variable_declarator") ? nx_arrow_binding(declarator) : (TSNode){0}; + if (nx_wanted(ctx, name, want)) { + nx_route_handler(ctx, declarator, name, path); + } + } +} + +/* `export { GET }`: route the file's own top-level declaration of each + * unrenamed, non-type specifier. */ +static void nx_route_export_clause(CBMExtractCtx *ctx, TSNode clause, const char *path) { + uint32_t count = ts_node_named_child_count(clause); + uint32_t top = ts_node_named_child_count(ctx->root); + for (uint32_t i = 0; i < count; i++) { + TSNode spec = ts_node_named_child(clause, i); + TSNode name = ts_node_child_by_field_name(spec, TS_FIELD("name")); + if (!nx_is(spec, "export_specifier") || !nx_is(name, "identifier") || + !ts_node_is_null(ts_node_child_by_field_name(spec, TS_FIELD("alias"))) || + nx_has_keyword(spec, "type") || nx_has_keyword(spec, "typeof")) { + continue; + } + const char *want = cbm_node_text(ctx->arena, name, ctx->source); + for (uint32_t j = 0; want && j < top; j++) { + nx_route_declaration(ctx, ts_node_named_child(ctx->root, j), path, want); + } + } +} + +void cbm_extract_nextjs_routes(CBMExtractCtx *ctx) { + if (ctx->language != CBM_LANG_TYPESCRIPT && ctx->language != CBM_LANG_JAVASCRIPT) { + return; + } + const char *path = nx_route_path(ctx); + if (!path) { + return; + } + uint32_t count = ts_node_named_child_count(ctx->root); + for (uint32_t i = 0; i < count; i++) { + TSNode node = ts_node_named_child(ctx->root, i); + /* A runtime export of this file: not `export default`, not + * `export type { ... }`, not a re-export `... from './x'`. */ + if (!nx_is(node, "export_statement") || nx_has_keyword(node, "default") || + nx_has_keyword(node, "type") || + !ts_node_is_null(ts_node_child_by_field_name(node, TS_FIELD("source")))) { + continue; + } + TSNode decl = ts_node_child_by_field_name(node, TS_FIELD("declaration")); + if (!ts_node_is_null(decl)) { + nx_route_declaration(ctx, decl, path, NULL); + continue; + } + uint32_t parts = ts_node_named_child_count(node); + for (uint32_t j = 0; j < parts; j++) { + TSNode part = ts_node_named_child(node, j); + if (nx_is(part, "export_clause")) { + nx_route_export_clause(ctx, part, path); + } + } + } +} diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h index fb5b724d6..bf72989a0 100644 --- a/src/pipeline/pipeline_internal.h +++ b/src/pipeline/pipeline_internal.h @@ -1645,8 +1645,13 @@ int cbm_pipeline_build_fresh_semantic_manifest(cbm_pipeline_t *p, const char *pr * a kube / k8s task DEPLOYS {via:ansible} the template it applies * (pass_ansible.c). An external Chart is keyed by its publisher URL. * An index built before holds none of them, so it rebuilds once on - * upgrade. */ -enum { CBM_SEMANTIC_INDEX_VERSION = 9 }; + * upgrade. + * 10: a Next.js App Router route handler, the HTTP verb Function a route.ts + * / route.js under app/ or src/app/ exports, carries the route_path its + * directories name and HANDLES its Route (extract_nextjs.c). An index + * built before has none of these Routes for its unchanged route files, + * so it rebuilds once on upgrade. */ +enum { CBM_SEMANTIC_INDEX_VERSION = 10 }; typedef struct { cbm_gbuf_t *gbuf; diff --git a/tests/test_extraction.c b/tests/test_extraction.c index e1c1e4491..15f03463a 100644 --- a/tests/test_extraction.c +++ b/tests/test_extraction.c @@ -5622,6 +5622,177 @@ TEST(extract_ts_nestjs_controller_routes_issue1428) { PASS(); } +/* #759: the one definition named `name`; NULL for none or more than one. */ +static const CBMDefinition *nextjs_only_def(CBMFileResult *r, const char *name) { + const CBMDefinition *found = NULL; + for (int i = 0; i < r->defs.count; i++) { + if (r->defs.items[i].name && strcmp(r->defs.items[i].name, name) == 0) { + if (found) { + return NULL; + } + found = &r->defs.items[i]; + } + } + return found; +} + +/* #759: a Next.js App Router route file's exported HTTP verb handlers are the + * Functions extraction already makes for them, now carrying the route path of + * the file's directories -- `[id]` as `:id`, `[...slug]` as `*slug`, a + * `(group)` adding nothing -- and the verb as their method. A local + * declaration exported by name (`export { GET }`) is that same Function; no + * second definition appears. The 255-byte path is the longest that fits. */ +TEST(extract_nextjs_route_metadata_contract_issue759) { + char long_file[CBM_SZ_512]; + char long_path[CBM_SZ_256]; + char segment[CBM_SZ_256]; + memset(segment, 'x', CBM_SZ_256 - PAIR_LEN); + segment[CBM_SZ_256 - PAIR_LEN] = '\0'; + snprintf(long_file, sizeof(long_file), "app/%s/route.ts", segment); + snprintf(long_path, sizeof(long_path), "/%s", segment); + static const char verbs_src[] = "export async function GET() {}\n" + "export async function POST() {}\n" + "export function PUT() {}\n" + "export function PATCH() {}\n" + "export function DELETE() {}\n" + "export function HEAD() {}\n" + "export function OPTIONS() {}\n"; + const struct { + const char *file; + const char *src; + const char *path; + const char *names[CBM_SZ_8]; + } cases[] = { + {"src/app/api/users/[id]/route.ts", + "export function GET() { return 1; }\nexport const POST = async () => 2;\n", + "/api/users/:id", + {"GET", "POST"}}, + {"app/api/verbs/route.ts", + verbs_src, + "/api/verbs", + {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}}, + {"src/app/(public)/api/[org]/users/[id]/route.ts", + "export async function GET() { return 1; }\n", + "/api/:org/users/:id", + {"GET"}}, + {"app/api/[...slug]/route.ts", "export function GET() {}\n", "/api/*slug", {"GET"}}, + {"app/api/typed/route.ts", + "type Handler = () => Promise;\nexport const GET: Handler = async () => 1;\n", + "/api/typed", + {"GET"}}, + {"app/route.js", "export function GET() { return 1; }\n", "/", {"GET"}}, + {"app/api/local/route.ts", + "function GET() { return 1; }\nconst POST = async () => 2;\nexport { GET, POST };\n", + "/api/local", + {"GET", "POST"}}, + {long_file, "export function GET() {}\n", long_path, {"GET"}}, + }; + for (size_t c = 0; c < sizeof(cases) / sizeof(cases[0]); c++) { + CBMLanguage lang = strstr(cases[c].file, ".js") ? CBM_LANG_JAVASCRIPT : CBM_LANG_TYPESCRIPT; + CBMFileResult *r = extract(cases[c].src, lang, "t", cases[c].file); + ASSERT_NOT_NULL(r); + ASSERT_FALSE(r->has_error); + int routed = 0; + for (int i = 0; i < r->defs.count; i++) { + routed += r->defs.items[i].route_path != NULL; + } + int want = 0; + for (; want < CBM_SZ_8 && cases[c].names[want]; want++) { + const CBMDefinition *d = nextjs_only_def(r, cases[c].names[want]); + ASSERT_NOT_NULL(d); + ASSERT_STR_EQ(d->label, "Function"); + ASSERT_STR_EQ(d->file_path, cases[c].file); + ASSERT_NOT_NULL(d->route_path); + ASSERT_STR_EQ(d->route_path, cases[c].path); + ASSERT_STR_EQ(d->route_method, cases[c].names[want]); + } + ASSERT_EQ(routed, want); + cbm_free_result(r); + } + PASS(); +} + +/* #759: nothing else routes. Not a route file, or a directory the route path + * cannot spell -- an optional catch-all, a private folder, a parallel slot, + * an intercepting route, a malformed bracket, a workspace package root, a path + * past 255 bytes. Not a runtime export of an HTTP verb Function of this file: + * an unexported, default, type-only or nested GET, a class method, a + * constant, a lower-case verb; and no handler is made up for a renamed, + * re-exported, wrapped or destructured export, or a `function` expression + * bound to a const: none of them has a Function of its own here. */ +TEST(extract_nextjs_rejects_nonroutes_issue759) { + char long_file[CBM_SZ_512]; + char segment[CBM_SZ_256]; + memset(segment, 'x', CBM_SZ_256 - SKIP_ONE); + segment[CBM_SZ_256 - SKIP_ONE] = '\0'; + snprintf(long_file, sizeof(long_file), "app/%s/route.ts", segment); + const char *files[] = { + "pages/api/route.ts", + "app/api/page.ts", + "app/api/route.test.ts", + "app/api/view/route.tsx", + "app/api/view/route.jsx", + "app/api/module/route.mjs", + "app/_private/route.ts", + "src/app/api/_lib/route.ts", + "app/@modal/route.ts", + "app/(.)photo/route.ts", + "app/(..)(..)photo/route.ts", + "app/api/[[...opt]]/route.ts", + "app/api/[broken/route.ts", + "app/api/broken]/route.ts", + "app/api/[]/route.ts", + "app/api/[...]/route.ts", + "app/api/a[id]/route.ts", + "app/()/route.ts", + "apps/web/app/api/route.ts", + long_file, + }; + const struct { + const char *file; + const char *src; + } sources[] = { + {"app/api/nonexports/route.ts", "function GET() {}\n" + "export default function POST() {}\n" + "function PUT() {}\n" + "export type { PUT };\n" + "function OPTIONS() {}\n" + "export { type OPTIONS };\n" + "export class Handlers { PATCH() {} }\n" + "export const DELETE = 42;\n" + "export function get() {}\n" + "export function helper() { function HEAD() {} }\n"}, + {"app/api/bindings/route.ts", "const handler = async () => 1;\n" + "export { handler as GET };\n" + "export { POST } from './impl';\n" + "export const PUT = wrap(handler);\n" + "export const DELETE = function () {};\n" + "export const { PATCH } = handlers;\n" + "export const HEAD = handler as Handler;\n" + "export const OPTIONS = (async () => 1) satisfies Handler;\n" + "export * from './all';\n"}, + }; + const int file_count = (int)(sizeof(files) / sizeof(files[0])); + const int source_count = (int)(sizeof(sources) / sizeof(sources[0])); + for (int c = 0; c < file_count + source_count; c++) { + bool by_file = c < file_count; + const char *file = by_file ? files[c] : sources[c - file_count].file; + CBMFileResult *r = + extract(by_file ? "export function GET() {}\n" : sources[c - file_count].src, + CBM_LANG_TYPESCRIPT, "t", file); + ASSERT_NOT_NULL(r); + ASSERT_FALSE(r->has_error); + if (by_file) { + ASSERT_NOT_NULL(nextjs_only_def(r, "GET")); + } + for (int i = 0; i < r->defs.count; i++) { + ASSERT_NULL(r->defs.items[i].route_path); + } + cbm_free_result(r); + } + PASS(); +} + /* Return the file's Module definition (extraction pushes it first), or NULL. */ static const CBMDefinition *find_module_def(CBMFileResult *r) { for (int i = 0; i < r->defs.count; i++) { @@ -13434,6 +13605,8 @@ SUITE(extraction) { RUN_TEST(extract_java_jaxrs_empty_path_means_class_path); RUN_TEST(extract_java_spring_relative_string_not_route_path); RUN_TEST(extract_ts_nestjs_controller_routes_issue1428); + RUN_TEST(extract_nextjs_route_metadata_contract_issue759); + RUN_TEST(extract_nextjs_rejects_nonroutes_issue759); RUN_TEST(extract_blazor_page_directive_routes_component); RUN_TEST(extract_blazor_component_without_page_has_no_route); RUN_TEST(extract_razor_page_directive_routes_cshtml_view); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index bd76775f3..060e87022 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -18874,6 +18874,423 @@ TEST(pipeline_semantic_version_3_index_is_rebuilt_in_full_c1) { PASS(); } +/* #759: index a Next.js App Router tree as project "nextjs" (a full index, or + * the incremental route a stored index of the same tree takes). */ +static int nextjs_index(const char *repo, const char *db_path) { + cbm_pipeline_t *p = cbm_pipeline_new(repo, db_path, CBM_MODE_FULL); + if (!p) { + return -1; + } + (void)cbm_pipeline_set_project_name(p, "nextjs"); + int rc = cbm_pipeline_run(p); + cbm_pipeline_free(p); + return rc; +} + +/* Every Route of a stored index with each handler that HANDLES it, one sorted + * line each: "METHOD path route_qn file_path handler_qn". A Route no handler + * reaches ends in "-". The properties are parsed (json_extract): a Route not + * from route metadata is marked "!source", a handler declared in another file + * "!file", a HANDLES edge whose handler property is not its handler's QN + * "!handler"; malformed JSON fails the query. */ +static bool nextjs_route_tuples(const char *db_path, char *out, size_t sz) { + sqlite3 *db = NULL; + sqlite3_stmt *st = NULL; + bool ok = false; + if (sqlite3_open_v2(db_path, &db, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK && + sqlite3_prepare_v2( + db, + "SELECT coalesce(group_concat(t, char(10)), '') FROM (SELECT " + "json_extract(r.properties,'$.method') || ' ' || r.name || ' ' || r.qualified_name || " + "' ' || r.file_path || ' ' || coalesce(h.qualified_name, '-') || CASE WHEN " + "json_extract(r.properties,'$.source') = 'decorator' THEN '' ELSE ' !source' END || " + "CASE WHEN h.id IS NULL OR h.file_path = r.file_path THEN '' ELSE ' !file' END || " + "CASE WHEN e.id IS NULL OR json_extract(e.properties,'$.handler') = h.qualified_name " + "THEN '' ELSE ' !handler' END AS t FROM nodes r LEFT JOIN edges e ON " + "e.target_id=r.id AND e.type='HANDLES' LEFT JOIN nodes h ON h.id=e.source_id WHERE " + "r.label='Route' ORDER BY t)", + -1, &st, NULL) == SQLITE_OK && + sqlite3_step(st) == SQLITE_ROW) { + snprintf(out, sz, "%s", (const char *)sqlite3_column_text(st, 0)); + ok = true; + } + sqlite3_finalize(st); + sqlite3_close(db); + return ok; +} + +static int nextjs_by_qn(const void *a, const void *b) { + return strcmp(((const cbm_search_result_t *)a)->node.qualified_name, + ((const cbm_search_result_t *)b)->node.qualified_name); +} + +/* The Routes a search by label Route and declaring-file glob finds, one + * "qualified_name file_path" line each in QN order. */ +static bool nextjs_found_routes(const char *db_path, const char *glob, char *out, size_t sz) { + cbm_store_t *s = cbm_store_open_path_existing(db_path); + if (!s) { + return false; + } + cbm_search_params_t params = {.project = "nextjs", + .label = "Route", + .file_pattern = glob, + .min_degree = -1, + .max_degree = -1, + .limit = 100}; + cbm_search_output_t res = {0}; + bool ok = cbm_store_search(s, ¶ms, &res) == CBM_STORE_OK; + if (ok && res.count > 1) { + qsort(res.results, (size_t)res.count, sizeof(res.results[0]), nextjs_by_qn); + } + size_t len = 0; + out[0] = '\0'; + for (int i = 0; ok && i < res.count; i++) { + int n = snprintf(out + len, sz - len, "%s%s %s", i ? "\n" : "", + res.results[i].node.qualified_name, res.results[i].node.file_path); + ok = n >= 0 && (size_t)n < sz - len; + len += ok ? (size_t)n : 0; + } + cbm_store_search_free(&res); + cbm_store_close(s); + return ok; +} + +/* One index of a Next.js tree: its result, the route it took and the stored + * Routes after it (nextjs_route_tuples). */ +typedef struct { + int rc; + cbm_incremental_route_t route; + bool read; + char tuples[1024]; +} nextjs_run_t; + +static void nextjs_run(const char *repo, const char *db_path, nextjs_run_t *run) { + run->rc = nextjs_index(repo, db_path); + run->route = cbm_pipeline_incremental_test_last_route(); + run->read = nextjs_route_tuples(db_path, run->tuples, sizeof(run->tuples)); +} + +/* #759: the HTTP verb Functions a Next.js route file exports HANDLE the Routes + * its directories name, in the stored graph: a dynamic segment, a group, a + * catch-all and the root, under src/app/ and app/. Each Route is there once, + * with its file, from its own handler, whose HANDLES property is its QN. A + * search by label Route and the declaring file's glob finds them. `fillers` + * more files put the index on the parallel extraction path. */ +static int nextjs_persisted_contract(int fillers) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_nextjs_routes_XXXXXX"); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + for (int i = 0; i < fillers; i++) { + char name[64]; + char body[128]; + snprintf(name, sizeof(name), "lib/filler%d.ts", i); + snprintf(body, sizeof(body), "export function filler%d(): number {\n return %d;\n}\n", i, + i); + write_temp_file(tmp, name, body); + } + write_temp_file(tmp, "src/app/api/users/[id]/route.ts", + "export function GET() {\n return 1;\n}\n" + "export const POST = async () => 1;\n"); + write_temp_file(tmp, "src/app/(public)/api/[org]/users/[id]/route.ts", + "export async function GET() {\n return 2;\n}\n"); + write_temp_file(tmp, "app/api/[...slug]/route.ts", "export function GET() {\n return 3;\n}\n"); + write_temp_file(tmp, "app/route.js", "export function GET() {\n return 4;\n}\n"); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/nextjs.db", tmp); + + char *old_workers = getenv("CBM_WORKERS"); + char *saved = old_workers ? strdup(old_workers) : NULL; + if (fillers > 0) { + cbm_setenv("CBM_WORKERS", "4", 1); + } + nextjs_run_t full; + nextjs_run(tmp, db_path, &full); + if (saved) { + cbm_setenv("CBM_WORKERS", saved, 1); + free(saved); + } else { + cbm_unsetenv("CBM_WORKERS"); + } + char found[1024]; + bool searched = + nextjs_found_routes(db_path, "src/app/api/users/*/route.ts", found, sizeof(found)); + th_rmtree(tmp); + + ASSERT_EQ(full.rc, 0); + ASSERT_TRUE(full.read); + ASSERT_STR_EQ( + full.tuples, + "GET / __route__GET__/ app/route.js nextjs.app.route.GET\n" + "GET /api/*slug __route__GET__/api/*slug app/api/[...slug]/route.ts " + "nextjs.app.api.[...slug].route.GET\n" + "GET /api/:org/users/:id __route__GET__/api/{}/users/{} " + "src/app/(public)/api/[org]/users/[id]/route.ts " + "nextjs.src.app.(public).api.[org].users.[id].route.GET\n" + "GET /api/users/:id __route__GET__/api/users/{} src/app/api/users/[id]/route.ts " + "nextjs.src.app.api.users.[id].route.GET\n" + "POST /api/users/:id __route__POST__/api/users/{} src/app/api/users/[id]/route.ts " + "nextjs.src.app.api.users.[id].route.POST"); + ASSERT_TRUE(searched); + ASSERT_STR_EQ(found, "__route__GET__/api/users/{} src/app/api/users/[id]/route.ts\n" + "__route__POST__/api/users/{} src/app/api/users/[id]/route.ts"); + PASS(); +} + +TEST(pipeline_nextjs_persisted_route_contract_issue759) { + return nextjs_persisted_contract(0); +} + +TEST(pipeline_nextjs_persisted_route_contract_parallel_issue759) { + return nextjs_persisted_contract(52); +} + +/* #759 over the life of a route file. Each step re-indexes the stored graph; + * after each, the file's current handlers are its only Routes, each once, and + * an unrelated route file keeps its Route. An unchanged tree is a no-op, and a + * change to another file rebuilds the unchanged route files' Routes from their + * stored handlers (pass_route_nodes.c), which a search still finds. */ +TEST(pipeline_nextjs_incremental_lifecycle_issue759) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_nextjs_life_XXXXXX"); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + write_temp_file(tmp, "app/api/items/route.ts", + "export function GET() {\n return 1;\n}\n" + "export async function POST() {\n return 2;\n}\n"); + write_temp_file(tmp, "app/api/health/route.ts", "export const GET = () => 'ok';\n"); + write_temp_file(tmp, "lib/helper.ts", "export function helper(): number {\n return 1;\n}\n"); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/nextjs.db", tmp); + + nextjs_run_t full; + nextjs_run(tmp, db_path, &full); + nextjs_run_t same; + nextjs_run(tmp, db_path, &same); + char found_same[1024]; + bool searched_same = + nextjs_found_routes(db_path, "app/api/*/route.ts", found_same, sizeof(found_same)); + + write_temp_file(tmp, "lib/helper.ts", "export function helper(): number {\n return 2;\n}\n"); + nextjs_run_t helper_only; + nextjs_run(tmp, db_path, &helper_only); + char found_repair[1024]; + bool searched_repair = + nextjs_found_routes(db_path, "app/api/*/route.ts", found_repair, sizeof(found_repair)); + + write_temp_file(tmp, "app/api/items/route.ts", "export function GET() {\n return 1;\n}\n"); + nextjs_run_t no_post; + nextjs_run(tmp, db_path, &no_post); + + write_temp_file(tmp, "app/api/items/route.ts", + "export function GET() {\n const n = 10;\n return n;\n}\n"); + nextjs_run_t new_body; + nextjs_run(tmp, db_path, &new_body); + + write_temp_file(tmp, "app/api/items/route.ts", "export function PATCH() {\n return 3;\n}\n"); + nextjs_run_t patch; + nextjs_run(tmp, db_path, &patch); + + write_temp_file(tmp, "app/api/products/route.ts", + "export function PATCH() {\n return 3;\n}\n"); + stem_unlink(tmp, "app/api/items/route.ts"); + nextjs_run_t moved; + nextjs_run(tmp, db_path, &moved); + + write_temp_file(tmp, "app/api/products/[id]/route.ts", + "export function PATCH() {\n return 3;\n}\n"); + stem_unlink(tmp, "app/api/products/route.ts"); + nextjs_run_t dynamic; + nextjs_run(tmp, db_path, &dynamic); + + stem_unlink(tmp, "app/api/products/[id]/route.ts"); + nextjs_run_t deleted; + nextjs_run(tmp, db_path, &deleted); + th_rmtree(tmp); + + static const char health[] = "GET /api/health __route__GET__/api/health " + "app/api/health/route.ts nextjs.app.api.health.route.GET"; + static const char routes[] = "GET /api/health __route__GET__/api/health " + "app/api/health/route.ts nextjs.app.api.health.route.GET\n" + "GET /api/items __route__GET__/api/items app/api/items/route.ts " + "nextjs.app.api.items.route.GET\n" + "POST /api/items __route__POST__/api/items app/api/items/route.ts " + "nextjs.app.api.items.route.POST"; + static const char get_only[] = "GET /api/health __route__GET__/api/health " + "app/api/health/route.ts nextjs.app.api.health.route.GET\n" + "GET /api/items __route__GET__/api/items app/api/items/route.ts " + "nextjs.app.api.items.route.GET"; + ASSERT_EQ(full.rc, 0); + ASSERT_TRUE(full.read); + ASSERT_STR_EQ(full.tuples, routes); + ASSERT_EQ(same.rc, 0); + ASSERT_EQ(same.route, CBM_INCREMENTAL_ROUTE_NOOP); + ASSERT_STR_EQ(same.tuples, routes); + ASSERT_TRUE(searched_same); + ASSERT_STR_EQ(found_same, "__route__GET__/api/health app/api/health/route.ts\n" + "__route__GET__/api/items app/api/items/route.ts\n" + "__route__POST__/api/items app/api/items/route.ts"); + ASSERT_EQ(helper_only.rc, 0); + ASSERT_EQ(helper_only.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_STR_EQ(helper_only.tuples, routes); + ASSERT_TRUE(searched_repair); + ASSERT_STR_EQ(found_repair, found_same); + ASSERT_EQ(no_post.rc, 0); + ASSERT_EQ(no_post.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_STR_EQ(no_post.tuples, get_only); + ASSERT_EQ(new_body.rc, 0); + ASSERT_EQ(new_body.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_STR_EQ(new_body.tuples, get_only); + ASSERT_EQ(patch.rc, 0); + ASSERT_STR_EQ(patch.tuples, "GET /api/health __route__GET__/api/health " + "app/api/health/route.ts nextjs.app.api.health.route.GET\n" + "PATCH /api/items __route__PATCH__/api/items " + "app/api/items/route.ts nextjs.app.api.items.route.PATCH"); + ASSERT_EQ(moved.rc, 0); + ASSERT_STR_EQ(moved.tuples, "GET /api/health __route__GET__/api/health " + "app/api/health/route.ts nextjs.app.api.health.route.GET\n" + "PATCH /api/products __route__PATCH__/api/products " + "app/api/products/route.ts nextjs.app.api.products.route.PATCH"); + ASSERT_EQ(dynamic.rc, 0); + ASSERT_STR_EQ(dynamic.tuples, + "GET /api/health __route__GET__/api/health " + "app/api/health/route.ts nextjs.app.api.health.route.GET\n" + "PATCH /api/products/:id __route__PATCH__/api/products/{} " + "app/api/products/[id]/route.ts nextjs.app.api.products.[id].route.PATCH"); + ASSERT_EQ(deleted.rc, 0); + ASSERT_STR_EQ(deleted.tuples, health); + PASS(); +} + +/* CBM_SEMANTIC_INDEX_VERSION 10 (#759): an index version 9 wrote has no route + * metadata, Route or HANDLES for a Next.js route file, and an unchanged tree + * is otherwise a no-op, so the version is what makes the new binary rebuild + * it. The stored index is put back to the version-9 state by hand (metadata, + * the handlers' route properties, the Routes and their edges); the run after + * that must replace it in full, the next one is a no-op. */ +TEST(pipeline_nextjs_semantic_upgrade_issue759) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_nextjs_upgrade_XXXXXX"); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + write_temp_file(tmp, "app/api/items/route.ts", + "export function GET() {\n return 1;\n}\n" + "export const POST = async () => 2;\n"); + write_temp_file(tmp, "lib/helper.ts", "export function helper(): number {\n return 1;\n}\n"); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/nextjs.db", tmp); + static const char all_nodes[] = "SELECT COUNT(*) FROM nodes"; + static const char all_edges[] = "SELECT COUNT(*) FROM edges"; + static const char routed[] = + "SELECT COUNT(*) FROM nodes WHERE json_extract(properties,'$.route_path') IS NOT NULL"; + + nextjs_run_t full; + nextjs_run(tmp, db_path, &full); + int nodes_before = k8s_inc_count(db_path, all_nodes); + int edges_before = k8s_inc_count(db_path, all_edges); + + /* Put the published index back to what version 9 wrote. */ + cbm_store_t *store = cbm_store_open_path(db_path); + ASSERT_NOT_NULL(store); + cbm_coverage_row_t *coverage_rows = NULL; + int coverage_count = 0; + ASSERT_EQ(cbm_store_coverage_get(store, "nextjs", &coverage_rows, &coverage_count), + CBM_STORE_OK); + cbm_coverage_meta_t meta = {0}; + ASSERT_EQ(cbm_store_coverage_meta_get(store, "nextjs", &meta), CBM_STORE_OK); + cbm_coverage_meta_t old_meta = meta; + old_meta.coverage_version = 9; + ASSERT_EQ( + cbm_store_coverage_replace_ex(store, "nextjs", coverage_rows, coverage_count, &old_meta), + CBM_STORE_OK); + cbm_store_free_coverage(coverage_rows, coverage_count); + cbm_store_coverage_meta_clear(&meta); + ASSERT_EQ(cbm_store_exec(store, + "DELETE FROM edges WHERE source_id IN (SELECT id FROM nodes WHERE " + "label = 'Route') OR target_id IN (SELECT id FROM nodes WHERE " + "label = 'Route');" + "DELETE FROM nodes WHERE label = 'Route';" + "UPDATE nodes SET properties = json_remove(properties, " + "'$.route_path', '$.route_method') " + "WHERE json_extract(properties, '$.route_path') IS NOT NULL;"), + CBM_STORE_OK); + cbm_store_close(store); + nextjs_run_t version_9 = {0}; + version_9.read = nextjs_route_tuples(db_path, version_9.tuples, sizeof(version_9.tuples)); + int routed_9 = k8s_inc_count(db_path, routed); + + /* Nothing in the tree changed: only the version says the index is stale. */ + nextjs_run_t upgrade; + nextjs_run(tmp, db_path, &upgrade); + int nodes_after = k8s_inc_count(db_path, all_nodes); + int edges_after = k8s_inc_count(db_path, all_edges); + int routed_after = k8s_inc_count(db_path, routed); + store = cbm_store_open_path(db_path); + ASSERT_NOT_NULL(store); + cbm_coverage_meta_t new_meta = {0}; + ASSERT_EQ(cbm_store_coverage_meta_get(store, "nextjs", &new_meta), CBM_STORE_OK); + int stored_version = new_meta.coverage_version; + cbm_store_coverage_meta_clear(&new_meta); + cbm_store_close(store); + nextjs_run_t again; + nextjs_run(tmp, db_path, &again); + th_rmtree(tmp); + + ASSERT_EQ(full.rc, 0); + ASSERT_STR_EQ(full.tuples, "GET /api/items __route__GET__/api/items app/api/items/route.ts " + "nextjs.app.api.items.route.GET\n" + "POST /api/items __route__POST__/api/items app/api/items/route.ts " + "nextjs.app.api.items.route.POST"); + ASSERT_TRUE(version_9.read); + ASSERT_STR_EQ(version_9.tuples, ""); + ASSERT_EQ(routed_9, 0); + ASSERT_EQ(upgrade.rc, 0); + ASSERT_EQ(upgrade.route, CBM_INCREMENTAL_ROUTE_FORCED_FULL); + ASSERT_STR_EQ(upgrade.tuples, full.tuples); + ASSERT_EQ(routed_after, 2); + ASSERT_EQ(nodes_after, nodes_before); + ASSERT_EQ(edges_after, edges_before); + ASSERT_EQ(stored_version, CBM_SEMANTIC_INDEX_VERSION); + ASSERT_EQ(again.rc, 0); + ASSERT_EQ(again.route, CBM_INCREMENTAL_ROUTE_NOOP); + ASSERT_STR_EQ(again.tuples, full.tuples); + ASSERT_GTE(CBM_SEMANTIC_INDEX_VERSION, 10); + PASS(); +} + +/* #759: a quote is legal in a POSIX directory name, so a route path, its file + * and its handler's QN can hold one, escaped in the stored JSON. The route pass + * builds the Route from its handler's stored properties on every index + * (pass_route_nodes.c), so the full index and an incremental one after an + * unrelated edit must both store it intact. */ +TEST(pipeline_nextjs_quoted_route_round_trip_issue759) { +#ifdef _WIN32 + SKIP_PLATFORM("a quote is not a legal Windows path character"); +#else + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_nextjs_quote_XXXXXX"); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + write_temp_file(tmp, "app/api/a\"b/route.ts", "export function GET() {\n return 1;\n}\n"); + write_temp_file(tmp, "lib/helper.ts", "export function helper(): number {\n return 1;\n}\n"); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/nextjs.db", tmp); + + nextjs_run_t full; + nextjs_run(tmp, db_path, &full); + write_temp_file(tmp, "lib/helper.ts", "export function helper(): number {\n return 2;\n}\n"); + nextjs_run_t helper_only; + nextjs_run(tmp, db_path, &helper_only); + th_rmtree(tmp); + + ASSERT_EQ(full.rc, 0); + ASSERT_TRUE(full.read); + ASSERT_STR_EQ(full.tuples, "GET /api/a\"b __route__GET__/api/a\"b app/api/a\"b/route.ts " + "nextjs.app.api.a\"b.route.GET"); + ASSERT_EQ(helper_only.rc, 0); + ASSERT_EQ(helper_only.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_TRUE(helper_only.read); + ASSERT_STR_EQ(helper_only.tuples, full.tuples); + PASS(); +#endif +} + /* `#include ` from arch/x/bugs.c: two headers end with the * include path (include/linux/device.h, tools/virtio/linux/device.h) and each * declares `struct device`. The exact-file lookup returned the first matching @@ -27771,6 +28188,11 @@ SUITE(pipeline) { RUN_TEST(pipeline_c_variants_on_sequential_and_parallel_paths_c1); RUN_TEST(pipeline_cpp_overloads_are_listed_as_variants_c1); RUN_TEST(pipeline_semantic_version_3_index_is_rebuilt_in_full_c1); + RUN_TEST(pipeline_nextjs_persisted_route_contract_issue759); + RUN_TEST(pipeline_nextjs_persisted_route_contract_parallel_issue759); + RUN_TEST(pipeline_nextjs_incremental_lifecycle_issue759); + RUN_TEST(pipeline_nextjs_semantic_upgrade_issue759); + RUN_TEST(pipeline_nextjs_quoted_route_round_trip_issue759); RUN_TEST(pipeline_python_app_factory_routes_issue1548); RUN_TEST(pipeline_python_nested_def_is_function_local_issue1548); RUN_TEST(pipeline_python_local_classes_stay_in_their_def_issue1548); From 349d80c64361df8d0aea8c695cf1549445088ddb Mon Sep 17 00:00:00 2001 From: Shane McCarron Date: Thu, 29 Oct 2026 11:46:19 -0500 Subject: [PATCH 23/32] perf(index): run supervised index workers at below-normal CPU priority A full index saturates every core in the parallel extraction pass, and interactive CLI/MCP queries (CPU-bound at start-up) were measured taking twice their wall time behind it with flat CPU time: pure run-queue contention. The index-worker role now lowers its own priority once, before any indexing thread is created: nice 10 on POSIX, BELOW_NORMAL_PRIORITY_CLASS on Windows. It never raises priority: a process already nicer than 10 (or in the IDLE / BELOW_NORMAL class) is left alone. Plain nice only, not macOS background QoS, which would pin indexing to efficiency cores and throttle its I/O. Failure is logged and ignored. The test runs the helper in a forked child and checks both legs: a normal-priority child ends at nice >= 10, and a child started nicer than that is left where it was. Refs #2834 Signed-off-by: Shane McCarron --- src/foundation/platform.c | 25 +++++++++++++++++++++ src/foundation/platform.h | 13 +++++++++++ src/main.c | 6 +++++ tests/test_platform.c | 47 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+) diff --git a/src/foundation/platform.c b/src/foundation/platform.c index d11df686e..3a4ac1642 100644 --- a/src/foundation/platform.c +++ b/src/foundation/platform.c @@ -729,3 +729,28 @@ const char *cbm_resolve_cache_dir(void) { } return buf; } + +/* ── CPU scheduling priority ────────────────── */ + +#ifndef _WIN32 +#include +#endif + +bool cbm_lower_cpu_priority(void) { +#ifdef _WIN32 + HANDLE self = GetCurrentProcess(); + DWORD current = GetPriorityClass(self); + if (current == IDLE_PRIORITY_CLASS || current == BELOW_NORMAL_PRIORITY_CLASS) { + return true; /* already at least this low: never raise priority */ + } + return SetPriorityClass(self, BELOW_NORMAL_PRIORITY_CLASS) != 0; +#else + /* getpriority can legitimately return -1, so errno is the only error signal. */ + errno = 0; + int current = getpriority(PRIO_PROCESS, 0); + if (errno == 0 && current >= CBM_LOW_CPU_PRIORITY_NICE) { + return true; /* already at least this nice: never raise priority */ + } + return setpriority(PRIO_PROCESS, 0, CBM_LOW_CPU_PRIORITY_NICE) == 0; +#endif +} diff --git a/src/foundation/platform.h b/src/foundation/platform.h index 40b020222..8eb462778 100644 --- a/src/foundation/platform.h +++ b/src/foundation/platform.h @@ -215,4 +215,17 @@ int64_t cbm_file_size(const char *path); * On POSIX, this is a no-op. Returns the input pointer. */ char *cbm_normalize_path_sep(char *path); +/* ── CPU scheduling priority ───────────────────────────────────── */ + +enum { CBM_LOW_CPU_PRIORITY_NICE = 10 }; + +/* Lower this process's CPU scheduling priority so background work yields the + * cores to interactive processes. POSIX: nice CBM_LOW_CPU_PRIORITY_NICE (never + * raises an already-nicer process). Plain nice only, deliberately not macOS + * background QoS: that pins work to efficiency cores and throttles I/O. + * Windows: BELOW_NORMAL_PRIORITY_CLASS. On Linux nice is per thread, so call + * this before creating threads; later threads inherit it. + * Returns false when the priority could not be changed. */ +bool cbm_lower_cpu_priority(void); + #endif /* CBM_PLATFORM_H */ diff --git a/src/main.c b/src/main.c index c2f22ada9..3f5e80e22 100644 --- a/src/main.c +++ b/src/main.c @@ -902,6 +902,12 @@ static int run_cli(int argc, char **argv, cbm_project_lock_manager_t *project_lo * own here, and only here (cbm_sqlite_dedicated_heap). */ cbm_sqlite_dedicated_heap(true); cbm_memev_process_role("worker"); + /* A full index saturates every core; run it below normal priority so + * interactive CLI/MCP queries are not starved. Before any indexing + * thread exists, so they all inherit it. Failure is harmless. */ + if (!cbm_lower_cpu_priority()) { + cbm_log_info("index.worker.priority", "lowered", "false"); + } } cbm_index_set_worker_role_options(index_worker, response_out, worker_single_thread, worker_marker, worker_quarantine, diff --git a/tests/test_platform.c b/tests/test_platform.c index 2c383c025..d83f90dab 100644 --- a/tests/test_platform.c +++ b/tests/test_platform.c @@ -16,6 +16,9 @@ #include #ifndef _WIN32 #include /* chmod for the symlink-policy mode legs */ +#include +#include /* getpriority for the worker-priority leg */ +#include #endif #ifdef __linux__ @@ -1442,6 +1445,49 @@ TEST(regex_estimate_counts_brackets_and_escapes_literally) { PASS(); } +/* An index worker lowers its own priority (#2834). A non-root process cannot + * raise it back, so the helper runs in a forked child that reports its nice. */ +TEST(platform_lower_cpu_priority_nices_the_process) { +#ifdef _WIN32 + SKIP_PLATFORM("POSIX nice contract"); +#else + int fds[2]; + ASSERT_EQ(pipe(fds), 0); + pid_t child = fork(); + if (child == 0) { + (void)close(fds[0]); + /* report: lowered ok, nice after; then, from a nicer start, ok, target, nice after */ + int report[5] = {cbm_lower_cpu_priority() ? 1 : 0, 0, 0, 0, 0}; + errno = 0; + report[1] = getpriority(PRIO_PROCESS, 0); + if (errno != 0) { + report[0] = 0; + } + /* Never-raise leg: start nicer than the helper's level; it must leave it. */ + report[3] = report[1] >= 15 ? 19 : 15; + if (setpriority(PRIO_PROCESS, 0, report[3]) == 0) { + report[2] = cbm_lower_cpu_priority() ? 1 : 0; + errno = 0; + report[4] = getpriority(PRIO_PROCESS, 0); + } + _exit(write(fds[1], report, sizeof(report)) == (ssize_t)sizeof(report) ? 0 : 1); + } + ASSERT_TRUE(child > 0); + (void)close(fds[1]); + int report[5] = {0, 0, 0, 0, 0}; + ssize_t got = read(fds[0], report, sizeof(report)); + (void)close(fds[0]); + int status = 0; + (void)waitpid(child, &status, 0); + ASSERT_EQ(got, (ssize_t)sizeof(report)); + ASSERT_EQ(report[0], 1); + ASSERT_TRUE(report[1] >= CBM_LOW_CPU_PRIORITY_NICE); + ASSERT_EQ(report[2], 1); + ASSERT_EQ(report[4], report[3]); + PASS(); +#endif +} + SUITE(platform) { RUN_TEST(platform_file_apis_survive_max_path_overflow); RUN_TEST(platform_mkdir_p_follows_own_symlink_only_when_opted_in); @@ -1477,6 +1523,7 @@ SUITE(platform) { RUN_TEST(platform_env_long_refuses_what_it_cannot_read); RUN_TEST(platform_env_dup_honours_the_settings_resolver); RUN_TEST(platform_system_info); + RUN_TEST(platform_lower_cpu_priority_nices_the_process); RUN_TEST(regex_compile_refuses_oversized_expansion); RUN_TEST(regex_compile_accepts_expansion_under_budget); RUN_TEST(regex_compile_refuses_overlong_pattern); From 11f20c578bf142a0a896f04f319491eec449c685 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:34:44 +0000 Subject: [PATCH 24/32] build(deps): bump actions/setup-python from 7.0.0 to 7.1.0 Bumps [actions/setup-python](https://github.com/actions/setup-python) from 7.0.0 to 7.1.0. - [Release notes](https://github.com/actions/setup-python/releases) - [Commits](https://github.com/actions/setup-python/compare/5fda3b95a4ea91299a34e894583c3862153e4b97...6d4fd22b20465ccc0f7354476588e8df7c9ca0e0) --- updated-dependencies: - dependency-name: actions/setup-python dependency-version: 7.1.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- .github/workflows/_test.yml | 2 +- .github/workflows/release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.yml index 501a82b20..ba967f283 100644 --- a/.github/workflows/_test.yml +++ b/.github/workflows/_test.yml @@ -318,7 +318,7 @@ jobs: with: node-version: "22" - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e4926260d..020ea3f0f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -535,7 +535,7 @@ jobs: # ── PyPI ───────────────────────────────────────────────── - name: Setup Python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.12' From 17415f6a3806a8529c0fc217b04f0cd9a056ce9f Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Sun, 1 Nov 2026 22:43:58 +0100 Subject: [PATCH 25/32] test(install): rename the Android guard test to the test_*.sh convention Every shell contract test under tests/ is named test_*.sh with underscores. A pure rename, so history and blame follow the file. Refs #1202 Signed-off-by: Martin Vogel --- ...est-install-android-guard.sh => test_install_android_guard.sh} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/{test-install-android-guard.sh => test_install_android_guard.sh} (100%) diff --git a/tests/test-install-android-guard.sh b/tests/test_install_android_guard.sh similarity index 100% rename from tests/test-install-android-guard.sh rename to tests/test_install_android_guard.sh From 1fc70c2024ed6ff7e4fb5c735a342143c8572e02 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Sun, 1 Nov 2026 22:43:58 +0100 Subject: [PATCH 26/32] test(install): run the Android guard test as Step 0x2 of scripts/test.sh scripts/test.sh lists every shell contract test explicitly and does not glob tests/, so an unlisted test never ran on any leg. Register tests/test_install_android_guard.sh as Step 0x2, right after Step 0x, in the same two-line shape as its neighbours. Give the two PATH stubs (uname, curl) the same shebang every other stub under tests/ uses, so they are proper executables on every leg instead of relying on the shell fallback for files without one. Refs #1202 Signed-off-by: Martin Vogel --- scripts/test.sh | 3 +++ tests/test_install_android_guard.sh | 2 ++ 2 files changed, 5 insertions(+) diff --git a/scripts/test.sh b/scripts/test.sh index 992aea837..baf41a935 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -278,6 +278,9 @@ bash "$ROOT/tests/test_language_count_contract.sh" echo "=== Step 0x: packaging version-metadata contract ===" bash "$ROOT/tests/test_version_metadata_contract.sh" +echo "=== Step 0x2: installer Android/Termux guard contract (#1202) ===" +bash "$ROOT/tests/test_install_android_guard.sh" + # Step 0y: the Windows leg must not decide its verdict from an exit status that # the ssh/msys2_shell chain can mangle — a channel that turns 0 into 1 can turn # 1 into 0, and that direction reports a RED Windows leg as green. Runs diff --git a/tests/test_install_android_guard.sh b/tests/test_install_android_guard.sh index 6b3a383a2..59503fc7d 100755 --- a/tests/test_install_android_guard.sh +++ b/tests/test_install_android_guard.sh @@ -7,6 +7,7 @@ trap 'rm -rf "$WORK"' EXIT mkdir -p "$WORK/bin" "$WORK/home" cat >"$WORK/bin/uname" <<'EOF' +#!/usr/bin/env bash case "$1" in -s) printf '%s\n' Linux ;; -m) printf '%s\n' aarch64 ;; @@ -15,6 +16,7 @@ case "$1" in esac EOF cat >"$WORK/bin/curl" <<'EOF' +#!/usr/bin/env bash printf 'curl must not run for Android/Termux\n' >&2 exit 99 EOF From 8b2b0d769f00dcfb994fd250ecbd9f58fd395973 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Sun, 1 Nov 2026 22:43:59 +0100 Subject: [PATCH 27/32] fix(install): say that Termux is not a supported platform yet The guard told users to build from source with scripts/build.sh in Termux, which reads as a supported path. Source builds under Termux still have open problems tracked in #1202, so the message now says why the portable binary cannot run there and that a source build may work but is not supported yet, pointing at #1202. The test still matches Android/Termux in the new message. Refs #1202 Signed-off-by: Martin Vogel --- install.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/install.sh b/install.sh index 01ab6c378..f3666e5d4 100755 --- a/install.sh +++ b/install.sh @@ -157,8 +157,8 @@ is_android() { OS=$(detect_os) ARCH=$(detect_arch) if [ "$OS" = "linux" ] && is_android; then - echo "error: Android/Termux is not supported by the Linux portable binary." >&2 - echo "Build from source with scripts/build.sh in Termux or use a supported Linux host." >&2 + echo 'error: Android/Termux cannot run the Linux portable binary (static glibc; Android kills it with "Bad system call").' >&2 + echo "Building from source in Termux may work but is not a supported platform yet - see issue #1202." >&2 exit 1 fi From 7a7ecb7356c152e0f6d22ac4d208b5919a21c862 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Sun, 1 Nov 2026 23:02:46 +0100 Subject: [PATCH 28/32] test(install): keep the Android guard test off the network Point CBM_DOWNLOAD_URL, the documented download-base override in install.sh, at a closed loopback port. If a curl stub were ever missed on some leg, the download would then fail locally instead of fetching a real release. Check that the uname stub is the one PATH resolves before running install.sh. Otherwise the test would quietly exercise the real host instead of an Android one and prove nothing. Refs #1202 Signed-off-by: Martin Vogel --- tests/test_install_android_guard.sh | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_install_android_guard.sh b/tests/test_install_android_guard.sh index 59503fc7d..b4bd6a704 100755 --- a/tests/test_install_android_guard.sh +++ b/tests/test_install_android_guard.sh @@ -22,8 +22,16 @@ exit 99 EOF chmod +x "$WORK/bin/uname" "$WORK/bin/curl" +# The stubs must be what install.sh sees, or this test proves nothing. +if [ "$(PATH="$WORK/bin:$PATH" uname -o)" != "Android" ]; then + printf 'FAIL: the uname stub is not picked up from PATH\n' >&2 + exit 1 +fi + set +e -output=$(PATH="$WORK/bin:$PATH" HOME="$WORK/home" bash "$ROOT/install.sh" --skip-config 2>&1) +output=$(PATH="$WORK/bin:$PATH" HOME="$WORK/home" \ + CBM_DOWNLOAD_URL="http://127.0.0.1:9/cbm-android-guard-test" \ + bash "$ROOT/install.sh" --skip-config 2>&1) rc=$? set -e From faf25ee4fa6a9ba7ff0f24a5091756f21f8611e3 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Mon, 2 Nov 2026 02:04:05 +0100 Subject: [PATCH 29/32] fix(config): drop the fuzz-link and Cypher hunks from the worktree change The review of 2026-10-01 asked to split these out of the ignore_worktrees change. Neither belongs to it, and both are already on main in another form, so this restores the three files to the branch merge-base: - Makefile.cbm: main links cbm-fuzz with -fsanitize-link-c++-runtime. - src/cypher/cypher.c and tests/test_cypher.c: main frees a partially parsed MATCH pattern since 70543ba82, with its own regression test cypher_parse_error_frees_partial_pattern. Signed-off-by: Martin Vogel --- Makefile.cbm | 4 ++-- src/cypher/cypher.c | 25 ++++++++----------------- tests/test_cypher.c | 19 ------------------- 3 files changed, 10 insertions(+), 38 deletions(-) diff --git a/Makefile.cbm b/Makefile.cbm index b2a655505..ab5c89db7 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -1381,10 +1381,10 @@ fuzz: CC=$(FUZZ_CC) CXX=$(FUZZ_CXX) SANITIZE="$(FUZZ_SANITIZE)" $(BUILD_DIR)/cbm-fuzz: $(FUZZ_SRC) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) - $(CXX) $(CFLAGS_TEST) -x c -fsanitize=fuzzer -o $@ \ + $(CC) $(CFLAGS_TEST) -fsanitize=fuzzer -o $@ \ $(FUZZ_SRC) $(PROD_SRCS) \ $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ - -x none $(OBJS_VENDORED_TEST) \ + $(OBJS_VENDORED_TEST) \ $(LDFLAGS_TEST) # Path-sensitive memory analysis: leak paths, null derefs, uninitialized reads. diff --git a/src/cypher/cypher.c b/src/cypher/cypher.c index 42ecb93c5..7c7a2f987 100644 --- a/src/cypher/cypher.c +++ b/src/cypher/cypher.c @@ -1862,8 +1862,6 @@ static int parse_return(parser_t *p, cbm_return_clause_t **out) { return parse_return_or_with(p, out, false); } -static void free_pattern(cbm_pattern_t *pat); - /* Parse a single MATCH pattern into pat */ static int parse_match_pattern(parser_t *p, cbm_pattern_t *pat) { memset(pat, 0, sizeof(*pat)); @@ -1872,38 +1870,31 @@ static int parse_match_pattern(parser_t *p, cbm_pattern_t *pat) { pat->nodes = malloc(node_cap * sizeof(cbm_node_pattern_t)); pat->rels = calloc(rel_cap, sizeof(cbm_rel_pattern_t)); - /* Count the slot before parsing so even partially filled nodes and - * relationships are released when a malformed pattern is rejected. */ - pat->node_count = SKIP_ONE; if (parse_node(p, &pat->nodes[0]) < 0) { - goto fail; + return CBM_NOT_FOUND; } + pat->node_count = SKIP_ONE; while (check(p, TOK_DASH) || check(p, TOK_LT)) { if (pat->rel_count >= rel_cap) { rel_cap *= PAIR_LEN; pat->rels = safe_realloc(pat->rels, rel_cap * sizeof(cbm_rel_pattern_t)); } - pat->rel_count++; - if (parse_rel(p, &pat->rels[pat->rel_count - SKIP_ONE]) < 0) { - goto fail; + if (parse_rel(p, &pat->rels[pat->rel_count]) < 0) { + return CBM_NOT_FOUND; } + pat->rel_count++; if (pat->node_count >= node_cap) { node_cap *= PAIR_LEN; pat->nodes = safe_realloc(pat->nodes, node_cap * sizeof(cbm_node_pattern_t)); } - pat->node_count++; - if (parse_node(p, &pat->nodes[pat->node_count - SKIP_ONE]) < 0) { - goto fail; + if (parse_node(p, &pat->nodes[pat->node_count]) < 0) { + return CBM_NOT_FOUND; } + pat->node_count++; } return 0; - -fail: - free_pattern(pat); - memset(pat, 0, sizeof(*pat)); - return CBM_NOT_FOUND; } /* Parse UNWIND [...] AS var clause into query */ diff --git a/tests/test_cypher.c b/tests/test_cypher.c index 5d198a0ef..7c251bd9b 100644 --- a/tests/test_cypher.c +++ b/tests/test_cypher.c @@ -274,24 +274,6 @@ TEST(cypher_parse_accepts_single_with_clause) { PASS(); } -TEST(cypher_parse_rejects_partial_patterns) { - const char *queries[] = { - "MATCH p = (a:Class)-[:INHERITS*1..3]->(b:Class) RETURN a.name, length(p)", - "MATCH (a)-[:CALLS]->(b) MATCH (c)-[:CALLS*]-> RETURN a.name", - "MATCH (a)-[:CALLS|]->(b)", - }; - for (size_t i = 0; i < sizeof(queries) / sizeof(queries[0]); i++) { - cbm_query_t *q = NULL; - char *err = NULL; - int rc = cbm_cypher_parse(queries[i], &q, &err); - ASSERT_NEQ(rc, 0); - ASSERT_NULL(q); - ASSERT_NOT_NULL(err); - free(err); - } - PASS(); -} - TEST(cypher_parse_relationship_outbound) { cbm_query_t *q = NULL; char *err = NULL; @@ -4860,7 +4842,6 @@ SUITE(cypher) { RUN_TEST(cypher_parse_rejects_trailing_tokens); RUN_TEST(cypher_parse_rejects_second_with_clause); RUN_TEST(cypher_parse_accepts_single_with_clause); - RUN_TEST(cypher_parse_rejects_partial_patterns); RUN_TEST(cypher_parse_relationship_outbound); RUN_TEST(cypher_parse_relationship_inbound); RUN_TEST(cypher_parse_relationship_any); From 77310d5f6f57a63a4bd0d65f6fc4035e41bc7cf3 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Mon, 2 Nov 2026 02:04:15 +0100 Subject: [PATCH 30/32] fix(cli): keep the hook default path untouched while ignore_worktrees is off The lifecycle hook now reads ignore_worktrees first and does nothing else for it while the key is off; the project lookup is then the one the hook did before the key existed. - cbm_mcp_ignore_worktrees_runtime_enabled() replaces cbm_mcp_server_attach_runtime_config(). It never attaches a store to the server, which may be the daemon session server. A server with a store answers from it. Otherwise the runtime store is opened only to read this key, and only when it already exists, so a hook event never creates _config.db. - cwd canonicalization, the linked-worktree probe and the parent-graph check moved into ha_resolve_project_ignoring_worktrees(), which runs only when the key is on. Test cli_hook_ignore_worktrees_default_off_does_no_worktree_work was red on the previous head (a default-off event created _config.db). It also pins, through a test-API counter, that neither an absent store nor a store without the key reaches the worktree gate, and that the key on reaches it once. mcp_ignore_worktrees_runtime_read_leaves_server_and_store_alone replaces the test of the removed helper. Signed-off-by: Martin Vogel --- src/cli/cli.h | 3 ++ src/cli/hook_augment.c | 93 ++++++++++++++++++++++++++---------------- src/mcp/mcp.c | 38 ++++++++++++----- src/mcp/mcp.h | 6 --- src/mcp/mcp_internal.h | 5 +++ tests/test_cli.c | 92 +++++++++++++++++++++++++++++++++++++++++ tests/test_mcp.c | 55 ++++++++++++++++--------- 7 files changed, 220 insertions(+), 72 deletions(-) diff --git a/src/cli/cli.h b/src/cli/cli.h index 4ac403387..6e0f85ff3 100644 --- a/src/cli/cli.h +++ b/src/cli/cli.h @@ -264,6 +264,9 @@ bool cbm_hook_path_contains_for_testing(const char *root, const char *candidate, bool case_insensitive); const char *cbm_hook_no_project_index_guidance_for_testing(const char *event, bool worktree_ignored); +/* Counts lifecycle calls that reached the ignore_worktrees resolution (cwd + * canonicalization and the linked-worktree probe). NULL stops counting. */ +void cbm_hook_set_worktree_gate_counter_for_testing(int *counter); bool cbm_hook_augment_parse_bash_pattern_for_testing(const char *cmd, char *out, size_t out_sz); bool cbm_mcp_command_path_probe_safe_for_testing(const char *command, bool windows); void cbm_set_mcp_command_path_probe_counter_for_testing(int *counter); diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.c index 384ba8467..61bc0100b 100644 --- a/src/cli/hook_augment.c +++ b/src/cli/hook_augment.c @@ -17,6 +17,7 @@ */ #include "cli/cli.h" +#include "foundation/compat.h" #include "foundation/compat_fs.h" #include "foundation/constants.h" #include "foundation/mem.h" @@ -1002,6 +1003,10 @@ static char *ha_resolve_indexed_project_with_root(cbm_mcp_server_t *srv, const c return ha_registry_project_for_path(srv, cwd, root_out, root_out_size); } +static char *ha_resolve_indexed_project(cbm_mcp_server_t *srv, const char *cwd) { + return ha_resolve_indexed_project_with_root(srv, cwd, NULL, 0U); +} + static const char *ha_hook_event_name(yyjson_val *root) { const char *event = ha_obj_str(root, "hook_event_name"); return event ? event : ha_obj_str(root, "hookEventName"); @@ -1459,6 +1464,41 @@ static bool ha_invocation_supported(ha_lifecycle_dialect_t dialect, const char * return !forced_event || ha_dialect_event_supported(dialect, forced_event); } +#ifdef CBM_CLI_ENABLE_TEST_API +static CBM_TLS int *g_ha_worktree_gate_counter = NULL; +#endif + +/* Project resolution once ignore_worktrees is on; the caller runs this only + * after reading the key, so the default path does none of it. A symlink alias + * has no .git of its own, and walking its lexical parents leaves the linked + * worktree. index_repository canonicalizes before the same gate, so the hook + * must too or it tells the agent to index a path the setting will refuse. The + * setting refuses a linked worktree even when it sits inside an indexed + * checkout or inside another linked worktree, so a match is kept only when its + * root belongs to this cwd's own linked worktree, not a parent graph. */ +static char *ha_resolve_project_ignoring_worktrees(cbm_mcp_server_t *srv, const char *cwd, + bool *drop_ancestor, bool *worktree_ignored) { +#ifdef CBM_CLI_ENABLE_TEST_API + if (g_ha_worktree_gate_counter) { + (*g_ha_worktree_gate_counter)++; + } +#endif + char canonical_cwd[4096]; + if (ha_canonical_path(cwd, canonical_cwd, sizeof(canonical_cwd))) { + cwd = canonical_cwd; + } + char project_root[4096]; + project_root[0] = '\0'; + char *project = + ha_resolve_indexed_project_with_root(srv, cwd, project_root, sizeof(project_root)); + bool linked = cbm_git_is_linked_worktree(cwd); + /* Drop a parent graph without a second free(): this file's raw free count + * is ratcheted, and the caller's single free(project) still releases it. */ + *drop_ancestor = linked && project && !cbm_git_same_linked_worktree(cwd, project_root); + *worktree_ignored = linked && (!project || *drop_ancestor); + return project; +} + static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root, const char *forced_event, ha_lifecycle_dialect_t dialect) { if (!root || !yyjson_is_obj(root)) { @@ -1471,47 +1511,24 @@ static char *ha_lifecycle_json_from_root(cbm_mcp_server_t *srv, yyjson_val *root char cwd_buffer[4096]; cbm_mcp_server_t *owned_server = NULL; - cbm_config_t *owned_config = NULL; if (!srv) { owned_server = cbm_mcp_server_new(NULL); srv = owned_server; } - /* cbm_mcp_server_new(NULL) does not attach the runtime store. The production - * hook uses that constructor, so ignore_worktrees would stay at its default - * (off) and the "not indexed" note would still tell the agent to run - * index_repository in a linked worktree the setting refuses. Load the store - * only when the caller has not already set one, then drop it before return - * so a caller-owned server is not left pointing at a closed config. */ - if (srv) { - owned_config = cbm_mcp_server_attach_runtime_config(srv); - } const char *cwd = ha_normalized_cwd_with_server(root, srv, cwd_buffer, sizeof(cwd_buffer)); - /* A symlink alias has no .git of its own, and walking its lexical parents - * leaves the linked worktree. index_repository canonicalizes before the - * same gate, so the hook must too or it tells the agent to index a path - * the setting will refuse. */ - char canonical_cwd[4096]; - if (cwd && ha_canonical_path(cwd, canonical_cwd, sizeof(canonical_cwd))) { - cwd = canonical_cwd; - } - char project_root[4096]; - project_root[0] = '\0'; - char *project = srv && cwd ? ha_resolve_indexed_project_with_root(srv, cwd, project_root, - sizeof(project_root)) - : NULL; - /* ignore_worktrees refuses a linked worktree, including one nested inside an - * indexed checkout or inside another linked worktree. Keep a match only when - * its root belongs to this cwd's own linked worktree, not a parent graph. */ - bool ignore_linked = - srv && cwd && cbm_mcp_ignore_worktrees_enabled(srv) && cbm_git_is_linked_worktree(cwd); - /* Drop a parent graph without a second free(): this file's raw free count - * is ratcheted, and the single free(project) below still releases it. */ - bool drop_ancestor = - ignore_linked && project && !cbm_git_same_linked_worktree(cwd, project_root); - bool worktree_ignored = ignore_linked && (!project || drop_ancestor); - if (owned_config) { - cbm_mcp_server_set_config(srv, NULL); - cbm_config_close(owned_config); + /* Read ignore_worktrees first and do nothing else for it while it is off. + * cbm_mcp_server_new(NULL) has no store, and srv may be the daemon's + * session server, so the read leaves srv untouched (see + * cbm_mcp_ignore_worktrees_runtime_enabled). Off, this is the resolution + * the hook did before the key existed. */ + bool drop_ancestor = false; + bool worktree_ignored = false; + char *project = NULL; + if (srv && cwd && cbm_mcp_ignore_worktrees_runtime_enabled(srv)) { + project = + ha_resolve_project_ignoring_worktrees(srv, cwd, &drop_ancestor, &worktree_ignored); + } else { + project = srv && cwd ? ha_resolve_indexed_project(srv, cwd) : NULL; } cbm_mcp_server_free(owned_server); @@ -1670,6 +1687,10 @@ const char *cbm_hook_no_project_index_guidance_for_testing(const char *event, return ha_no_project_index_guidance(event, worktree_ignored); } +void cbm_hook_set_worktree_gate_counter_for_testing(int *counter) { + g_ha_worktree_gate_counter = counter; +} + bool cbm_hook_augment_parse_bash_pattern_for_testing(const char *cmd, char *out, size_t out_sz) { return ha_parse_bash_search_pattern(cmd, out, out_sz); } diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c index c45ec6de8..00479171b 100644 --- a/src/mcp/mcp.c +++ b/src/mcp/mcp.c @@ -1849,17 +1849,6 @@ void cbm_mcp_server_set_config(cbm_mcp_server_t *srv, struct cbm_config *cfg) { } } -struct cbm_config *cbm_mcp_server_attach_runtime_config(cbm_mcp_server_t *srv) { - if (!srv || srv->config) { - return NULL; - } - cbm_config_t *config = cbm_config_open(cbm_resolve_cache_dir()); - if (config) { - cbm_mcp_server_set_config(srv, config); - } - return config; -} - #ifdef CBM_ENABLE_TEST_SEAMS void cbm_mcp_server_set_auto_index_count_test_hook(cbm_mcp_server_t *srv, cbm_mcp_auto_index_count_test_hook_fn hook, @@ -17928,6 +17917,33 @@ bool cbm_mcp_ignore_worktrees_enabled(const cbm_mcp_server_t *srv) { return cbm_config_get_bool(srv->config, CBM_CONFIG_IGNORE_WORKTREES, false); } +/* The same key for a caller whose server may have no store: the stand-alone + * lifecycle hook builds one with cbm_mcp_server_new(NULL), and the daemon lends + * its session server, which this must not modify. A server with a store answers + * from it. Otherwise the runtime store is opened only to read this key, and only + * when it exists: a missing store leaves every key at its default, so this read + * never creates one. */ +bool cbm_mcp_ignore_worktrees_runtime_enabled(const cbm_mcp_server_t *srv) { + if (srv && srv->config) { + return cbm_mcp_ignore_worktrees_enabled(srv); + } + const char *cache_dir = cbm_resolve_cache_dir(); + if (!cache_dir) { + return false; + } + char store_path[CBM_SZ_4K]; + int written = snprintf(store_path, sizeof(store_path), "%s/" CBM_CONFIG_DB_FILENAME, cache_dir); + cbm_path_info_t info; + if (written < 0 || (size_t)written >= sizeof(store_path) || + cbm_path_info_utf8(store_path, &info) != CBM_PATH_INFO_OK || !info.is_regular) { + return false; + } + cbm_config_t *config = cbm_config_open(cache_dir); + bool enabled = config && cbm_config_get_bool(config, CBM_CONFIG_IGNORE_WORKTREES, false); + cbm_config_close(config); + return enabled; +} + /* Register the session project with the background watcher for ongoing * change detection — unless auto_watch is disabled. */ static void register_watcher_if_enabled(cbm_mcp_server_t *srv) { diff --git a/src/mcp/mcp.h b/src/mcp/mcp.h index f2fe09b26..31ffd69b0 100644 --- a/src/mcp/mcp.h +++ b/src/mcp/mcp.h @@ -182,12 +182,6 @@ void cbm_mcp_server_set_watcher(cbm_mcp_server_t *srv, struct cbm_watcher *w); /* Set external config store reference (for auto_index setting). Not owned. */ void cbm_mcp_server_set_config(cbm_mcp_server_t *srv, struct cbm_config *cfg); -/* Open the runtime config and attach it when srv has none. The returned store - * is owned by the caller, who must clear it with cbm_mcp_server_set_config - * before closing. Returns NULL when a config is already set or the store - * cannot be opened. */ -struct cbm_config *cbm_mcp_server_attach_runtime_config(cbm_mcp_server_t *srv); - /* Set an explicit session context for an embedded/daemon-backed server. * session_root is copied and its project name is derived using the same naming * rule as indexing. allowed_root is copied when non-NULL; an explicit NULL diff --git a/src/mcp/mcp_internal.h b/src/mcp/mcp_internal.h index 8e78f9f40..fc4f37cb4 100644 --- a/src/mcp/mcp_internal.h +++ b/src/mcp/mcp_internal.h @@ -68,6 +68,11 @@ bool cbm_mcp_auto_index_within_file_limit(const char *root_path, int file_limit, * automatic index of a linked worktree should be skipped. */ bool cbm_mcp_ignore_worktrees_enabled(const cbm_mcp_server_t *srv); +/* The same key when srv may have no store (the lifecycle hook). Never attaches + * a store to srv and never creates the runtime store; reads it only when it + * already exists. */ +bool cbm_mcp_ignore_worktrees_runtime_enabled(const cbm_mcp_server_t *srv); + /* detect_changes seed scoping (#1363): does `node`'s line range overlap any * recorded hunk for `file`? Exposed for direct unit testing of the overlap * logic, independent of the git/subprocess/index plumbing around it. */ diff --git a/tests/test_cli.c b/tests/test_cli.c index af140c53f..586b78884 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -10944,6 +10945,96 @@ TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent) { FAIL("the indexed main checkout must still resolve in the same matrix"); PASS(); } + +/* With ignore_worktrees unset, the lifecycle hook must do what it did before + * the key existed. It may read the key, but it must not create a runtime + * config store just to find the key unset, and it must not canonicalize the + * cwd or probe for a linked worktree. Turning the key on is the positive + * control: the same call then reaches the worktree gate exactly once. */ +TEST(cli_hook_ignore_worktrees_default_off_does_no_worktree_work) { + char tmpdir[256]; + char *raw = th_mktempdir("cbm_hook_wt_off"); + if (!raw) + FAIL("th_mktempdir returned NULL"); + snprintf(tmpdir, sizeof(tmpdir), "%s", raw); + char cache[512]; + char maindir[512]; + char wtdir[512]; + char store_path[600]; + snprintf(cache, sizeof(cache), "%s/cache", tmpdir); + snprintf(maindir, sizeof(maindir), "%s/checkout-main", tmpdir); + snprintf(wtdir, sizeof(wtdir), "%s/checkout-side", tmpdir); + snprintf(store_path, sizeof(store_path), "%s/" CBM_CONFIG_DB_FILENAME, cache); + test_mkdirp(cache); + test_mkdirp(maindir); + + char cmd[2048]; + snprintf(cmd, sizeof(cmd), + "cd \"%s\" && git init -q && git config user.email t@t && git config user.name t && " + ": > f.txt && git add f.txt && git commit -qm init && " + "git worktree add -q \"%s\" -b wtoff", + maindir, wtdir); + if (system(cmd) != 0) { + th_rmtree(tmpdir); + SKIP_PLATFORM("git worktree add unavailable"); + } + + char *saved_cache = save_test_env("CBM_CACHE_DIR"); + cbm_setenv("CBM_CACHE_DIR", cache, 1); + + char input[1024]; + snprintf(input, sizeof(input), "{\"hook_event_name\":\"SessionStart\",\"cwd\":\"%s\"}", wtdir); + struct stat st; + int gate_calls = 0; + cbm_hook_set_worktree_gate_counter_for_testing(&gate_calls); + bool store_absent_before = stat(store_path, &st) != 0; + char *off_out = cbm_hook_augment_lifecycle_json(input); + bool off_note = off_out && strstr(off_out, "Run index_repository") && + !strstr(off_out, "ignore_worktrees is enabled"); + free(off_out); + bool store_absent_after = stat(store_path, &st) != 0; + int off_gate_calls = gate_calls; + + /* A store that leaves the key unset may be read for the key, nothing more. */ + cbm_config_t *cfg = cbm_config_open(cache); + bool other_key_set = cfg && cbm_config_set(cfg, CBM_CONFIG_AUTO_WATCH, "true") == 0; + cbm_config_close(cfg); + gate_calls = 0; + char *unset_out = other_key_set ? cbm_hook_augment_lifecycle_json(input) : NULL; + bool unset_note = unset_out && strstr(unset_out, "Run index_repository") && + !strstr(unset_out, "ignore_worktrees is enabled"); + free(unset_out); + int unset_gate_calls = gate_calls; + + cfg = cbm_config_open(cache); + bool enabled = cfg && cbm_config_set(cfg, CBM_CONFIG_IGNORE_WORKTREES, "true") == 0; + cbm_config_close(cfg); + gate_calls = 0; + char *on_out = enabled ? cbm_hook_augment_lifecycle_json(input) : NULL; + bool on_note = on_out && strstr(on_out, "ignore_worktrees is enabled"); + free(on_out); + int on_gate_calls = gate_calls; + cbm_hook_set_worktree_gate_counter_for_testing(NULL); + + restore_test_env("CBM_CACHE_DIR", saved_cache); + snprintf(cmd, sizeof(cmd), "cd \"%s\" && git worktree remove --force \"%s\" >/dev/null 2>&1", + maindir, wtdir); + (void)system(cmd); + th_rmtree(tmpdir); + + ASSERT_TRUE(store_absent_before); + ASSERT_TRUE(off_note); + if (!store_absent_after) + FAIL("a default-off lifecycle event must not create the runtime config store"); + ASSERT_EQ(off_gate_calls, 0); + ASSERT_TRUE(other_key_set); + ASSERT_TRUE(unset_note); + ASSERT_EQ(unset_gate_calls, 0); + ASSERT_TRUE(enabled); + ASSERT_TRUE(on_note); + ASSERT_EQ(on_gate_calls, 1); + PASS(); +} #endif TEST(cli_hook_session_sanitizes_untrusted_project_metadata) { @@ -16975,6 +17066,7 @@ SUITE(cli) { #ifndef _WIN32 RUN_TEST(cli_hook_worktree_cwd_resolves_own_indexed_project); RUN_TEST(cli_hook_unindexed_worktree_reports_no_match_not_silent); + RUN_TEST(cli_hook_ignore_worktrees_default_off_does_no_worktree_work); #endif RUN_TEST(cli_hook_session_sanitizes_untrusted_project_metadata); RUN_TEST(cli_hook_ownership_requires_exact_command_identity); diff --git a/tests/test_mcp.c b/tests/test_mcp.c index 8eab275a2..257e799ad 100644 --- a/tests/test_mcp.c +++ b/tests/test_mcp.c @@ -10,6 +10,7 @@ #include "../src/foundation/log.h" #include "../src/foundation/platform.h" /* cbm_file_size */ #include "../src/foundation/mem.h" /* cbm_mem_set_budget_for_tests — over-budget seam */ +#include "../src/foundation/str_util.h" #include "../src/foundation/subprocess.h" #include "../src/foundation/workspace.h" #include "../src/mcp/compact_out.h" @@ -1202,37 +1203,53 @@ TEST(mcp_initialize_response) { PASS(); } -TEST(mcp_attach_runtime_config_respects_caller_ownership) { - char *cache = th_mktempdir("cbm_mcp_runtime_config"); - ASSERT_NOT_NULL(cache); +/* The lifecycle hook reads ignore_worktrees through this reader. It must never + * attach a store to the server (the daemon lends its session server) and never + * create the runtime store; a server with its own store answers from it. */ +TEST(mcp_ignore_worktrees_runtime_read_leaves_server_and_store_alone) { + char *raw = th_mktempdir("cbm_mcp_runtime_config"); + ASSERT_NOT_NULL(raw); + char cache[256]; + snprintf(cache, sizeof(cache), "%s", raw); + char own_dir[320]; + snprintf(own_dir, sizeof(own_dir), "%s/own", cache); + char store_path[400]; + snprintf(store_path, sizeof(store_path), "%s/" CBM_CONFIG_DB_FILENAME, cache); const char *saved = getenv("CBM_CACHE_DIR"); char *saved_copy = saved ? strdup(saved) : NULL; cbm_setenv("CBM_CACHE_DIR", cache, 1); - cbm_config_t *config = cbm_config_open(cache); cbm_mcp_server_t *server = cbm_mcp_server_new(NULL); - bool stored = config && cbm_config_set(config, CBM_CONFIG_IGNORE_WORKTREES, "true") == 0; - bool default_off = server && !cbm_mcp_ignore_worktrees_enabled(server); - cbm_config_t *attached = server ? cbm_mcp_server_attach_runtime_config(server) : NULL; - bool enabled = attached && cbm_mcp_ignore_worktrees_enabled(server); - bool not_replaced = server && cbm_mcp_server_attach_runtime_config(server) == NULL; + struct stat st; + bool absent_off = server && !cbm_mcp_ignore_worktrees_runtime_enabled(server); + bool still_absent = stat(store_path, &st) != 0; + + cbm_config_t *runtime = cbm_config_open(cache); + bool stored = runtime && cbm_config_set(runtime, CBM_CONFIG_IGNORE_WORKTREES, "true") == 0; + cbm_config_close(runtime); + bool runtime_on = server && cbm_mcp_ignore_worktrees_runtime_enabled(server); + bool server_untouched = server && !cbm_mcp_ignore_worktrees_enabled(server); + + cbm_config_t *own = cbm_config_open(own_dir); + if (server && own) { + cbm_mcp_server_set_config(server, own); + } + bool own_store_wins = server && own && !cbm_mcp_ignore_worktrees_runtime_enabled(server); if (server) { - cbm_mcp_server_set_config(server, config); + cbm_mcp_server_set_config(server, NULL); } - cbm_config_close(attached); - bool caller_config_kept = server && cbm_mcp_server_attach_runtime_config(server) == NULL && - cbm_mcp_ignore_worktrees_enabled(server); cbm_mcp_server_free(server); - cbm_config_close(config); + cbm_config_close(own); restore_cache_dir(saved_copy); free(saved_copy); int removed = th_rmtree(cache); + ASSERT(absent_off); + ASSERT(still_absent); ASSERT(stored); - ASSERT(default_off); - ASSERT(enabled); - ASSERT(not_replaced); - ASSERT(caller_config_kept); + ASSERT(runtime_on); + ASSERT(server_untouched); + ASSERT(own_store_wins); ASSERT_EQ(removed, 0); PASS(); } @@ -21182,7 +21199,7 @@ SUITE(mcp) { /* MCP protocol helpers */ RUN_TEST(mcp_initialize_response); - RUN_TEST(mcp_attach_runtime_config_respects_caller_ownership); + RUN_TEST(mcp_ignore_worktrees_runtime_read_leaves_server_and_store_alone); RUN_TEST(mcp_tools_list); RUN_TEST(mcp_tools_help_list_matches_registry); RUN_TEST(mcp_tools_list_latest_metadata); From 04ed0240e9f62778b578444f67494421c41a064e Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Mon, 2 Nov 2026 02:04:21 +0100 Subject: [PATCH 31/32] docs(config): state how ignore_worktrees treats subdirectories The review of 2026-10-01 asked for this to be a stated decision rather than a side effect. Detection walks up from the given path to the nearest .git entry, so a subdirectory of a linked worktree is treated as that worktree: index_repository on it is refused, and a session root or hook working directory inside it is handled the same way. The walk stops at the first .git; outside any checkout it runs to the filesystem root one directory at a time. None of it runs while the key is off. Signed-off-by: Martin Vogel --- docs/CONFIGURATION.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 99a2a328a..181a8aad4 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -154,6 +154,15 @@ The main checkout of the same repository is unaffected, as are ordinary clones and submodules. Detection is git plumbing only: a linked worktree's `.git` is a file pointing at a gitdir that contains a `commondir` entry. +A subdirectory counts as the worktree it sits in. Detection walks up from the +given path to the nearest `.git` entry, so `index_repository` on any +subdirectory of a linked worktree is refused the same way, and a session root or +hook working directory inside one is treated as that worktree. The walk stops at +the first `.git` it finds; a main checkout or a submodule ends it as "not a +worktree". A path outside any git checkout is checked one directory at a time up +to the filesystem root and is never treated as a worktree. None of this runs +while the key is off. + The default is `false`, so indexing behavior is unchanged unless you opt in. ## 3. UI Settings From 141b25af7b46ffff462615b8003d3f27ee263e45 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Mon, 2 Nov 2026 02:16:53 +0100 Subject: [PATCH 32/32] fix(mcp): do not shadow cache_dir() in the ignore_worktrees reader cppcheck 2.20 (the CI version) reports shadowFunction: the local cache_dir in cbm_mcp_ignore_worktrees_runtime_enabled() shadows the static cache_dir() helper in mcp.c. Rename the local to store_dir; no behavior change. Signed-off-by: Martin Vogel --- src/mcp/mcp.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c index 4166b74e6..c82f90f11 100644 --- a/src/mcp/mcp.c +++ b/src/mcp/mcp.c @@ -21589,18 +21589,18 @@ bool cbm_mcp_ignore_worktrees_runtime_enabled(const cbm_mcp_server_t *srv) { if (srv && srv->config) { return cbm_mcp_ignore_worktrees_enabled(srv); } - const char *cache_dir = cbm_resolve_cache_dir(); - if (!cache_dir) { + const char *store_dir = cbm_resolve_cache_dir(); + if (!store_dir) { return false; } char store_path[CBM_SZ_4K]; - int written = snprintf(store_path, sizeof(store_path), "%s/" CBM_CONFIG_DB_FILENAME, cache_dir); + int written = snprintf(store_path, sizeof(store_path), "%s/" CBM_CONFIG_DB_FILENAME, store_dir); cbm_path_info_t info; if (written < 0 || (size_t)written >= sizeof(store_path) || cbm_path_info_utf8(store_path, &info) != CBM_PATH_INFO_OK || !info.is_regular) { return false; } - cbm_config_t *config = cbm_config_open(cache_dir); + cbm_config_t *config = cbm_config_open(store_dir); bool enabled = config && cbm_config_get_bool(config, CBM_CONFIG_IGNORE_WORKTREES, false); cbm_config_close(config); return enabled;