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.

fix: harden cross-platform daemon startup smoke

Martin Vogelf35b10b79bfe
diff --git a/scripts/test-windows.ps1 b/scripts/test-windows.ps1
index a0d7451f4..8fb975f91 100644
--- a/scripts/test-windows.ps1
+++ b/scripts/test-windows.ps1
@@ -133,24 +133,26 @@ Write-Host "Payload: $bin" -ForegroundColor Green
Write-Host "Launcher: $launcherBin" -ForegroundColor Green
Write-Host "ABI mismatch fixture: $abiMismatchLauncher" -ForegroundColor Green
-$localAppData = [Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData)
-if (-not $localAppData) { throw "could not resolve the current user's local application-data directory" }
-$guardRoot = Join-Path $localAppData "Temp"
-New-Item -ItemType Directory -Path $guardRoot -Force | Out-Null
-$guardBundle = Join-Path $guardRoot ("cbm-windows-guards-" + [guid]::NewGuid().ToString("N"))
-New-Item -ItemType Directory -Path $guardBundle | Out-Null
-$guardBin = Join-Path $guardBundle "codebase-memory-mcp.exe"
-$guardPayload = Join-Path $guardBundle "codebase-memory-mcp.payload.exe"
-Copy-Item -LiteralPath $launcherBin -Destination $guardBin
-Copy-Item -LiteralPath $bin -Destination $guardPayload
-Write-Host "Guard bundle: $guardBin" -ForegroundColor Green
-
$previousTemp = $env:TEMP
$previousTmp = $env:TMP
$previousTmpDir = $env:TMPDIR
+$guardRoot = $null
try {
- # The launcher deliberately rejects GitHub's shared D:\a ancestry. Keep
- # launcher fixtures and Python-created descendants inside this account.
+ $userProfile = [Environment]::GetFolderPath([Environment+SpecialFolder]::UserProfile)
+ if (-not $userProfile) { throw "could not resolve the current user's profile directory" }
+ $guardRoot = Join-Path $userProfile ("cbm-windows-guards-root-" + [guid]::NewGuid().ToString("N"))
+ New-Item -ItemType Directory -Path $guardRoot | Out-Null
+ $guardBundle = Join-Path $guardRoot ("cbm-windows-guards-" + [guid]::NewGuid().ToString("N"))
+ New-Item -ItemType Directory -Path $guardBundle | Out-Null
+ $guardBin = Join-Path $guardBundle "codebase-memory-mcp.exe"
+ $guardPayload = Join-Path $guardBundle "codebase-memory-mcp.payload.exe"
+ Copy-Item -LiteralPath $launcherBin -Destination $guardBin
+ Copy-Item -LiteralPath $bin -Destination $guardPayload
+ Write-Host "Guard bundle: $guardBin" -ForegroundColor Green
+
+ # The launcher deliberately rejects GitHub's shared D:\a ancestry and the
+ # hosted runner's inherited LocalAppData\Temp ACL. Keep launcher fixtures
+ # and Python-created descendants below the accepted profile ancestry.
$env:TEMP = $guardRoot
$env:TMP = $guardRoot
$env:TMPDIR = $guardRoot
@@ -215,10 +217,12 @@ if (-not $GuardsOnly) {
}
}
} finally {
- Remove-Item -LiteralPath $guardBundle -Recurse -Force -ErrorAction SilentlyContinue
$env:TEMP = $previousTemp
$env:TMP = $previousTmp
$env:TMPDIR = $previousTmpDir
+ if ($guardRoot) {
+ Remove-Item -LiteralPath $guardRoot -Recurse -Force -ErrorAction SilentlyContinue
+ }
}
Write-Host ""
diff --git a/scripts/test_mcp_interactive.py b/scripts/test_mcp_interactive.py
index 47c7249e8..d37e2d57c 100644
--- a/scripts/test_mcp_interactive.py
+++ b/scripts/test_mcp_interactive.py
@@ -17,7 +17,7 @@ import subprocess
import sys
import threading
import time
-from typing import Any, BinaryIO
+from typing import Any, BinaryIO, Optional
INITIALIZE_PARAMS = {
@@ -68,6 +68,21 @@ def drain(stream: BinaryIO, chunks: list[bytes]) -> None:
chunks.append(chunk)
+def daemon_log_tail(limit: int = 16384) -> str:
+ cache_dir = os.environ.get("CBM_CACHE_DIR")
+ if not cache_dir:
+ return ""
+ path = os.path.join(cache_dir, "logs", "cbm-daemon.log")
+ try:
+ with open(path, "rb") as stream:
+ stream.seek(0, os.SEEK_END)
+ size = stream.tell()
+ stream.seek(max(0, size - limit), os.SEEK_SET)
+ return stream.read(limit).decode("utf-8", errors="replace")
+ except OSError:
+ return ""
+
+
def send(process: subprocess.Popen[bytes], message: dict[str, Any]) -> None:
if process.stdin is None:
raise SmokeFailure("MCP stdin is unavailable")
@@ -143,6 +158,39 @@ def request(
return wait_response(process, responses, request_id, timeout, accept_tool_error)
+def grouped_search_qualified_name(
+ structured: Any, expected_name: str
+) -> Optional[str]:
+ """Extract a qualified name from search_graph's grouped JSON tree."""
+ if not isinstance(structured, dict):
+ return None
+ columns = structured.get("cols")
+ groups = structured.get("groups")
+ if not isinstance(columns, list) or not isinstance(groups, list):
+ return None
+ try:
+ name_column = columns.index("name")
+ except ValueError:
+ return None
+
+ for group in groups:
+ if not isinstance(group, dict):
+ return None
+ prefix = group.get("qn_prefix")
+ rows = group.get("rows")
+ if not isinstance(prefix, str) or not isinstance(rows, list):
+ return None
+ for row in rows:
+ if not isinstance(row, list) or name_column >= len(row):
+ return None
+ name = row[name_column]
+ if not isinstance(name, str):
+ return None
+ if name == expected_name:
+ return f"{prefix}.{name}" if prefix else name
+ return None
+
+
def run_scenario(
process: subprocess.Popen[bytes],
responses: "queue.Queue[dict[str, Any]]",
@@ -245,17 +293,8 @@ def run_scenario(
if isinstance(discovery_result, dict)
else None
)
- matches = (
- discovery_structured.get("results")
- if isinstance(discovery_structured, dict)
- else None
- )
- qualified_name = (
- matches[0].get("qualified_name")
- if isinstance(matches, list) and matches and isinstance(matches[0], dict)
- else None
- )
- if not isinstance(qualified_name, str) or not qualified_name:
+ qualified_name = grouped_search_qualified_name(discovery_structured, "compute")
+ if not qualified_name:
raise SmokeFailure("search_graph did not discover compute's qualified name")
request(
process,
@@ -346,10 +385,18 @@ def main() -> int:
except SmokeFailure as error:
stop_process(process)
stderr = b"".join(stderr_chunks).decode("utf-8", errors="replace")
+ daemon_log = daemon_log_tail()
print(f"FAIL: {error}", file=sys.stderr)
if stderr:
print("--- MCP stderr ---", file=sys.stderr)
print(stderr, file=sys.stderr, end="" if stderr.endswith("\n") else "\n")
+ if daemon_log:
+ print("--- daemon log (tail) ---", file=sys.stderr)
+ print(
+ daemon_log,
+ file=sys.stderr,
+ end="" if daemon_log.endswith("\n") else "\n",
+ )
return 1
diff --git a/src/daemon/bootstrap.c b/src/daemon/bootstrap.c
index ff080114d..f41eba8fb 100644
--- a/src/daemon/bootstrap.c
+++ b/src/daemon/bootstrap.c
@@ -520,7 +520,9 @@ typedef struct bootstrap_production_cohort {
typedef struct {
bootstrap_production_cohort_t *cohort;
-#ifdef __APPLE__
+#ifdef _WIN32
+ DWORD spawn_error;
+#elif defined(__APPLE__)
int spawn_error;
#endif
} bootstrap_production_context_t;
@@ -674,17 +676,29 @@ static bool bootstrap_production_handoff(void *context, cbm_daemon_bootstrap_loc
#ifdef _WIN32
static bool bootstrap_production_spawn(void *context,
const cbm_daemon_bootstrap_launch_spec_t *spec) {
- (void)context;
+ bootstrap_production_context_t *production = context;
+ if (production) {
+ production->spawn_error = ERROR_SUCCESS;
+ }
if (!spec || !spec->detached || spec->inherit_standard_handles || spec->use_shell) {
+ if (production) {
+ production->spawn_error = ERROR_INVALID_PARAMETER;
+ }
return false;
}
char command_line[BOOTSTRAP_PATH_CAP * 2];
if (!cbm_build_win_cmdline(command_line, sizeof(command_line), spec->argv)) {
+ if (production) {
+ production->spawn_error = ERROR_INVALID_PARAMETER;
+ }
return false;
}
wchar_t *application = cbm_utf8_to_wide(spec->executable_path);
wchar_t *command = cbm_utf8_to_wide(command_line);
if (!application || !command) {
+ if (production) {
+ production->spawn_error = ERROR_NOT_ENOUGH_MEMORY;
+ }
free(application);
free(command);
return false;
@@ -712,8 +726,12 @@ static bool bootstrap_production_spawn(void *context,
}
BOOL created = CreateProcessW(application, command, NULL, NULL, FALSE, flags, NULL, NULL,
&startup, &child);
+ DWORD spawn_error = created ? ERROR_SUCCESS : GetLastError();
free(application);
free(command);
+ if (production) {
+ production->spawn_error = spawn_error;
+ }
if (!created) {
return false;
}
@@ -895,7 +913,15 @@ static bool bootstrap_production_spawn(void *context,
static void bootstrap_production_diagnostic(void *context, const char *message) {
bootstrap_production_context_t *production = context;
-#ifdef __APPLE__
+#ifdef _WIN32
+ if (production && production->spawn_error != ERROR_SUCCESS) {
+ (void)fprintf(stderr, "codebase-memory-mcp: %s (daemon launch error %lu)\n",
+ message ? message : "daemon startup failed",
+ (unsigned long)production->spawn_error);
+ (void)fflush(stderr);
+ return;
+ }
+#elif defined(__APPLE__)
if (production && production->spawn_error != 0) {
(void)fprintf(stderr, "codebase-memory-mcp: %s (daemon launch: %s)\n",
message ? message : "daemon startup failed",
diff --git a/src/daemon/host.c b/src/daemon/host.c
index 7c96f518d..e7cde9cb0 100644
--- a/src/daemon/host.c
+++ b/src/daemon/host.c
@@ -757,6 +757,12 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) {
!config->identity.semantic_version || !config->identity.build_fingerprint) {
return -1;
}
+ cbm_ui_log_init();
+ char conflict_log[HOST_PATH_CAP];
+ if (!host_log_open(conflict_log)) {
+ (void)fprintf(stderr, "codebase-memory: daemon log path is not private or safe\n");
+ return -1;
+ }
cbm_version_cohort_manager_t *cohort_manager = cbm_version_cohort_manager_new(config->endpoint);
cbm_version_cohort_lease_t *cohort_lease = NULL;
cbm_daemon_conflict_t cohort_conflict;
@@ -770,6 +776,7 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) {
&cohort_lease, &cohort_conflict)
: CBM_VERSION_COHORT_IO;
if (cohort_status != CBM_VERSION_COHORT_OK) {
+ cbm_log_error("daemon.start_failed", "component", "cohort");
char message[CBM_DAEMON_CONFLICT_MESSAGE_SIZE];
bool formatted = cohort_status == CBM_VERSION_COHORT_CONFLICT &&
cbm_daemon_conflict_format(&cohort_conflict, message, sizeof(message));
@@ -779,41 +786,38 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) {
(void)fprintf(stderr, "codebase-memory: %s\n",
formatted ? message : "daemon exact-build admission failed");
host_cohort_close(&cohort_lease, &cohort_manager);
+ host_log_close();
return -1;
}
cbm_daemon_ipc_participant_guard_t *participant_guard = NULL;
if (cbm_daemon_ipc_participant_guard_try_join(config->endpoint, &participant_guard) != 1) {
+ cbm_log_error("daemon.start_failed", "component", "participant");
(void)fprintf(stderr, "codebase-memory: daemon participant admission failed\n");
host_participant_guard_close(&participant_guard);
host_cohort_close(&cohort_lease, &cohort_manager);
+ host_log_close();
return -1;
}
cbm_daemon_ipc_lifetime_reservation_t *lifetime_reservation = NULL;
if (host_lifetime_reservation_acquire(config->endpoint, &lifetime_reservation) != 1) {
+ cbm_log_error("daemon.start_failed", "component", "lifetime");
host_participant_guard_close(&participant_guard);
host_cohort_close(&cohort_lease, &cohort_manager);
+ host_log_close();
return -1;
}
cbm_version_cohort_daemon_claim_t *daemon_claim = NULL;
if (cbm_version_cohort_daemon_claim_acquire(cohort_manager, &daemon_claim) !=
CBM_VERSION_COHORT_OK) {
+ cbm_log_error("daemon.start_failed", "component", "claim");
cbm_daemon_ipc_lifetime_reservation_release(lifetime_reservation);
host_daemon_claim_close(&daemon_claim);
host_participant_guard_close(&participant_guard);
host_cohort_close(&cohort_lease, &cohort_manager);
+ host_log_close();
return -1;
}
cbm_mem_init(cbm_mem_ram_fraction_for_total(cbm_system_info().total_ram));
- cbm_ui_log_init();
- char conflict_log[HOST_PATH_CAP];
- if (!host_log_open(conflict_log)) {
- (void)fprintf(stderr, "codebase-memory: daemon log path is not private or safe\n");
- cbm_daemon_ipc_lifetime_reservation_release(lifetime_reservation);
- host_daemon_claim_close(&daemon_claim);
- host_participant_guard_close(&participant_guard);
- host_cohort_close(&cohort_lease, &cohort_manager);
- return -1;
- }
cbm_http_server_set_binary_path(config->executable_path);
cbm_index_supervisor_mark_host();
diff --git a/tests/test_daemon_runtime.c b/tests/test_daemon_runtime.c
index 9985dc4c5..ff54b2b1c 100644
--- a/tests/test_daemon_runtime.c
+++ b/tests/test_daemon_runtime.c
@@ -15,6 +15,7 @@
#include "daemon/ipc.h"
#include "daemon/runtime.h"
#include "daemon/service.h"
+#include "daemon/version_cohort.h"
#include "foundation/compat.h"
#include "foundation/compat_fs.h"
#include "foundation/compat_thread.h"
@@ -1398,6 +1399,92 @@ static bool runtime_test_read_log(const char *path, char out[RUNTIME_TEST_LOG_CA
return complete;
}
+/* A detached daemon loses its inherited stderr by design. Failures before the
+ * runtime listener exists must therefore reach the owner-private operation log
+ * or users and smoke tests see only a generic bootstrap timeout. An existing
+ * daemon claim deterministically fails before runtime startup. */
+TEST(daemon_host_early_coordination_failure_is_durable) {
+ const char *old_cache = getenv("CBM_CACHE_DIR");
+ bool had_cache = old_cache != NULL;
+ char *saved_cache = old_cache ? cbm_strdup(old_cache) : NULL;
+ bool snapshot_ok = !had_cache || saved_cache;
+
+ char parent[RUNTIME_TEST_PATH_CAP] = {0};
+ char cache[RUNTIME_TEST_PATH_CAP] = {0};
+ char log_path[RUNTIME_TEST_PATH_CAP] = {0};
+ int parent_written =
+ snprintf(parent, sizeof(parent), "%s/cbm-host-early-log-XXXXXX", cbm_tmpdir());
+ bool parent_created = snapshot_ok && parent_written > 0 &&
+ parent_written < (int)sizeof(parent) && cbm_mkdtemp(parent) != NULL;
+ int cache_written = parent_created ? snprintf(cache, sizeof(cache), "%s/cache", parent) : -1;
+ int log_written = parent_created
+ ? snprintf(log_path, sizeof(log_path), "%s/logs/cbm-daemon.log", cache)
+ : -1;
+ bool environment_ready = cache_written > 0 && cache_written < (int)sizeof(cache) &&
+ log_written > 0 && log_written < (int)sizeof(log_path) &&
+ cbm_mkdir_p(cache, 0700) && cbm_setenv("CBM_CACHE_DIR", cache, 1) == 0;
+ cbm_daemon_ipc_endpoint_t *endpoint =
+ environment_ready ? cbm_daemon_ipc_endpoint_new("0123456789abcdef", parent) : NULL;
+ cbm_version_cohort_manager_t *active_manager =
+ endpoint ? cbm_version_cohort_manager_new(endpoint) : NULL;
+ cbm_version_cohort_lease_t *active_lease = NULL;
+ cbm_version_cohort_daemon_claim_t *active_claim = NULL;
+ cbm_daemon_conflict_t active_conflict;
+ cbm_daemon_build_identity_t active_identity =
+ runtime_test_identity("active-host", runtime_test_self_build());
+ active_identity.cache_fingerprint = RUNTIME_BUILD_B;
+ cbm_version_cohort_status_t active_status =
+ active_manager
+ ? cbm_version_cohort_acquire(active_manager, &active_identity, UINT64_MAX,
+ &active_lease, &active_conflict)
+ : CBM_VERSION_COHORT_IO;
+ cbm_version_cohort_status_t claim_status =
+ active_status == CBM_VERSION_COHORT_OK
+ ? cbm_version_cohort_daemon_claim_acquire(active_manager, &active_claim)
+ : CBM_VERSION_COHORT_IO;
+ atomic_int stop_requested = ATOMIC_VAR_INIT(0);
+ cbm_daemon_host_config_t config = {
+ .endpoint = endpoint,
+ .identity = active_identity,
+ .executable_path = "/host-early-log-test",
+ .stop_requested = &stop_requested,
+ };
+ int run_result = claim_status == CBM_VERSION_COHORT_OK ? cbm_daemon_host_run(&config) : 0;
+
+ char log[RUNTIME_TEST_LOG_CAP] = {0};
+ bool durable = runtime_test_read_log(log_path, log) &&
+ strstr(log, "daemon.start_failed") != NULL &&
+ strstr(log, "claim") != NULL;
+ bool endpoint_created = endpoint != NULL;
+ while (active_claim &&
+ cbm_version_cohort_daemon_claim_release(&active_claim) != CBM_PRIVATE_FILE_LOCK_OK) {
+ cbm_usleep(1000);
+ }
+ while (active_lease &&
+ cbm_version_cohort_lease_release(&active_lease) != CBM_PRIVATE_FILE_LOCK_OK) {
+ cbm_usleep(1000);
+ }
+ while (active_manager &&
+ cbm_version_cohort_manager_free(&active_manager) != CBM_PRIVATE_FILE_LOCK_OK) {
+ cbm_usleep(1000);
+ }
+ cbm_daemon_ipc_endpoint_free(endpoint);
+ runtime_test_restore_environment("CBM_CACHE_DIR", saved_cache, had_cache);
+ free(saved_cache);
+ bool cleaned = !parent_created || th_rmtree(parent) == 0;
+
+ ASSERT_TRUE(snapshot_ok);
+ ASSERT_TRUE(parent_created);
+ ASSERT_TRUE(environment_ready);
+ ASSERT_TRUE(endpoint_created);
+ ASSERT_EQ(active_status, CBM_VERSION_COHORT_OK);
+ ASSERT_EQ(claim_status, CBM_VERSION_COHORT_OK);
+ ASSERT_EQ(run_result, -1);
+ ASSERT_TRUE(durable);
+ ASSERT_TRUE(cleaned);
+ PASS();
+}
+
/* RED on the former host preparation contract: a failed _config.db open was
* silently converted into default settings, so startup continued and could
* enable background behavior the user had explicitly disabled. */
@@ -4166,6 +4253,7 @@ TEST(daemon_runtime_process_fingerprint_never_hashes_replacement_path) {
#endif
SUITE(daemon_runtime) {
+ RUN_TEST(daemon_host_early_coordination_failure_is_durable);
RUN_TEST(daemon_host_refuses_unopenable_runtime_config_database);
RUN_TEST(daemon_host_http_reconcile_rate_limits_and_retries_transient_failures);
RUN_TEST(daemon_host_http_retry_backoff_is_bounded);
diff --git a/tests/test_lock_registry.c b/tests/test_lock_registry.c
index c83fc6bf6..c1f823696 100644
--- a/tests/test_lock_registry.c
+++ b/tests/test_lock_registry.c
@@ -42,13 +42,12 @@ typedef struct {
cbm_lock_registry_t *registry;
} lock_registry_fixture_t;
+/* The stress fixtures that use this helper are POSIX-only. */
+#ifndef _WIN32
static void lock_registry_test_yield(void) {
-#ifdef _WIN32
- (void)SwitchToThread();
-#else
(void)sched_yield();
-#endif
}
+#endif
#ifndef _WIN32
static cbm_private_lock_directory_t *lock_registry_test_directory_open(const char *root) {
diff --git a/tests/test_windows_bundle_contract.sh b/tests/test_windows_bundle_contract.sh
index 823fedc75..53b524ea7 100644
--- a/tests/test_windows_bundle_contract.sh
+++ b/tests/test_windows_bundle_contract.sh
@@ -353,16 +353,26 @@ require(
all(
needle in windows_test_driver
for needle in (
- "[Environment+SpecialFolder]::LocalApplicationData",
- '$guardRoot = Join-Path $localAppData "Temp"',
+ "[Environment+SpecialFolder]::UserProfile",
+ '$guardRoot = Join-Path $userProfile '
+ '("cbm-windows-guards-root-" + [guid]::NewGuid().ToString("N"))',
'$env:TEMP = $guardRoot',
'$env:TMP = $guardRoot',
'$env:TMPDIR = $guardRoot',
+ 'Remove-Item -LiteralPath $guardRoot -Recurse -Force',
)
),
"Windows launcher guards must keep staged and Python-created fixtures "
"beneath the current account profile",
)
+require(
+ '$guardRoot = $null\ntry {\n $userProfile = '
+ '[Environment]::GetFolderPath([Environment+SpecialFolder]::UserProfile)'
+ in windows_test_driver
+ and 'if ($guardRoot) {\n Remove-Item -LiteralPath $guardRoot -Recurse -Force'
+ in windows_test_driver,
+ "Windows launcher guard setup must be covered by profile-fixture cleanup",
+)
# Launcher supervision has two distinct failure directions: killing the
# launcher must kill its payload job, and killing only the launcher's immediate