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.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(daemon,win): CI-green fixes and a daemon-stability guard
Martin Vogel34f9ad1b3d5a
diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.shindex e02455bfd..1a28b0e22 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -1109,6 +1109,20 @@ path_match() {return 1}+# A Windows path lands in a YAML/TOML config as a double-quoted scalar with+# ESCAPED backslashes ("C:\\Users\\..."), so a raw grep for the msys-form+# $SELF_PATH can never match it. Unquote, unescape, normalize separators,+# then path_match.+quoted_path_value_matches() {+ local value="${1%$'\r'}"+ local expected="$2"+ value="${value#\"}"+ value="${value%\"}"+ value="${value//\\\\/\\}"+ value="${value//\\//}"+ [ -n "$value" ] && path_match "$value" "$expected"+}+json_instructions_contain_path() {local config="$1"local expected="$2"@@ -1554,9 +1568,11 @@ fiecho "OK 8w-ii: Kiro MCP + steering + isolated exact-tool graph agent"# 8x: Hermes Agent YAML MCP mapping+HERMES_CMD=$(sed -n '/^ codebase-memory-mcp:/{n;s/^ *command: *//p;}' \+ "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null | head -1)if ! grep -q '^mcp_servers:' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||! grep -q '^ codebase-memory-mcp:' "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null ||- ! grep -Fq "$SELF_PATH" "$FAKE_HOME/.hermes/config.yaml" 2>/dev/null; then+ ! quoted_path_value_matches "$HERMES_CMD" "$SELF_PATH"; thenecho "FAIL 8x: Hermes MCP mapping missing or malformed"exit 1fi@@ -1728,9 +1744,11 @@ if [[ "$BINARY" == *.exe ]]; thenelseGOOSE_CFG="$FAKE_HOME/.config/goose/config.yaml"fi+GOOSE_CMD=$(sed -n '/^ codebase-memory-mcp:/,/^ [^ ]/{s/^ *cmd: *//p;}' \+ "$GOOSE_CFG" 2>/dev/null | head -1)if ! grep -q '^extensions:' "$GOOSE_CFG" 2>/dev/null ||! grep -q '^ codebase-memory-mcp:' "$GOOSE_CFG" 2>/dev/null ||- ! grep -Fq "$SELF_PATH" "$GOOSE_CFG" 2>/dev/null; then+ ! quoted_path_value_matches "$GOOSE_CMD" "$SELF_PATH"; thenecho "FAIL 8ae: Goose extension missing or malformed"exit 1fi@@ -1743,9 +1761,10 @@ fiecho "OK 8ae-i: Goose durable hints"# 8af: Mistral Vibe TOML array table+VIBE_CMD=$(sed -n 's/^command *= *//p' "$FAKE_HOME/.vibe/config.toml" 2>/dev/null | head -1)if ! grep -q '^\[\[mcp_servers\]\]' "$FAKE_HOME/.vibe/config.toml" 2>/dev/null ||! grep -q '^name = "codebase-memory-mcp"' "$FAKE_HOME/.vibe/config.toml" 2>/dev/null ||- ! grep -Fq "$SELF_PATH" "$FAKE_HOME/.vibe/config.toml" 2>/dev/null; then+ ! quoted_path_value_matches "$VIBE_CMD" "$SELF_PATH"; thenecho "FAIL 8af: Mistral Vibe MCP table missing or malformed"exit 1fidiff --git a/scripts/soak-test.sh b/scripts/soak-test.shindex 784511147..76b09bc75 100755--- a/scripts/soak-test.sh+++ b/scripts/soak-test.sh@@ -294,7 +294,12 @@ try:project = ""for item in content:if isinstance(item, dict) and item.get("type") == "text":- payload = json.loads(item.get("text", ""))+ # The summary JSON may be preceded by plain-text banner items+ # (update-available notice); skip anything that is not JSON.+ try:+ payload = json.loads(item.get("text", ""))+ except ValueError:+ continuecandidate = payload.get("project") if isinstance(payload, dict) else Noneif isinstance(candidate, str) and candidate:project = candidate@@ -575,6 +580,32 @@ elseecho "SKIP: idle daemon CPU is unavailable across the Windows PID boundary"fi+# ── Phase 4b: one-shot CLI admission churn ───────────────────────+# Every `cli` one-shot is a complete daemon client cycle (connect → commit →+# execute → close-intent → drain) against the SAME daemon the metrics sampler+# is watching. The long-lived MCP session above never exercises that path, so+# a per-admission leak in the accept/worker-finish cycle would be invisible+# without this churn — it lands in the same RSS/FD analysis below.++echo "--- Phase 4b: CLI one-shot admission churn ---"+CHURN_CYCLES=${SOAK_CLI_CHURN_CYCLES:-40}+CHURN_FAILS=0+churn_index=0+while [ "$churn_index" -lt "$CHURN_CYCLES" ]; do+ if ! CBM_CACHE_DIR="$SOAK_CACHE_DIR_VALUE" "$BINARY" cli list_projects '{}' \+ >/dev/null 2>>"$RESULTS_DIR/cli-churn-stderr.log"; then+ CHURN_FAILS=$((CHURN_FAILS + 1))+ fi+ churn_index=$((churn_index + 1))+done+if [ "$CHURN_FAILS" -gt 0 ]; then+ echo "FAIL: $CHURN_FAILS of $CHURN_CYCLES one-shot CLI churn cycles failed"+ PASS=false+else+ echo "OK: $CHURN_CYCLES one-shot CLI churn cycles recycled the live daemon"+fi+collect_snapshot+# ── Phase 5: Crash recovery test ────────────────────────────────# Skipped in query-leak mode: crash recovery re-indexes (Phase 5 calls# index_repository), which triggers cbm_mem_collect and would mask the #581@@ -705,7 +736,8 @@ fi# Check 3: Idle daemon CPU (where the PID is host-addressable)if [ -n "$IDLE_CPU" ]; then- IDLE_INT=$(echo "$IDLE_CPU" | cut -d. -f1)+ # ps %cpu may carry a locale decimal comma; strip either separator.+ IDLE_INT=$(echo "$IDLE_CPU" | cut -d. -f1 | cut -d, -f1)echo "Idle daemon CPU: ${IDLE_CPU}%" | tee -a "$SUMMARY"if [ "${IDLE_INT:-0}" -gt 5 ] 2>/dev/null; thenecho "FAIL: idle daemon CPU ${IDLE_CPU}% > 5%" | tee -a "$SUMMARY"diff --git a/scripts/test-windows.ps1 b/scripts/test-windows.ps1index 50188649a..bd3dd7b26 100644--- a/scripts/test-windows.ps1+++ b/scripts/test-windows.ps1@@ -18,6 +18,8 @@* test_hook_augment.py guards #618 (fixed by #619)* test_ui_drive_listing.py guards #548 (roots field)* test_cli_non_ascii_arg.py guards #423/#20 (wide-argv main())+ * test_daemon_stability.py guards the daemon parameter+ surface, crash recovery, busy-stop refusal, and churn* test_windows_launcher.py guards the permanent launcher,managed layout, portable refusal, and crash containment@@ -196,6 +198,7 @@ $guards = @("tests\windows\test_non_ascii_path.py","tests\windows\test_non_ascii_cache_dump.py","tests\windows\test_daemon_lifecycle.py",+ "tests\windows\test_daemon_stability.py","tests\windows\test_hook_augment.py","tests\windows\test_ui_drive_listing.py","tests\windows\test_cli_non_ascii_arg.py",diff --git a/src/cli/cli.c b/src/cli/cli.cindex b9b00f4ef..a9df19fd5 100644--- a/src/cli/cli.c+++ b/src/cli/cli.c@@ -8114,7 +8114,7 @@ static void cbm_agent_installed_binary_path(const char *home, char *binary_path,size_t binary_path_size) {#ifdef _WIN32char *managed = g_windows_launcher_context.present && g_windows_launcher_context.managed- ? cbm_wide_to_utf8(g_windows_launcher_context.canonical_launcher_path)+ ? cli_windows_plain_utf8(g_windows_launcher_context.canonical_launcher_path): NULL;if (managed) {(void)snprintf(binary_path, binary_path_size, "%s", managed);@@ -11631,11 +11631,10 @@ static void uninstall_additional_agents(const cbm_detected_agents_t *agents, conAUGMENT_SESSION_SCRIPT);snprintf(coverage_hp, sizeof(coverage_hp), "%s/.augment/hooks/%s", home,AUGMENT_COVERAGE_SCRIPT);-#ifdef _WIN32- snprintf(binary_path, sizeof(binary_path), "%s/.local/bin/codebase-memory-mcp.exe", home);-#else- snprintf(binary_path, sizeof(binary_path), "%s/.local/bin/codebase-memory-mcp", home);-#endif+ /* The owned-document match must rebuild the scripts with the exact+ * binary path the install embedded — the managed canonical plain form+ * on Windows, not a hand-assembled default. */+ cbm_agent_installed_binary_path(home, binary_path, sizeof(binary_path));uninstall_agent_mcp_instr((mcp_uninstall_args_t){"Augment/Auggie", cp, ip}, dry_run,cbm_remove_editor_mcp_owned);uninstall_tiered_agent_profiles(@@ -12047,7 +12046,8 @@ static int cli_windows_managed_uninstall(const char *home, bool dry_run) {printf("Indexes kept.\n");}}- char *canonical_utf8 = cbm_wide_to_utf8(g_windows_launcher_context.canonical_launcher_path);+ char *canonical_utf8 =+ cli_windows_plain_utf8(g_windows_launcher_context.canonical_launcher_path);if (!canonical_utf8) {return CLI_TRUE;}@@ -12368,8 +12368,9 @@ static int cli_windows_extract_and_activate_update(const char *archive_path, cong_windows_launcher_context.canonical_launcher_path, previous_launcher_backing,CBM_WINDOWS_LAUNCHER_PATH_CAP, backing_error, sizeof(backing_error));char *canonical_utf8 =- current_compatible ? cbm_wide_to_utf8(g_windows_launcher_context.canonical_launcher_path)- : NULL;+ current_compatible+ ? cli_windows_plain_utf8(g_windows_launcher_context.canonical_launcher_path)+ : NULL;if (!canonical_utf8) {cbm_windows_release_pair_free(&pair);(void)fprintf(stderr,@@ -12979,7 +12980,8 @@ int cbm_cmd_update(int argc, char **argv) {if (dry_run) {printf("\n(dry-run — skipping download, extraction, and binary replacement)\n");#ifdef _WIN32- char *dry_run_target = cbm_wide_to_utf8(g_windows_launcher_context.canonical_launcher_path);+ char *dry_run_target =+ cli_windows_plain_utf8(g_windows_launcher_context.canonical_launcher_path);printf(" target: %s\n", dry_run_target ? dry_run_target : "(managed launcher)");free(dry_run_target);#elsediff --git a/src/daemon/version_cohort.c b/src/daemon/version_cohort.cindex 17f0808a7..aaa521ff1 100644--- a/src/daemon/version_cohort.c+++ b/src/daemon/version_cohort.c@@ -83,6 +83,16 @@ static uint64_t version_cohort_deadline_after(uint32_t timeout_ms) {return now > UINT64_MAX - timeout_ms ? UINT64_MAX : now + timeout_ms;}+/* flock's LOCK_NB retries never queue in the kernel, so fairness comes only+ * from the retry schedule. Two participants retrying with the SAME fixed+ * period can phase-lock — every try landing inside the peer's brief hold+ * window — starving an EX acquisition until one side's budget expires. A+ * per-process, time-scattered jitter decorrelates the schedules. */+static void version_cohort_retry_sleep(void) {+ uint64_t mix = (cbm_now_ms() + version_cohort_current_pid()) * 2654435761ULL;+ cbm_usleep(VERSION_COHORT_RETRY_US / 2U + (uint32_t)(mix % VERSION_COHORT_RETRY_US));+}+static cbm_private_file_lock_status_t version_cohort_lock_release_until(cbm_private_file_lock_t **lock_io, uint64_t deadline_ms) {cbm_private_file_lock_status_t result = CBM_PRIVATE_FILE_LOCK_OK;@@ -100,7 +110,7 @@ static cbm_private_file_lock_status_t version_cohort_lock_release_until(if (cbm_now_ms() >= deadline_ms) {return result == CBM_PRIVATE_FILE_LOCK_OK ? CBM_PRIVATE_FILE_LOCK_IO : result;}- cbm_usleep(VERSION_COHORT_RETRY_US);+ version_cohort_retry_sleep();}return result;}@@ -132,7 +142,7 @@ static void version_cohort_startup_lock_release_complete(cbm_daemon_ipc_startup_if (cbm_now_ms() >= deadline) {version_cohort_cleanup_fail_stop("startup_lock_cleanup");}- cbm_usleep(VERSION_COHORT_RETRY_US);+ version_cohort_retry_sleep();}}#endif@@ -249,7 +259,7 @@ static cbm_private_file_lock_status_t version_cohort_lock_until((deadline_ms != UINT64_MAX && cbm_now_ms() >= deadline_ms)) {return status;}- cbm_usleep(VERSION_COHORT_RETRY_US);+ version_cohort_retry_sleep();}}diff --git a/src/main.c b/src/main.cindex c47ebd998..33b5a1e96 100644--- a/src/main.c+++ b/src/main.c@@ -1163,13 +1163,15 @@ static bool main_project_lock_manager_close(cbm_project_lock_manager_t **manager}static bool main_local_transition_close(cbm_daemon_ipc_local_transition_t **transition) {- bool ok = true;uint64_t deadline = main_deadline_after(MAIN_COORDINATION_CLEANUP_MS);while (transition && *transition) {- bool released = cbm_daemon_ipc_local_transition_release(transition);- if (!released) {- ok = false;- }+ /* A failed release always RETAINS the transition and is retriable by+ * contract: the Windows release transition must briefly try-hold the+ * shared startup-v2/legacy gates, so concurrent one-shot teardowns+ * legitimately collide and succeed on retry. Success consumes the+ * transition; only never-finishing cleanup is a failure, and the+ * deadline escalation below owns that. */+ (void)cbm_daemon_ipc_local_transition_release(transition);if (*transition) {if (cbm_now_ms() >= deadline) {main_coordination_cleanup_fail_stop("local_transition_cleanup");@@ -1177,7 +1179,7 @@ static bool main_local_transition_close(cbm_daemon_ipc_local_transition_t **trancbm_usleep(1000);}}- return ok;+ return true;}static bool main_session_context(const char *preferred_root, char root_out[MAIN_PATH_CAP],@@ -1517,16 +1519,20 @@ static void main_daemon_ctl_open_browser(int port) {char url[64];(void)snprintf(url, sizeof(url), "http://127.0.0.1:%d", port);#if defined(_WIN32)- char command[96];- (void)snprintf(command, sizeof(command), "start \"\" %s", url);+ /* ShellExecuteW resolves the http protocol association directly — no+ * command shell interprets the argument. Values > 32 signal success. */+ wchar_t *wide_url = cbm_utf8_to_wide(url);+ bool opened =+ wide_url && (INT_PTR)ShellExecuteW(NULL, L"open", wide_url, NULL, NULL, SW_SHOWNORMAL) > 32;+ free(wide_url);#elif defined(__APPLE__)- char command[96];- (void)snprintf(command, sizeof(command), "open %s", url);+ const char *open_argv[] = {"open", url, NULL};+ bool opened = cbm_exec_no_shell(open_argv) == 0;#else- char command[96];- (void)snprintf(command, sizeof(command), "xdg-open %s >/dev/null 2>&1", url);+ const char *open_argv[] = {"xdg-open", url, NULL};+ bool opened = cbm_exec_no_shell(open_argv) == 0;#endif- if (system(command) != 0) {+ if (!opened) {(void)fprintf(stderr, "hint: could not open a browser automatically; visit %s\n", url);}}diff --git a/src/ui/http_server.c b/src/ui/http_server.cindex 8bbdaab47..a282dbb3c 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -83,9 +83,12 @@ static bool origin_is_same_server(const char *origin, int port) {}static bool origin_matches_host(const char *origin, const char *host, int port) {- const char *hostname = strncmp(host, "localhost", 9) == 0 ? "localhost" : "127.0.0.1";+ /* Two literal loopback forms only — spelled out so the static URL audit+ * sees the complete URL each branch can produce. */char expected[128];- int length = snprintf(expected, sizeof(expected), "http://%s:%d", hostname, port);+ int length = strncmp(host, "localhost", 9) == 0+ ? snprintf(expected, sizeof(expected), "http://localhost:%d", port)+ : snprintf(expected, sizeof(expected), "http://127.0.0.1:%d", port);return length > 0 && (size_t)length < sizeof(expected) && strcmp(origin, expected) == 0;}diff --git a/tests/test_build_dir_safety.sh b/tests/test_build_dir_safety.shindex 5294e6f61..e2b2a2166 100644--- a/tests/test_build_dir_safety.sh+++ b/tests/test_build_dir_safety.sh@@ -33,31 +33,60 @@ for path in \fidone+# Create a real directory link: a native symlink, or an NTFS junction on+# Windows (MSYS reports junctions as symlinks). MSYS2's default `ln -s`+# silently DEEP-COPIES the target, which would turn these traversal fixtures+# into vacuous copies that the validator rightly accepts. Returns nonzero+# when this environment cannot create a real link at all — the traversal+# scenario then cannot exist, and the caller skips instead of asserting+# against a copy.+make_real_dir_link() {+ local target="$1" link="$2"+ if MSYS=winsymlinks:nativestrict ln -s -- "$target" "$link" 2>/dev/null &&+ [ -L "$link" ]; then+ return 0+ fi+ rm -rf -- "$link"+ case "$(uname -s)" in+ MINGW* | MSYS* | CYGWIN*)+ cmd //c "mklink /J \"$(cygpath -w "$link")\" \"$(cygpath -w "$target")\"" \+ >/dev/null 2>&1 || true+ ;;+ esac+ [ -L "$link" ]+}+# Lexical containment is not enough: an attacker-controlled or accidental# build/ symlink would make ROOT/build/c traverse outside the repository.symlink_fixture="$(mktemp -d "${TMPDIR:-/tmp}/cbm-build-dir-symlink.XXXXXX")"trap 'rm -rf -- "$symlink_fixture"' EXITmkdir -p "$symlink_fixture/repo" "$symlink_fixture/outside"-ln -s "$symlink_fixture/outside" "$symlink_fixture/repo/build"-if (- cd "$symlink_fixture/repo"- cbm_require_safe_build_dir build/c "$symlink_fixture/repo"-); then- echo "FAIL: BUILD_DIR accepted a symlinked build/ ancestor" >&2- exit 1+if make_real_dir_link "$symlink_fixture/outside" "$symlink_fixture/repo/build"; then+ if (+ cd "$symlink_fixture/repo"+ cbm_require_safe_build_dir build/c "$symlink_fixture/repo"+ ); then+ echo "FAIL: BUILD_DIR accepted a symlinked build/ ancestor" >&2+ exit 1+ fi+else+ echo "SKIP: no real symlink/junction support here; ancestor-traversal fixture not exercisable"fimkdir -p "$symlink_fixture/safe-repo/build" "$symlink_fixture/final-target"printf 'keep\n' >"$symlink_fixture/final-target/sentinel"-ln -s "$symlink_fixture/final-target" "$symlink_fixture/safe-repo/build/c"-if ! cbm_remove_build_dir "$symlink_fixture/safe-repo" build/c; then- echo "FAIL: safe removal rejected a final-component symlink" >&2- exit 1-fi-if [ -e "$symlink_fixture/safe-repo/build/c" ] ||- [ ! -f "$symlink_fixture/final-target/sentinel" ]; then- echo "FAIL: final-component symlink removal followed the link" >&2- exit 1+if make_real_dir_link "$symlink_fixture/final-target" "$symlink_fixture/safe-repo/build/c"; then+ if ! cbm_remove_build_dir "$symlink_fixture/safe-repo" build/c; then+ echo "FAIL: safe removal rejected a final-component symlink" >&2+ exit 1+ fi+ if [ -e "$symlink_fixture/safe-repo/build/c" ] ||+ [ ! -f "$symlink_fixture/final-target/sentinel" ]; then+ echo "FAIL: final-component symlink removal followed the link" >&2+ exit 1+ fi+else+ echo "SKIP: no real symlink/junction support here; final-component fixture not exercisable"fimkdir -p "$symlink_fixture/safe-repo/build/ordinary"printf 'remove\n' >"$symlink_fixture/safe-repo/build/ordinary/artifact"diff --git a/tests/test_cli.c b/tests/test_cli.cindex 422480587..bcde3343f 100644--- a/tests/test_cli.c+++ b/tests/test_cli.c@@ -764,7 +764,14 @@ TEST(cli_activation_quiesce_does_not_wait_on_bootstrap_startup) {char ready = setup ? 'R' : 'E';(void)write(ready_pipe[1], &ready, 1);bool saw_maintenance = false;- uint64_t maintenance_deadline = cbm_now_ms() + 30000U;+ /* The installer only reaches the cohort barrier after STAGING the+ * candidate — three tamper-defense SHA-256 passes over the whole+ * binary. The candidate here is this test runner itself (~1 GB with+ * sanitizers), which costs ~40 s on container/CI I/O, so the+ * observation window must cover worst-case staging. On success the+ * child exits the moment it observes the request, so the fast path+ * stays fast. */+ uint64_t maintenance_deadline = cbm_now_ms() + 120000U;while (setup && cbm_now_ms() < maintenance_deadline) {cbm_version_cohort_maintenance_presence_t presence =cbm_version_cohort_maintenance_presence(manager);@@ -776,7 +783,12 @@ TEST(cli_activation_quiesce_does_not_wait_on_bootstrap_startup) {presence == CBM_VERSION_COHORT_MAINTENANCE_IO) {break;}- cbm_usleep(1000);+ /* REQUESTED is level-triggered: the installer holds maintenance EX+ * for the whole mutation window, which cannot complete before this+ * child releases its lease. A realistic probe cadence therefore+ * cannot miss it; a 1 kHz probe storm would only be an observer+ * artifact no production participant produces. */+ cbm_usleep(25000);}uint64_t bootstrap_stall_deadline = cbm_now_ms() + 3000U;while (saw_maintenance && cbm_now_ms() < bootstrap_stall_deadline) {@@ -8390,6 +8402,14 @@ TEST(cli_installer_rejects_symlinked_agent_roots) {snprintf(junie_link, sizeof(junie_link), "%s/.junie", tmpdir);if (symlink(qoder_target, qoder_link) != 0 || symlink(junie_target, junie_link) != 0)FAIL("symlink failed");+ /* Root-owned symlinks are deliberately trusted as infrastructure (distro+ * /home indirection, macOS /tmp) — only root can create them, so they are+ * outside the attacker model. The contract under test is refusal of+ * USER-planted links; a root test run (containers) must demote its links+ * to an unprivileged owner or it would assert against the wrong model. */+ if (geteuid() == 0 &&+ (lchown(qoder_link, 65534, 65534) != 0 || lchown(junie_link, 65534, 65534) != 0))+ FAIL("lchown to unprivileged owner failed");char qoder_executable[512];snprintf(qoder_executable, sizeof(qoder_executable), "%s/qodercli", tmpdir);diff --git a/tests/windows/test_daemon_stability.py b/tests/windows/test_daemon_stability.pynew file mode 100644index 000000000..dbe496fef--- /dev/null+++ b/tests/windows/test_daemon_stability.py@@ -0,0 +1,404 @@+r"""GREEN guard — daemon stability, parameter surface, and failure modes.++Extends the basic lifecycle guard (test_daemon_lifecycle.py) with the angles+that guard the daemon's PRODUCT contract under stress and misuse:++* Parameter surface: bare ``daemon`` and unknown options print usage and fail;+ an out-of-range ``--port=`` value is rejected before anything spawns.+* Hook fail-open without a daemon: ``hook-augment`` exits 0, surfaces the+ visible one-time notice (stderr + Claude systemMessage), stamps the+ cache-scoped rate-limit marker, and stays silent on the next call.+* ``daemon start`` while a permanent daemon is active reports already-active+ with the SAME pid (no second daemon, no restart); ``daemon status`` reports+ the active pid; a ``--port=N`` pointing at an occupied port must not block+ the start (the UI bind is retried in the background by design).+* ``daemon stop`` REFUSES while an MCP session is attached, lists the blocking+ client, and succeeds once the session closes.+* Crash recovery: after a kill -9 the stale daemon state must clear, a cold+ one-shot works again, and a fresh ``daemon start`` yields a NEW pid.+* Churn stability: a permanent daemon must survive sequential and parallel+ one-shot client storms with its pid UNCHANGED (no silent restart) and stay+ responsive afterwards.+* Concurrent cold start: parallel one-shots racing with no daemon must all+ succeed, and the ephemeral daemon they share must retire afterwards.++Every daemon this guard starts carries a kill-by-pid backstop so a stuck+daemon can never hang the suite. Each section runs under its OWN cache+directory: daemon coordination is cache-scoped, so sections are isolated from+each other and from any interactive CBM use on the host.++Exit code: 0 == all sections green, 1 == regression, 2 == setup error.++Usage:+ python test_daemon_stability.py <path-to-codebase-memory-mcp[.exe]>+"""+import json+import os+import re+import shutil+import socket+import subprocess+import sys+import tempfile+import threading+import time++STATUS_POLL_S = 0.5+++def run_cli(binary, cache, args, stdin=None, timeout=90):+ env = dict(os.environ)+ env["CBM_CACHE_DIR"] = cache+ return subprocess.run([binary] + args, capture_output=True, timeout=timeout,+ env=env, input=stdin)+++def out_text(result):+ return ((result.stdout or b"") + (result.stderr or b"")).decode("utf-8", "replace")+++def kill_pid(pid):+ if not pid:+ return+ if os.name == "nt":+ subprocess.run(["taskkill", "/F", "/PID", str(pid)], capture_output=True, timeout=30)+ else:+ subprocess.run(["kill", "-9", str(pid)], capture_output=True, timeout=30)+++def pid_from(text):+ match = re.search(r"pid[: ]+(\d+)", text)+ return int(match.group(1)) if match else 0+++def wait_status_not_running(binary, cache, deadline_s):+ deadline = time.monotonic() + deadline_s+ while time.monotonic() < deadline:+ status = run_cli(binary, cache, ["daemon", "status"], timeout=30)+ if status.returncode != 0 and "not running" in out_text(status):+ return True+ time.sleep(STATUS_POLL_S)+ return False+++def read_line_with_timeout(stream, timeout_s):+ box = []++ def _reader():+ try:+ box.append(stream.readline())+ except Exception:+ box.append(b"")++ thread = threading.Thread(target=_reader, daemon=True)+ thread.start()+ thread.join(timeout_s)+ return box[0] if box else None+++def section_params(binary, work):+ cache = os.path.join(work, "cache-params")+ os.makedirs(cache, exist_ok=True)+ bare = run_cli(binary, cache, ["daemon"])+ if bare.returncode == 0 or "usage:" not in out_text(bare):+ print("RED: bare `daemon` should print usage and fail:\n%s" % out_text(bare)[:300])+ return False+ unknown = run_cli(binary, cache, ["daemon", "bogus"])+ if unknown.returncode == 0 or "unknown daemon option" not in out_text(unknown):+ print("RED: `daemon bogus` should be rejected:\n%s" % out_text(unknown)[:300])+ return False+ bad_port = run_cli(binary, cache, ["daemon", "start", "--port=0"])+ if bad_port.returncode == 0 or "--port requires" not in out_text(bad_port):+ print("RED: `--port=0` should be rejected before spawning:\n%s"+ % out_text(bad_port)[:300])+ return False+ print("PASS: parameter surface rejects bare/unknown/out-of-range daemon invocations")+ return True+++def section_hook_fail_open(binary, work):+ cache = os.path.join(work, "cache-hook")+ os.makedirs(cache, exist_ok=True)+ payload = json.dumps({+ "hook_event_name": "PreToolUse",+ "tool_name": "Grep",+ "cwd": work.replace("\\", "/"),+ "tool_input": {"pattern": "anything"},+ }).encode("utf-8")+ first = run_cli(binary, cache, ["hook-augment"], stdin=payload, timeout=60)+ first_out = (first.stdout or b"").decode("utf-8", "replace")+ first_err = (first.stderr or b"").decode("utf-8", "replace")+ marker = os.path.join(cache, ".hook-daemon-absent-notice")+ if first.returncode != 0:+ print("RED: hook-augment without a daemon must fail OPEN (exit 0), got rc=%d:\n%s"+ % (first.returncode, (first_out + first_err)[:300]))+ return False+ if "systemMessage" not in first_out or "no CBM daemon" not in first_err:+ print("RED: the first absent-daemon hook call must surface the visible notice "+ "(stdout systemMessage + stderr):\nstdout=%r\nstderr=%r"+ % (first_out[:200], first_err[:200]))+ return False+ if not os.path.exists(marker):+ print("RED: the absent-daemon notice did not stamp its rate-limit marker: %s" % marker)+ return False+ second = run_cli(binary, cache, ["hook-augment"], stdin=payload, timeout=60)+ second_out = (second.stdout or b"").decode("utf-8", "replace")+ if second.returncode != 0 or "systemMessage" in second_out:+ print("RED: the second absent-daemon hook call must stay silent (rate-limited), "+ "rc=%d stdout=%r" % (second.returncode, second_out[:200]))+ return False+ print("PASS: hook fails open without a daemon; notice is visible once, then rate-limited")+ return True+++def section_start_status_port(binary, work):+ cache = os.path.join(work, "cache-start")+ os.makedirs(cache, exist_ok=True)+ daemon_pid = 0+ blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ try:+ blocker.bind(("127.0.0.1", 0))+ blocker.listen(1)+ busy_port = blocker.getsockname()[1]+ start = run_cli(binary, cache, ["daemon", "start", "--port=%d" % busy_port], timeout=60)+ start_text = out_text(start)+ daemon_pid = pid_from(start_text)+ if start.returncode != 0 or "permanent" not in start_text or not daemon_pid:+ print("RED: `daemon start --port=<occupied>` must still start the daemon "+ "(UI bind is non-blocking):\n%s" % start_text[:400])+ return False+ status = run_cli(binary, cache, ["daemon", "status"])+ status_text = out_text(status)+ if status.returncode != 0 or "active (permanent" not in status_text or \+ pid_from(status_text) != daemon_pid:+ print("RED: status must report the active permanent daemon pid %d:\n%s"+ % (daemon_pid, status_text[:400]))+ return False+ again = run_cli(binary, cache, ["daemon", "start"], timeout=60)+ again_text = out_text(again)+ if again.returncode != 0 or "already active (permanent" not in again_text or \+ pid_from(again_text) != daemon_pid:+ print("RED: a second `daemon start` must report already-active with the SAME "+ "pid %d:\n%s" % (daemon_pid, again_text[:400]))+ return False+ stop = run_cli(binary, cache, ["daemon", "stop"])+ if stop.returncode != 0 or not wait_status_not_running(binary, cache, 45):+ print("RED: the daemon did not stop cleanly after the start/status checks")+ return False+ daemon_pid = 0+ print("PASS: start survives an occupied --port, status reports the pid, "+ "second start is a no-op on the same daemon")+ return True+ finally:+ blocker.close()+ kill_pid(daemon_pid)+++def section_stop_refuses_busy(binary, work):+ cache = os.path.join(work, "cache-busy")+ os.makedirs(cache, exist_ok=True)+ daemon_pid = 0+ session = None+ try:+ start = run_cli(binary, cache, ["daemon", "start"], timeout=60)+ daemon_pid = pid_from(out_text(start))+ if start.returncode != 0 or not daemon_pid:+ print("SETUP FAIL: permanent daemon did not start for the busy-stop check")+ return False+ env = dict(os.environ)+ env["CBM_CACHE_DIR"] = cache+ session = subprocess.Popen([binary], stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,+ env=env)+ session.stdin.write(b'{"jsonrpc":"2.0","id":0,"method":"initialize",'+ b'"params":{"capabilities":{}}}\n')+ session.stdin.flush()+ reply = read_line_with_timeout(session.stdout, 45)+ if not reply or b'"result"' not in reply:+ print("SETUP FAIL: MCP session did not complete initialize: %r"+ % (reply[:200] if reply else reply))+ return False+ busy = run_cli(binary, cache, ["daemon", "stop"])+ busy_text = out_text(busy)+ listed_pids = re.findall(r"- pid (\d+)", busy_text)+ # The daemon lists its authenticated peer process. On Windows the MCP+ # frontend's daemon client is an internal child of the spawned .exe, so+ # the listed pid need not equal the Popen pid (the same process-boundary+ # caveat the soak's idle-CPU check documents); POSIX peers match exactly.+ pids_ok = bool(listed_pids) if os.name == "nt" else str(session.pid) in listed_pids+ if busy.returncode == 0 or "NOT stopped" not in busy_text or not pids_ok:+ print("RED: `daemon stop` with an attached MCP session (pid %d) must refuse "+ "and list the blocking client:\n%s" % (session.pid, busy_text[:400]))+ return False+ session.stdin.close()+ session.wait(timeout=45)+ deadline = time.monotonic() + 45+ stopped = False+ while time.monotonic() < deadline:+ retry = run_cli(binary, cache, ["daemon", "stop"])+ if retry.returncode == 0:+ stopped = True+ break+ time.sleep(STATUS_POLL_S)+ if not stopped or not wait_status_not_running(binary, cache, 45):+ print("RED: `daemon stop` did not succeed after the blocking session closed")+ return False+ daemon_pid = 0+ print("PASS: stop refuses while a session is attached (listing its pid) and "+ "succeeds once the session closes")+ return True+ finally:+ if session and session.poll() is None:+ session.kill()+ kill_pid(daemon_pid)+++def section_crash_recovery(binary, work):+ cache = os.path.join(work, "cache-crash")+ os.makedirs(cache, exist_ok=True)+ daemon_pid = 0+ second_pid = 0+ try:+ start = run_cli(binary, cache, ["daemon", "start"], timeout=60)+ daemon_pid = pid_from(out_text(start))+ if start.returncode != 0 or not daemon_pid:+ print("SETUP FAIL: permanent daemon did not start for the crash check")+ return False+ kill_pid(daemon_pid)+ if not wait_status_not_running(binary, cache, 60):+ print("RED: after kill -9 of pid %d the stale daemon state never cleared "+ "(`daemon status` kept reporting it)" % daemon_pid)+ return False+ cold = run_cli(binary, cache, ["cli", "list_projects", "{}"], timeout=90)+ if cold.returncode != 0 or "daemon start" not in out_text(cold):+ print("RED: a cold one-shot after the daemon crash should succeed with the "+ "startup-tax hint:\n%s" % out_text(cold)[:400])+ return False+ restart = run_cli(binary, cache, ["daemon", "start"], timeout=60)+ second_pid = pid_from(out_text(restart))+ if restart.returncode != 0 or not second_pid or second_pid == daemon_pid:+ print("RED: `daemon start` after the crash must launch a FRESH daemon:\n%s"+ % out_text(restart)[:400])+ return False+ daemon_pid = 0+ stop = run_cli(binary, cache, ["daemon", "stop"])+ if stop.returncode != 0 or not wait_status_not_running(binary, cache, 45):+ print("RED: the recovered daemon did not stop cleanly")+ return False+ second_pid = 0+ print("PASS: kill -9 recovery — stale state cleared, cold client worked, fresh "+ "start got a new pid")+ return True+ finally:+ kill_pid(daemon_pid)+ kill_pid(second_pid)+++def _parallel_one_shots(binary, cache, count):+ results = [None] * count++ def _one(index):+ results[index] = run_cli(binary, cache, ["cli", "list_projects", "{}"], timeout=120)++ threads = [threading.Thread(target=_one, args=(i,)) for i in range(count)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(150)+ return results+++def section_churn_stability(binary, work):+ cache = os.path.join(work, "cache-churn")+ os.makedirs(cache, exist_ok=True)+ daemon_pid = 0+ try:+ start = run_cli(binary, cache, ["daemon", "start"], timeout=60)+ daemon_pid = pid_from(out_text(start))+ if start.returncode != 0 or not daemon_pid:+ print("SETUP FAIL: permanent daemon did not start for the churn check")+ return False+ for round_index in range(10):+ one = run_cli(binary, cache, ["cli", "list_projects", "{}"], timeout=90)+ if one.returncode != 0:+ print("RED: sequential churn one-shot %d failed:\n%s"+ % (round_index, out_text(one)[:300]))+ return False+ for wave in range(2):+ results = _parallel_one_shots(binary, cache, 6)+ for index, result in enumerate(results):+ if result is None or result.returncode != 0:+ print("RED: parallel churn wave %d client %d failed (rc=%s):\n"+ "stdout=%r\nstderr=%r"+ % (wave, index,+ result.returncode if result else "none",+ (result.stdout or b"")[-300:] if result else b"",+ (result.stderr or b"")[-400:] if result else b""))+ return False+ status = run_cli(binary, cache, ["daemon", "status"])+ status_text = out_text(status)+ if status.returncode != 0 or pid_from(status_text) != daemon_pid:+ print("RED: after the churn the daemon must still be the SAME process "+ "(expected pid %d):\n%s" % (daemon_pid, status_text[:400]))+ return False+ stop = run_cli(binary, cache, ["daemon", "stop"])+ if stop.returncode != 0 or not wait_status_not_running(binary, cache, 45):+ print("RED: the churned daemon did not stop cleanly")+ return False+ daemon_pid = 0+ print("PASS: permanent daemon survived 10 sequential + 2x6 parallel clients "+ "with an unchanged pid")+ return True+ finally:+ kill_pid(daemon_pid)+++def section_cold_storm(binary, work):+ cache = os.path.join(work, "cache-storm")+ os.makedirs(cache, exist_ok=True)+ results = _parallel_one_shots(binary, cache, 6)+ for index, result in enumerate(results):+ if result is None or result.returncode != 0:+ print("RED: cold-storm client %d failed (racing daemon spawn):\n%s"+ % (index, out_text(result)[:300] if result else "(no result)"))+ return False+ if not wait_status_not_running(binary, cache, 90):+ print("RED: the ephemeral daemon shared by the cold storm never retired")+ return False+ print("PASS: 6 racing cold clients all succeeded and the shared ephemeral daemon retired")+ return True+++def main():+ if len(sys.argv) < 2:+ print("usage: python test_daemon_stability.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_daemon_stab_")+ sections = [+ section_params,+ section_hook_fail_open,+ section_start_status_port,+ section_stop_refuses_busy,+ section_crash_recovery,+ section_churn_stability,+ section_cold_storm,+ ]+ try:+ for section in sections:+ if not section(binary, work):+ print("\nRED (tests/windows/test_daemon_stability.py): %s failed"+ % section.__name__)+ return 1+ print("\nGREEN: daemon stability, parameters, and failure modes behave.")+ return 0+ finally:+ shutil.rmtree(work, ignore_errors=True)+++if __name__ == "__main__":+ sys.exit(main())