101 Commits
Author SHA1 Message Date
Martin Vogel bebc6d8d57 Use GIT_AUTHOR/COMMITTER env vars in test_watcher instead of git config
Previous tests ran `cd <tmpdir> && git config user.email test@test && ...`
to set up author info for test commits. If the tmpdir path was ever
interpreted differently (or if the test process inherited a cwd inside
a real git repo), the `git config` call could write to a real repo's
.git/config instead of the temp repo's.

Replace with `export GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t ...` which
are ephemeral env vars that can never leak into persistent config.
2026-04-16 11:09:09 +02:00
test 2c8be91757 Merge branch 'worktree-add-new-languages'
# Conflicts:
#	internal/cbm/lang_specs.c
2026-04-16 10:47:10 +02:00
testandDustin Obrecht a8406bd4c9 fix: implement overflow pages in sqlite_writer to prevent SIGBUS on large records
When a single record payload exceeds 65KB (max_local=65501), the writer
now splits it across overflow pages per SQLite's B-tree spec instead of
underflowing the content_offset and corrupting memory.

Closes #139, closes #187.
Based on #175 by dLo999.

Co-Authored-By: Dustin Obrecht <dustin@kurtnoble.com>
2026-04-15 23:56:03 +02:00
testandDustin Obrecht 404b5f822c feat: add Kiro CLI support (#96)
Detect ~/.kiro/ directory, auto-configure MCP at ~/.kiro/settings/mcp.json
using standard mcpServers format. Adds install, uninstall, detection, and test.

Based on #174 by dLo999, rebased onto refactored install infrastructure.

Co-Authored-By: Dustin Obrecht <dustin@kurtnoble.com>
2026-04-15 23:56:03 +02:00
test 8babe67bea feat: add persistent artifact storage for team sharing
Add .codebase-memory/graph.db.zst — a zstd-compressed knowledge graph
artifact that can be committed to the repo. Teammates bootstrap from
the artifact instead of running a full reindex from scratch.

- Vendor zstd 1.5.7 (amalgamated build) for 8-13:1 compression
- Two-tier export: zstd -9 + index stripping for explicit index,
  zstd -3 for watcher/incremental auto-updates
- Import: decompress → integrity check → auto-recreate indexes
- Bootstrap in handle_index_repository: when no local DB exists but
  artifact is present, import first then run incremental
- Auto-create .gitattributes with merge=ours to prevent conflicts
- Fix: add missing idx_edges_url_path to create_user_indexes and
  url_path_gen generated column to init_schema
- 13 new tests (5 zstd wrapper + 8 artifact round-trip/edge cases)
2026-04-15 23:56:03 +02:00
test ea98c91cf5 Add 77 extension mapping tests for new languages
Add automated extension-to-language mapping tests for all new grammars
that have file extensions. Removes conflicting extensions:
- .blade.php: compound extension, handled by userconfig system
- .env*: filenames, not extensions (no auto-discovery for dotfiles)
- .sv/.svh: already mapped to Verilog, SystemVerilog uses same grammar
2026-04-15 22:28:31 +02:00
Martin VogelanddLo999 6f268d0f91 Respect nested .gitignore files during indexing, security audit all variants
Nested .gitignore support (fixes #178):
- Load per-subdirectory .gitignore during walk, match paths relative to
  the gitignore's directory via local_rel_path()
- Root and nested gitignores stack independently
- Owned gitignores collected and freed at walk end (avoids use-after-free
  from borrowed pointers on the iterative stack)

Security:
- Run security-strings/install/network + ClamAV + Windows Defender on
  ALL binary variants (standard + UI), not just standard
- Whitelist UI bundle URLs (React, Three.js, Google Fonts, Tailwind, W3C)

Co-Authored-By: dLo999 <dLo999@users.noreply.github.com>
2026-04-06 19:44:16 +02:00
Martin Vogel 36aaa5d9f8 Add missing platform.h include for cbm_safe_getenv in userconfig test 2026-04-06 14:34:07 +02:00
Martin Vogel 07f78e8933 Fix userconfig test on Windows: use APPDATA instead of XDG_CONFIG_HOME
cbm_app_config_dir() reads APPDATA on Windows, not XDG_CONFIG_HOME.
Test now sets the platform-appropriate env var and restores it after.
2026-04-06 14:20:59 +02:00
Martin Vogel 616a4307df Fix Windows agent detection paths to use home_dir consistently
Zed: AppData/Local/Zed, Kilocode/VSCode: AppData/Roaming/Code/...
Tests now have #ifdef _WIN32 branches matching the detection paths.
2026-04-06 14:01:03 +02:00
Martin Vogel e81a796fe6 Embed Nomic nomic-embed-code pretrained vectors (40K tokens × 768d) for semantic search quality
Major quality improvement: replace random index vectors with pre-trained
Nomic nomic-embed-code token embeddings. Tokens like 'error' and 'exception' now start
with similar vectors (learned from millions of code repos) instead of
arbitrary random projections. Co-occurrence enrichment adds project-specific
context on top.

Architecture:
- vendored/nomic/code_vectors.bin: 37.7MB raw int8 vectors
- vendored/nomic/code_vectors_blob.S: assembler .incbin (instant build)
- vendored/nomic/code_vectors.h: extern declarations + pretrained_vec_at()
- vendored/nomic/code_tokens.h: 40856 token strings (575KB)
- semantic.c: cbm_sem_random_index() now looks up pretrained vectors first,
  falls back to sparse random for unknown tokens
- CBM_SEM_DIM raised from 256 to 768 to match Nomic nomic-embed-code

Also: RRI (Reflective Random Indexing), code pattern vocabulary injection,
120+ abbreviation expansions, callee/caller/body token enrichment,
label filter (Function/Method/Class only) in vector search SQL.

Binary size: 136MB → 169MB (+33MB from embedded vectors).
Search quality: keyword queries return relevant error-handling functions.
Domain-specific keyword queries return the expected functions.
2026-04-06 12:41:29 +02:00
Martin Vogel 7a9b7db830 Add semantic_query to search_graph: vector search via cbm_cosine_i8 SQL function
Vector search pipeline (end-to-end):
- store.c: cbm_cosine_i8 custom SQLite function (int8 dot product with
  sqrt magnitude), registered at store open time
- store.c: cbm_store_vector_search() builds merged query vector from
  keywords via base RI vectors (xxHash), int8-quantizes, runs SQL query
  with JOIN nodes ON node_id = id for metadata
- mcp.c: search_graph gains semantic_query param (array of strings),
  returns semantic_results alongside regular results
- sqlite_writer.c: fixed build_vector_record to include node_id in
  record body (matches build_node_record pattern)
- mcp.c: use yyjson_mut_obj_add_strcpy (not add_str) to avoid
  use-after-free when vector results are freed before JSON serialization

Quality note: base RI vectors at query time don't capture co-occurrence
enrichment — results are moderate quality. Storing enriched token vectors
would improve this significantly (future work).
2026-04-04 17:14:47 +02:00
Martin Vogel 09ce20afc8 Improve MinHash quality: leaf-only tokens, structural weighting, unique trigram gate
Four changes to reduce false positives from 382K to 58K SIMILAR_TO edges
on the Linux kernel while maintaining ~98% precision:

1. MIN_NODES raised to 30 (leaf tokens) — aligns with BigCloneBench
   standard of 50 raw source tokens / 6 lines minimum clone size

2. collect_ast_tokens now records LEAF nodes only, not internal grammar
   nodes. Leaf-only counting is language-agnostic: leaves correspond to
   actual source tokens regardless of grammar verbosity (C tree-sitter
   produces 2x more internal nodes than Python for the same logic)

3. hash_trigrams tracks unique structural trigram count via hash set.
   Functions with < 32 unique structural trigrams are skipped — too few
   distinct features for K=64 MinHash to produce reliable estimates

4. Structural-weighted MinHash via repetition: each trigram gets weight
   0-3 based on count of non-normalised tokens (I/S/N/T = normalised).
   Weight-0 trigrams (all-normalised, e.g. I|I|I) are pure noise and
   skipped entirely. Weight 1-3 trigrams use repetition-based weighted
   MinHash — higher weight = more hash attempts per seed = more likely
   to dominate the signature. Achieves IDF-like effect without needing
   corpus-wide statistics.

Also adds O(1) hash-set dedup in LSH query (replacing O(n) linear scan)
and bucket size cap of 200 to skip oversized buckets.

Linux kernel: 1:41, similarity 7.7s, 395K fp, 58K edges, ~98% precision.
Tests updated with larger Go functions to meet new thresholds.
2026-04-03 22:35:01 +02:00
Martin Vogel 452f5a7b1f Add MinHash fingerprinting and SIMILAR_TO edges for near-clone detection
Compute K=64 MinHash signatures from normalized AST node-type trigrams
during function extraction, then generate SIMILAR_TO edges via LSH
(b=32, r=2) for function pairs with Jaccard >= 0.95.

- src/simhash/minhash.{h,c}: MinHash compute, Jaccard, hex encode/decode,
  LSH index with band hashing for O(n) candidate generation
- src/pipeline/pass_similarity.c: post-pass reads fingerprints from node
  properties, builds LSH index, emits SIMILAR_TO edges with jaccard and
  same_file metadata. Same-language only, max 10 edges per node.
- internal/cbm/cbm.h: fingerprint fields on CBMDefinition
- internal/cbm/extract_defs.c: compute_fingerprint() hook at 3 extraction
  sites after complexity, skip functions with < 10 AST body nodes
- pass_definitions.c + pass_parallel.c: serialize fingerprint to "fp" hex
  in properties_json for both sequential and parallel pipeline paths
- pipeline.c + pipeline_incremental.c: register pass_similarity in both
  full and incremental post-pass lists
- tests/test_simhash.c: 28 tests across 4 suites (core, LSH, edge gen,
  pipeline integration with generated Go project + incremental)
2026-04-03 20:06:33 +02:00
Martin Vogel 80e2752c09 Fix KiloCode config paths on Windows and macOS
KiloCode is a VS Code extension — uses the same base config dir.
Apply same platform-aware paths as Zed/VS Code: macOS uses
$HOME/Library/Application Support/Code/, Windows uses %APPDATA%/Code/.
2026-04-03 16:23:36 +02:00
Martin Vogelandmaplenk f25dafadff Add include_tests param to trace_path, mark test files in BFS results
When include_tests=false (default), test files are filtered from trace
results. When true, test nodes appear with is_test=true marker. Helps
answer "which tests cover this function's blast radius?"

Also adds tests for include_tests and risk_labels params.

Co-Authored-By: maplenk <maplenk@users.noreply.github.com>
2026-04-03 01:51:32 +02:00
Martin Vogelandgdilla 191428557b Consolidate 4 skills into 1 with progressive disclosure
Merge codebase-memory-exploring, codebase-memory-tracing,
codebase-memory-quality, codebase-memory-reference into single
codebase-memory skill with decision matrix, workflows, and gotchas.

Old skill directories are cleaned up automatically during install.

Factual corrections vs original PR: trace_call_path -> trace_path,
removed non-existent tools (read_file, list_directory) and edge types
(OVERRIDE, USAGE, FILE_CHANGES_WITH), removed risk_labels parameter.

Co-Authored-By: gdilla <gdilla@users.noreply.github.com>
2026-04-02 23:15:43 +02:00
Martin Vogel 8e8fac9294 Skip POSIX-only CLI path lookup tests on Windows
cli_find_cli_on_path and cli_find_cli_fallback_paths use /tmp paths
and #!/bin/sh shebangs that don't work on MSYS2/Windows.
2026-04-02 18:52:52 +02:00
Martin Vogel 05454009c9 Fix incremental test data: inject in setup, use unique names in modify test
Inject incr_test_injected/helper in suite setup so tool tests work
with CBM_SKIP_PERF=1. Use different function names in incr_modify_file
to avoid duplicate injection. Update baseline counts after injection.
Lower graph thresholds for sparse checkout on CI.
2026-04-02 18:17:25 +02:00
Martin Vogel c761106516 Fix CBM_SKIP_PERF to only skip incremental delta tests, not tool tests
CBM_SKIP_PERF=1 now skips only phases 2-7 (incremental delta, stress,
perf regression) inside the suite. Phase 1 (initial index) and phases
8-30 (135 tool integration tests) always run. This keeps ~2672 tests
on CI vs the full ~2692 locally.

Also fix Windows build: guard symlink() with #ifndef _WIN32.
2026-04-02 16:34:06 +02:00
Martin Vogel 8349f819de Fix Windows build: guard symlink() call with #ifndef _WIN32
The SKIP() macro returns at runtime but the compiler still sees the
undeclared symlink() function. Use #else to hide the entire body.
2026-04-02 16:29:24 +02:00
Martin Vogel 1b84943000 Separate perf tests from CI, fix cross-platform build issues
- Add CBM_SKIP_PERF=1 env var to skip incremental/perf test suite
- CI and Docker test targets skip perf by default (run.sh perf for manual)
- Convert all perf assertions to warnings (log timing, never block)
- Fix store.h anonymous enum in struct (GCC rejects, clang accepts)
- Fix test_store_search.c mkstemp on non-template path
- Add ca-certificates to Docker test image for git HTTPS
- Add cbm_gmtime_r shim in compat.h (Windows gmtime_s wrapper)
- Fix compat.c missing constants.h include (Windows build)
- Fix platform.c _environ redeclaration on mingw
- Rename trace_call_path -> trace_path in smoke/soak/fuzz scripts
2026-04-02 14:52:14 +02:00
Martin Vogel 7f8359316c Use sparse checkout on CI to halve incremental test time
On CI runners, skip docs/ and tests/ directories when cloning
FastAPI (62% of 18K files). The fastapi/ package source remains
intact for all test assertions. Locally, full clone is preserved.
2026-04-02 13:41:01 +02:00
Martin Vogel e582df3194 Convert perf assertions to warnings, add CI job timeout
Shared CI runners are too variable for hard timing thresholds.
Performance is still logged and warns above 15s, but no longer
blocks the test suite. Added 30min timeout on test-unix jobs.
2026-04-02 13:33:43 +02:00
Martin Vogel 7fa3acd0c6 WIP: strict linting + RAM-first pipeline (lint fixes pending) 2026-04-01 23:22:44 +02:00
Martin Vogel f26acd4ced Eliminate NOLINTNEXTLINE suppressions + iterative AST walkers
Remove ~480 dead per-line NOLINTNEXTLINE comments. Update .clang-tidy with
documented upstream bug references for disabled checks.

Convert key AST walkers to iterative with explicit stacks: walk_defs (with
context-aware stack frames for class nesting), walk_throws, walk_readwrites,
walk_calls, walk_usages, walk_env_accesses, extract_elixir_call, glob_match,
cbm_yaml_free, rmdir_recursive, resolve_func_name, walk_variables_iter,
count_branching. Reversed child push for left-to-right traversal.

Disable readability-implicit-bool-conversion globally — designed for C++,
flags all idiomatic C patterns (bool = x && y) with no config to allow them.

Fix clang-format, implicit-bool edge cases, add test_helpers.h.
2026-03-31 20:04:11 +02:00
Martin Vogel 88fea661bc Fix prefix-decorator false positives + HCL infra binding extraction
Prefix-to-decorator bridge now matches by file path segments: prefix
"/bq/bulk/ranked" only connects to handlers in paths containing
"bq/bulk/ranked", not all handlers in the service.

HCL infra binding extraction: scan resource blocks for attribute pairs
with source keys (topic, queue_name) and target keys (uri, push_endpoint).
Handles nested blocks (push_config { push_endpoint = "..." }).
2026-03-31 20:04:11 +02:00
Martin Vogel 1c7b0a4d6c Pure AST decorator route extraction + end-to-end DATA_FLOWS
Extract route_path and route_method directly from decorator AST nodes
during tree-sitter walk. Route + HANDLES edges created during
definition node creation. ensure_decorator_routes pass recreates
Route+HANDLES for existing nodes in incremental mode.

Prefix Routes bridged to handler Functions by service directory matching.
2026-03-31 20:04:11 +02:00
Martin Vogel 85c6c6f00c Fix B-tree sep_cell leak in sqlite_writer + CI test timing
sqlite_writer.c pb_build_interior: final root-level sep_cell
allocations were not freed. Each cbm_write_db call leaked 84 bytes.
Detected by ASan on Linux CI with 155 incremental test iterations.

Also fix CI timing: use MAX_TOOL_MS (15s) for perf assertions,
skip timing on full re-index operations (CI runners are slower).
2026-03-28 16:15:25 +01:00
Martin Vogel c84dd6f32f Fix CI test flakes: no timing on full re-index, portable path assertion 2026-03-28 15:08:46 +01:00
Martin Vogel 17db27adfa Schema properties, DATA_FLOWS, YAML nested extraction, trace_path tool
- Serialize return_type, parent_class, base_classes on definition nodes
- DATA_FLOWS edges link callers through Route nodes to handlers
- YAML nested field extraction with dotted key paths (key_path property)
- Rename trace_call_path → trace_path with mode parameter:
  calls (default), data_flow, cross_service
- Backward compatible: trace_call_path alias still accepted
- Updated CLI help text and all tests
2026-03-28 13:59:42 +01:00
Martin Vogel b5e288a640 Argument-to-parameter mapping + field access chains (Phase B2+B3)
CBMCallArg struct captures up to 8 arguments per call with expression
text, resolved constant values, keyword names, and positional index.
Member expressions produce dotted chain expressions automatically.

Serialized as "args" array on CALLS, HTTP_CALLS, ASYNC_CALLS, and
CONFIGURES edge properties. Enables data flow tracing across function
and service boundaries.
2026-03-28 13:59:42 +01:00
Martin Vogel c02d3c96a1 Incremental indexing + MCP tool integration tests (155 tests)
Comprehensive test suite using real repo (FastAPI 0.99.1, ~1100 files):
- Full index baseline with perf metrics (nodes, edges, RSS, timing)
- Incremental: modify/add/delete/rename files, noop, formatter run
- Adversarial: empty file, syntax errors, 5000-line function, binary
- Stress: rapid reindex, batch 20 files, delete-all + re-add
- Accuracy: incremental vs full within ±2 nodes/edges
- MCP tools: all 14 tools, every parameter, content validation
- Error handling: bad project, missing params for each tool
- Performance: 5s timeout on every tool call

Fix use-after-free in detect_changes and manage_adr:
yyjson_mut_arr_add_str stored pointer to stack buffer without copy.
Changed to yyjson_mut_arr_add_strcpy / yyjson_mut_obj_add_strcpy.
2026-03-28 13:59:42 +01:00
Chitral Verma 5743e1a1f3 fix: opencode MCP config format (#134)
Fixes OpenCode config to match their documented format:
- `"enabled": true` 
- `"type": "local"`
- `"command": ["path"]` (array, not string)

Thanks @chitralverma for the fix and test coverage!
2026-03-25 22:47:37 +01:00
Martin Vogel 65a38be478 Fix Windows test failures: backslash allowed, skip shell-dependent test 2026-03-25 10:12:44 +01:00
Martin Vogel 4c2e74dc99 Fix switch fallthrough: return false before #ifndef _WIN32 backslash case 2026-03-25 09:47:59 +01:00
Martin Vogel 8f56f3d81a Fix Windows build: add missing stdint.h include in test_dyn_array 2026-03-25 09:28:11 +01:00
Martin Vogel e6e9c58e80 Fix all memory leaks + Docker test infra gaps
Leaks fixed (5506 bytes → 0):
- sqlite3_open_v2 allocates handle even on CANTOPEN — must call
  sqlite3_close before freeing struct (4x 792 bytes, 32 indirect)
- graph_buffer node_by_id: reuse existing heap key on hash table
  replace to avoid leak (2 bytes)

Docker test infrastructure:
- python3 (full) instead of python3-minimal (missing json module)
- git installed (19 tests were silently skipped)
- sqlite3_close_v2 + sqlite3_shutdown at test exit
2026-03-25 01:59:36 +01:00
Martin Vogel 7f579f91ad Add 480+ tests, fix 3 bugs discovered by new test coverage
New tests (6481 lines across 23 files):
- Arena: reset invariants, growth, sized init, destroy safety
- Dynamic array: capacity, remove, clear, grow patterns
- FQN: module/package/class name computation (592 lines)
- Graph buffer: node/edge CRUD, dedup, merge, concurrent access
- Hash table: collision, resize, iteration, edge cases
- MCP: tool dispatch, argument parsing, error handling
- Memory: allocation tracking, collection, limits
- Pipeline: test detection (path + func name patterns)
- Store: node/edge CRUD, search, batch ops, persistence
- String: intern dedup, util edge cases, YAML parsing (1105 lines)
- Traces: ingestion, dedup, query
- Watcher: baseline, polling, change detection
- Worker pool: task distribution, completion

Bugs found and fixed:
1. Arena reset overflow: block_size not reset to block_sizes[0]
   after growth — subsequent allocations could overflow blocks[0]
2. Test path detection: missing __tests__/, tests/, spec/ directory
   patterns and _spec.rb suffix
3. Test func detection: "Testable" falsely matched as Go test —
   now requires uppercase or end-of-string after "Test" prefix
2026-03-24 23:48:23 +01:00
Martin Vogel cbac7be1e0 Fix #139 #133 #137: thread stack, Windows paths, detect_changes
#139 Stack overflow in autoindex: all threads now get 8MB stack
by default (CBM_DEFAULT_STACK_SIZE). macOS ARM64 default was
512KB, too small for deep pipeline passes like configlink.

#133 search_code rejects Windows backslash paths: allow backslash
in cbm_validate_shell_arg on _WIN32 builds.

#137 detect_changes fails on paths with spaces: replace cd with
git -C flag, use double quotes on Windows.

Also fix arena test: allocations must exceed 64KB block size to
force multiple blocks (test was always wrong, never caught because
it wasn't in the test suite until now).
2026-03-24 23:14:33 +01:00
Martin Vogel eaf9c83066 Eliminate rename() — reindex deletes old DB, index writes directly
Architecture change to prevent concurrent write corruption:

  Indexing (new project): cbm_write_db writes project.db directly
  Reindexing (existing): delete project.db, then index as new
  Incremental: upsert changes into existing project.db (unchanged)

Root cause: rename(project.db.tmp, project.db) while watcher/MCP
had the old file open via SQLite caused WAL corruption — stale
connections wrote to deleted inodes.

Changes:
- cbm_gbuf_dump_to_sqlite: write to final path, no .tmp + rename
- pipeline.c: if DB exists but not eligible for incremental, delete
  it before proceeding with full index (reindex = delete + index)
- Pipeline lock (atomic spinlock) serializes concurrent runs:
  MCP/autoindex block, watcher skips if busy
- delete_project acquires pipeline lock before unlinking
- BEGIN IMMEDIATE for all write transactions (respects busy_timeout)
- cbm_store_check_integrity: detects corrupt DBs (>5 project rows
  or invalid root_path), auto-deletes with ERROR log
- cbm_store_get_db accessor for test corruption simulation

Tests: 5 integrity tests + 4 concurrency lock tests
2026-03-24 23:14:33 +01:00
Martin Vogel 68cc19ebf2 Auto-detect and clean corrupt index databases
Add cbm_store_check_integrity() that validates:
- projects table has <= 5 rows (1 project per .db file)
- root_path starts with / or drive letter (not numeric garbage)

Wire into resolve_store (MCP queries) and pipeline routing:
- MCP: corrupt DB auto-deleted with ERROR log, returns "not indexed"
- Pipeline: corrupt DB deleted, falls through to full reindex

Root cause: user-reported corrupt DBs had 48K rows in projects table
with node IDs in text columns. Exact write path TBD, but detection
+ auto-clean prevents the symptom from persisting.

5 unit tests: clean DB, empty DB, bad path, too many rows, NULL.
2026-03-24 23:14:33 +01:00
Martin Vogel 8951647d3e Fix remaining install/update gaps + in-memory zip extraction
Install command:
- Add cbm_kill_other_instances() to kill stale MCP servers
- Add cbm_macos_adhoc_sign() to sign binary if placed unsigned

Update command:
- Replace skills-only reinstall with full cbm_install_agent_configs()
- Replace external unzip with cbm_extract_binary_from_zip() via zlib

Refactor: extract 10-agent config loop into cbm_install_agent_configs()
called by both install and update.

New: cbm_extract_binary_from_zip() — in-memory zip extraction with
stored + deflate support, path traversal rejection, bounds checks.
4 unit tests. Smoke: add install.ps1 E2E for Windows.
2026-03-24 23:14:33 +01:00
Shane McCarron 178bea2cd8 fix(cbm): convert 7 O(N²) import extractors to O(N) TSTreeCursor iteration (#131)
Fixes #130
2026-03-24 23:12:18 +01:00
Martin Vogel c00723e5c8 Require project param on all MCP tool calls
Make project a required parameter for all query tools (search_graph,
query_graph, trace_call_path, get_code_snippet, get_graph_schema,
get_architecture, search_code, index_status, detect_changes,
manage_adr, ingest_traces). Removes implicit fallback to session
project or last-opened store.

When project is missing or not found, return error with list of
available indexed projects so agents can self-correct.

Rename delete_project param from project_name to project for
consistency. Fix smoke test trace_call_path depth param name
(max_depth -> depth).
2026-03-24 13:38:25 +01:00
Martin Vogel 64144a2729 Fix integration test: avoid querying unlinked .db (SQLite WAL leak)
On Linux, unlink defers file removal until all fds close. Querying a
just-deleted project reopens the unlinked .db inode, and SQLite's WAL
mode connection on an unlinked file leaks internal allocations that
sqlite3_close cannot reclaim. Remove the post-delete search_graph call;
guard behavior is tested separately in smoke_guard.sh.
2026-03-23 17:48:46 +01:00
Martin Vogel 7d6b3af341 Fix memory leak in resolve_store + Windows setenv build error
- resolve_store: verify project exists in database after opening;
  close store immediately if project is absent (prevents SQLite
  connection leak when querying deleted/empty projects)
- test_userconfig.c: use cbm_setenv/cbm_unsetenv instead of raw
  POSIX setenv/unsetenv (fixes Windows build)
2026-03-23 17:37:21 +01:00
Martin Vogel 8fc19497e7 Add cbm_replace_binary: unlink-before-write for update command
TDD: two tests (overwrite read-only file, create new file) written
first, then cbm_replace_binary() implemented and wired into update.

The update command failed when the existing binary had no write
permission (e.g., 0500). unlink() only requires write permission on
the parent directory, not the file itself, so removing first then
creating with O_CREAT | 0755 handles all permission combinations.

Fixes #114.
2026-03-23 15:47:05 +01:00
Martin Vogel 8f59934fcf Merge branch 'main' into fix/manage-adr-use-after-free 2026-03-23 15:13:27 +01:00
Martin Vogel 4788b0d396 Fix session project name mismatch with indexed project name
detect_session used a two-component path algorithm (e.g. "project_dir-
codebase-memory-mcp") while the pipeline used cbm_project_name_from_path
with the full absolute path (e.g. "Users-martinvogel-project_dir-
codebase-memory-mcp"). This caused session queries to look for a .db
file that didn't match the indexed name, silently returning empty results.

Fix: use cbm_project_name_from_path in detect_session so both paths
produce the same project name. Update integration test to accept guard
error after project deletion (correct new behavior from PR #120).
2026-03-23 14:53:27 +01:00