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
Merge main into CBM Lens Beta
Martin Vogel0392068d496c
diff --cc Makefile.cbmindex fb64cf56c,cd5eb4124..54517bbac--- a/Makefile.cbm+++ b/Makefile.cbm@@@ -318,13 -438,15 +438,15 @@@ PREPROCESSOR_SRC = $(CBM_DIR)/preprocesSQLITE_WRITER_SRC = $(CBM_DIR)/sqlite_writer.c# Store module (new)- STORE_SRCS = src/store/store.c src/store/architecture_projection.c-STORE_SRCS = src/store/store.c src/store/store_impact.c src/store/store_graph_digest.c src/store/store_content_digest.c++STORE_SRCS = src/store/store.c src/store/architecture_projection.c src/store/store_impact.c src/store/store_graph_digest.c src/store/store_content_digest.c# Cypher module (new)CYPHER_SRCS = src/cypher/cypher.c# MCP server module (new)- MCP_SRCS = src/mcp/mcp.c src/mcp/index_supervisor.c src/mcp/compact_out.c src/mcp/architecture_jobs.c-MCP_SRCS = src/mcp/mcp.c src/mcp/index_supervisor.c src/mcp/compact_out.c \++MCP_SRCS = src/mcp/mcp.c src/mcp/index_supervisor.c src/mcp/compact_out.c src/mcp/architecture_jobs.c \+ src/mcp/test_impact.c src/mcp/test_impact_diff.c src/mcp/test_impact_classify.c src/mcp/test_impact_source.c src/mcp/test_impact_seed.c src/mcp/test_impact_engine.c src/mcp/test_impact_engine_snapshot.c src/mcp/test_impact_engine_reach.c src/mcp/test_impact_engine_artifact.c src/mcp/test_impact_cli.c src/mcp/test_impact_artifact.c src/mcp/test_impact_changes.c src/mcp/test_impact_origins.c src/mcp/test_impact_coverage.c src/mcp/test_impact_config.c src/mcp/test_impact_select.c src/mcp/test_impact_policy.c src/mcp/test_impact_git.c src/mcp/test_impact_inventory.c src/mcp/test_impact_inventory_input.c src/mcp/test_impact_tree.c src/mcp/test_impact_tree_audit.c src/mcp/test_impact_tree_read.c src/mcp/test_impact_tree_batch.c src/mcp/test_impact_tree_digest.c src/mcp/test_impact_tree_names.c src/mcp/test_impact_tree_plan.c src/mcp/test_impact_tree_posix.c src/mcp/test_impact_tree_posix_acl.c src/mcp/test_impact_tree_posix_io.c src/mcp/test_impact_tree_util.c src/mcp/test_impact_tree_windows.c src/mcp/test_impact_tree_windows_acl.c src/mcp/test_impact_tree_windows_io.c \+ src/mcp/test_impact_result.c src/mcp/test_impact_result_json.c src/mcp/test_impact_result_project.c src/mcp/test_impact_result_receipt.c src/mcp/test_impact_result_rows.c src/mcp/test_impact_result_util.c src/mcp/test_impact_result_validate.c src/mcp/test_impact_result_wire.c# Shared MCP daemon coordination and local transportDAEMON_SRCS = \@@@ -404,10 -547,10 +547,10 @@@ WATCHER_SRCS = src/watcher/watcher.GIT_SRCS = src/git/git_context.c# CLI module (new)-CLI_SRCS = src/cli/cli.c src/cli/progress_sink.c src/cli/hook_augment.c src/cli/client_adapter.c \+CLI_SRCS = src/cli/cli.c src/cli/runtime_settings.c src/cli/progress_sink.c src/cli/hook_augment.c src/cli/client_adapter.c \src/cli/agent_clients.c src/cli/agent_profiles.c \src/cli/config_json_like.c src/cli/config_toml_edit.c src/cli/config_yaml_edit.c \- src/cli/config_text_edit.c src/cli/activation_transaction.c+ src/cli/config_text_edit.c src/cli/config_edit_path.c src/cli/activation_transaction.c# UI module (graph visualization)UI_SRCS = \@@@ -561,9 -709,11 +718,12 @@@ TEST_EXTRACTION_SRCS =TEST_STORE_SRCS = \tests/test_store_nodes.c \tests/test_store_edges.c \+ tests/test_store_impact.c \+ tests/test_store_scope.c \+ tests/test_store_graph_digest.c \tests/test_store_search.c \tests/test_store_arch.c \+ tests/test_architecture_projection.c \tests/test_store_bulk.c \tests/test_store_pragmas.c \tests/test_store_checkpoint.c \diff --cc README.mdindex 3210a2b60,acf836f66..1ef376d9a--- a/README.md+++ b/README.md@@@ -35,9 -35,9 +35,9 @@@ High-quality parsing through [tree-sitt- **162 languages** — vendored tree-sitter grammars compiled into the binary. Nothing to install, nothing that breaks.- **120x fewer tokens** — 5 structural queries: ~3,400 tokens vs ~412,000 via file-by-file search. One graph query replaces dozens of grep/read cycles.- **45 supported automatic/conditional client surfaces** — `install` configures detected clients and safely activates conditional clients only when their documented platform, marker, or explicit existing config path is present. See [Multi-Agent Support](#multi-agent-support) for the complete matrix and manual/UI-only boundaries.-- **Built-in graph visualization** — 3D interactive UI at `localhost:9749`, served from the binary itself.+- **CBM Atlas** — the built-in human interface at `localhost:9749`: a reading IDE over the index (explorer and read-only Monaco reader, a semantic twin that follows the caret, flow, bug-hunt and change-scope reading modes, the 3D galaxy, source-cited answers, project management), served from the binary itself.- **Infrastructure-as-code indexing** — Dockerfiles, Kubernetes manifests, and Kustomize overlays indexed as graph nodes with cross-references. `Resource` nodes for K8s kinds, `Module` nodes for Kustomize overlays with `IMPORTS` edges to referenced resources.- - **15 MCP tools** — search, trace, architecture, impact analysis, targeted index-coverage checks, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.+ - **17 MCP tools** — search, trace, architecture, impact analysis, targeted index-coverage checks, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.## Quick Start@@@ -129,11 -129,11 +129,11 @@@ The native `install`, `update`, and `unPackage-manager setup (npm, PyPI, or Go) verifies and publishes a coherent private cached runtime set. Sidecars are replaced before the executable with per-file atomic renames; an interrupted multi-file publication is detected and repaired on the next launch rather than being described as one crash-atomic filesystem transaction. It does not replace the active native installation and therefore does not stop running CBM sessions. When that cached binary is executed, it still enters the same exact-build admission barrier. The shell and PowerShell installers invoke the verified candidate's native `install` command, so they do receive the full account-wide activation guarantee.- The ordinary `cli` mode is intentionally separate: it runs one command locally and never starts or connects to the coordination daemon, registers a daemon session, or starts watchers/UI. Its only shared state is the OS admission barrier plus per-project locks for graph mutations. While the command is running, a temporary monitor lets activation cancel that operation and its supervised worker safely; the monitor exits with the command and never becomes a standing daemon. See [CLI Mode](#cli-mode) for details.+ The ordinary `cli` mode runs one command locally, but it is not disconnected from the daemon above: it connects to the shared coordination daemon — starting one if none is already running — for that same admission barrier plus per-project locks on graph mutations. Its connection is a `cli_session`: it never registers with the background watcher and never starts a UI, and it holds the admission lease only for the command's lifetime. If the command's own connection is what started the daemon, that daemon exits again once the command closes and no other session is attached; if a daemon was already running, the command simply joins and leaves it exactly as found. While the command is running, a temporary monitor separately lets activation cancel that operation and its supervised worker safely; the monitor exits with the command and never becomes a standing daemon. See [CLI Mode](#cli-mode) for details.-### Graph Visualization UI+### CBM Lens Beta — the human interface-The graph UI is built into the binary — every install on every channel has it. Then run it:+The MCP tools are the agent's interface to the code graph; **CBM Lens Beta** is the human's. It is built into the binary — every install on every channel has it:```bashcodebase-memory-mcp --ui=true --port=9749diff --cc internal/cbm/lsp/scope.hindex 2aefa9788,5ba7265a3..823fcdb20--- a/internal/cbm/lsp/scope.h+++ b/internal/cbm/lsp/scope.h@@@ -3,9 -3,9 +3,10 @@@#include "type_rep.h"#include "../arena.h"+#include "../../../src/foundation/platform.h"#include <stdatomic.h> /* relaxed cache for cbm_lsp_max_walk_depth */- #include <stdlib.h> /* atoi (cbm_lsp_max_walk_depth) */-#include <stdlib.h> /* getenv, atoi (cbm_lsp_max_walk_depth) */-#include <string.h> /* strcmp (cbm_scope_lookup_binding) */++#include <stdlib.h> /* atoi (cbm_lsp_max_walk_depth) */++#include <string.h> /* strcmp (cbm_scope_lookup_binding) */typedef struct {const char* name;diff --cc scripts/run-test-wave.pyindex 0f0ce463e,e47852ba1..1174a0bf3--- a/scripts/run-test-wave.py+++ b/scripts/run-test-wave.py@@@ -25,24 -26,19 +26,38 @@@ SUITE_NAME = re.compile(r"^[a-z0-9_]+$"SUMMARY = re.compile(r"^ (?P<passed>[0-9]+) passed")FAILED = re.compile(r"(?:^|, )(?P<failed>[0-9]+) failed")SKIPPED = re.compile(r"(?:^|, )(?P<skipped>[0-9]+) skipped")+# Suites on the slow tier carry a stated reason (O10: no unexplained+# entries). incremental/store_arch/daemon_runtime: the heaviest sanitized+# suites by steady-state cost. node_creation_probe/grammar_probe_b: full-+# pipeline indexing probes whose FIRST run in a fresh checkout pays a+# one-time environment tax (every artifact is AV-scan-cold on the Windows+# VM; grammar_probe_b hit it 2026-08-? under host contention, node_creation+# _probe 2026-08-28 at exactly 900s on a new run checkout, both green on+# the warm rerun). That state is deterministic, not racy — the stable-state+# budget rule applies.++#+ # Suites whose honest runtime does not fit the default per-suite budget, and so+ # get --slow-timeout instead. This is a statement about SIZE, never about+ # flakiness: every suite here is deterministic and simply long, and a racy suite+ # must be made deterministic rather than given more clock.+ #+ # `cli` joined the list because the classification had gone stale, not because+ # anything regressed. It spends 497s of the 900s default on macos-14 -- the+ # FASTEST macOS runner -- while the macos-15-intel runner in the same matrix is+ # 2.4-3.6x slower on comparable suites (daemon_runtime 842s vs 349s,+ # stack_overflow_b 277s vs 76s). 497s at that ratio cannot fit, so the suite was+ # killed at 900s and reported as hung. daemon_runtime, at 842s on that same+ # runner, survives only because it was already listed here.-SLOW_SUITES = frozenset(("incremental", "store_arch", "daemon_runtime", "cli"))+SLOW_SUITES = frozenset(+ (+ "incremental",+ "store_arch",+ "daemon_runtime",++ "cli",+ "node_creation_probe",+ "grammar_probe_b",+ )+)POLL_SECONDS = 0.05# WHY: the Windows descendant probe below is a cold `powershell.exe` + CIMdiff --cc src/cli/hook_augment.cindex 5e55bd5b3,7a5e596e7..d0ca8d320--- a/src/cli/hook_augment.c+++ b/src/cli/hook_augment.c@@@ -106,23 -112,25 +112,29 @@@ static bool ha_fits(int written, size_static void ha_open_crumb_log(int deadline_ms) {const char *override = getenv("CBM_HOOK_TIMEOUT_LOG"); /* tests + power users */char path[CBM_SZ_1K];+ /* A path cut off at the buffer names some other file, and O_CREAT would+ * create it. Such a path means no breadcrumb; the hook itself runs on. */if (override && override[0]) {- snprintf(path, sizeof(path), "%s", override);- } else {- const char *home = getenv("HOME");- if (!home || !home[0]) {+ if (!ha_fits(snprintf(path, sizeof(path), "%s", override), sizeof(path))) {return;}+ } else {+ /* <cache_dir>/logs, where every cbm component logs: the cache dir is+ * CBM_CACHE_DIR, else HOME (then USERPROFILE) + the default. */+ const char *cache = cbm_resolve_cache_dir();char dir[CBM_SZ_1K];- snprintf(dir, sizeof(dir), "%s/.cache/codebase-memory-mcp/logs", home);- cbm_mkdir_p(dir, 0755);- snprintf(path, sizeof(path), "%s/hook-augment-timeouts.log", dir);+ if (!cache || !ha_fits(snprintf(dir, sizeof(dir), "%s/logs", cache), sizeof(dir)) ||+ !ha_fits(snprintf(path, sizeof(path), "%s/hook-augment-timeouts.log", dir),+ sizeof(path))) {+ return;+ }+ cbm_mkdir_p_ex(dir, 0755, CBM_MKDIR_FOLLOW_OWNED);}- g_ha_crumb_fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644);+ /* Startup may re-arm after resolving saved settings. Keep the original+ * diagnostic descriptor and refresh only the deadline text below. */+ if (g_ha_crumb_fd < 0) {+ g_ha_crumb_fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644);+ }if (g_ha_crumb_fd < 0) {return;}diff --cc src/foundation/subprocess.cindex c574080da,80daeccf2..f0deb7e49--- a/src/foundation/subprocess.c+++ b/src/foundation/subprocess.c@@@ -450,135 -457,11 +463,150 @@@ static void cbm_subprocess_result_init(result->forced = false;result->tree_quiesced = false;result->supervision_failed = false;+ result->job_memory_limit_bytes = 0;+ result->peak_job_memory_bytes = 0;+ result->job_memory_available = false;}+#ifdef _WIN32+/* Preserve the native Unicode environment, including Windows' hidden =C:+ * drive entries. Names compare ordinally without case, independent of locale. */+static size_t cbm_win_environment_name_length(const wchar_t *entry) {+ const wchar_t *equals = wcschr(entry + (entry[0] == L'=' ? 1 : 0), L'=');+ return equals ? (size_t)(equals - entry) : wcslen(entry);+}++static int cbm_win_environment_compare(const void *left, const void *right) {+ const wchar_t *a = *(const wchar_t *const *)left;+ const wchar_t *b = *(const wchar_t *const *)right;+ return CompareStringOrdinal(a, (int)cbm_win_environment_name_length(a), b,+ (int)cbm_win_environment_name_length(b), TRUE) -+ CSTR_EQUAL;+}++static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const char *const *overrides,+ size_t override_count) {- wchar_t *inherited = GetEnvironmentStringsW();++ wchar_t *inherited =++ process->strip_git_repo_env ? cbm_git_child_env_block() : GetEnvironmentStringsW();+ if (!inherited) {+ return false;+ }+ size_t count = 0;+ for (const wchar_t *entry = inherited; *entry; entry += wcslen(entry) + 1) {+ count++;+ }+ wchar_t **entries = calloc(count + override_count, sizeof(*entries));+ wchar_t **converted = calloc(override_count, sizeof(*converted));+ bool ok = false;+ if (!entries || !converted) {+ goto done;+ }+ size_t index = 0;+ for (wchar_t *entry = inherited; *entry; entry += wcslen(entry) + 1) {+ entries[index++] = entry;+ }+ for (size_t i = 0; i < override_count; i++) {++ if (process->strip_git_repo_env && cbm_git_env_entry_is_repo_local(overrides[i])) {++ continue;++ }+ converted[i] = cbm_utf8_to_wide(overrides[i]);+ if (!converted[i]) {+ goto done;+ }+ size_t slot = 0;+ while (slot < count && cbm_win_environment_compare(&entries[slot], &converted[i]) != 0) {+ slot++;+ }+ entries[slot] = converted[i];+ if (slot == count) {+ count++;+ }+ }+ qsort(entries, count, sizeof(*entries), cbm_win_environment_compare);- size_t length = 1; /* Final NUL, in addition to each entry's terminator. */++ size_t length = count ? 1 : 2; /* Empty blocks also need two NUL characters. */+ for (size_t i = 0; i < count; i++) {+ size_t entry_length = wcslen(entries[i]) + 1;+ if (entry_length > SIZE_MAX / sizeof(wchar_t) - length) {+ goto done;+ }+ length += entry_length;+ }+ process->environment = calloc(length, sizeof(*process->environment));+ if (!process->environment) {+ goto done;+ }+ wchar_t *next = process->environment;+ for (size_t i = 0; i < count; i++) {+ size_t entry_length = wcslen(entries[i]) + 1;+ wmemcpy(next, entries[i], entry_length);+ next += entry_length;+ }+ ok = true;+done:+ if (converted) {+ for (size_t i = 0; i < override_count; i++) {+ free(converted[i]);+ }+ }+ free(converted);+ free(entries);- FreeEnvironmentStringsW(inherited);++ if (process->strip_git_repo_env) {++ cbm_git_child_env_free(inherited);++ } else {++ FreeEnvironmentStringsW(inherited);++ }+ return ok;+}+#else+static bool cbm_subprocess_copy_environment(cbm_subprocess_t *process, const char *const *overrides,+ size_t override_count) {+#ifdef __APPLE__+ const char *search_path = getenv("PATH");+ process->search_path = cbm_strdup(search_path ? search_path : _PATH_DEFPATH);+ if (!process->search_path) {+ return false;+ }+#endif++ char **inherited = process->envp ? process->envp : environ;+ size_t count = 0;- while (environ && environ[count]) {++ while (inherited && inherited[count]) {+ count++;+ }+ process->environment = calloc(count + override_count + 1, sizeof(*process->environment));+ if (!process->environment) {+ return false;+ }+ for (size_t i = 0; i < count; i++) {- process->environment[i] = cbm_strdup(environ[i]);++ process->environment[i] = cbm_strdup(inherited[i]);+ if (!process->environment[i]) {+ return false;+ }+ }+ for (size_t i = 0; i < override_count; i++) {++ if (process->strip_git_repo_env && cbm_git_env_entry_is_repo_local(overrides[i])) {++ continue;++ }+ size_t name_length = (size_t)(strchr(overrides[i], '=') - overrides[i]);+ size_t slot = 0;+ while (slot < count &&+ !(strncmp(process->environment[slot], overrides[i], name_length) == 0 &&+ process->environment[slot][name_length] == '=')) {+ slot++;+ }+ char *entry = cbm_strdup(overrides[i]);+ if (!entry) {+ return false;+ }+ free(process->environment[slot]);+ process->environment[slot] = entry;+ if (slot == count) {+ count++;+ }+ }+ return true;+}+#endif+static void cbm_subprocess_free_config(cbm_subprocess_t *process) {if (!process) {return;@@@ -689,7 -570,20 +741,25 @@@ static cbm_subprocess_t *cbm_subprocessif (process->cancel_grace_ms > CBM_SUBPROCESS_MAX_CANCEL_GRACE_MS) {process->cancel_grace_ms = CBM_SUBPROCESS_MAX_CANCEL_GRACE_MS;}+ process->memory_limit_bytes = opts->memory_limit_bytes;process->delete_log_on_exit = opts->delete_log_on_exit;+ process->strip_git_repo_env = opts->strip_git_repo_env;+ #ifndef _WIN32+ /* Built before the spawn: the fork child may only assign it (malloc is+ * not async-signal-safe there). Fail closed rather than inherit GIT_DIR. */+ if (opts->strip_git_repo_env) {+ process->envp = cbm_git_child_envp();+ if (!process->envp) {+ cbm_subprocess_free_config(process);+ return NULL;+ }+ }+ #endif++ if (override_count > 0 &&++ !cbm_subprocess_copy_environment(process, opts->env_overrides, override_count)) {++ cbm_subprocess_free_config(process);++ return NULL;++ }atomic_init(&process->lifecycle, CBM_SUBPROCESS_ACTIVE);cbm_subprocess_result_init(&process->result);return process;@@@ -900,10 -890,17 +1066,22 @@@ static int cbm_subprocess_spawn_win(cbmPROCESS_INFORMATION child;ZeroMemory(&child, sizeof(child));DWORD flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP |- CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT;- BOOL created = CreateProcessW(wbin, wcmdline, NULL, NULL, TRUE, flags, process->environment,- NULL, &startup.StartupInfo, &child);- cbm_win_close_spawn_handles(nul, log, attrs, attrs_init);+ CREATE_NO_WINDOW;- /* Fail closed: a git child must never inherit a caller's GIT_DIR. */- wchar_t *env = process->strip_git_repo_env ? cbm_git_child_env_block() : NULL;++ /* Scrubbing remains authoritative even when explicit overrides are present. */++ wchar_t *env = process->environment;++ if (!env && process->strip_git_repo_env) {++ env = cbm_git_child_env_block();++ }+ if (env) {+ flags |= CREATE_UNICODE_ENVIRONMENT;+ }+ BOOL created = (!process->strip_git_repo_env || env) &&+ CreateProcessW(wbin, wcmdline, NULL, NULL, TRUE, flags, (LPVOID)env, NULL,+ &startup.StartupInfo, &child);- cbm_git_child_env_free(env); /* CreateProcessW copied the block into the child */++ if (!process->environment) {++ cbm_git_child_env_free(env); /* CreateProcessW copied the block into the child */++ }+ cbm_win_close_spawn_handles(nul, input, log, stdout_capture, attrs, attrs_init);free(wbin);free(wcmdline);if (!created) {@@@ -1296,12 -1371,11 +1565,15 @@@ static int cbm_posix_spawn_apple(cbm_suposix_spawnattr_setsigdefault(&attr, &all_signals) == 0 &&posix_spawn_file_actions_adddup2(&actions, input, STDIN_FILENO) == 0 &&posix_spawn_file_actions_adddup2(&actions, output, STDOUT_FILENO) == 0 &&- posix_spawn_file_actions_adddup2(&actions, output, STDERR_FILENO) == 0;+ posix_spawn_file_actions_adddup2(&actions, error, STDERR_FILENO) == 0;pid_t pid = -1;- char **environment = process->environment ? process->environment : environ;- int rc = configured ? posix_spawnp(&pid, process->bin, &actions, &attr, process->argv,- process->envp ? process->envp : environ)- : -1;++ char **environment = process->environment;++ if (!environment) {++ environment = process->envp ? process->envp : environ;++ }+ int rc = configured+ ? posix_spawnp(&pid, process->bin, &actions, &attr, process->argv, environment)+ : -1;(void)posix_spawn_file_actions_destroy(&actions);(void)posix_spawnattr_destroy(&attr);if (configured && rc == 0 && pid > 0) {diff --cc src/foundation/subprocess.hindex 010b20665,5d482d5ba..e534dba1e--- a/src/foundation/subprocess.h+++ b/src/foundation/subprocess.h@@@ -53,28 -56,42 +56,49 @@@ typedef structtypedef void (*cbm_proc_log_cb)(const char *line, void *ud);typedef struct {- const char *bin; /* executable path or literal PATH name;- * also argv[0] when argv is NULL */- const char *const *argv; /* NULL-terminated argv; NULL => { bin, NULL } */- const char *windows_cmd_payload; /* Windows-only cmd.exe command text. When set, bin must- * be an absolute path ending in cmd.exe and argv must be- * NULL. The fixed /D /S /V:OFF /C prefix is added while- * this payload is copied verbatim for cmd.exe to parse. */- const char *log_file; /* stderr and, when stdout_file is NULL, stdout are- * redirected here and tailed; NULL => discard those- * streams, no tailing */- cbm_proc_log_cb on_log_line; /* optional per-line callback */- void *log_ud; /* user data for on_log_line */- int quiet_timeout_ms; /* <= 0 => no timeout; else kill+HANG after this many- * ms with no new completed log line */- int cancel_grace_ms; /* graceful tree-termination window; <= 0 uses the finite- * CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS */- size_t memory_limit_bytes; /* Windows-only hard commit limit for the entire Job Object;- * 0 => no OS-enforced memory limit */- bool delete_log_on_exit; /* unlink log_file after reaping */- bool strip_git_repo_env; /* child env omits git's repository-local variables- * (foundation/git_env.h) — set for every git spawn so- * an inherited GIT_DIR never overrides `git -C` */- const char *stdout_file; /* optional separate stdout capture; NULL preserves- * merged log_file behavior. Must be nonempty and- * distinct from log_file; caller supplies private,- * non-aliasing paths and owns capture-file cleanup.- * Not tailed; quiet_timeout_ms observes log_file only.- * delete_log_on_exit never deletes this file. */- const char *stdin_file; /* optional private, immutable regular binary input;- * NULL => null device, never inherited stdin.- * Must be nonempty and non-aliasing with log_file and- * stdout_file; exact equal strings are rejected.- * Caller closes its writer before spawn and retains- * the file until the child tree is quiescent.- * The child chooses its CRT binary mode on Windows.- * Never modified or deleted by this API. */+ const char *bin; /* executable path or literal PATH name;+ * also argv[0] when argv is NULL */+ const char *const *argv; /* NULL-terminated argv; NULL => { bin, NULL } */+ const char *const *env_overrides; /* NULL-terminated NAME=value entries, merged with the+ * inherited environment for this child only. NAME= keeps+ * an empty value; the last duplicate wins. Names must be+ * nonempty (case-insensitive on Windows). NULL or an empty+ * list preserves normal inheritance. Executable lookup- * continues to use the caller's PATH. */++ * continues to use the caller's PATH. strip_git_repo_env++ * also removes repository-local entries from overrides. */+ const char *windows_cmd_payload; /* Windows-only cmd.exe command text. When set, bin must+ * be an absolute path ending in cmd.exe and argv must be+ * NULL. The fixed /D /S /V:OFF /C prefix is added while+ * this payload is copied verbatim for cmd.exe to parse. */- const char *log_file; /* child stdout+stderr are redirected here and tailed;- * NULL => discard child output, no tailing */++ const char *log_file; /* stderr and, when stdout_file is NULL, stdout are++ * redirected here and tailed; NULL => discard those++ * streams, no tailing */+ cbm_proc_log_cb on_log_line; /* optional per-line callback */+ void *log_ud; /* user data for on_log_line */+ int quiet_timeout_ms; /* <= 0 => no timeout; else kill+HANG after this many+ * ms with no new completed log line */+ int cancel_grace_ms; /* graceful tree-termination window; <= 0 uses the finite+ * CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS */++ size_t memory_limit_bytes; /* Windows-only hard commit limit for the entire Job Object;++ * 0 => no OS-enforced memory limit */+ bool delete_log_on_exit; /* unlink log_file after reaping */++ bool strip_git_repo_env; /* child env omits git's repository-local variables++ * (foundation/git_env.h) — set for every git spawn so++ * an inherited GIT_DIR never overrides `git -C` */++ const char *stdout_file; /* optional separate stdout capture; NULL preserves++ * merged log_file behavior. Must be nonempty and++ * distinct from log_file; caller supplies private,++ * non-aliasing paths and owns capture-file cleanup.++ * Not tailed; quiet_timeout_ms observes log_file only.++ * delete_log_on_exit never deletes this file. */++ const char *stdin_file; /* optional private, immutable regular binary input;++ * NULL => null device, never inherited stdin.++ * Must be nonempty and non-aliasing with log_file and++ * stdout_file; exact equal strings are rejected.++ * Caller closes its writer before spawn and retains++ * the file until the child tree is quiescent.++ * The child chooses its CRT binary mode on Windows.++ * Never modified or deleted by this API. */} cbm_proc_opts_t;#define CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS 1000diff --cc src/main.cindex acbc253f7,c9c67e83e..4d3d8122c--- a/src/main.c+++ b/src/main.c@@@ -33,9 -33,8 +33,10 @@@#include "daemon/version_cohort.h"#include "mcp/mcp.h"#include "mcp/index_supervisor.h"+ #include "mcp/test_impact_engine.h"#include "cli/cli.h"+#include "cli/runtime_settings.h"+#include "foundation/platform.h"#include "cli/progress_sink.h"#include "foundation/constants.h"@@@ -64,27 -65,16 +69,35 @@@ enumMAIN_HOOK_NOTICE_INTERVAL_SECONDS = 900,MAIN_CLOSE_TIMEOUT_MS = 5000,MAIN_COORDINATION_CLEANUP_MS = 500,- PARENT_WATCHDOG_STACK_SIZE = 64 * CBM_SZ_1K, /* watchdog only polls — tiny stack suffices */+ /* The watchdog only polls, so the STACK it needs is tiny — but on glibc the+ * thread's static TLS block is carved out of this same allocation, and this+ * image's TLS is ~50 KB. At the old 64 KB the request was almost entirely+ * TLS, and when TLS grew past it the thread stopped being creatable at all:+ * the worker then refused to index without containment and SIGKILLed its own+ * group, reported everywhere as a bare "killed (signal 9)" (PR #2233).+ * Sized to hold the TLS block AND a real stack; tests/+ * test_thread_stack_tls_contract.sh keeps the two from converging again. */+ PARENT_WATCHDOG_STACK_SIZE = 256 * CBM_SZ_1K,};++/* Daemon startup budget, overridable for loaded hosts: a fixed 30 s races+ * whatever else the machine is doing (parallel test waves, CI legs), and a+ * cold daemon on a starved host loses through no fault of its own.+ * CBM_STARTUP_TIMEOUT_MS, clamped to [1s, 10min]; malformed -> default. */+static uint32_t main_startup_timeout_ms(void) {+ const char *raw = cbm_runtime_getenv("CBM_STARTUP_TIMEOUT_MS");+ if (!raw || !raw[0])+ return MAIN_MCP_STARTUP_TIMEOUT_MS;+ char *end = NULL;+ long value = strtol(raw, &end, 10);+ if (!end || *end != '\0' || value <= 0)+ return MAIN_MCP_STARTUP_TIMEOUT_MS;+ if (value < MAIN_STARTUP_TIMEOUT_MIN_MS)+ return MAIN_STARTUP_TIMEOUT_MIN_MS;+ if (value > MAIN_STARTUP_TIMEOUT_MAX_MS)+ return MAIN_STARTUP_TIMEOUT_MAX_MS;+ return (uint32_t)value;+}#define SLEN(s) (sizeof(s) - 1)#include "foundation/log.h"#include "foundation/diagnostics.h"diff --cc src/mcp/mcp.cindex d339e0abc,9466b7fa8..a7d7351cc--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@@ -53,8 -56,10 +56,11 @@@ enum#define SLEN(s) (sizeof(s) - 1)#include "mcp/mcp.h"#include "mcp/mcp_internal.h"+#include "mcp/architecture_jobs.h"+ #include "mcp/test_impact.h"+ #include "mcp/test_impact_engine.h"#include "store/store.h"+ #include "store/store_impact.h"#include <sqlite3.h>#include "cypher/cypher.h"#include "discover/discover.h"diff --cc src/ui/http_server.cindex 87f18a9e9,3d4121f4d..8de5d9ff0--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@@ -15,16 -15,13 +15,17 @@@*/#include "ui/http_server.h"#include "ui/httpd.h"+#include "ui/activity.h"+#include "pipeline/pipeline.h" /* canonical project identity for job logs */#include "ui/embedded_assets.h"#include "ui/layout3d.h"+#include "ui/atlas.h"#include "mcp/mcp.h"#include "store/store.h"+ #include "pipeline/pass_cross_repo.h"#include "watcher/watcher.h"#include "cli/cli.h"+#include "cli/runtime_settings.h"#include "git/git_context.h"#if defined(HAVE_LIBGIT2)diff --cc src/watcher/watcher.cindex d8c08a9c1,efb46ac72..f8d04c4c6--- a/src/watcher/watcher.c+++ b/src/watcher/watcher.c@@@ -97,7 -123,9 +123,10 @@@ struct cbm_watchercbm_watcher_project_pruned_fn project_pruned;void *mutation_context;atomic_int stopped;+ atomic_bool running;+ /* Opt-in (#1948): poll non-git roots by tree signature. Default false —+ * non-git roots are not watched. Read at each project's baseline. */+ atomic_bool poll_non_git;/* Deferred-free list: freed after the next poll_once. */project_state_t **pending_free;int pending_free_count;@@@ -983,7 -1105,7 +1106,8 @@@ cbm_watcher_t *cbm_watcher_new(cbm_storcbm_mutex_init(&w->projects_lock);cbm_mutex_init(&w->coordination_lock);atomic_init(&w->stopped, 0);+ atomic_init(&w->running, false);+ atomic_init(&w->poll_non_git, false);return w;}@@@ -1132,21 -1260,36 +1262,51 @@@ void cbm_watcher_touch(cbm_watcher_t *wcbm_mutex_unlock(&w->projects_lock);}+cbm_watcher_project_status_t cbm_watcher_project_status(cbm_watcher_t *w,- const char *project_name) {++ const char *project_name) {+ cbm_watcher_project_status_t status = {0};+ if (!w) {+ return status;+ }+ cbm_mutex_lock(&w->projects_lock);+ project_state_t *project = project_name ? cbm_ht_get(w->projects, project_name) : NULL;+ status.registered = project && atomic_load_explicit(&project->registered, memory_order_acquire);+ status.running = atomic_load_explicit(&w->running, memory_order_acquire) &&+ !atomic_load_explicit(&w->stopped, memory_order_acquire);+ cbm_mutex_unlock(&w->projects_lock);+ return status;+}++ int cbm_watcher_index_failure_count(cbm_watcher_t *w, const char *project_name) {+ if (!w || !project_name) {+ return -1;+ }+ cbm_mutex_lock(&w->projects_lock);+ project_state_t *s = cbm_ht_get(w->projects, project_name);+ int failures = s ? s->index_failures : -1;+ cbm_mutex_unlock(&w->projects_lock);+ return failures;+ }++ bool cbm_watcher_project_info(cbm_watcher_t *w, const char *project_name,+ cbm_watcher_project_info_t *out) {+ if (out) {+ memset(out, 0, sizeof(*out));+ }+ if (!w || !project_name || !out) {+ return false;+ }+ cbm_mutex_lock(&w->projects_lock);+ project_state_t *s = cbm_ht_get(w->projects, project_name);+ if (s) {+ out->strategy = (cbm_watcher_strategy_t)atomic_load(&s->status_strategy);+ out->poll_interval_ms = atomic_load(&s->status_interval_ms);+ out->last_scan_unix_s = atomic_load(&s->status_last_scan_s);+ }+ cbm_mutex_unlock(&w->projects_lock);+ return s != NULL;+ }+int cbm_watcher_watch_count(cbm_watcher_t *w) {if (!w) {return 0;@@@ -1586,28 -1805,13 +1824,38 @@@ int cbm_watcher_run(cbm_watcher_t *w, i}#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS+/* Test seam: expose one project's dirty-state signatures so a failing+ * watcher assertion can print WHY. The watcher-poll flake family blocked+ * two releases precisely because a bare count assert cannot distinguish+ * "the poll saw an unchanged signature" (sigs equal — a detection miss)+ * from "the reindex path itself misbehaved" (sigs differ). Returns 0 and+ * fills the committed and pending signatures, or nonzero when the project+ * is not watched. */+int cbm_watcher_test_dirty_sigs(cbm_watcher_t *w, const char *project, uint64_t *last_out,+ uint64_t *pending_out) {+ if (!w || !project) {+ return -1;+ }+ project_state_t *s = cbm_ht_get(w->projects, project);+ if (!s) {+ return -1;+ }+ if (last_out) {+ *last_out = s->last_dirty_sig;+ }+ if (pending_out) {+ *pending_out = s->pending_dirty_sig;+ }+ return 0;+}+++ int cbm_watcher_test_pending_free_count(cbm_watcher_t *w) {+ if (!w) {+ return -1;+ }+ cbm_mutex_lock(&w->projects_lock);+ int count = w->pending_free_count;+ cbm_mutex_unlock(&w->projects_lock);+ return count;+ }#endifdiff --cc tests/test_daemon_application.cindex 733e98041,1f77e1e58..e3b684d83--- a/tests/test_daemon_application.c+++ b/tests/test_daemon_application.c@@@ -5477,7 -6841,9 +6885,10 @@@ SUITE(daemon_application)RUN_TEST(daemon_application_thread_start_failure_rolls_back_job_reservation);RUN_TEST(daemon_application_queues_explicit_index_behind_physical_job_limit);RUN_TEST(daemon_application_default_limit_admits_four_and_rejects_fifth);+ RUN_TEST(daemon_application_worker_slice_is_aggregate_over_active_jobs);+ RUN_TEST(daemon_application_over_budget_response_passes_through_without_recovery);RUN_TEST(daemon_application_free_reports_retained_live_ownership);+ RUN_TEST(daemon_application_tool_error_is_failed_job_even_after_clean_worker_exit);RUN_TEST(daemon_application_rejects_clean_exit_when_process_tree_is_not_contained);+ RUN_TEST(daemon_application_clean_exit_without_response_is_named_failure_issue1300);}diff --cc tests/test_httpd.cindex 9e7a3359c,4408f4ef5..ada1c26d3--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@@ -1073,762 -1055,285 +1080,1041 @@@ TEST(ui_server_free_never_joins_active_PASS();}+/* ── Frontend log file (POST/GET /api/ui-log) ─────────────────── */++static int ui_log_read_file(const char *path, char *out, size_t outsz) {+ FILE *f = cbm_fopen(path, "rb");+ if (!f)+ return -1;+ size_t n = fread(out, 1, outsz - 1, f);+ fclose(f);+ out[n] = '\0';+ return (int)n;+}++static int ui_log_count_char(const char *s, char ch) {+ int n = 0;+ for (; *s; s++) {+ if (*s == ch)+ n++;+ }+ return n;+}++static int ui_log_post(int port, const char *body, char *resp, size_t respsz) {+ size_t cap = strlen(body) + 512;+ char *req = malloc(cap);+ if (!req)+ return 0;+ snprintf(req, cap,+ "POST /api/ui-log HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"+ "Content-Type: application/json\r\nContent-Length: %zu\r\n\r\n%s",+ port, strlen(body), body);+ int n = th_http(port, req, resp, respsz);+ free(req);+ return n;+}++static int activity_interrupt_rows(unsigned kind, void *database, void *statement, void *unused) {+ (void)kind;+ (void)unused;+ const char *sql = sqlite3_sql(statement);+ if (sql && (strstr(sql, "SELECT id,ts,level,source,message") ||+ strstr(sql, "SELECT id,payload FROM agent_events")))+ sqlite3_interrupt(database);+ return 0;+}++TEST(activity_preserves_severity_and_reports_interrupted_reads) {+ sqlite3 *db = cbm_activity_open(":memory:");+ ASSERT_NOT_NULL(db);+ ASSERT_TRUE(cbm_activity_log(+ db, "{\"level\":\"info\",\"msg\":\"read.file\",\"path\":\"notes/level=error.md\"}"));+ ASSERT_TRUE(cbm_activity_log(db, "level=info msg=read.file path=notes/level=error.md"));+ char *json = cbm_activity_logs(db, -1, 10, 2);+ ASSERT_NOT_NULL(json);+ ASSERT_NOT_NULL(strstr(json, "\"total\":0"));+ free(json);+ ASSERT_EQ(sqlite3_trace_v2(db, SQLITE_TRACE_STMT, activity_interrupt_rows, db), SQLITE_OK);+ ASSERT_NULL(cbm_activity_logs(db, -1, 10, 0));+ ASSERT_NULL(cbm_activity_agents(db, "test", 0, 10));+ sqlite3_trace_v2(db, 0, NULL, NULL);+ sqlite3_close(db);+ PASS();+}++TEST(activity_pruned_start_events_do_not_resurrect_on_retry) {+ sqlite3 *db = cbm_activity_open(":memory:");+ ASSERT_NOT_NULL(db);+ const char *batch =+ "{\"project\":\"fixture-a\",\"events\":[{\"run\":\"r1\",\"agent\":\"fixture\",\"tool\":"+ "\"Read\",\"seq\":1,\"ts\":1000,\"phase\":\"start\"}]}";+ char *reply = NULL;+ ASSERT_EQ(cbm_activity_ingest(db, batch, &reply), 200);+ free(reply);+ ASSERT_EQ(+ sqlite3_exec(+ db,+ "WITH RECURSIVE n(v) AS (SELECT 1 UNION ALL SELECT v+1 FROM n WHERE v<10001) INSERT "+ "INTO agent_events(project,run,seq,payload) SELECT 'fixture-b','filler',v,'{}' FROM n",+ NULL, NULL, NULL),+ SQLITE_OK);+ ASSERT_EQ(cbm_activity_ingest(db, "{\"project\":\"fixture-b\",\"events\":[]}", &reply), 200);+ free(reply);+ ASSERT_EQ(cbm_activity_ingest(db, batch, &reply), 200);+ ASSERT_NOT_NULL(strstr(reply, "\"accepted\":0"));+ ASSERT_NOT_NULL(strstr(reply, "\"duplicates\":1"));+ free(reply);+ reply = cbm_activity_agents(db, "fixture-a", 0, 10);+ ASSERT_NOT_NULL(strstr(reply, "\"events\":[]"));+ ASSERT_NOT_NULL(strstr(reply, "\"truncated\":true"));+ free(reply);+ sqlite3_close(db);+ PASS();+}++TEST(activity_migration_preserves_v1_logs_and_rejects_future_schema) {+ char *dir = th_mktempdir("cbm_activity_migration");+ ASSERT_NOT_NULL(dir);+ char path[1024];+ snprintf(path, sizeof(path), "%s/activity.db", dir);+ sqlite3 *db = NULL;+ ASSERT_EQ(sqlite3_open(path, &db), SQLITE_OK);+ ASSERT_EQ(+ sqlite3_exec(db,+ "CREATE TABLE daemon_logs(id INTEGER PRIMARY KEY AUTOINCREMENT,ts TEXT NOT "+ "NULL,level INTEGER NOT NULL,source TEXT NOT NULL,message TEXT NOT NULL);"+ "INSERT INTO daemon_logs(ts,level,source,message) "+ "VALUES('2026-09-09T00:00:00Z',3,'migration fixture','preserved "+ "failure');PRAGMA user_version=1",+ NULL, NULL, NULL),+ SQLITE_OK);+ sqlite3_close(db);+ db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ char *json = cbm_activity_logs(db, -1, 10, 2);+ ASSERT_NOT_NULL(json);+ ASSERT_NOT_NULL(strstr(json, "preserved failure"));+ ASSERT_NOT_NULL(strstr(json, "\"total\":1"));+ free(json);+ const char *ui = "{\"session\":\"migration-fixture\",\"seq\":1,\"level\":\"error\",\"source\":"+ "\"frontend\",\"message\":\"retry-safe\"}";+ ASSERT_TRUE(cbm_activity_log(db, ui));+ ASSERT_TRUE(cbm_activity_log(db, ui));+ json = cbm_activity_logs(db, -1, 10, 2);+ ASSERT_NOT_NULL(strstr(json, "\"total\":2"));+ free(json);+ ASSERT_EQ(sqlite3_exec(db, "PRAGMA user_version=99", NULL, NULL, NULL), SQLITE_OK);+ sqlite3_close(db);+ ASSERT_NULL(cbm_activity_open(path));+ th_cleanup(dir);+ PASS();+}++TEST(activity_log_project_scope_preserves_unknown_v2_history_and_filters_before_limit) {+ char *dir = th_mktempdir("cbm_activity_project_scope");+ ASSERT_NOT_NULL(dir);+ char path[1024];+ snprintf(path, sizeof(path), "%s/activity.db", dir);+ sqlite3 *db = NULL;+ ASSERT_EQ(sqlite3_open(path, &db), SQLITE_OK);+ ASSERT_EQ(+ sqlite3_exec(+ db,+ "CREATE TABLE daemon_logs(id INTEGER PRIMARY KEY AUTOINCREMENT,ts TEXT NOT NULL,"+ "level INTEGER NOT NULL,source TEXT NOT NULL,message TEXT NOT NULL,event_key TEXT);"+ "INSERT INTO daemon_logs VALUES(1,'2026-09-09',3,'old-worker',"+ "'legacy project=fixture-a path=repo-a/broken.c',NULL);PRAGMA user_version=2",+ NULL, NULL, NULL),+ SQLITE_OK);+ sqlite3_close(db);+ db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ ASSERT_TRUE(cbm_activity_log(db, "{\"level\":\"error\",\"source\":\"fixture\","+ "\"project\":\"fixture-a\",\"message\":\"first-a\"}"));+ ASSERT_TRUE(+ cbm_activity_log(db, "level=error msg=index.worker project=fixture-a record=last-a"));+ ASSERT_TRUE(cbm_activity_log(+ db, "{\"level\":\"error\",\"source\":\"unknown\","+ "\"message\":\" project=fixture-a \",\"page\":\"/?project=fixture-a\"}"));+ ASSERT_TRUE(cbm_activity_log(db, "level=error msg=unknown record=project=fixture-a"));+ ASSERT_EQ(+ sqlite3_exec(db,+ "WITH RECURSIVE n(v) AS (SELECT 1 UNION ALL SELECT v+1 FROM n WHERE v<600) "+ "INSERT INTO daemon_logs(ts,level,source,message,project) "+ "SELECT '2026-09-09',3,'fixture-b','unrelated flood','fixture-b' FROM n",+ NULL, NULL, NULL),+ SQLITE_OK);+ char *page = cbm_activity_logs_scoped(db, -1, 1, 2, "fixture-a", false);+ ASSERT_NOT_NULL(page);+ ASSERT_NOT_NULL(strstr(page, "last-a"));+ ASSERT_NOT_NULL(strstr(page, "\"total\":2"));+ ASSERT_NOT_NULL(strstr(page, "\"scope\":\"project\""));+ ASSERT_NULL(strstr(page, "unrelated flood"));+ ASSERT_NULL(strstr(page, "legacy"));+ free(page);+ page = cbm_activity_logs_scoped(db, 0, 1, 2, "fixture-a", false);+ ASSERT_NOT_NULL(strstr(page, "first-a"));+ ASSERT_NOT_NULL(strstr(page, "\"cursor\":2"));+ ASSERT_NOT_NULL(strstr(page, "\"has_more\":true"));+ free(page);+ sqlite3_close(db);+ db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ page = cbm_activity_logs_scoped(db, 2, 1, 2, "fixture-a", false);+ ASSERT_NOT_NULL(strstr(page, "last-a"));+ ASSERT_NOT_NULL(strstr(page, "\"cursor\":3"));+ ASSERT_NOT_NULL(strstr(page, "\"has_more\":false"));+ free(page);+ page = cbm_activity_logs_scoped(db, -1, 10, 2, NULL, true);+ ASSERT_NOT_NULL(strstr(page, "legacy project=fixture-a"));+ ASSERT_NOT_NULL(strstr(page, "\"total\":3"));+ ASSERT_NOT_NULL(strstr(page, "\"project\":null"));+ ASSERT_NOT_NULL(strstr(page, "\"scope\":\"unattributed\""));+ free(page);+ page = cbm_activity_logs(db, -1, 1, 2);+ ASSERT_NOT_NULL(strstr(page, "\"total\":605"));+ ASSERT_NOT_NULL(strstr(page, "\"scope\":\"daemon\""));+ free(page);+ sqlite3_close(db);+ th_cleanup(dir);+ PASS();+}++TEST(ui_log_scopes_use_explicit_entry_ownership_and_survive_server_restart) {+ ui_delete_fixture_t fx;+ ASSERT_EQ(ui_delete_fixture_init(&fx), 0);+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);+ const char *body =+ "{\"project\":\"fixture-a\",\"page\":\"/?project=wrong\","+ "\"session\":\"project-scope-fixture\",\"entries\":["+ "{\"seq\":1,\"level\":\"error\",\"message\":\"owned-a\"},"+ "{\"seq\":2,\"level\":\"error\",\"project\":\"fixture-b\",\"message\":\"owned-b\"},"+ "{\"seq\":3,\"level\":\"error\",\"project\":null,\"message\":\"unknown-owner\"}]}";+ char response[8192];+ ASSERT_GT(ui_log_post(port, body, response, sizeof(response)), 0);+ ASSERT_EQ(th_status(response), 200);+ th_server_stop(&ts);+ ASSERT_EQ(th_server_start(&ts), 0);+ port = cbm_http_server_port(ts.srv);+ ASSERT_GT(th_http(port,+ "GET /api/logs?project=fixture-a&lines=1&min_level=error HTTP/1.1\r\n\r\n",+ response, sizeof(response)),+ 0);+ ASSERT_EQ(th_status(response), 200);+ ASSERT_NOT_NULL(strstr(response, "owned-a"));+ ASSERT_NULL(strstr(response, "owned-b"));+ ASSERT_NULL(strstr(response, "unknown-owner"));+ ASSERT_NOT_NULL(strstr(response, "\"total\":1"));+ ASSERT_GT(th_http(port, "GET /api/logs?project=fixture-b&lines=1 HTTP/1.1\r\n\r\n", response,+ sizeof(response)),+ 0);+ ASSERT_NOT_NULL(strstr(response, "owned-b"));+ ASSERT_GT(th_http(port, "GET /api/logs?scope=unattributed&lines=10 HTTP/1.1\r\n\r\n", response,+ sizeof(response)),+ 0);+ ASSERT_NOT_NULL(strstr(response, "unknown-owner"));+ ASSERT_NULL(strstr(response, "owned-a"));+ ASSERT_NULL(strstr(response, "owned-b"));+ ASSERT_GT(th_http(port, "GET /api/logs?project= HTTP/1.1\r\n\r\n", response, sizeof(response)),+ 0);+ ASSERT_EQ(th_status(response), 400);+ ASSERT_GT(th_http(port, "GET /api/logs?project=fixture-a&scope=unattributed HTTP/1.1\r\n\r\n",+ response, sizeof(response)),+ 0);+ ASSERT_EQ(th_status(response), 400);+ th_server_stop(&ts);+ ui_delete_fixture_cleanup(&fx);+ PASS();+}++TEST(activity_log_search_and_severity_apply_before_limit_and_survive_reopen) {+ char *dir = th_mktempdir("cbm_log_filter_fixture");+ ASSERT_NOT_NULL(dir);+ char path[1024];+ snprintf(path, sizeof(path), "%s/activity.db", dir);+ sqlite3 *db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ ASSERT_EQ(+ sqlite3_exec(db,+ "WITH RECURSIVE n(v) AS (SELECT 1 UNION ALL SELECT v+1 FROM n WHERE v<49) "+ "INSERT INTO daemon_logs(ts,level,source,message,project) "+ "SELECT '2026-09-09',3,'parser','src/10%_broken.c','fixture-a' FROM n;"+ "WITH RECURSIVE n(v) AS (SELECT 1 UNION ALL SELECT v+1 FROM n WHERE v<600) "+ "INSERT INTO daemon_logs(ts,level,source,message,project) "+ "SELECT '2026-09-09',1,'http','routine','fixture-a' FROM n",+ NULL, NULL, NULL),+ SQLITE_OK);+ char *json = cbm_activity_logs(db, -1, 200, 0);+ ASSERT_NOT_NULL(json);+ ASSERT_NULL(strstr(json, "10%_broken"));+ free(json);+ json = cbm_activity_logs_filtered(db, -1, 200, 3, "fixture-a", false, "10%_");+ ASSERT_NOT_NULL(json);+ ASSERT_NOT_NULL(strstr(json, "\"total\":49"));+ ASSERT_NOT_NULL(strstr(json, "\"query\":\"10%_\""));+ ASSERT_NOT_NULL(strstr(json, "10%_broken.c"));+ ASSERT_NULL(strstr(json, "routine"));+ free(json);+ sqlite3_close(db);+ db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ json = cbm_activity_logs_filtered(db, 0, 1, 3, "fixture-a", false, "BROKEN");+ ASSERT_NOT_NULL(json);+ ASSERT_NOT_NULL(strstr(json, "\"cursor\":1"));+ ASSERT_NOT_NULL(strstr(json, "\"has_more\":true"));+ ASSERT_NOT_NULL(strstr(json, "\"total\":49"));+ free(json);+ json = cbm_activity_logs_filtered(db, 1, 1, 3, "fixture-a", false, "BROKEN");+ ASSERT_NOT_NULL(strstr(json, "\"cursor\":2"));+ free(json);+ json = cbm_activity_logs_filtered(db, -1, 200, 3, "fixture-b", false, "10%_");+ ASSERT_NOT_NULL(strstr(json, "\"total\":0"));+ free(json);+ sqlite3_close(db);+ th_cleanup(dir);+ PASS();+}++TEST(ui_log_retention_prevents_expired_retry_and_preserves_full_json) {+ char *dir = th_mktempdir("cbm_ui_retention_fixture");+ ASSERT_NOT_NULL(dir);+ char path[1024];+ snprintf(path, sizeof(path), "%s/activity.db", dir);+ sqlite3 *db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ char message[12000];+ memset(message, 'x', sizeof(message));+ const char *prefix =+ "{\"received\":\"2026-01-01T00:00:00Z\",\"page\":\"/\","+ "\"session\":\"retention-fixture\",\"seq\":1,\"level\":\"info\",\"message\":\"";+ memcpy(message, prefix, strlen(prefix));+ memcpy(message + sizeof(message) - 3, "\"}", 3);+ ASSERT_EQ(cbm_activity_ui_log(db, message, false), 1);+ char *json = cbm_activity_ui_logs(db, 200, path, "", NULL);+ ASSERT_NOT_NULL(json);+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ const char *line =+ yyjson_get_str(yyjson_arr_get(yyjson_obj_get(yyjson_doc_get_root(doc), "lines"), 0));+ ASSERT_NOT_NULL(line);+ ASSERT_EQ(strlen(line), strlen(message));+ yyjson_doc *full = yyjson_read(line, strlen(line), 0);+ ASSERT_NOT_NULL(full);+ yyjson_doc_free(full);+ yyjson_doc_free(doc);+ free(json);+ ASSERT_EQ(+ sqlite3_exec(db,+ "WITH RECURSIVE n(v) AS (SELECT 1 UNION ALL SELECT v+1 FROM n WHERE v<3000) "+ "INSERT INTO daemon_logs(ts,level,source,message) SELECT "+ "'2026-09-09',1,'fixture','flood' FROM n",+ NULL, NULL, NULL),+ SQLITE_OK);+ ASSERT_TRUE(cbm_activity_log(db, "level=info msg=retention.trigger"));+ ASSERT_EQ(cbm_activity_ui_log(db, message, false), 0);+ sqlite3_close(db);+ db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ ASSERT_EQ(cbm_activity_ui_log(db, message, false), 0);+ json = cbm_activity_ui_logs(db, 200, path, "", NULL);+ ASSERT_NOT_NULL(strstr(json, "\"total\":0"));+ free(json);+ sqlite3_close(db);+ th_cleanup(dir);+ PASS();+}++TEST(ui_log_journal_is_canonical_for_info_retry_and_restart) {+ ui_delete_fixture_t fx;+ ASSERT_EQ(ui_delete_fixture_init(&fx), 0);+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);+ char response[16384];+ const char *body =+ "{\"page\":\"/\",\"session\":\"canonical-fixture\",\"entries\":["+ "{\"seq\":1,\"level\":\"info\",\"source\":\"console\",\"project\":\"fixture-a\","+ "\"message\":\"ordinary retained 10%_detail\"}]}";+ ASSERT_GT(ui_log_post(port, body, response, sizeof(response)), 0);+ ASSERT_EQ(th_status(response), 200);+ ASSERT_NOT_NULL(strstr(response, "\"accepted\":1"));+ ASSERT_GT(ui_log_post(port, body, response, sizeof(response)), 0);+ ASSERT_NOT_NULL(strstr(response, "\"accepted\":0"));+ ASSERT_NOT_NULL(strstr(response, "\"duplicates\":1"));+ char path[1024];+ snprintf(path, sizeof(path), "%s/logs/ui.log", fx.cache_dir);+ char content[4096];+ ASSERT_GT(ui_log_read_file(path, content, sizeof(content)), 0);+ ASSERT_EQ(ui_log_count_char(content, '\n'), 1);+ FILE *file = cbm_fopen(path, "wb");+ ASSERT_NOT_NULL(file);+ fputs("unrelated export mutation\n", file);+ fclose(file);+ th_server_stop(&ts);+ ASSERT_EQ(th_server_start(&ts), 0);+ port = cbm_http_server_port(ts.srv);+ ASSERT_GT(th_http(port, "GET /api/ui-log HTTP/1.1\r\n\r\n", response, sizeof(response)), 0);+ ASSERT_EQ(th_status(response), 200);+ ASSERT_NOT_NULL(strstr(response, "ordinary retained 10%_detail"));+ ASSERT_NOT_NULL(strstr(response, "\"source\":\"sqlite\""));+ ASSERT_NOT_NULL(strstr(response, "activity.db"));+ ASSERT_NOT_NULL(strstr(response, "\"total\":1"));+ ASSERT_NULL(strstr(response, "unrelated export mutation"));+ ASSERT_GT(th_http(port,+ "GET /api/logs?project=fixture-a&min_level=info&q=10%25_ HTTP/1.1\r\n\r\n",+ response, sizeof(response)),+ 0);+ ASSERT_EQ(th_status(response), 200);+ ASSERT_NOT_NULL(strstr(response, "ordinary retained 10%_detail"));+ ASSERT_NOT_NULL(strstr(response, "\"total\":1"));+ ASSERT_GT(th_http(port, "GET /api/logs?q= HTTP/1.1\r\n\r\n", response, sizeof(response)), 0);+ ASSERT_EQ(th_status(response), 400);+ ASSERT_GT(ui_log_post(port, body, response, sizeof(response)), 0);+ ASSERT_NOT_NULL(strstr(response, "\"duplicates\":1"));+ th_server_stop(&ts);+ ui_delete_fixture_cleanup(&fx);+ PASS();+}++TEST(ui_log_legacy_import_is_once_and_preserves_unknown_provenance_and_time) {+ ui_delete_fixture_t fx;+ ASSERT_EQ(ui_delete_fixture_init(&fx), 0);+ char path[1024];+ snprintf(path, sizeof(path), "%s/logs", fx.cache_dir);+ ASSERT_TRUE(cbm_mkdir_p(path, 0700));+ snprintf(path, sizeof(path), "%s/logs/ui.log", fx.cache_dir);+ FILE *file = cbm_fopen(path, "wb");+ ASSERT_NOT_NULL(file);+ fputs("{\"received\":\"2026-01-01T00:00:00Z\",\"page\":\"/?project=wrong\","+ "\"session\":\"\",\"level\":\"info\",\"source\":\"old-ui\","+ "\"project\":\"not-current\",\"message\":\"legacy info fixture\"}\n",+ file);+ fclose(file);+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);+ char response[16384];+ ASSERT_GT(th_http(port, "GET /api/ui-log HTTP/1.1\r\n\r\n", response, sizeof(response)), 0);+ ASSERT_EQ(th_status(response), 200);+ ASSERT_NOT_NULL(strstr(response, "legacy info fixture"));+ ASSERT_NOT_NULL(strstr(response, "\"total\":1"));+ th_server_stop(&ts);+ ASSERT_EQ(th_server_start(&ts), 0);+ port = cbm_http_server_port(ts.srv);+ ASSERT_GT(th_http(port, "GET /api/ui-log HTTP/1.1\r\n\r\n", response, sizeof(response)), 0);+ ASSERT_NOT_NULL(strstr(response, "\"total\":1"));+ ASSERT_GT(th_http(port, "GET /api/logs?scope=unattributed&q=legacy HTTP/1.1\r\n\r\n", response,+ sizeof(response)),+ 0);+ ASSERT_NOT_NULL(strstr(response, "\"project\":null"));+ ASSERT_NOT_NULL(strstr(response, "\"ts\":\"2026-01-01T00:00:00Z\""));+ ASSERT_GT(th_http(port, "GET /api/logs?project=not-current&q=legacy HTTP/1.1\r\n\r\n", response,+ sizeof(response)),+ 0);+ ASSERT_NOT_NULL(strstr(response, "\"total\":0"));+ th_server_stop(&ts);+ ui_delete_fixture_cleanup(&fx);+ PASS();+}++TEST(activity_journal_reopen_cursor_dedup_and_project_isolation) {+ char *dir = th_mktempdir("cbm_activity");+ ASSERT_NOT_NULL(dir);+ char path[1024];+ snprintf(path, sizeof(path), "%s/activity.db", dir);+ sqlite3 *db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ const char *batch = "{\"project\":\"demo\",\"events\":["+ "{\"ts\":1000,\"agent\":\"test\",\"run\":\"run\",\"seq\":2,\"phase\":"+ "\"end\",\"tool\":\"Read\",\"response\":\"never-store-this\"},"+ "{\"ts\":999,\"agent\":\"test\",\"run\":\"run\",\"seq\":1,\"phase\":"+ "\"end\",\"tool\":\"Read\"}]}";+ char *reply = NULL;+ ASSERT_EQ(cbm_activity_ingest(db, batch, &reply), 200);+ ASSERT_NOT_NULL(strstr(reply, "\"accepted\":2"));+ free(reply);+ ASSERT_EQ(cbm_activity_ingest(db, batch, &reply), 200);+ ASSERT_NOT_NULL(strstr(reply, "\"duplicates\":2"));+ free(reply);+ char *page = cbm_activity_agents(db, "demo", 0, 1);+ ASSERT_NOT_NULL(page);+ ASSERT_NULL(strstr(page, "never-store-this"));+ ASSERT_NOT_NULL(strstr(page, "\"has_more\":true"));+ yyjson_doc *parsed = yyjson_read(page, strlen(page), 0);+ int64_t cursor = yyjson_get_sint(yyjson_obj_get(yyjson_doc_get_root(parsed), "cursor"));+ yyjson_doc_free(parsed);+ free(page);+ sqlite3_close(db);+ db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ page = cbm_activity_agents(db, "demo", cursor, 10);+ ASSERT_NOT_NULL(strstr(page, "\"seq\":1"));+ ASSERT_NULL(strstr(page, "\"seq\":2"));+ free(page);+ page = cbm_activity_agents(db, "other", 0, 10);+ ASSERT_NOT_NULL(strstr(page, "\"events\":[]"));+ free(page);+ ASSERT_EQ(cbm_activity_ingest(db, "{\"events\":[{\"run\":\"bad\"}]}", &reply), 400);+ sqlite3_close(db);+ th_cleanup(dir);+ PASS();+}++TEST(activity_errors_survive_routine_log_retention_and_reopen) {+ char *dir = th_mktempdir("cbm_activity_logs");+ ASSERT_NOT_NULL(dir);+ char path[1024];+ snprintf(path, sizeof(path), "%s/activity.db", dir);+ sqlite3 *db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ ASSERT_TRUE(cbm_activity_log(db, "level=error msg=index.parse.failed path=src/broken.c"));+ for (int i = 0; i < 3010; i++)+ ASSERT_TRUE(cbm_activity_log(db, "level=info msg=http.request"));+ sqlite3 *reader = cbm_activity_open(path);+ ASSERT_NOT_NULL(reader);+ char *page = cbm_activity_logs(reader, -1, 10, 2);+ ASSERT_NOT_NULL(strstr(page, "index.parse.failed"));+ ASSERT_NOT_NULL(strstr(page, "\"level\":\"error\""));+ ASSERT_NOT_NULL(strstr(page, "\"total\":1"));+ ASSERT_NULL(strstr(page, "http.request"));+ free(page);+ sqlite3_close(reader);+ sqlite3_close(db);+ db = cbm_activity_open(path);+ ASSERT_NOT_NULL(db);+ page = cbm_activity_logs(db, -1, 10, 0);+ ASSERT_NOT_NULL(strstr(page, "\"total\":3001"));+ free(page);+ sqlite3_close(db);+ th_cleanup(dir);+ PASS();+}++TEST(ui_agent_events_and_errors_use_daemon_port_and_survive_restart) {+ ui_delete_fixture_t fx;+ ASSERT_EQ(ui_delete_fixture_init(&fx), 0);+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ const char *body =+ "{\"project\":\"demo\",\"events\":[{\"ts\":1000,\"agent\":\"test "+ "fixture\",\"run\":\"restart-fixture\",\"seq\":1,\"phase\":\"end\",\"tool\":\"Read\"}]}";+ char request[2048], resp[16384];+ snprintf(request, sizeof(request),+ "POST /api/agent-events HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: "+ "%zu\r\n\r\n%s",+ strlen(body), body);+ ASSERT_GT(th_http(cbm_http_server_port(ts.srv), request, resp, sizeof(resp)), 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "\"accepted\":1"));+ cbm_ui_log_append("level=error msg=index.failure.fixture path=test-fixture/broken.c");+ th_server_stop(&ts);+ ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);+ ASSERT_GT(+ th_http(port, "GET /api/agent-events?project=demo HTTP/1.1\r\n\r\n", resp, sizeof(resp)),+ 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "restart-fixture"));+ ASSERT_GT(th_http(port, request, resp, sizeof(resp)), 0);+ ASSERT_NOT_NULL(strstr(resp, "\"duplicates\":1"));+ ASSERT_GT(th_http(port, "GET /api/logs?min_level=warn HTTP/1.1\r\n\r\n", resp, sizeof(resp)),+ 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "index.failure.fixture"));+ ASSERT_NOT_NULL(strstr(resp, "\"persistent\":true"));+ th_server_stop(&ts);+ ui_delete_fixture_cleanup(&fx);+ PASS();+}++/* One post, two entries: both are durable in SQLite and mirrored as JSONL+ * for compatibility. Both readers use the journal, including ordinary logs. */+TEST(ui_log_post_writes_jsonl_and_tail_reads_it) {+ ui_delete_fixture_t fx;+ ASSERT_EQ(ui_delete_fixture_init(&fx), 0);+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);++ const char *body =+ "{\"page\":\"/?project=demo\",\"session\":\"s1\",\"entries\":["+ "{\"ts\":\"2026-09-08T10:00:00.000Z\",\"seq\":1,\"level\":\"error\",\"source\":\"rpc\","+ "\"message\":\"get_code_snippet returned no source\",\"detail\":\"HTTP 200\","+ "\"stack\":\"Error: x\\n at y\"},"+ "{\"ts\":\"2026-09-08T10:00:01.000Z\",\"seq\":2,\"level\":\"log\",\"source\":\"console\","+ "\"message\":\"galaxy \\\"ready\\\"\"}]}";+ char resp[16384];+ ASSERT_TRUE(ui_log_post(port, body, resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "\"accepted\":2"));+ ASSERT_NOT_NULL(strstr(resp, "\"dropped\":0"));+ ASSERT_NOT_NULL(strstr(resp, "\"file_error\":false"));+ ASSERT_NOT_NULL(strstr(resp, "/logs/ui.log\""));++ char path[1024];+ snprintf(path, sizeof(path), "%s/logs/ui.log", fx.cache_dir);+ char content[8192];+ ASSERT_TRUE(ui_log_read_file(path, content, sizeof(content)) > 0);+ ASSERT_EQ(ui_log_count_char(content, '\n'), 2);+ ASSERT_TRUE(strncmp(content, "{\"received\":\"", 13) == 0);+ ASSERT_NOT_NULL(strstr(content, "\"page\":\"/?project=demo\",\"session\":\"s1\",\"seq\":1"));+ ASSERT_NOT_NULL(strstr(content, "\"level\":\"error\",\"source\":\"rpc\","+ "\"message\":\"get_code_snippet returned no source\","+ "\"detail\":\"HTTP 200\",\"stack\":\"Error: x\\n at y\"}"));+ ASSERT_NOT_NULL(strstr(content,+ "\"seq\":2,\"ts\":\"2026-09-08T10:00:01.000Z\",\"level\":\"log\","+ "\"source\":\"console\",\"message\":\"galaxy \\\"ready\\\"\"}"));++ /* The tail, asked for one line: the newest, and it says it is partial. */+ char req[256];+ snprintf(req, sizeof(req), "GET /api/ui-log?lines=1 HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n",+ port);+ ASSERT_TRUE(th_http(port, req, resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "\"partial\":true"));+ ASSERT_NOT_NULL(strstr(resp, "\"total\":2"));+ ASSERT_NOT_NULL(strstr(resp, "galaxy"));+ ASSERT_TRUE(strstr(resp, "get_code_snippet") == NULL);+ ASSERT_NOT_NULL(strstr(resp, "\"size_bytes\":"));+ ASSERT_TRUE(strstr(resp, "previous_path") == NULL);++ /* Asked for more than there is: both, complete. */+ snprintf(req, sizeof(req), "GET /api/ui-log?lines=10 HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n",+ port);+ ASSERT_TRUE(th_http(port, req, resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "\"partial\":false"));+ ASSERT_NOT_NULL(strstr(resp, "get_code_snippet"));+ ASSERT_NOT_NULL(strstr(resp, "galaxy"));++ /* The same journal carries both the error and the ordinary info line. */+ snprintf(req, sizeof(req), "GET /api/logs?lines=50 HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n",+ port);+ ASSERT_TRUE(th_http(port, req, resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "ui.error rpc: get_code_snippet returned no source"));+ ASSERT_NOT_NULL(strstr(resp, "ui.info console: galaxy"));++ th_server_stop(&ts);+ ui_delete_fixture_cleanup(&fx);+ PASS();+}++/* Refused bodies never create the file: empty, not JSON, no entries[], and a+ * post above the 64 KiB cap. Entries that are not objects are counted as+ * dropped rather than refused, so one bad entry does not cost the rest. */+TEST(ui_log_post_refuses_bad_bodies) {+ ui_delete_fixture_t fx;+ ASSERT_EQ(ui_delete_fixture_init(&fx), 0);+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);+ char resp[4096];+ char req[512];++ snprintf(req, sizeof(req),+ "POST /api/ui-log HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"+ "Content-Type: application/json\r\nContent-Length: 0\r\n\r\n",+ port);+ ASSERT_TRUE(th_http(port, req, resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 400);++ ASSERT_TRUE(ui_log_post(port, "not json", resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 400);++ ASSERT_TRUE(ui_log_post(port, "{\"page\":\"/\"}", resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 400);++ size_t big_len = 70000;+ char *big = malloc(big_len + 64);+ ASSERT_NOT_NULL(big);+ strcpy(big, "{\"entries\":[{\"message\":\"");+ size_t at = strlen(big);+ memset(big + at, 'a', big_len);+ strcpy(big + at + big_len, "\"}]}");+ ASSERT_TRUE(ui_log_post(port, big, resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 413);+ free(big);++ char path[1024];+ snprintf(path, sizeof(path), "%s/logs/ui.log", fx.cache_dir);+ ASSERT_TRUE(!cbm_file_exists(path));++ ASSERT_TRUE(ui_log_post(port, "{\"entries\":[42,{\"message\":\"kept\"}]}", resp, sizeof(resp)) >+ 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "\"accepted\":1,\"dropped\":1"));+ ASSERT_TRUE(cbm_file_exists(path));++ th_server_stop(&ts);+ ui_delete_fixture_cleanup(&fx);+ PASS();+}++/* The file rotates once to ui.log.1 when it has reached the configured size+ * at the time of a post; the tail names the previous file. */+TEST(ui_log_rotates_at_configured_size) {+ ui_delete_fixture_t fx;+ ASSERT_EQ(ui_delete_fixture_init(&fx), 0);+ cbm_setenv("CBM_UI_LOG_ROTATE_BYTES", "300", 1);+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);+ char resp[8192];++ const char *names[] = {"first", "second", "third"};+ for (int i = 0; i < 3; i++) {+ char body[1024];+ char pad[320];+ memset(pad, 'p', sizeof(pad) - 1);+ pad[sizeof(pad) - 1] = '\0';+ snprintf(body, sizeof(body), "{\"entries\":[{\"level\":\"info\",\"message\":\"%s %s\"}]}",+ names[i], pad);+ ASSERT_TRUE(ui_log_post(port, body, resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 200);+ }++ char path[1024], previous[1040];+ snprintf(path, sizeof(path), "%s/logs/ui.log", fx.cache_dir);+ snprintf(previous, sizeof(previous), "%s.1", path);+ char content[4096];+ ASSERT_TRUE(ui_log_read_file(path, content, sizeof(content)) > 0);+ ASSERT_NOT_NULL(strstr(content, "\"message\":\"third "));+ ASSERT_TRUE(strstr(content, "second") == NULL);+ ASSERT_TRUE(ui_log_read_file(previous, content, sizeof(content)) > 0);+ ASSERT_NOT_NULL(strstr(content, "\"message\":\"second "));+ ASSERT_TRUE(strstr(content, "first") == NULL);++ char req[256];+ snprintf(req, sizeof(req), "GET /api/ui-log HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n", port);+ ASSERT_TRUE(th_http(port, req, resp, sizeof(resp)) > 0);+ ASSERT_EQ(th_status(resp), 200);+ ASSERT_NOT_NULL(strstr(resp, "\"previous_path\":\""));+ ASSERT_NOT_NULL(strstr(resp, "ui.log.1\""));+ ASSERT_NOT_NULL(strstr(resp, "third "));++ th_server_stop(&ts);+ cbm_unsetenv("CBM_UI_LOG_ROTATE_BYTES");+ ui_delete_fixture_cleanup(&fx);+ PASS();+}++/* The UI connections have a fixed allowlist: one optional local inference service and the+ * model host plus its verified download CDN. Browser consent controls model+ * downloads; script sources remain local, with no unrestricted CDN or eval+ * allowance. */+TEST(ui_csp_connect_src_has_explicit_download_hosts) {+ const char *csp = CBM_UI_CSP_VALUE;+ ASSERT_NOT_NULL(strstr(csp, "connect-src 'self' http://127.0.0.1:4141 "+ "https://huggingface.co https://us.aws.cdn.hf.co;"));+ ASSERT_NOT_NULL(strstr(csp, "script-src 'self' 'wasm-unsafe-eval';"));+ ASSERT_NOT_NULL(strstr(csp, "worker-src 'self' blob:;"));+ ASSERT_TRUE(strstr(csp, "*") == NULL);+ ASSERT_TRUE(strstr(csp, "'unsafe-eval'") == NULL);+ ASSERT_TRUE(strstr(csp, "ws://") == NULL);+ ASSERT_TRUE(strstr(csp, "wss://") == NULL);+ int hosts = 0;+ const char *p = csp;+ while ((p = strstr(p, "http://")) != NULL) {+ ASSERT_TRUE(strncmp(p, "http://127.0.0.1:4141", 21) == 0);+ hosts++;+ p += 7;+ }+ ASSERT_EQ(hosts, 1);+ int secure_hosts = 0;+ p = csp;+ while ((p = strstr(p, "https://")) != NULL) {+ secure_hosts++;+ p += 8;+ }+ ASSERT_EQ(secure_hosts, 2);+ ASSERT_NOT_NULL(strstr(csp, "frame-ancestors 'none'"));+ ASSERT_NOT_NULL(strstr(csp, "object-src 'none'"));+ PASS();+}++ /* ── POST /api/index carries the resolved root ────────────────── */++ /* The route resolves the request's root_path, runs the workspace check on the+ * resolved form, and the job must then carry exactly that string: what was+ * checked is what the daemon receives. These cases drive the real endpoint+ * with the recording executor and read every place the stored root surfaces+ * (the executor argument, the 202 reply, /api/index-status). */++ typedef struct {+ bool was_set;+ char value[4096];+ } th_allowed_root_saved_t;++ /* Set (or, with NULL, clear) CBM_ALLOWED_ROOT and remember the previous value+ * so the test can put it back before asserting — a failed assertion returns+ * early, and a boundary left behind would leak into every later test. */+ static void th_allowed_root_set(th_allowed_root_saved_t *saved, const char *value) {+ const char *current = getenv("CBM_ALLOWED_ROOT");+ saved->was_set = current != NULL;+ snprintf(saved->value, sizeof(saved->value), "%s", current ? current : "");+ if (value) {+ cbm_setenv("CBM_ALLOWED_ROOT", value, 1);+ } else {+ cbm_unsetenv("CBM_ALLOWED_ROOT");+ }+ }++ static void th_allowed_root_restore(const th_allowed_root_saved_t *saved) {+ if (saved->was_set) {+ cbm_setenv("CBM_ALLOWED_ROOT", saved->value, 1);+ } else {+ cbm_unsetenv("CBM_ALLOWED_ROOT");+ }+ }++ typedef struct {+ th_ui_index_executor_t executor;+ int status; /* HTTP status of the POST, -1 when no reply came */+ bool executor_called; /* only waited for after a 202 */+ char response[8192]; /* the raw POST reply */+ char index_status[16384]; /* GET /api/index-status, read after the POST */+ } th_ui_index_probe_t;++ /* Response body: everything after the header block, or "" when absent. */+ static const char *th_response_body(const char *response) {+ const char *body = strstr(response, "\r\n\r\n");+ return body ? body + 4 : "";+ }++ /* Boot a server with the recording executor, POST one /api/index request,+ * wait for the worker only when the route accepted the job, read+ * /api/index-status and stop the server. Everything observed lands in the+ * probe so the caller asserts after teardown. */+ static void th_ui_index_probe(th_ui_index_probe_t *probe, const char *root_path,+ const char *project_name) {+ memset(probe, 0, sizeof(*probe));+ atomic_init(&probe->executor.calls, 0);+ probe->status = -1;+ th_server_t ts;+ ts.srv = cbm_http_server_new(0);+ if (!ts.srv) {+ return;+ }+ cbm_http_server_set_index_executor(ts.srv, th_ui_index_executor, &probe->executor);+ if (th_server_thread_start(&ts.tid, ts.srv) != 0) {+ (void)cbm_http_server_free(ts.srv);+ return;+ }+ int port = cbm_http_server_port(ts.srv);+ char body[8192];+ snprintf(body, sizeof(body), "{\"root_path\":\"%s\",\"project_name\":\"%s\"}", root_path,+ project_name);+ char request[8192 + 256];+ snprintf(request, sizeof(request),+ "POST /api/index HTTP/1.1\r\nContent-Type: application/json\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ strlen(body), body);+ if (th_http(port, request, probe->response, sizeof(probe->response)) > 0) {+ probe->status = th_status(probe->response);+ }+ if (probe->status == 202) {+ probe->executor_called = th_wait_atomic_int(&probe->executor.calls, 1, 2000);+ }+ char status_request[128];+ snprintf(status_request, sizeof(status_request),+ "GET /api/index-status HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n", port);+ (void)th_http(port, status_request, probe->index_status, sizeof(probe->index_status));+ th_server_stop(&ts);+ }++ TEST(ui_server_index_start_refuses_root_outside_allowed) {+ char *tmp = th_mktempdir("cbm_httpd_index_bound");+ ASSERT_NOT_NULL(tmp);+ char base[256];+ snprintf(base, sizeof(base), "%s", tmp);+ char allowed[512];+ char outside[512];+ snprintf(allowed, sizeof(allowed), "%s/allowed", base);+ snprintf(outside, sizeof(outside), "%s/outside", base);+ ASSERT_EQ(th_mkdir_p(allowed), 0);+ ASSERT_EQ(th_mkdir_p(outside), 0);+ /* The boundary is declared in resolved form, as allow-root records it. */+ char canonical_base[4096];+ ASSERT_TRUE(cbm_canonical_path(base, canonical_base, sizeof(canonical_base)));+ char allowed_root[4096 + 16];+ snprintf(allowed_root, sizeof(allowed_root), "%s/allowed", canonical_base);+ /* Spelled under the allowed root, resolving beside it: the verdict has to+ * come from the resolved form. */+ char request_path[600];+ snprintf(request_path, sizeof(request_path), "%s/allowed/../outside", base);++ th_allowed_root_saved_t saved;+ th_allowed_root_set(&saved, allowed_root);+ th_ui_index_probe_t probe;+ th_ui_index_probe(&probe, request_path, "bound");+ th_allowed_root_restore(&saved);+ th_cleanup(base);++ ASSERT_EQ(probe.status, 403);+ ASSERT_NOT_NULL(strstr(probe.response, "outside the allowed root"));+ ASSERT_EQ(atomic_load(&probe.executor.calls), 0);+ ASSERT_STR_EQ(th_response_body(probe.index_status), "[]");+ PASS();+ }++ TEST(ui_server_index_start_stores_resolved_root) {+ char *tmp = th_mktempdir("cbm_httpd_index_root");+ ASSERT_NOT_NULL(tmp);+ char base[256];+ snprintf(base, sizeof(base), "%s", tmp);+ char inner[512];+ snprintf(inner, sizeof(inner), "%s/allowed/inner", base);+ ASSERT_EQ(th_mkdir_p(inner), 0);+ /* The resolved form of the allowed directory itself, as the server+ * computes it. A "/allowed" suffix on a resolved parent is not that form+ * on Windows, where the resolved path uses backslashes throughout. */+ char allowed_dir[512];+ snprintf(allowed_dir, sizeof(allowed_dir), "%s/allowed", base);+ char allowed_root[4096];+ ASSERT_TRUE(cbm_canonical_path(allowed_dir, allowed_root, sizeof(allowed_root)));+ /* The request names the allowed root through a ".." segment, so its+ * spelling is not the resolved form (on macOS /tmp is itself a link to+ * /private/tmp, so the prefix differs as well). */+ char request_path[600];+ snprintf(request_path, sizeof(request_path), "%s/allowed/inner/..", base);+ ASSERT_TRUE(strcmp(request_path, allowed_root) != 0);++ th_allowed_root_saved_t saved;+ th_allowed_root_set(&saved, allowed_root);+ th_ui_index_probe_t probe;+ th_ui_index_probe(&probe, request_path, "resolved");+ th_allowed_root_restore(&saved);+ th_cleanup(base);++ ASSERT_EQ(probe.status, 202);+ ASSERT_TRUE(probe.executor_called);+ /* The daemon receives the string the check ran on, not the request+ * spelling. */+ ASSERT_STR_EQ(probe.executor.root_path, allowed_root);+ ASSERT_STR_EQ(probe.executor.project_name, "resolved");+ /* The 202 reply and the status listing report that same stored root,+ * JSON-escaped (a Windows path carries backslashes). */+ char escaped[8192];+ cbm_json_escape(escaped, (int)sizeof(escaped), allowed_root);+ char expected[8192 + 64];+ snprintf(expected, sizeof(expected), "\"path\":\"%s\"}", escaped);+ ASSERT_NOT_NULL(strstr(probe.response, expected));+ snprintf(expected, sizeof(expected), "\"path\":\"%s\",\"error\"", escaped);+ ASSERT_NOT_NULL(strstr(probe.index_status, expected));+ PASS();+ }++ TEST(ui_server_index_start_long_root_not_truncated) {+ char *tmp = th_mktempdir("cbm_httpd_index_long");+ ASSERT_NOT_NULL(tmp);+ char base[256];+ snprintf(base, sizeof(base), "%s", tmp);+ /* A root well past 1 KB, the capacity the job used to hold, and well+ * inside the 4 KB the route resolves; 200-byte components keep every+ * component under NAME_MAX. */+ char component[201];+ memset(component, 'd', sizeof(component) - 1);+ component[sizeof(component) - 1] = '\0';+ char deep[2048];+ int n = snprintf(deep, sizeof(deep), "%s", base);+ while (n < 1400) {+ n += snprintf(deep + n, sizeof(deep) - (size_t)n, "/%s", component);+ }+ bool created = th_mkdir_p(deep) == 0;+ char canonical[4096];+ bool resolved = created && cbm_canonical_path(deep, canonical, sizeof(canonical)) != 0;++ /* No boundary here: the question is the length the job keeps. */+ th_allowed_root_saved_t saved;+ th_allowed_root_set(&saved, NULL);+ th_ui_index_probe_t probe;+ th_ui_index_probe(&probe, deep, "long");+ th_allowed_root_restore(&saved);+ th_cleanup(base);++ if (probe.status == 202) {+ /* The platform resolved the path, so the worker has to receive it+ * whole — the same string the route checked. */+ ASSERT_TRUE(resolved);+ ASSERT_TRUE(probe.executor_called);+ ASSERT_TRUE(strlen(probe.executor.root_path) > 1023);+ ASSERT_STR_EQ(probe.executor.root_path, canonical);+ } else {+ /* The platform cannot resolve a path this long (macOS: PATH_MAX is+ * 1024, so mkdir and stat refuse it before the route sees it); the+ * route answers 400 and keeps nothing. */+ ASSERT_EQ(probe.status, 400);+ ASSERT_EQ(atomic_load(&probe.executor.calls), 0);+ ASSERT_STR_EQ(th_response_body(probe.index_status), "[]");+ }+ #if defined(PATH_MAX) && PATH_MAX >= 2048+ /* Linux resolves it (PATH_MAX 4096), and that is the one platform where a+ * cut-off could reach the worker; the accepted branch is the only honest+ * outcome there, so the refusal branch may not stand in for it. */+ ASSERT_TRUE(created);+ ASSERT_EQ(probe.status, 202);+ #endif+ PASS();+ }++ /* The 202 reply names the stored root; a quote or backslash in it has to+ * travel escaped or the reply is not JSON. */+ TEST(ui_server_index_start_reply_escapes_path) {+ char *tmp = th_mktempdir("cbm_httpd_index_quote");+ ASSERT_NOT_NULL(tmp);+ char base[256];+ snprintf(base, sizeof(base), "%s", tmp);+ char root[512];+ #ifdef _WIN32+ /* A quote is not a legal file-name byte on Windows; the separators of the+ * resolved path already need escaping there. */+ snprintf(root, sizeof(root), "%s\\plain", base);+ #else+ snprintf(root, sizeof(root), "%s/q\"uote", base);+ #endif+ ASSERT_EQ(th_mkdir_p(root), 0);+ char canonical[4096];+ ASSERT_TRUE(cbm_canonical_path(root, canonical, sizeof(canonical)));+ /* The request body is JSON too, so the root goes in escaped. */+ char request_path[1024];+ cbm_json_escape(request_path, (int)sizeof(request_path), root);++ th_ui_index_probe_t probe;+ th_ui_index_probe(&probe, request_path, "quoted");+ th_cleanup(base);++ bool parsed = false;+ int slot = -1;+ char reply_path[4096] = "";+ const char *body = th_response_body(probe.response);+ yyjson_doc *doc = yyjson_read(body, strlen(body), 0);+ if (doc) {+ yyjson_val *obj = yyjson_doc_get_root(doc);+ yyjson_val *path = yyjson_obj_get(obj, "path");+ yyjson_val *slot_val = yyjson_obj_get(obj, "slot");+ parsed = yyjson_is_obj(obj);+ if (yyjson_is_str(path)) {+ snprintf(reply_path, sizeof(reply_path), "%s", yyjson_get_str(path));+ }+ if (yyjson_is_int(slot_val)) {+ slot = yyjson_get_int(slot_val);+ }+ yyjson_doc_free(doc);+ }++ ASSERT_EQ(probe.status, 202);+ ASSERT_TRUE(probe.executor_called);+ ASSERT_STR_EQ(probe.executor.root_path, canonical);+ ASSERT_TRUE(parsed);+ ASSERT_STR_EQ(reply_path, canonical);+ ASSERT_TRUE(slot >= 0);+ PASS();+ }+TEST(ui_server_root_without_embedded_assets_is_not_found) {/* The frontend is linked into the image, so its availability is decided at* build time, not warmed at runtime: a binary built without --with-ui has@@@ -3356,41 -2703,177 +3695,240 @@@ TEST(ui_server_index_status_long_paths_#endif}+TEST(ui_server_configuration_is_atomic_and_origin_protected) {+ char directory[256];- snprintf(directory,sizeof(directory),"%s/cbm-http-settings-XXXXXX",cbm_tmpdir());++ snprintf(directory, sizeof(directory), "%s/cbm-http-settings-XXXXXX", cbm_tmpdir());+ ASSERT_NOT_NULL(cbm_mkdtemp(directory));- char *previous=getenv("CBM_CACHE_DIR")?strdup(getenv("CBM_CACHE_DIR")):NULL;- ASSERT_EQ(cbm_setenv("CBM_CACHE_DIR",directory,1),0);- th_server_t server;ASSERT_EQ(th_server_start(&server),0);- int port=cbm_http_server_port(server.srv);- char *response=malloc(131072);ASSERT_NOT_NULL(response);- ASSERT_GT(th_http(port,"GET /api/config HTTP/1.1\r\n\r\n",response,131072),0);- ASSERT_EQ(th_status(response),200);- ASSERT_NOT_NULL(strstr(response,"Cache-Control: no-store"));- char *body=strstr(response,"\r\n\r\n");ASSERT_NOT_NULL(body);body+=4;- yyjson_doc *document=yyjson_read(body,strlen(body),0);ASSERT_NOT_NULL(document);- const char *revision=yyjson_get_str(yyjson_obj_get(yyjson_doc_get_root(document),"revision"));ASSERT_NOT_NULL(revision);- char payload[256];snprintf(payload,sizeof(payload),"{\"revision\":\"%s\",\"changes\":{\"auto_index\":\"true\"}}",revision);++ char *previous = getenv("CBM_CACHE_DIR") ? strdup(getenv("CBM_CACHE_DIR")) : NULL;++ ASSERT_EQ(cbm_setenv("CBM_CACHE_DIR", directory, 1), 0);++ th_server_t server;++ ASSERT_EQ(th_server_start(&server), 0);++ int port = cbm_http_server_port(server.srv);++ char *response = malloc(131072);++ ASSERT_NOT_NULL(response);++ ASSERT_GT(th_http(port, "GET /api/config HTTP/1.1\r\n\r\n", response, 131072), 0);++ ASSERT_EQ(th_status(response), 200);++ ASSERT_NOT_NULL(strstr(response, "Cache-Control: no-store"));++ char *body = strstr(response, "\r\n\r\n");++ ASSERT_NOT_NULL(body);++ body += 4;++ yyjson_doc *document = yyjson_read(body, strlen(body), 0);++ ASSERT_NOT_NULL(document);++ const char *revision =++ yyjson_get_str(yyjson_obj_get(yyjson_doc_get_root(document), "revision"));++ ASSERT_NOT_NULL(revision);++ char payload[256];++ snprintf(payload, sizeof(payload),++ "{\"revision\":\"%s\",\"changes\":{\"auto_index\":\"true\"}}", revision);+ yyjson_doc_free(document);- char request[1024];snprintf(request,sizeof(request),"POST /api/config HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nOrigin: http://foreign.example\r\nContent-Type: application/json\r\nContent-Length: %zu\r\n\r\n%s",port,strlen(payload),payload);- ASSERT_GT(th_http_raw(port,request,response,131072),0);ASSERT_EQ(th_status(response),403);- snprintf(request,sizeof(request),"POST /api/config HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nContent-Type: text/plain\r\nContent-Length: %zu\r\n\r\n%s",port,strlen(payload),payload);- ASSERT_GT(th_http_raw(port,request,response,131072),0);ASSERT_EQ(th_status(response),415);- snprintf(request,sizeof(request),"POST /api/config HTTP/1.1\r\nContent-Length: %zu\r\n\r\n%s",strlen(payload),payload);- ASSERT_GT(th_http(port,request,response,131072),0);ASSERT_EQ(th_status(response),200);- ASSERT_GT(th_http(port,request,response,131072),0);ASSERT_EQ(th_status(response),409);- ASSERT_GT(th_http(port,"GET /api/config-extra HTTP/1.1\r\n\r\n",response,131072),0);ASSERT_EQ(th_status(response),404);- th_server_stop(&server);free(response);- if(previous){cbm_setenv("CBM_CACHE_DIR",previous,1);free(previous);}else cbm_unsetenv("CBM_CACHE_DIR");- char path[512];snprintf(path,sizeof(path),"%s/_config.db",directory);remove(path);cbm_rmdir(directory);++ char request[1024];++ snprintf(++ request, sizeof(request),++ "POST /api/config HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nOrigin: "++ "http://foreign.example\r\nContent-Type: application/json\r\nContent-Length: %zu\r\n\r\n%s",++ port, strlen(payload), payload);++ ASSERT_GT(th_http_raw(port, request, response, 131072), 0);++ ASSERT_EQ(th_status(response), 403);++ snprintf(request, sizeof(request),++ "POST /api/config HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nContent-Type: "++ "text/plain\r\nContent-Length: %zu\r\n\r\n%s",++ port, strlen(payload), payload);++ ASSERT_GT(th_http_raw(port, request, response, 131072), 0);++ ASSERT_EQ(th_status(response), 415);++ snprintf(request, sizeof(request), "POST /api/config HTTP/1.1\r\nContent-Length: %zu\r\n\r\n%s",++ strlen(payload), payload);++ ASSERT_GT(th_http(port, request, response, 131072), 0);++ ASSERT_EQ(th_status(response), 200);++ ASSERT_GT(th_http(port, request, response, 131072), 0);++ ASSERT_EQ(th_status(response), 409);++ ASSERT_GT(th_http(port, "GET /api/config-extra HTTP/1.1\r\n\r\n", response, 131072), 0);++ ASSERT_EQ(th_status(response), 404);++ th_server_stop(&server);++ free(response);++ if (previous) {++ cbm_setenv("CBM_CACHE_DIR", previous, 1);++ free(previous);++ } else++ cbm_unsetenv("CBM_CACHE_DIR");++ char path[512];++ snprintf(path, sizeof(path), "%s/_config.db", directory);++ remove(path);++ cbm_rmdir(directory);++ PASS();++}+++ /* Grow path in place to exactly target bytes with 'd' components, none+ * longer than 200 so every component stays under NAME_MAX. */+ static void th_pad_path_to(char *path, size_t cap, int target) {+ char fill[201];+ memset(fill, 'd', sizeof(fill) - 1);+ fill[sizeof(fill) - 1] = '\0';+ int n = (int)strlen(path);+ while (n < target && (size_t)n + 2 < cap) {+ int room = target - n - 1; /* after the '/' */+ int len = room > 200 ? 200 : room;+ if (len <= 0) {+ break;+ }+ n += snprintf(path + n, cap - (size_t)n, "/%.*s", len, fill);+ }+ }++ /* Parse an index-status body and compare each entry's "path" with the root+ * expected for its slot. Results go to out-params so the caller can tear+ * down before asserting. */+ static void th_index_status_check(const char *body, int expected_count, char expected[][4096],+ bool *parsed, int *count, bool *paths_whole) {+ *parsed = false;+ *count = 0;+ *paths_whole = false;+ yyjson_doc *doc = yyjson_read(body, strlen(body), 0);+ if (!doc) {+ return;+ }+ yyjson_val *arr = yyjson_doc_get_root(doc);+ if (yyjson_is_arr(arr)) {+ *parsed = true;+ *count = (int)yyjson_arr_size(arr);+ bool whole = *count == expected_count;+ size_t idx;+ size_t max_entries;+ yyjson_val *entry;+ yyjson_arr_foreach(arr, idx, max_entries, entry) {+ yyjson_val *slot = yyjson_obj_get(entry, "slot");+ yyjson_val *path = yyjson_obj_get(entry, "path");+ int s = yyjson_is_int(slot) ? yyjson_get_int(slot) : -1;+ whole = whole && s >= 0 && s < expected_count && yyjson_is_str(path) &&+ strcmp(yyjson_get_str(path), expected[s]) == 0;+ }+ *paths_whole = whole;+ }+ yyjson_doc_free(doc);+ }++ /* The listing is sized for what the job table holds. Every slot takes a root+ * as long as the platform resolves; the body has to parse as JSON and carry+ * each root whole, first with one job and then with the table full. Roots+ * enter the table the way the clamp test's do: real directories through the+ * route, held open by the blocking executor so every slot stays occupied. */+ TEST(ui_server_index_status_long_roots_render_whole) {+ char *tmp = th_mktempdir("cbm_status_whole");+ ASSERT_NOT_NULL(tmp);+ char base[256];+ snprintf(base, sizeof(base), "%s", tmp);+ /* Linux: just under the 4 KB field; the 4 KB request body still wraps it. */+ int target = 4096 - 160;+ #if defined(_WIN32)+ /* MAX_PATH: long roots are not characterised there; the listing is still+ * checked for shape and content with every slot occupied. */+ target = 200;+ #elif defined(PATH_MAX) && PATH_MAX < 4096+ /* macOS: the longest root the route can resolve; four still exceed 2 KB. */+ target = PATH_MAX - 96;+ #endif+ char deep[MAX_TEST_INDEX_JOBS][4096];+ char expected[MAX_TEST_INDEX_JOBS][4096];+ for (int j = 0; j < MAX_TEST_INDEX_JOBS; j++) {+ snprintf(deep[j], sizeof(deep[j]), "%s/%d", base, j);+ th_pad_path_to(deep[j], sizeof(deep[j]), target);+ ASSERT_EQ((int)strlen(deep[j]), target);+ ASSERT_EQ(th_mkdir_p(deep[j]), 0);+ ASSERT_TRUE(cbm_canonical_path(deep[j], expected[j], sizeof(expected[j])));+ }++ th_ui_blocking_index_executor_t executor = {0};+ atomic_init(&executor.calls, 0);+ atomic_init(&executor.release, 0);+ th_server_t ts;+ ts.srv = cbm_http_server_new(0);+ ASSERT_NOT_NULL(ts.srv);+ cbm_http_server_set_index_executor(ts.srv, th_ui_blocking_index_executor, &executor);+ ASSERT_EQ(th_server_thread_start(&ts.tid, ts.srv), 0);+ int port = cbm_http_server_port(ts.srv);+ char status_request[128];+ snprintf(status_request, sizeof(status_request),+ "GET /api/index-status HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n", port);++ int accepted = 0;+ bool started = true;+ bool one_parsed = false;+ bool one_whole = false;+ bool all_parsed = false;+ bool all_whole = false;+ int one_count = 0;+ int all_count = 0;+ size_t one_body_len = 0;+ size_t all_body_len = 0;+ char listing[65536];+ for (int j = 0; j < MAX_TEST_INDEX_JOBS; j++) {+ char body[4600];+ snprintf(body, sizeof(body), "{\"root_path\":\"%s\",\"project_name\":\"p%d\"}", deep[j], j);+ char request[4900];+ snprintf(request, sizeof(request),+ "POST /api/index HTTP/1.1\r\nContent-Type: application/json\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ strlen(body), body);+ char response[8192];+ int rn = th_http(port, request, response, sizeof(response));+ if (rn > 0 && th_status(response) == 202) {+ accepted++;+ }+ /* Wait for the state the listing depends on: this job running. */+ started = started && th_wait_atomic_int(&executor.calls, j + 1, 5000);+ if (j == 0 || j == MAX_TEST_INDEX_JOBS - 1) {+ int n = th_http(port, status_request, listing, sizeof(listing));+ const char *status_body = n > 0 ? th_response_body(listing) : "";+ if (j == 0) {+ one_body_len = strlen(status_body);+ th_index_status_check(status_body, 1, expected, &one_parsed, &one_count,+ &one_whole);+ } else {+ all_body_len = strlen(status_body);+ th_index_status_check(status_body, MAX_TEST_INDEX_JOBS, expected, &all_parsed,+ &all_count, &all_whole);+ }+ }+ }+ /* Release the workers and tear down; free refuses until each worker has+ * flagged completion, the same way the active-worker test waits. */+ atomic_store(&executor.release, 1);+ cbm_http_server_stop(ts.srv);+ ASSERT_EQ(cbm_thread_join(&ts.tid), 0);+ bool freed = false;+ uint64_t deadline = cbm_now_ms() + 2000;+ while (!freed && cbm_now_ms() < deadline) {+ freed = cbm_http_server_free(ts.srv);+ if (!freed)+ cbm_usleep(1000);+ }+ th_cleanup(base);++ ASSERT_TRUE(freed);+ ASSERT_EQ(accepted, MAX_TEST_INDEX_JOBS);+ ASSERT_TRUE(started);+ if (!one_parsed) {+ char m[128];+ snprintf(m, sizeof(m), "one-job index-status body of %zu bytes is not JSON", one_body_len);+ FAIL(m);+ }+ ASSERT_EQ(one_count, 1);+ ASSERT_TRUE(one_whole);+ if (!all_parsed) {+ char m[128];+ snprintf(m, sizeof(m), "full-table index-status body of %zu bytes is not JSON",+ all_body_len);+ FAIL(m);+ }+ ASSERT_EQ(all_count, MAX_TEST_INDEX_JOBS);+ ASSERT_TRUE(all_whole);PASS();}/* ── Suite ────────────────────────────────────────────────────── */SUITE(httpd) {+ RUN_TEST(ui_server_configuration_is_atomic_and_origin_protected);+ RUN_TEST(ui_server_browse_non_ascii_directory);RUN_TEST(ui_server_browse_wide_dir_no_overflow);RUN_TEST(ui_server_logs_escape_dense_no_overflow);RUN_TEST(ui_server_index_status_long_paths_no_overflow);@@@ -3426,25 -2910,12 +3965,29 @@@RUN_TEST(ui_server_rejects_non_loopback_host);RUN_TEST(ui_server_unknown_path_404);RUN_TEST(ui_server_process_kill_route_is_unavailable);+ RUN_TEST(ui_server_process_measurements_declare_platform_semantics);RUN_TEST(ui_server_routes_indexing_through_joinable_daemon_executor);RUN_TEST(ui_server_free_never_joins_active_index_worker);+ RUN_TEST(ui_csp_connect_src_has_explicit_download_hosts);+ RUN_TEST(activity_preserves_severity_and_reports_interrupted_reads);+ RUN_TEST(activity_pruned_start_events_do_not_resurrect_on_retry);+ RUN_TEST(activity_migration_preserves_v1_logs_and_rejects_future_schema);+ RUN_TEST(activity_log_project_scope_preserves_unknown_v2_history_and_filters_before_limit);+ RUN_TEST(ui_log_scopes_use_explicit_entry_ownership_and_survive_server_restart);+ RUN_TEST(activity_log_search_and_severity_apply_before_limit_and_survive_reopen);+ RUN_TEST(ui_log_retention_prevents_expired_retry_and_preserves_full_json);+ RUN_TEST(ui_log_journal_is_canonical_for_info_retry_and_restart);+ RUN_TEST(ui_log_legacy_import_is_once_and_preserves_unknown_provenance_and_time);+ RUN_TEST(activity_journal_reopen_cursor_dedup_and_project_isolation);+ RUN_TEST(activity_errors_survive_routine_log_retention_and_reopen);+ RUN_TEST(ui_agent_events_and_errors_use_daemon_port_and_survive_restart);+ RUN_TEST(ui_log_post_writes_jsonl_and_tail_reads_it);+ RUN_TEST(ui_log_post_refuses_bad_bodies);+ RUN_TEST(ui_log_rotates_at_configured_size);+ RUN_TEST(ui_server_index_start_refuses_root_outside_allowed);+ RUN_TEST(ui_server_index_start_stores_resolved_root);+ RUN_TEST(ui_server_index_start_long_root_not_truncated);+ RUN_TEST(ui_server_index_start_reply_escapes_path);RUN_TEST(ui_server_root_without_embedded_assets_is_not_found);RUN_TEST(ui_server_same_origin_request_is_allowed);RUN_TEST(ui_server_rejects_foreign_and_null_origins);diff --cc tests/test_main.cindex 47b23a53d,145e96ef6..4b83162dc--- a/tests/test_main.c+++ b/tests/test_main.c@@@ -791,7 -1779,8 +1779,9 @@@ extern void suite_discover(void)extern void suite_graph_buffer(void);extern void suite_registry(void);extern void suite_pipeline(void);+extern void suite_pipeline_objectscript_timeout(void);+ extern void suite_pipeline_conventions(void);+ extern void suite_pipeline_frozen(void);extern void suite_importance(void);extern void suite_pipeline_semantic_manifest_repro(void);extern void suite_cross_repo(void);@@@ -829,9 -1817,16 +1819,17 @@@ extern void suite_store_pragmas(void)extern void suite_store_checkpoint(void);extern void suite_traces(void);extern void suite_configlink(void);+ extern void suite_doclinks(void);+ extern void suite_doc_mentions(void);+ extern void suite_doc_mentions_cost(void);+ extern void suite_doc_mentions_msbuild(void);+ extern void suite_doc_links_md(void);+ extern void suite_doc_links_pdf(void);+ extern void suite_doc_links_rst(void);+ extern void suite_doc_links_adoc(void);extern void suite_infrascan(void);extern void suite_cli(void);+extern void suite_runtime_settings(void);extern void suite_agent_clients(void);extern void suite_agent_profiles(void);extern void suite_config_json_like(void);@@@ -896,19 -1894,97 +1897,121 @@@ extern void suite_dump_verify_io(void)* caches at thread teardown (pass_parallel.c). */extern void cbm_kind_in_set_free_cache(void);+ /* Native subprocess capture probe; implemented with its tests. */+ extern int tf_maybe_run_subprocess_stdout_probe(int argc, char **argv);+ extern void tf_test_impact_runner_filter_set_binary(const char *path);+ extern int tf_maybe_run_git_facts_diff_probe(int argc, char **argv);++ /* The runner's own image, for the tests that start or copy it again. argv[0]+ * is the caller's spelling, and a Windows parent that found the runner by+ * search (the native python scheduler, scripts/run-test-wave.py) passes it+ * without ".exe", which an exact spawn or copy of that path cannot open. */+ const char *tf_runner_image(int argc, char **argv);+ const char *tf_runner_image(int argc, char **argv) {+ #ifdef _WIN32+ static char image[4096];+ if (!image[0]) {+ char *module = cbm_module_path_utf8();+ if (module && strlen(module) < sizeof(image)) {+ memcpy(image, module, strlen(module) + 1);+ }+ free(module);+ }+ if (image[0]) {+ return image;+ }+ #endif+ return argc > 0 && argv ? argv[0] : NULL;+ }++const char *cbm_test_program_path;+int main(int argc, char **argv) {- cbm_test_program_path = argv[0];++ cbm_test_program_path = tf_runner_image(argc, argv);+ if (argc >= 4 && argc % 2 == 0 && strcmp(argv[1], "__cbm_env_values") == 0) {+ for (int i = 2; i < argc; i += 2) {+ const char *value = getenv(argv[i]);+ if (!value || strcmp(value, argv[i + 1]) != 0) {+ return 61;+ }+ }+ return 0;+ }++ if (argc >= 5 && strcmp(argv[1], "__cbm_env_isolation") == 0) {++ const char *value = getenv(argv[2]);++ if (!value || strcmp(value, argv[3]) != 0) {++ return 61;++ }++ for (int i = 4; i < argc; i++) {++ if (getenv(argv[i])) {++ return 62;++ }++ }++ return 0;++ }+ /* #2003: never let a caller's GIT_DIR/GIT_INDEX_FILE/... redirect fixture+ * git commands at the caller's real repository. */+ th_clear_git_repo_env();+ tf_test_impact_runner_filter_set_binary(tf_runner_image(argc, argv));+ #ifdef CBM_TEST_COVERAGE+ tf_coverage_process_init();+ #ifndef _WIN32+ int coverage_child_rc = tf_coverage_children_dispatch(argc, argv);+ if (coverage_child_rc >= 0) {+ return coverage_child_rc;+ }+ #endif+ #endif+ int stdout_probe_rc = tf_maybe_run_subprocess_stdout_probe(argc, argv);+ if (stdout_probe_rc >= 0) {+ return stdout_probe_rc;+ }+ int git_facts_probe_rc = tf_maybe_run_git_facts_diff_probe(argc, argv);+ if (git_facts_probe_rc >= 0) {+ return git_facts_probe_rc;+ }+ int memory_limit_probe_rc = tf_maybe_run_windows_memory_limit_probe(argc, argv);+ if (memory_limit_probe_rc >= 0) {+ return memory_limit_probe_rc;+ }+ int blocking_git_rc = tf_maybe_run_blocking_git_probe(argc, argv);+ if (blocking_git_rc >= 0) {+ return blocking_git_rc;+ }+ /* Installation tests use this executable as a structurally real candidate.+ * Mirror the production binary's minimal verification contract. */+ if (argc == 2 && strcmp(argv[1], "--version") == 0) {+ (void)puts("codebase-memory-mcp test-runner");+ return 0;+ }+ if (argc == 2 && strcmp(argv[1], "--build-config") == 0) {+ #ifdef _WIN32+ if (_setmode(cbm_fileno(stdout), _O_BINARY) == -1) {+ fprintf(stderr, "failed to set build-config stdout to binary mode\n");+ return 2;+ }+ #endif+ #if defined(CBM_SANITIZED_BUILD) && CBM_SANITIZED_BUILD+ const int sanitized = 1;+ #else+ const int sanitized = 0;+ #endif+ #if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS+ const int test_seams = 1;+ #else+ const int test_seams = 0;+ #endif+ (void)printf("sanitized=%d test_seams=%d\n", sanitized, test_seams);+ return 0;+ }+ /* A test's verdict is a pure function of code, test, platform and seed --+ * never of how full this machine's disk is. The spill store refuses to open+ * below 10 GB free, so without this pin every spill test failed, and every+ * budget-driven pipeline test silently took the no-store path, on a host+ * with less free space. Pin ample space for this process and every worker+ * it re-execs; the refusal itself is pinned on purpose by+ * extraction::extract_spill_refuses_below_the_free_disk_floor. */+ (void)cbm_result_spill_pin_free_bytes_for_tests((size_t)64 * 1024 * 1024 * 1024);/* Skip the multi-hundred-MB executable-image hash that computes the exact* build fingerprint: it is tens of seconds per spawned worker/daemon under* ASan on constrained CI runners and the sole cause of the daemon-family@@@ -1080,7 -2218,8 +2245,9 @@@/* Pipeline (M8) */RUN_SELECTED_SUITE(registry);RUN_SELECTED_SUITE(pipeline);+ RUN_SELECTED_SUITE(pipeline_objectscript_timeout);+ RUN_SELECTED_SUITE(pipeline_conventions);+ RUN_SELECTED_SUITE(pipeline_frozen);RUN_SELECTED_SUITE(importance);RUN_SELECTED_SUITE(index_format);RUN_SELECTED_SUITE(pipeline_semantic_manifest_repro);diff --cc tests/test_mcp.cindex aa64cbcbb,abd19c124..6007ce610--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@@ -15184,12 -17288,224 +17576,227 @@@ TEST(detect_changes_cursor_bound_to_walPASS();}- TEST(store_idle_evict_protects_initial_store) {- /* Evicting with NULL server should not crash */- cbm_mcp_server_evict_idle(NULL, 0);-- /* Evicting server whose store was never accessed via a named project- * should NOT evict the initial in-memory store (store_last_used == 0). */+ /* Golden: a request that names none of the walk parameters gets the answer it+ * got before they existed, byte for byte, in both encodings. The project name+ * and every qualified name are fixed, so the only varying bytes are the commit+ * id of the fixture, which is replaced before comparing. */+ static void dc_golden_blank_oids(char *text) {+ for (char *p = text; *p;) {+ size_t run = 0;+ while (isxdigit((unsigned char)p[run])) {+ run++;+ }+ if (run == 40) {+ memset(p, '#', run);+ }+ p += run ? run : 1;+ }+ }++ TEST(detect_changes_default_output_is_byte_identical_golden) {+ char repo[CBM_SZ_4K];+ snprintf(repo, sizeof(repo), "%s/cbm-detect-golden-XXXXXX", cbm_tmpdir());+ ASSERT_NOT_NULL(cbm_mkdtemp(repo));+ char cache[CBM_SZ_4K];+ snprintf(cache, sizeof(cache), "%s/cbm-detect-golden-cache-XXXXXX", cbm_tmpdir());+ ASSERT_NOT_NULL(cbm_mkdtemp(cache));+ char src[CBM_SZ_4K];+ snprintf(src, sizeof(src), "%s/mod.py", repo);+ ASSERT_EQ(th_write_file(src, DC_WALK_SRC_HEAD " x = 1\n" DC_WALK_SRC_TAIL), 0);++ const char *const init_args[] = {"-c", "init.defaultBranch=main", "init", "-q", NULL};+ const char *const add_args[] = {"add", "-A", NULL};+ const char *const commit_args[] = {+ "-c", "user.name=cbm-test",+ "-c", "[email protected]",+ "-c", "commit.gpgsign=false",+ "commit", "-q",+ "-m", "fixture",+ NULL,+ };+ ASSERT_EQ(mcp_test_git(repo, init_args), 0);+ ASSERT_EQ(mcp_test_git(repo, add_args), 0);+ ASSERT_EQ(mcp_test_git(repo, commit_args), 0);+ ASSERT_EQ(th_write_file(src, DC_WALK_SRC_HEAD " x = 11\n" DC_WALK_SRC_TAIL), 0);++ const char *saved_cache = getenv("CBM_CACHE_DIR");+ char *saved_cache_copy = saved_cache ? strdup(saved_cache) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_CACHE_DIR", cache, 1), 0);+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ cbm_store_t *store = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(store);+ const char *project = "detect-golden";+ ASSERT_EQ(cbm_store_upsert_project(store, project, repo), CBM_STORE_OK);+ cbm_mcp_server_set_project(srv, project);++ /* The graph of DC_WALK_SRC: leaf <- mid1 <- mid2 <- mid3 <- top. */+ static const struct {+ const char *name;+ int start;+ int end;+ } defs[] = {+ {"leaf", 1, 3}, {"mid1", 6, 7}, {"mid2", 10, 11}, {"mid3", 14, 15}, {"top", 18, 19}};+ int64_t ids[5];+ for (int i = 0; i < 5; i++) {+ char qn[64];+ snprintf(qn, sizeof(qn), "detect-golden.mod.%s", defs[i].name);+ cbm_node_t node = {.project = project,+ .label = "Function",+ .name = defs[i].name,+ .qualified_name = qn,+ .file_path = "mod.py",+ .start_line = defs[i].start,+ .end_line = defs[i].end};+ ids[i] = cbm_store_upsert_node(store, &node);+ ASSERT_GT(ids[i], 0);+ }+ for (int i = 1; i < 5; i++) {+ cbm_edge_t edge = {+ .project = project, .source_id = ids[i], .target_id = ids[i - 1], .type = "CALLS"};+ ASSERT_GT(cbm_store_insert_edge(store, &edge), 0);+ }++ char *tree_response = cbm_mcp_handle_tool(+ srv, "detect_changes", "{\"project\":\"detect-golden\",\"base_branch\":\"HEAD\"}");+ char *tree = extract_text_content(tree_response);+ char *json_response = cbm_mcp_handle_tool(+ srv, "detect_changes",+ "{\"project\":\"detect-golden\",\"base_branch\":\"HEAD\",\"format\":\"json\"}");+ char *json = extract_text_content(json_response);+ ASSERT_NOT_NULL(tree);+ ASSERT_NOT_NULL(json);+ dc_golden_blank_oids(tree);+ dc_golden_blank_oids(json);+ if (getenv("CBM_PRINT_DETECT_GOLDEN")) {+ printf("GOLDEN-TREE<<%s>>\nGOLDEN-JSON<<%s>>\n", tree, json);+ }+ static const char *const golden_tree = "base: HEAD\n"+ "merge_base: ########################################\n"+ "direction: inbound\n"+ "changed_total: 1\n"+ "changed_returned: 1\n"+ "changed_has_more: false\n"+ "changed_files: 1 (cols: path)\n"+ " mod.py\n"+ "seed_symbols: 1\n"+ "impacted_total: 2\n"+ "impacted_total_relation: eq\n"+ "impacted_shown: 2\n"+ "impacted: 2 (cols: qn label file hop)\n"+ " detect-golden.mod.mid1 Function mod.py 1\n"+ " detect-golden.mod.mid2 Function mod.py 2\n"+ "impacted_has_more: false\n"+ "module_total: 1\n"+ "module_total_relation: eq\n"+ "module_returned: 1\n"+ "module_has_more: false\n"+ "impacted_modules: 1 (cols: module count)\n"+ " mod.py 2\n";+ static const char *const golden_json =+ "{\"base\":\"HEAD\",\"merge_base\":\"########################################\",\"dir"+ "ection\":\"inbound\",\"changed_total\":1,\"changed_returned\":1,\"changed_has_more\""+ ":false,\"changed_files\":[\"mod.py\"],\"seed_symbols\":1,\"impacted_total\":2,\"impa"+ "cted_total_relation\":\"eq\",\"impacted_shown\":2,\"impacted\":[{\"qn\":\"detect-gol"+ "den.mod.mid1\",\"label\":\"Function\",\"file\":\"mod.py\",\"hop\":1},{\"qn\":\"detec"+ "t-golden.mod.mid2\",\"label\":\"Function\",\"file\":\"mod.py\",\"hop\":2}],\"impacte"+ "d_has_more\":false,\"module_total\":1,\"module_total_relation\":\"eq\",\"module_retu"+ "rned\":1,\"module_has_more\":false,\"impacted_modules\":[{\"module\":\"mod.py\",\"co"+ "unt\":2}],\"truncated\":false}";+ ASSERT_STR_EQ(tree, golden_tree);+ ASSERT_STR_EQ(json, golden_json);++ free(json);+ free(json_response);+ free(tree);+ free(tree_response);+ cbm_mcp_server_free(srv);+ restore_cache_dir(saved_cache_copy);+ free(saved_cache_copy);+ ASSERT_EQ(th_rmtree(cache), 0);+ ASSERT_EQ(th_rmtree(repo), 0);+ PASS();+ }+++/* ingest_traces stores for real now (the stub answered "accepted" and++ * discarded). Without a resolvable project there is nothing to store++ * against — a tool error, not a polite lie. */+ TEST(tool_ingest_traces_basic) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);++ char *resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":37,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"ingest_traces\","+ "\"arguments\":{\"traces\":[{\"caller\":\"a\",\"callee\":\"b\"}]}}}");+ ASSERT_NOT_NULL(resp);- ASSERT_NOT_NULL(strstr(resp, "accepted"));- ASSERT_NOT_NULL(strstr(resp, "traces_received"));++ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));++ ASSERT_NULL(strstr(resp, "accepted"));+ free(resp);++ cbm_mcp_server_free(srv);+ PASS();+ }++ TEST(tool_ingest_traces_empty) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);++ char *resp =+ cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":38,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"ingest_traces\","+ "\"arguments\":{\"traces\":[]}}}");+ ASSERT_NOT_NULL(resp);- ASSERT_NOT_NULL(strstr(resp, "accepted"));++ ASSERT_NOT_NULL(strstr(resp, "\"isError\":true"));+ free(resp);++ cbm_mcp_server_free(srv);+ PASS();+ }++ /* ══════════════════════════════════════════════════════════════════+ * IDLE STORE EVICTION+ * ══════════════════════════════════════════════════════════════════ */++ TEST(store_idle_eviction) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ cbm_mcp_server_set_project(srv, "test-evict");++ /* Trigger resolve_store via a tool call to set store_last_used */+ char *resp = cbm_mcp_handle_tool(srv, "get_graph_schema", "{\"project\":\"test-evict\"}");+ free(resp);++ ASSERT_TRUE(cbm_mcp_server_has_cached_store(srv));++ /* Evict with 0s timeout → should evict immediately */+ cbm_mcp_server_evict_idle(srv, 0);+ ASSERT_FALSE(cbm_mcp_server_has_cached_store(srv));++ cbm_mcp_server_free(srv);+ PASS();+ }++ TEST(store_idle_no_eviction_within_timeout) {+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ cbm_mcp_server_set_project(srv, "test-evict");++ char *resp = cbm_mcp_handle_tool(srv, "get_graph_schema", "{\"project\":\"test-evict\"}");+ free(resp);++ ASSERT_TRUE(cbm_mcp_server_has_cached_store(srv));++ /* Evict with large timeout → should NOT evict */+ cbm_mcp_server_evict_idle(srv, 99999);+ ASSERT_TRUE(cbm_mcp_server_has_cached_store(srv));++ cbm_mcp_server_free(srv);+ PASS();+ }++ TEST(store_idle_evict_protects_initial_store) {+ /* Evicting with NULL server should not crash */+ cbm_mcp_server_evict_idle(NULL, 0);++ /* Evicting server whose store was never accessed via a named project+ * should NOT evict the initial in-memory store (store_last_used == 0). */cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);ASSERT_TRUE(cbm_mcp_server_has_cached_store(srv));cbm_mcp_server_evict_idle(srv, 0);@@@ -20258,8 -23920,8 +24212,9 @@@ SUITE(mcp)RUN_TEST(tool_list_projects_tree_uses_one_stable_header_and_keeps_json_direct);RUN_TEST(tool_list_projects_preserves_root_beyond_one_kib);RUN_TEST(tool_index_status_no_project);+ RUN_TEST(tool_ingest_traces_stores_observed_calls);RUN_TEST(tool_check_index_coverage_finds_path_beyond_status_cap);+ RUN_TEST(tool_check_index_coverage_reports_truncation_marker_issue963);RUN_TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges);RUN_TEST(tool_check_index_coverage_pages_exact_paths_and_restores_raw_diagnostics);RUN_TEST(tool_check_index_coverage_preserves_multiple_scope_labels);diff --cc tests/test_subprocess.cindex 0fb5ba3d7,41dc4d4fa..6adee0c01--- a/tests/test_subprocess.c+++ b/tests/test_subprocess.c@@@ -21,11 -25,20 +25,21 @@@#ifndef _WIN32#include <fcntl.h>#include <signal.h>+#include <sys/stat.h>#include <sys/time.h>+ #include <sys/wait.h>#include <unistd.h>+ #ifdef __linux__+ #include <sys/syscall.h>+ #if !defined(SYS_close_range) && (defined(__x86_64__) || defined(__aarch64__))+ #define SYS_close_range 436+ #endif+ #endif#else+ #include <fcntl.h>+ #include <io.h>#include <windows.h>+ #include "../src/foundation/win_utf8.h"#endif/* ── Layer 1: pure classifier (all platforms) ─────────────────────────────── */@@@ -88,78 -101,6 +102,137 @@@ TEST(subprocess_outcome_str)/* ── Layer 2: real spawn/reap (POSIX) ─────────────────────────────────────── */+extern const char *cbm_test_program_path;++TEST(subprocess_environment_is_child_local) {+ const char *names[] = {"CBM_ENV_TEST_VALUE", "CBM_ENV_TEST_KEEP", "CBM_ENV_TEST_EMPTY",+ "CBM_ENV_TEST_NEW"};+ char *saved[4] = {0};+ for (int i = 0; i < 4; i++) {+ const char *value = getenv(names[i]);+ saved[i] = value ? cbm_strdup(value) : NULL;+ if (i == 3) {+ (void)cbm_unsetenv(names[i]);+ } else {+ (void)cbm_setenv(names[i], i == 1 ? "kept" : "parent", 1);+ }+ }+ const char *args[] = {cbm_test_program_path,+ "__cbm_env_values",+ names[0],+ "child",+ names[1],+ "kept",+ names[2],+ "",+ names[3],+ "last=tail",+ NULL};+ const char *overrides[] = {+#ifdef _WIN32+ "cbm_env_test_value=child",+#else+ "CBM_ENV_TEST_VALUE=child",+#endif+ "CBM_ENV_TEST_EMPTY=", "CBM_ENV_TEST_NEW=first", "CBM_ENV_TEST_NEW=last=tail", NULL};+ cbm_proc_opts_t opts = {.bin = cbm_test_program_path,+ .argv = args,+ .env_overrides = overrides,+ .quiet_timeout_ms = 5000};+ cbm_proc_result_t result;+ int rc = cbm_subprocess_run(&opts, &result);+ bool parent_unchanged = strcmp(getenv(names[0]), "parent") == 0 &&+ strcmp(getenv(names[1]), "kept") == 0 &&+ strcmp(getenv(names[2]), "parent") == 0 && getenv(names[3]) == NULL;+ for (int i = 0; i < 4; i++) {+ if (saved[i]) {+ (void)cbm_setenv(names[i], saved[i], 1);+ } else {+ (void)cbm_unsetenv(names[i]);+ }+ free(saved[i]);+ }+ ASSERT_EQ(rc, 0);+ ASSERT_EQ(result.outcome, CBM_PROC_CLEAN);+ ASSERT_TRUE(parent_unchanged);+ PASS();+}++TEST(subprocess_environment_rejects_invalid_override) {+ const char *args[] = {cbm_test_program_path, "--version", NULL};+ const char *invalid[] = {"MISSING_EQUALS", "", "=value"};+ for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); i++) {+ const char *overrides[] = {invalid[i], NULL};+ cbm_proc_opts_t opts = {.bin = cbm_test_program_path,+ .argv = args,+ .env_overrides = overrides,+ .quiet_timeout_ms = 5000};+ cbm_proc_result_t result;+ ASSERT_EQ(cbm_subprocess_run(&opts, &result), -1);+ ASSERT_EQ(result.outcome, CBM_PROC_SPAWN_FAILED);+ }+ PASS();+}+++/* Git scrubbing wins over a repository-local override, while ordinary overrides++ * remain child-local. The early child probe runs before test-runner scrubbing. */++TEST(subprocess_environment_overrides_preserve_git_isolation) {++ const char *names[] = {"GIT_DIR", "GIT_WORK_TREE", "GIT_DIFF_OPTS", "CBM_ENV_GIT_KEEP"};++ char *saved[4] = {0};++ bool present[4] = {0};++ bool setup = true;++ for (int i = 0; i < 4; i++) {++ const char *value = getenv(names[i]);++ present[i] = value != NULL;++ saved[i] = value ? cbm_strdup(value) : NULL;++ setup = setup && (!present[i] || saved[i]);++ }++ if (setup) {++ for (int i = 0; i < 4; i++) {++ setup = cbm_setenv(names[i], "parent", 1) == 0 && setup;++ }++ }++ const char *args[] = {cbm_test_program_path,++ "__cbm_env_isolation",++ names[3],++ "child",++ names[0],++ names[1],++ names[2],++ NULL};++ const char *overrides[] = {++#ifdef _WIN32++ "git_dir=/cbm-override-repo",++#else++ "GIT_DIR=/cbm-override-repo",++#endif++ "GIT_DIFF_OPTS=--unified=999", "CBM_ENV_GIT_KEEP=child", NULL};++ cbm_proc_opts_t opts = {.bin = cbm_test_program_path,++ .argv = args,++ .env_overrides = overrides,++ .strip_git_repo_env = true,++ .quiet_timeout_ms = 5000};++ cbm_proc_result_t result = {0};++ int rc = setup ? cbm_subprocess_run(&opts, &result) : -1;++ bool parent_unchanged = true;++ for (int i = 0; i < 4; i++) {++ const char *value = getenv(names[i]);++ parent_unchanged = parent_unchanged && value && strcmp(value, "parent") == 0;++ if (saved[i]) {++ (void)cbm_setenv(names[i], saved[i], 1);++ } else if (!present[i]) {++ (void)cbm_unsetenv(names[i]);++ }++ free(saved[i]);++ }++ ASSERT_TRUE(setup);++ ASSERT_EQ(rc, 0);++ ASSERT_EQ(result.exit_code, 0);++ ASSERT_EQ(result.outcome, CBM_PROC_CLEAN);++ ASSERT_TRUE(parent_unchanged);++ PASS();++}++#ifndef _WIN32static cbm_proc_result_t run_sh(const char *script, int quiet_timeout_ms) {const char *argv[] = {"/bin/sh", "-c", script, NULL};@@@ -1379,13 -2360,10 +2585,16 @@@ SUITE(subprocess)RUN_TEST(subprocess_classify_non_fault_signal_is_killed);RUN_TEST(subprocess_classify_timeout_dominates);RUN_TEST(subprocess_outcome_str);+ RUN_TEST(subprocess_environment_is_child_local);+ RUN_TEST(subprocess_environment_rejects_invalid_override);++ RUN_TEST(subprocess_environment_overrides_preserve_git_isolation);+#ifndef _WIN32+ RUN_TEST(subprocess_environment_path_preserves_caller_lookup);+#endifRUN_TEST(subprocess_run_clean);RUN_TEST(subprocess_run_exit_nonzero);+ RUN_TEST(subprocess_run_child_exited_before_group_check);+ RUN_TEST(subprocess_run_child_exiting_at_group_check);RUN_TEST(subprocess_run_resolves_literal_binary_name_from_path);RUN_TEST(subprocess_run_crash_is_crash);RUN_TEST(subprocess_run_hang_is_hang);