Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

test(windows): add red regressions for hook augmenter and UI drive picker

Flippera4dbe89941e3
diff --git a/scripts/test-windows.ps1 b/scripts/test-windows.ps1
index b426fa350..620692a4a 100644
--- a/scripts/test-windows.ps1
+++ b/scripts/test-windows.ps1
@@ -63,12 +63,19 @@ Write-Host "Binary: $bin" -ForegroundColor Green
$env:PYTHONUTF8 = "1" # ensure the harness encodes argv/stdio as UTF-8
+# test_ui_drive_listing.py reproduces the UI directory-picker bug (#548) and
+# therefore needs a UI build (make -f Makefile.cbm cbm-with-ui) plus a machine
+# with more than one drive. Against a non-UI binary it reports a precondition
+# (exit 2), which is treated as a skip-with-reason, not a failure.
$tests = @(
"tests\windows\test_non_ascii_path.py",
- "tests\windows\test_cli_non_ascii_arg.py"
+ "tests\windows\test_cli_non_ascii_arg.py",
+ "tests\windows\test_hook_augment.py",
+ "tests\windows\test_ui_drive_listing.py"
)
-$failed = @()
+$reds = @()
+$precond = @()
foreach ($t in $tests) {
Write-Host "`n=== $t ===" -ForegroundColor Cyan
& $py $t $bin
@@ -77,18 +84,22 @@ foreach ($t in $tests) {
Write-Host "GREEN ($t)" -ForegroundColor Green
} elseif ($code -eq 1) {
Write-Host "RED ($t) - Windows-specific failure reproduced" -ForegroundColor Red
- $failed += $t
+ $reds += $t
} else {
- Write-Host "SETUP ERROR ($t) exit=$code" -ForegroundColor Yellow
- $failed += $t
+ Write-Host "PRECONDITION ($t) exit=$code - skipped (see message above)" -ForegroundColor Yellow
+ $precond += $t
}
}
Write-Host ""
-if ($failed.Count -gt 0) {
- Write-Host ("RED suite: {0}/{1} Windows red tests failed (expected until the " -f $failed.Count, $tests.Count) -ForegroundColor Red
- Write-Host "platform issues are fixed). See tests/windows/RED_TEST_ANALYSIS.md." -ForegroundColor Red
+if ($precond.Count -gt 0) {
+ Write-Host ("Precondition-skipped: {0} (e.g. test_ui_drive_listing needs a UI " -f $precond.Count) -ForegroundColor Yellow
+ Write-Host "build: make -f Makefile.cbm cbm-with-ui, and >1 drive)." -ForegroundColor Yellow
+}
+if ($reds.Count -gt 0) {
+ Write-Host ("RED suite: {0} Windows red tests reproduced platform failures " -f $reds.Count) -ForegroundColor Red
+ Write-Host "(expected until fixed). See tests/windows/RED_TEST_ANALYSIS.md." -ForegroundColor Red
exit 1
}
-Write-Host "All Windows red tests are GREEN." -ForegroundColor Green
+Write-Host "All runnable Windows red tests are GREEN." -ForegroundColor Green
exit 0
diff --git a/tests/windows/RED_TEST_ANALYSIS.md b/tests/windows/RED_TEST_ANALYSIS.md
index 2c13db967..a24251c29 100644
--- a/tests/windows/RED_TEST_ANALYSIS.md
+++ b/tests/windows/RED_TEST_ANALYSIS.md
@@ -121,6 +121,77 @@ flows that shell out to it, not the stdio server path. Holds on Linux/macOS
---
+## windows_hook_augment_emits_context
+
+- Class: integration
+- Test: `tests/windows/test_hook_augment.py`
+- Related issues: #618
+- Environment: Windows 11 26200, `hook-augment` CLI subcommand
+- Fixture: a repo with a known function `someIndexedSymbol`, indexed; a realistic
+ Claude Code PreToolUse Grep payload with a Windows drive-letter `cwd`
+- Expected: `codebase-memory-mcp hook-augment` emits a `hookSpecificOutput` with
+ `additionalContext` listing the matching graph symbol (the control
+ `search_graph` finds the symbol, so the index and project name are fine)
+- Actual: `hook-augment` emits **empty stdout** for every payload
+- Command: `python tests/windows/test_hook_augment.py build\c\codebase-memory-mcp.exe`
+- Minimal failure output:
+
+ ```
+ control: search_graph finds someIndexedSymbol in project C-...-repo
+ hook-augment rc=0 stdout=''
+ ```
+
+- Suspected implementation area: `src/cli/hook_augment.c` has two POSIX-only path
+ guards. `cbm_cmd_hook_augment` (`_WIN32` branch, ~L330):
+ `if (!cwd || cwd[0] != '/') { ...; return 0; }` and the `ha_resolve_and_query`
+ walk-up loop (~L254): `for (...; dir[0] == '/'; ...)`. A Windows `cwd` is a
+ drive-letter path (`C:\...` / `C:/...`), so `cwd[0]` is never `'/'`; the
+ augmenter bails before it queries the graph. The PreToolUse Grep/Glob graph
+ augmentation therefore never fires on Windows. Fix direction: accept
+ drive-letter absolute paths (and climb them in the walk-up loop).
+
+Holds on Linux/macOS (`cwd` starts with `/`).
+
+---
+
+## windows_ui_picker_reaches_all_drives
+
+- Class: integration
+- Test: `tests/windows/test_ui_drive_listing.py`
+- Related issues: #548
+- Environment: Windows 11 26200 with drives `C:\`, `D:\`, `E:\`; UI build
+ (`make -f Makefile.cbm cbm-with-ui`); embedded HTTP server on a local port
+- Fixture: none — exercises the live `GET /api/browse` endpoint
+- Expected: browsing the filesystem root (`/api/browse?path=/`) lets the user
+ reach every fixed drive (`D:\`, `E:\`), so a project on a non-system drive can
+ be selected
+- Actual: the control browse of an explicit directory returns entries (endpoint
+ works), but `browse('/')` returns **0 entries** and no drive letters — `D:\`
+ and `E:\` are unreachable from the picker root
+- Command: `python tests/windows/test_ui_drive_listing.py build\c\codebase-memory-mcp.exe`
+- Minimal failure output:
+
+ ```
+ control browse('C:/Users/jacob') -> dirs(23)
+ browse('/') -> path='/' dirs(0)=[]
+ RED: drives ['D:\\', 'E:\\'] are not reachable from the UI root picker
+ ```
+
+- Suspected implementation area: `handle_browse` in `src/ui/http_server.c` does
+ `opendir(path)` for the requested path. For the root it lists only the current
+ drive's contents and never enumerates the logical drives
+ (`GetLogicalDriveStrings`). Fix direction: when the path is the filesystem root
+ on Windows, return the available drive letters as the directory list so the
+ picker can descend into any drive.
+
+This test requires a UI build because the HTTP server only starts when the
+frontend is embedded (`CBM_EMBEDDED_FILE_COUNT > 0`); against a non-UI binary it
+reports a precondition (exit 2), and on a single-drive machine it is not
+meaningful (exit 2). Holds on Linux/macOS (a single `/` root with no drive
+letters).
+
+---
+
## Seed areas revisited and ruled out (green on native Windows)
Each was reproduced as a concrete attempt against the production binary and
@@ -128,8 +199,10 @@ behaved correctly — recorded as green and **not** included as a red test:
| Area | Seed | Result on Windows |
|---|---|---|
-| stdio `initialize` returns before stdin EOF | #513, #635 | green |
+| stdio `initialize` returns before stdin EOF; stdout flushes before EOF | #513, #530.1, #635 | green |
| `tools/list` non-empty; all 14 tools return valid JSON-RPC | #530 | green |
+| `get_code_snippet` on a CP949 file emits valid UTF-8 (invalid bytes → U+FFFD) | #530.3 | green |
+| Indexing a mapped (subst) drive `W:\` — no `bad_root_path`/`store.corrupt`, DB kept | #227, #367 | green (subst; real SMB not testable here) |
| Client exit terminates the server process (no residual `.exe`) | #185, #406 | green |
| `--help` / `--version` exit 0 in PowerShell, cmd, Git Bash | — | green |
| `search_code` works without bash/GNU grep (PowerShell `Select-String`) | #422, #348 | green |
@@ -157,6 +230,18 @@ behaved correctly — recorded as green and **not** included as a red test:
paths over `MAX_PATH` are unreachable by every application, not just CBM.
CBM could opt in via the `\\?\` prefix + wide APIs, but the failure is gated by
a machine-wide policy rather than a clean CBM-only defect, so it is excluded.
+- **Cascading nested `.gitignore` (#530.2) and `.git/info/exclude` (#530.5).**
+ `try_load_nested_gitignore` in `src/discover/discover.c` skips nested
+ `.gitignore` files once a parent ignore is loaded, and discovery never reads
+ `.git/info/exclude`. Both are real, but the discovery logic is
+ platform-independent and reproduces identically on Linux, so they are out of
+ scope for a Windows-only PR.
+- **libgit2 1.8+ build break (#530.4).** `git_allocator` moved to
+ `<git2/sys/alloc.h>`; cross-platform compile issue, not a Windows runtime bug.
+- **Memory growth over hours (#581).** Requires a multi-hour soak to surface and
+ is not deterministic in a unit/integration test; the existing
+ `scripts/soak-test.sh` RSS-trend harness is the right vehicle and is not
+ reproduced as a red test here.
- **C `test-runner` failures on Windows.** The in-process C suite reports many
extraction-count failures concentrated in `test_grammar_probe_*`,
`test_node_creation_probe`, `test_edge_*`, `test_matrix_*`, and
diff --git a/tests/windows/test_hook_augment.py b/tests/windows/test_hook_augment.py
new file mode 100644
index 000000000..8f0365502
--- /dev/null
+++ b/tests/windows/test_hook_augment.py
@@ -0,0 +1,112 @@
+r"""RED integration test — the PreToolUse hook augmenter is a no-op on Windows.
+
+Reproduces issue #618 at the product surface.
+
+`codebase-memory-mcp hook-augment` is the non-blocking Claude Code PreToolUse
+Grep/Glob augmenter: given a hook payload it should emit a `hookSpecificOutput`
+with `additionalContext` listing graph symbols that match the searched token.
+
+On Windows it emits nothing for every payload. `src/cli/hook_augment.c` gates on
+POSIX-style absolute paths in two places:
+
+ cbm_cmd_hook_augment (_WIN32 branch): if (!cwd || cwd[0] != '/') return 0;
+ ha_resolve_and_query walk-up loop: for (... ; dir[0] == '/'; ...)
+
+A Windows `cwd` is a drive-letter path (`C:\...` / `C:/...`), so `cwd[0]` is
+never `'/'`; the augmenter bails before it ever queries the graph.
+
+This test indexes a repo with a known symbol, confirms `search_graph` finds it
+(control — proves the index and project name are fine), then invokes
+`hook-augment` exactly as the installed PreToolUse hook does and asserts a
+`hookSpecificOutput` payload is produced.
+
+Passes on Linux/macOS (`cwd` starts with `/`). Fails on native Windows until the
+path guards accept drive-letter absolute paths (and the walk-up loop climbs them).
+
+Exit code: 0 == augmenter fired (green), 1 == no-op (red), 2 == setup error.
+
+Usage:
+ python test_hook_augment.py <path-to-codebase-memory-mcp[.exe]>
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+
+SYMBOL = "someIndexedSymbol"
+SRC = "export function %s(a: number): number { return a + 1; }\n" % SYMBOL
+
+
+def run_cli(binary, cache, args, stdin=None, timeout=120):
+ env = dict(os.environ)
+ env["CBM_CACHE_DIR"] = cache
+ return subprocess.run([binary] + args, capture_output=True, timeout=timeout,
+ env=env, input=stdin)
+
+
+def main():
+ if len(sys.argv) < 2:
+ print("usage: python test_hook_augment.py <binary>")
+ return 2
+ binary = os.path.abspath(sys.argv[1])
+ if not os.path.exists(binary):
+ print("FAIL: binary not found: %s" % binary)
+ return 2
+
+ work = tempfile.mkdtemp(prefix="cbm_win_hook_")
+ try:
+ repo = os.path.join(work, "repo")
+ os.makedirs(os.path.join(repo, "src"), exist_ok=True)
+ with open(os.path.join(repo, "src", "m.ts"), "wb") as f:
+ f.write(SRC.encode("utf-8"))
+ cache = os.path.join(work, "cache")
+ os.makedirs(cache, exist_ok=True)
+
+ # repo_path / cwd in the forward-slash drive form Claude Code passes.
+ repo_fwd = repo.replace("\\", "/")
+ idx = run_cli(binary, cache, ["cli", "index_repository",
+ json.dumps({"repo_path": repo_fwd})])
+ idx_out = (idx.stdout or b"").decode("utf-8", "replace")
+ if '"nodes"' not in idx_out:
+ print("SETUP FAIL: index did not run:\n%s" % idx_out[:300])
+ return 2
+
+ # Control: prove the symbol is indexed and queryable.
+ lp = run_cli(binary, cache, ["cli", "list_projects", "{}"])
+ projects = json.loads((lp.stdout or b"").decode("utf-8", "replace"))["projects"]
+ name = projects[0]["name"]
+ sg = run_cli(binary, cache, ["cli", "search_graph",
+ json.dumps({"label": "Function",
+ "name_pattern": ".*%s.*" % SYMBOL,
+ "project": name})])
+ if SYMBOL not in (sg.stdout or b"").decode("utf-8", "replace"):
+ print("SETUP FAIL: control search_graph did not find %s" % SYMBOL)
+ return 2
+ print("control: search_graph finds %s in project %s" % (SYMBOL, name))
+
+ # Invoke hook-augment exactly as the installed PreToolUse hook does.
+ payload = json.dumps({
+ "hook_event_name": "PreToolUse",
+ "tool_name": "Grep",
+ "cwd": repo_fwd,
+ "tool_input": {"pattern": SYMBOL},
+ }).encode("utf-8")
+ ha = run_cli(binary, cache, ["hook-augment"], stdin=payload, timeout=60)
+ out = (ha.stdout or b"").decode("utf-8", "replace").strip()
+ print("hook-augment rc=%d stdout=%r" % (ha.returncode, out[:200]))
+
+ fired = ("hookSpecificOutput" in out) and ("additionalContext" in out)
+ if fired:
+ print("\nGREEN: PreToolUse augmenter emitted additionalContext.")
+ return 0
+ print("\nRED: hook-augment produced no hookSpecificOutput on Windows "
+ "(drive-letter cwd fails the cwd[0]=='/' guards in hook_augment.c).")
+ return 1
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/windows/test_ui_drive_listing.py b/tests/windows/test_ui_drive_listing.py
new file mode 100644
index 000000000..9457bb4e9
--- /dev/null
+++ b/tests/windows/test_ui_drive_listing.py
@@ -0,0 +1,176 @@
+r"""RED integration test — the UI directory picker cannot reach non-system drives.
+
+Reproduces issue #548 at the product surface (the embedded HTTP UI).
+
+The UI directory picker calls `GET /api/browse?path=...` (handle_browse in
+src/ui/http_server.c). For the filesystem root it does `opendir("/")`, which on
+Windows resolves to the *current* drive's root and lists only that drive's
+subdirectories. There is no `GetLogicalDriveStrings` drive enumeration, so when a
+user opens the picker at root, drives other than the system drive (e.g. `D:\`,
+`E:\`) never appear and cannot be selected.
+
+This test requires a UI build (`make -f Makefile.cbm cbm-with-ui`) because the
+HTTP server only starts when the frontend is embedded. It launches the server,
+queries `/api/browse?path=/`, and asserts that every fixed drive on the machine
+is reachable from the root listing. It is meaningful only on a machine with more
+than one drive; with a single drive it reports a precondition error (exit 2).
+
+Passes on a correct picker that enumerates drives; fails on native Windows until
+handle_browse enumerates logical drives for the root path.
+
+Exit code: 0 == all drives reachable (green), 1 == non-system drives missing
+(red), 2 == precondition not met (single drive / no UI build / server down).
+
+Usage:
+ python test_ui_drive_listing.py <path-to-codebase-memory-mcp-ui[.exe]> [port]
+"""
+import json
+import os
+import shutil
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.request
+
+
+def list_fixed_drives():
+ # Python 3.12+: os.listdrives(). Fall back to scanning A:..Z:.
+ listdrives = getattr(os, "listdrives", None)
+ if listdrives:
+ try:
+ return [d for d in listdrives()]
+ except Exception:
+ pass
+ found = []
+ for ch in "CDEFGHIJKLMNOPQRSTUVWXYZ":
+ root = "%s:\\" % ch
+ if os.path.isdir(root):
+ found.append(root)
+ return found
+
+
+def free_port():
+ s = socket.socket()
+ s.bind(("127.0.0.1", 0))
+ p = s.getsockname()[1]
+ s.close()
+ return p
+
+
+def http_get_json(url, timeout=5):
+ with urllib.request.urlopen(url, timeout=timeout) as r:
+ return json.loads(r.read().decode("utf-8", "replace"))
+
+
+def wait_for_server(port, timeout=20):
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ try:
+ with socket.create_connection(("127.0.0.1", port), timeout=1):
+ return True
+ except OSError:
+ time.sleep(0.3)
+ return False
+
+
+def main():
+ if len(sys.argv) < 2:
+ print("usage: python test_ui_drive_listing.py <ui-binary> [port]")
+ return 2
+ binary = os.path.abspath(sys.argv[1])
+ if not os.path.exists(binary):
+ print("FAIL: binary not found: %s" % binary)
+ return 2
+
+ drives = list_fixed_drives()
+ extra = [d for d in drives if not d.upper().startswith("C:")]
+ print("fixed drives: %s" % drives)
+ if not extra:
+ print("PRECONDITION: only one drive present; cannot test multi-drive "
+ "picker. Re-run on a machine with a D:/E: drive.")
+ return 2
+
+ work = tempfile.mkdtemp(prefix="cbm_win_uidrv_")
+ port = int(sys.argv[2]) if len(sys.argv) > 2 else free_port()
+ env = dict(os.environ)
+ env["CBM_CACHE_DIR"] = os.path.join(work, "cache")
+ os.makedirs(env["CBM_CACHE_DIR"], exist_ok=True)
+ proc = subprocess.Popen([binary, "--ui=true", "--port=%d" % port],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, env=env)
+ try:
+ if not wait_for_server(port, timeout=25):
+ err = b""
+ try:
+ proc.stderr.settimeout = None
+ except Exception:
+ pass
+ print("PRECONDITION: HTTP server did not start on port %d. Is this a "
+ "UI build (make cbm-with-ui)?" % port)
+ return 2
+
+ # Control: browsing an explicit existing directory must return entries,
+ # proving the endpoint works and isolating the bug to root enumeration.
+ import urllib.parse
+ home = os.environ.get("USERPROFILE") or os.path.expanduser("~")
+ home_fwd = home.replace("\\", "/")
+ try:
+ ctrl = http_get_json("http://127.0.0.1:%d/api/browse?path=%s" %
+ (port, urllib.parse.quote(home_fwd)))
+ except Exception as ex:
+ print("PRECONDITION: control /api/browse?path=%s failed: %r" %
+ (home_fwd, ex))
+ return 2
+ print("control browse(%r) -> dirs(%d)" % (home_fwd, len(ctrl.get("dirs", []))))
+ if not ctrl.get("dirs"):
+ print("PRECONDITION: control browse returned no dirs; endpoint may be "
+ "non-functional in this build.")
+ return 2
+
+ # Browse the filesystem root.
+ try:
+ root = http_get_json("http://127.0.0.1:%d/api/browse?path=/" % port)
+ except Exception as ex:
+ print("PRECONDITION: /api/browse?path=/ failed: %r" % ex)
+ return 2
+ root_dirs = root.get("dirs", [])
+ print("browse('/') -> path=%r dirs(%d)=%s" %
+ (root.get("path"), len(root_dirs), root_dirs[:20]))
+
+ # A correct root listing must let the user reach every drive. Accept a
+ # match whether the API returns "D:", "D", or "D:\\"/"D:/".
+ def reachable(drive_root):
+ letter = drive_root[0].upper()
+ cands = {letter, letter + ":", letter + ":\\", letter + ":/",
+ drive_root, drive_root.rstrip("\\/")}
+ return any(str(d).rstrip("\\/").upper() in
+ {x.rstrip("\\/").upper() for x in cands} for d in root_dirs)
+
+ missing = [d for d in extra if not reachable(d)]
+ if not missing:
+ print("\nGREEN: all non-system drives reachable from the root picker.")
+ return 0
+ print("\nRED: drives %s are not reachable from the UI root picker "
+ "(/api/browse?path=/ lists only the current drive; handle_browse "
+ "does not enumerate logical drives)." % missing)
+ return 1
+ finally:
+ try:
+ proc.stdin.close()
+ except Exception:
+ pass
+ try:
+ proc.terminate()
+ proc.wait(timeout=5)
+ except Exception:
+ try:
+ proc.kill()
+ except Exception:
+ pass
+ shutil.rmtree(work, ignore_errors=True)
+
+
+if __name__ == "__main__":
+ sys.exit(main())