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
daemon: permanent lifecycle, daemon-backed CLI/hooks, real-Windows hardening, long-path launcher transactions
Martin Vogel0baddf788737
diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.ymlindex c6e308801..c7d623bd0 100644--- a/.github/workflows/_test.yml+++ b/.github/workflows/_test.yml@@ -285,8 +285,8 @@ jobs:- name: Windows regression guards (#636/#357, #618, #548, #423/#20)shell: pwsh- # -GuardsOnly runs the four green guards and gates on them. The runner sets- # CBM_INDEX_SUPERVISOR=0 for determinism, but the non-ASCII CLI guard drops that- # override so it exercises the real supervisor->worker spawn (where #423/#20's- # second half lives); the other guards test path/hook/drive fixes in-process.+ # -GuardsOnly runs the four green guards and gates on them. All guards run+ # against the real supervisor->worker spawn path: under the mandatory+ # coordination daemon, CBM_INDEX_SUPERVISOR=0 is a fail-closed refusal, so+ # the driver no longer sets it anywhere.run: ./scripts/test-windows.ps1 -GuardsOnly -Binary build/c/codebase-memory-mcp.exediff --git a/Makefile.cbm b/Makefile.cbmindex 831781370..7bb700fc4 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -65,7 +65,8 @@ CXXFLAGS_PROD = $(CXXFLAGS_COMMON) -O2SANITIZE = -fsanitize=address,undefined -fno-omit-frame-pointerEDITOR_TEST_DEFINES = -DCBM_JSON_LIKE_ENABLE_TEST_API=1 \-DCBM_TOML_EDIT_ENABLE_TEST_API=1 -DCBM_YAML_ENABLE_TEST_API=1 \- -DCBM_TEXT_EDIT_ENABLE_TEST_API=1 -DCBM_CLI_ENABLE_TEST_API=1+ -DCBM_TEXT_EDIT_ENABLE_TEST_API=1 -DCBM_CLI_ENABLE_TEST_API=1 \+ -DCBM_DIAGNOSTICS_ENABLE_TEST_API=1CFLAGS_TEST = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) -g -O1 $(SANITIZE)CXXFLAGS_TEST = $(CXXFLAGS_COMMON) -g -O1 $(SANITIZE)@@ -348,6 +349,7 @@ TEST_FOUNDATION_SRCS = \tests/test_log.c \tests/test_str_util.c \tests/test_platform.c \+ tests/test_diagnostics.c \tests/test_dump_verify.c \tests/test_subprocess.c \tests/test_private_file_lock.c \@@ -826,8 +828,9 @@ cbm-with-ui: embed $(OBJS_VENDORED_PROD) $(WINDOWS_LAUNCHER_TARGET)$(LDFLAGS)@echo "Built with UI: $(BUILD_DIR)/codebase-memory-mcp"+clean-c: export BUILD_DIR := $(BUILD_DIR)clean-c:- rm -rf $(BUILD_DIR)+ @bash -c 'source scripts/path-safety.sh && cbm_remove_build_dir "$$PWD" "$$BUILD_DIR"'# ── Linting ─────────────────────────────────────────────────────diff --git a/README.md b/README.mdindex 74160bc90..e16d17310 100644--- a/README.md+++ b/README.md@@ -274,14 +274,14 @@ codebase-memory-mcp runs **100% locally and collects no telemetry** — your cod### Capture a diagnostics log-Set `CBM_DIAGNOSTICS=1` before the first daemon-backed MCP session starts, then reproduce the problem (let it run as long as it takes — a slow leak needs time to show in the trend). The shared daemon captures this setting from the session that starts it. If it is already running, close all daemon-backed sessions so it exits before changing the setting. The daemon writes two files to your system temp directory (`$TMPDIR` or `/tmp` on macOS/Linux, `%TEMP%` on Windows):+Set `CBM_DIAGNOSTICS=1` before the first daemon-backed MCP session starts, then reproduce the problem (let it run as long as it takes — a slow leak needs time to show in the trend). The shared daemon captures this setting from the session that starts it. If it is already running, close all daemon-backed sessions so it exits before changing the setting. The daemon creates a fresh owner-private `cbm-diagnostics-<pid>-<random>` directory below the system temp directory (`$TMPDIR` or `/tmp` on macOS/Linux, `%TEMP%` on Windows). The exact paths are recorded by the `diagnostics.start` event in `${CBM_CACHE_DIR}/logs/cbm-daemon.log`:| File | What it is ||------|------------|-| `cbm-diagnostics-<pid>.ndjson` | **The memory trajectory** — one JSON line every 5 s with `rss`, `committed` (Windows commit charge), `peak_*`, `page_faults`, `fd`, and `queries`. **This is the file we need for memory/leak reports** — the *trend over time* is what pinpoints a leak. It is **kept on disk after the server exits** (so you can grab it post-mortem) and rotates to `.ndjson.1` past ~8 MB. |-| `cbm-diagnostics-<pid>.json` | The latest snapshot only — handy for a quick live check. Removed on clean exit. |+| `trajectory.ndjson` | **The memory trajectory** — one JSON line every 5 s with `rss`, `committed` (Windows commit charge), `peak_*`, `page_faults`, `fd`, and `queries`. **This is the file we need for memory/leak reports** — the *trend over time* is what pinpoints a leak. It is **kept on disk after the server exits** (so you can grab it post-mortem) and rotates to `trajectory.ndjson.1` past ~8 MB. |+| `snapshot.json` | The latest snapshot only — handy for a quick live check. Removed on clean exit. |-The `<pid>` component is the shared daemon's process ID, also recorded by the `daemon.start` event in `${CBM_CACHE_DIR}/logs/cbm-daemon.log`. Set the variable consistently in the `env` block of each agent's MCP server config, or export it before launching the first session.+The private randomized directory prevents another local account from pre-placing a link or special file at a predictable diagnostics path. Its `<pid>` component is the shared daemon's process ID, also recorded by the `daemon.start` event. Set the variable consistently in the `env` block of each agent's MCP server config, or export it before launching the first session.### What to share@@ -635,7 +635,7 @@ codebase-memory-mcp config reset auto_index # reset to default|----------|---------|-------------|| `CBM_ALLOWED_ROOT` | *(unset)* | Restrict `index_repository` to paths within this directory. When set, a `repo_path` that resolves (after symlink / `..` resolution) outside this root is refused; unset imposes no restriction. Useful when the server may be driven by an untrusted caller, e.g. agentic or multi-tenant deployments. || `CBM_CACHE_DIR` | `~/.cache/codebase-memory-mcp` | Override the database storage directory. All project indexes and config are stored here. One account can use only one canonical cache root at a time; close active CBM sessions/commands before switching it. |-| `CBM_DIAGNOSTICS` | `false` | Set to `1` or `true` to enable the shared daemon's periodic snapshot and trajectory files in the system temp directory (`cbm-diagnostics-<pid>.json` and `cbm-diagnostics-<pid>.ndjson`). |+| `CBM_DIAGNOSTICS` | `false` | Set to `1` or `true` to enable the shared daemon's periodic `snapshot.json` and retained `trajectory.ndjson` below a fresh owner-private directory in the system temp directory. Exact paths are logged by `diagnostics.start`. || `CBM_DOWNLOAD_URL` | *(GitHub releases)* | Override the download URL for updates. Used for testing or self-hosted deployments. || `CBM_LOG_LEVEL` | `info` | Set the minimum log level. Accepted values (case-insensitive): `debug`, `info`, `warn`, `error`, `none` — or their numeric equivalents `0`–`4` matching the internal enum. Thin-frontend messages go to that session's stderr; detached daemon events go to `${CBM_CACHE_DIR}/logs/cbm-daemon.log`. Stdout is reserved for MCP JSON-RPC. || `CBM_WORKERS` | *(detected)* | Override the parallel-indexing worker count returned by `cbm_default_worker_count`. Useful inside containers where `sysconf(_SC_NPROCESSORS_ONLN)` reports host CPUs rather than the cgroup's effective quota. Range 1–256; invalid values are ignored with a warning. |diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex b178a255f..e8dc608c3 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -118,7 +118,7 @@ These environment variables affect runtime behavior:|---|---|---|| `CBM_ALLOWED_ROOT` | *(unset)* | Restrict `index_repository` to paths within this directory. When set, a `repo_path` that resolves (after symlink / `..` resolution) outside this root is refused; unset imposes no restriction. Useful when the server may be driven by an untrusted caller (agentic or multi-tenant deployments). || `CBM_CACHE_DIR` | `~/.cache/codebase-memory-mcp` | Override the cache directory used for indexes, `_config.db`, and UI `config.json`. |-| `CBM_DIAGNOSTICS` | `false` | Enable the shared daemon's periodic snapshot and trajectory files in the system temp directory (`cbm-diagnostics-<pid>.json` and `cbm-diagnostics-<pid>.ndjson`). |+| `CBM_DIAGNOSTICS` | `false` | Enable periodic `snapshot.json` and retained `trajectory.ndjson` below a fresh owner-private directory in the system temp directory. The daemon records the randomized paths in the `diagnostics.start` discovery record (a single JSON line) in `${CBM_CACHE_DIR}/logs/cbm-daemon.log`; that one record is emitted even when `CBM_LOG_LEVEL` suppresses ordinary logging, so the paths always remain discoverable. || `CBM_DOWNLOAD_URL` | GitHub releases | Override the update download URL. || `CBM_LOG_LEVEL` | `info` | Set the log level to `debug`, `info`, `warn`, `error`, or `none` (or `0`-`4`). Thin-frontend messages use that session's stderr; detached daemon events use `${CBM_CACHE_DIR}/logs/cbm-daemon.log`. || `CBM_WORKERS` | auto-detected | Override the indexing worker count. |diff --git a/graph-ui/vite.config.ts b/graph-ui/vite.config.tsindex d7a3a0b85..fe59c23c1 100644--- a/graph-ui/vite.config.ts+++ b/graph-ui/vite.config.ts@@ -1,9 +1,30 @@/// <reference types="vitest" />-import { defineConfig } from "vite";+import { defineConfig, type ProxyOptions } from "vite";import react from "@vitejs/plugin-react";import tailwindcss from "@tailwindcss/vite";import path from "path";+const uiBackendOrigin = "http://127.0.0.1:9749";+const uiDevOrigins = new Set([+ "http://127.0.0.1:5173",+ "http://localhost:5173",+]);+const uiBackendProxy = (): ProxyOptions => ({+ target: uiBackendOrigin,+ changeOrigin: true,+ // The backend deliberately accepts only its own exact loopback authority.+ // Reject foreign browser origins before normalizing the trusted Vite origin.+ headers: { Origin: uiBackendOrigin },+ bypass(req, res) {+ const origin = req.headers.origin;+ if (origin !== undefined && !uiDevOrigins.has(origin)) {+ res.writeHead(403, { "Content-Type": "application/json" });+ res.end('{"error":"forbidden origin"}');+ return false;+ }+ },+});+export default defineConfig({plugins: [react(), tailwindcss()],resolve: {@@ -27,9 +48,10 @@ export default defineConfig({},server: {port: 5173,+ strictPort: true,proxy: {- "/rpc": "http://127.0.0.1:9749",- "/api": "http://127.0.0.1:9749",+ "/rpc": uiBackendProxy(),+ "/api": uiBackendProxy(),},},});diff --git a/scripts/build.sh b/scripts/build.shindex 71d1c8120..1b9003b28 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -32,6 +32,8 @@ done# shellcheck source=env.shsource "$ROOT/scripts/env.sh"+# shellcheck source=path-safety.sh+source "$ROOT/scripts/path-safety.sh"# Parse remaining arguments. BUILD_DIR is tracked for the clean step below so# containerized legs can build in their own directory instead of deleting and@@ -92,7 +94,7 @@ echo " ui=$WITH_UI version=${VERSION:-dev}"verify_compiler "$CC"# Step 1: Clean C build artifacts only (not node_modules — npm ci handles that)-rm -rf "${ROOT:?}/${BUILD_DIR}"+cbm_remove_build_dir "$ROOT" "$BUILD_DIR"# Step 2: Build (Makefile applies $ARCHFLAGS for the target arch on macOS)if $WITH_UI; thendiff --git a/scripts/clean.sh b/scripts/clean.shindex 1d0128c74..882e88c53 100755--- a/scripts/clean.sh+++ b/scripts/clean.sh@@ -11,6 +11,9 @@ set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"+# shellcheck source=path-safety.sh+source "$ROOT/scripts/path-safety.sh"+# Containerized legs build in their own directory (BUILD_DIR env) so a# container clean never deletes the host's native build/c mid-build.BUILD_DIR="${BUILD_DIR:-build/c}"@@ -18,7 +21,7 @@ BUILD_DIR="${BUILD_DIR:-build/c}"echo "=== Cleaning build artifacts ($BUILD_DIR) ==="# C build artifacts-rm -rf "${ROOT:?}/${BUILD_DIR}"+cbm_remove_build_dir "$ROOT" "$BUILD_DIR"# Frontend build artifactsrm -rf "$ROOT/graph-ui/dist"diff --git a/scripts/path-safety.sh b/scripts/path-safety.shnew file mode 100644index 000000000..b67972270--- /dev/null+++ b/scripts/path-safety.sh@@ -0,0 +1,52 @@+#!/usr/bin/env bash+# Shared destructive-path validation for build/test/clean entrypoints.++cbm_require_safe_build_dir() {+ local build_dir="${1-}"+ local root="${2:-$PWD}"+ local leaf+ local physical_root+ local physical_build++ # Keep cleanup targets to one ordinary repository-owned directory directly+ # beneath build/. Besides rejecting absolute and parent-relative paths,+ # the single-component rule prevents an intermediate symlink from routing+ # rm into a directory outside the repository.+ if [[ ! "$build_dir" =~ ^build/[A-Za-z0-9._-]+$ ]]; then+ echo "ERROR: BUILD_DIR must be one direct child of build/ (got '$build_dir')" >&2+ return 1+ fi+ leaf="${build_dir#build/}"+ if [[ "$leaf" == "." || "$leaf" == ".." ]]; then+ echo "ERROR: BUILD_DIR must name an ordinary build/ child (got '$build_dir')" >&2+ return 1+ fi+ if ! physical_root="$(cd "$root" 2>/dev/null && pwd -P)"; then+ echo "ERROR: repository root is missing or inaccessible" >&2+ return 1+ fi+ if [ -L "$physical_root/build" ] ||+ { [ -e "$physical_root/build" ] && [ ! -d "$physical_root/build" ]; }; then+ echo "ERROR: repository build/ ancestor must be absent or a real directory" >&2+ return 1+ fi+ if [ -d "$physical_root/build" ]; then+ if ! physical_build="$(cd "$physical_root/build" 2>/dev/null && pwd -P)" ||+ [ "$physical_build" != "$physical_root/build" ]; then+ echo "ERROR: repository build/ ancestor resolves outside the repository" >&2+ return 1+ fi+ fi+}++cbm_remove_build_dir() {+ local root="${1-}"+ local build_dir="${2-}"+ local physical_root+ local leaf++ cbm_require_safe_build_dir "$build_dir" "$root" || return 1+ physical_root="$(cd "$root" 2>/dev/null && pwd -P)" || return 1+ leaf="${build_dir#build/}"+ rm -rf -- "$physical_root/build/$leaf"+}diff --git a/scripts/run-tests-parallel.sh b/scripts/run-tests-parallel.shindex e8a06b202..eab4607ed 100644--- a/scripts/run-tests-parallel.sh+++ b/scripts/run-tests-parallel.sh@@ -100,7 +100,7 @@ run_one() {# Uses `timeout` where available (always in the Linux container / CI); on a# host without it the suite runs uncapped (no regression vs before).case "$s" in- incremental) st="${CBM_SUITE_TIMEOUT_SLOW:-3600}" ;;+ incremental | store_arch) st="${CBM_SUITE_TIMEOUT_SLOW:-3600}" ;;*) st="${CBM_SUITE_TIMEOUT:-900}" ;;esacif command -v timeout >/dev/null 2>&1; thendiff --git a/scripts/smoke-test.sh b/scripts/smoke-test.shindex a36e8bc55..e02455bfd 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -1027,9 +1027,11 @@ ROVO_AGENT="$FAKE_HOME/.rovodev/subagents/codebase-memory.md"AMAZON_Q_MCP="$FAKE_HOME/.aws/amazonq/default.json"mkdir -p "$GITLAB_DIR" "$(dirname "$GITLAB_HOOKS")" "$DEVIN_DIR"mkdir -p "$FAKE_HOME/.local/bin"-# Copy binary with correct name for platform+# A Windows portable pair is the installer source, not a valid managed target.+# Leave the canonical destination absent so install can publish the authenticated+# generation backing + canonical hard-link pair. A one-link copy at that path is+# deliberately rejected as an unknown/conflicting installation.if [[ "$BINARY" == *.exe ]]; then- copy_smoke_binary "$FAKE_HOME/.local/bin/codebase-memory-mcp.exe"SELF_PATH="$FAKE_HOME/.local/bin/codebase-memory-mcp.exe"elsecp "$BINARY" "$FAKE_HOME/.local/bin/codebase-memory-mcp"@@ -2748,8 +2750,9 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; thenUPDATE_HOME=$(smoke_mktemp_dir)mkdir -p "$UPDATE_HOME/.claude" "$UPDATE_HOME/.local/bin"if [[ "$BINARY" == *.exe ]]; then- copy_smoke_binary "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"- chmod 755 "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"+ # Keep the managed canonical absent until WINDOWS_PAYLOAD installs the+ # authenticated two-link launcher layout below.+ :elsecp "$BINARY" "$UPDATE_HOME/.local/bin/codebase-memory-mcp"chmod 755 "$UPDATE_HOME/.local/bin/codebase-memory-mcp"diff --git a/scripts/soak-test.sh b/scripts/soak-test.shindex ab0dff778..784511147 100755--- a/scripts/soak-test.sh+++ b/scripts/soak-test.sh@@ -2,7 +2,8 @@# soak-test.sh — Endurance test for codebase-memory-mcp.## Runs compressed workload cycles: queries, file mutations, reindexes, idle periods.-# Reads diagnostics from /tmp/cbm-diagnostics-<pid>.json (requires CBM_DIAGNOSTICS=1).+# Reads the randomized diagnostics path emitted by the daemon (requires+# CBM_DIAGNOSTICS=1).# Outputs metrics to soak-results/ and exits 0 (pass) or 1 (fail).## Usage:@@ -37,13 +38,27 @@ CBM_SOAK_MODE="${CBM_SOAK_MODE:-default}"RESULTS_DIR="${RESULTS_DIR:-soak-results}"mkdir -p "$RESULTS_DIR"+# Isolate daemon coordination from interactive CBM sessions and give this run+# a deterministic host-side daemon log. Wine needs a Windows-form cache path+# in the child environment while this Bash harness retains the host path.+SOAK_CACHE_DIR_HOST=$(mktemp -d "${TMPDIR:-/tmp}/cbm-soak-cache.XXXXXX")+SOAK_CACHE_DIR_VALUE="$SOAK_CACHE_DIR_HOST"+if [[ "$BINARY" == *.exe ]] && command -v winepath >/dev/null 2>&1; then+ SOAK_CACHE_DIR_VALUE=$(winepath -w "$SOAK_CACHE_DIR_HOST")+elif [[ "$BINARY" == *.exe ]] && command -v cygpath >/dev/null 2>&1; then+ SOAK_CACHE_DIR_VALUE=$(cygpath -w "$SOAK_CACHE_DIR_HOST")+fi+DAEMON_LOG="$SOAK_CACHE_DIR_HOST/logs/cbm-daemon.log"+DIAG_FILE=""+METRICS_CSV="$RESULTS_DIR/metrics.csv"LATENCY_CSV="$RESULTS_DIR/latency.csv"SUMMARY="$RESULTS_DIR/summary.txt"echo "timestamp,uptime_s,rss_bytes,heap_committed,fd_count,query_count,query_max_us" > "$METRICS_CSV"echo "timestamp,tool,duration_ms,exit_code" > "$LATENCY_CSV"-> "$SUMMARY"+: > "$SUMMARY"+PASS=trueDURATION_S=$((DURATION_MIN * 60))@@ -52,6 +67,44 @@ echo "=== soak-test: binary=$BINARY duration=${DURATION_MIN}m mode=${CBM_SOAK_MO# ── Helper: generate realistic test project (~200 files) ─────────SOAK_PROJECT=$(mktemp -d)+SOAK_PROJECT_VALUE="$SOAK_PROJECT"+if [[ "$BINARY" == *.exe ]] && command -v winepath >/dev/null 2>&1; then+ SOAK_PROJECT_VALUE=$(winepath -w "$SOAK_PROJECT")+ SOAK_PROJECT_VALUE=${SOAK_PROJECT_VALUE//\\//}+elif [[ "$BINARY" == *.exe ]] && command -v cygpath >/dev/null 2>&1; then+ SOAK_PROJECT_VALUE=$(cygpath -m "$SOAK_PROJECT")+fi+# Every JSON request uses one pre-escaped spelling of the path. The Bash+# harness keeps SOAK_PROJECT in its host/MSYS form for file and Git operations,+# while a native Windows child receives the drive-letter form above.+SOAK_PROJECT_JSON=$(python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$SOAK_PROJECT_VALUE")+SERVER_PID=""+SERVER_IN=""+SERVER_OUT=""+SOAK_CLEANED=false++soak_cleanup() {+ if $SOAK_CLEANED; then+ return+ fi+ SOAK_CLEANED=true+ { exec 3>&-; } 2>/dev/null || true+ { exec 4<&-; } 2>/dev/null || true+ if [[ "${SERVER_PID:-}" =~ ^[0-9]+$ ]]; then+ kill "$SERVER_PID" 2>/dev/null || true+ wait "$SERVER_PID" 2>/dev/null || true+ SERVER_PID=""+ fi+ [ -z "${SERVER_IN:-}" ] || rm -f -- "$SERVER_IN"+ [ -z "${SERVER_OUT:-}" ] || rm -f -- "$SERVER_OUT"+ if [ -f "$DAEMON_LOG" ]; then+ cp "$DAEMON_LOG" "$RESULTS_DIR/cbm-daemon.log" 2>/dev/null || true+ fi+ rm -rf -- "$SOAK_PROJECT" "$SOAK_CACHE_DIR_HOST"+}++trap soak_cleanup EXIT+trap 'exit 130' INT TERMgenerate_project() {local root="$1"@@ -198,9 +251,68 @@ echo "OK: $FILE_COUNT files in test project"# Query ID counterQUERY_ID=1+MCP_LAST_RESPONSE=""# Send a JSON-RPC tool call to the running server via its stdin pipe.# Reads response from server stdout. Records latency.+json_rpc_response_ok() {+ local expected_id="$1"+ local response="$2"+ python3 -c '+import json+import sys++try:+ message = json.loads(sys.stdin.read())+ result = message.get("result") if isinstance(message, dict) else None+ ok = (+ isinstance(message, dict)+ and message.get("id") == int(sys.argv[1])+ and "error" not in message+ and "result" in message+ and not (isinstance(result, dict) and result.get("isError") is True)+ )+except (ValueError, TypeError):+ ok = False+sys.exit(0 if ok else 1)+' "$expected_id" <<<"$response"+}++# Read the authoritative project key from index_repository's nested text JSON.+# This mirrors the path canonicalization actually performed by CBM instead of+# guessing from a host/MSYS spelling that can differ on macOS and Windows.+mcp_response_project() {+ local response="$1"+ python3 -c '+import json+import sys++try:+ message = json.loads(sys.stdin.read())+ result = message.get("result", {})+ content = result.get("content", []) if isinstance(result, dict) else []+ project = ""+ for item in content:+ if isinstance(item, dict) and item.get("type") == "text":+ payload = json.loads(item.get("text", ""))+ candidate = payload.get("project") if isinstance(payload, dict) else None+ if isinstance(candidate, str) and candidate:+ project = candidate+ break+ if not project:+ raise ValueError("index response has no project")+ print(project)+except (ValueError, TypeError, AttributeError):+ sys.exit(1)+' <<<"$response"+}++mcp_initialize() {+ local response=""+ echo '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"capabilities":{}}}' >&3+ read -r -t 10 response <&4 2>/dev/null && json_rpc_response_ok 0 "$response"+}+mcp_call() {local tool="$1"local args="$2"@@ -214,29 +326,107 @@ mcp_call() {# Send request to server stdinecho "$req" >&3- # Read response (wait up to 30s)+ # Read and validate one response (wait up to 30s). A JSON-RPC error or+ # tool-level isError is a failed operation, not a successful round-trip.local resp=""- if read -t 30 resp <&4 2>/dev/null; then- local t1- t1=$(python3 -c "import time; print(int(time.time()*1000))")- local dur=$((t1 - t0))- echo "$(date +%s),$tool,$dur,0" >> "$LATENCY_CSV"- else- local t1- t1=$(python3 -c "import time; print(int(time.time()*1000))")- local dur=$((t1 - t0))- echo "$(date +%s),$tool,$dur,1" >> "$LATENCY_CSV"+ local exit_code=1+ MCP_LAST_RESPONSE=""+ if read -r -t 30 resp <&4 2>/dev/null; then+ MCP_LAST_RESPONSE="$resp"+ if json_rpc_response_ok "$id" "$resp"; then+ exit_code=0+ fifi+ local t1+ t1=$(python3 -c "import time; print(int(time.time()*1000))")+ local dur=$((t1 - t0))+ echo "$(date +%s),$tool,$dur,$exit_code" >> "$LATENCY_CSV"+ return "$exit_code"}# ── Helper: collect diagnostics snapshot ─────────────────────────+diagnostics_host_path() {+ local emitted_path="$1"+ if [[ "$emitted_path" =~ ^[A-Za-z]:[/\\] ]] && command -v winepath >/dev/null 2>&1; then+ winepath -u "$emitted_path"+ elif [[ "$emitted_path" =~ ^[A-Za-z]:[/\\] ]] && command -v cygpath >/dev/null 2>&1; then+ cygpath -u "$emitted_path"+ else+ printf '%s\n' "$emitted_path"+ fi+}++refresh_diagnostics_paths() {+ [ -f "$DAEMON_LOG" ] || return 1+ local start_line snapshot_path trajectory_path+ start_line=$(grep '"event":"diagnostics.start"' "$DAEMON_LOG" 2>/dev/null | tail -n 1) || true+ [ -n "$start_line" ] || return 1+ # The discovery record is JSON (a control record survives CBM_LOG_LEVEL+ # suppression); decode the two standard escapes temp paths can carry.+ snapshot_path=$(printf '%s\n' "$start_line" | sed -n 's/.*"snapshot":"\([^"]*\)".*/\1/p' |+ sed 's/\\\([\"\\/]\)/\1/g')+ trajectory_path=$(printf '%s\n' "$start_line" | sed -n 's/.*"trajectory":"\([^"]*\)".*/\1/p' |+ sed 's/\\\([\"\\/]\)/\1/g')+ [ -n "$snapshot_path" ] && [ -n "$trajectory_path" ] || return 1+ DIAG_FILE=$(diagnostics_host_path "$snapshot_path")+}++diagnostics_start_count() {+ if [ -f "$DAEMON_LOG" ]; then+ grep -c '"event":"diagnostics.start"' "$DAEMON_LOG" 2>/dev/null || true+ else+ echo 0+ fi+}++daemon_stop_count() {+ if [ -f "$DAEMON_LOG" ]; then+ grep -c 'msg=daemon.stop' "$DAEMON_LOG" 2>/dev/null || true+ else+ echo 0+ fi+}++wait_for_daemon_stop() {+ local after_count="$1"+ local attempts=300+ while [ "$attempts" -gt 0 ]; do+ local current_count+ current_count=$(daemon_stop_count)+ if [ "${current_count:-0}" -gt "$after_count" ]; then+ return 0+ fi+ attempts=$((attempts - 1))+ sleep 0.1+ done+ return 1+}++wait_for_diagnostics_snapshot() {+ local after_count="${1:-0}"+ local previous_path="${2:-}"+ local attempts=100+ while [ "$attempts" -gt 0 ]; do+ local current_count+ current_count=$(diagnostics_start_count)+ if [ "${current_count:-0}" -gt "$after_count" ] && refresh_diagnostics_paths &&+ [ -f "$DIAG_FILE" ] &&+ { [ -z "$previous_path" ] || [ "$DIAG_FILE" != "$previous_path" ]; }; then+ return 0+ fi+ attempts=$((attempts - 1))+ sleep 0.1+ done+ return 1+}+collect_snapshot() {- local diag_file="/tmp/cbm-diagnostics-${SERVER_PID}.json"- if [ -f "$diag_file" ]; then+ refresh_diagnostics_paths || return 0+ if [ -f "$DIAG_FILE" ]; thenpython3 -c "import json, time-d = json.load(open('$diag_file'))+d = json.load(open('$DIAG_FILE'))# Use heap_committed if available, otherwise RSS (mimalloc may report 0 for committed)mem = d.get('heap_committed_bytes', 0)if mem == 0: mem = d.get('rss_bytes', 0)@@ -245,6 +435,19 @@ print(f\"{int(time.time())},{d.get('uptime_s',0)},{d.get('rss_bytes',0)},{mem},{fi}+diagnostics_json_value() {+ local key="$1"+ refresh_diagnostics_paths || return 1+ python3 -c '+import json+import sys++with open(sys.argv[1], encoding="utf-8") as stream:+ value = json.load(stream).get(sys.argv[2], "")+print(value)+' "$DIAG_FILE" "$key" 2>/dev/null+}+# ── Phase 1: Start MCP server with diagnostics ──────────────────echo "--- Phase 1: start server ---"@@ -253,7 +456,9 @@ SERVER_IN=$(mktemp -u).inSERVER_OUT=$(mktemp -u).outmkfifo "$SERVER_IN" "$SERVER_OUT"-CBM_DIAGNOSTICS=1 "$BINARY" < "$SERVER_IN" > "$SERVER_OUT" 2>"$RESULTS_DIR/server-stderr.log" &+CBM_CACHE_DIR="$SOAK_CACHE_DIR_VALUE" CBM_DIAGNOSTICS=1 CBM_LOG_LEVEL=info \+ CBM_LOG_FORMAT=text "$BINARY" < "$SERVER_IN" > "$SERVER_OUT" \+ 2>"$RESULTS_DIR/server-stderr.log" &SERVER_PID=$!# Open fds AFTER server starts (otherwise fifo blocks)@@ -269,21 +474,32 @@ if ! kill -0 "$SERVER_PID" 2>/dev/null; thenfiecho "OK: server running (pid=$SERVER_PID)"-# Send initialize handshake-echo '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"capabilities":{}}}' >&3-read -t 10 INIT_RESP <&4 || true+if ! wait_for_diagnostics_snapshot; then+ echo "FAIL: daemon did not emit a usable diagnostics.start path"+ exec 3>&- 4<&-+ kill "$SERVER_PID" 2>/dev/null || true+ wait "$SERVER_PID" 2>/dev/null || true+ rm -f "$SERVER_IN" "$SERVER_OUT"+ exit 1+fi++# Send and validate the initialize handshake.+if ! mcp_initialize; then+ echo "FAIL: server did not complete initialize"+ exit 1+fi# ── Phase 2: Initial index ───────────────────────────────────────echo "--- Phase 2: initial index ---"-mcp_call index_repository "{\"repo_path\":\"$SOAK_PROJECT\"}"+mcp_call index_repository "{\"repo_path\":$SOAK_PROJECT_JSON}" || PASS=false+if ! PROJ_NAME=$(mcp_response_project "$MCP_LAST_RESPONSE"); then+ echo "FAIL: initial index response did not report its canonical project key"+ exit 1+fisleep 6 # wait for diagnostics writecollect_snapshot-# Derive project name (same logic as cbm_project_name_from_path)-PROJ_NAME=$(echo "$SOAK_PROJECT" | sed 's|^/||; s|/|-|g')--DIAG_FILE="/tmp/cbm-diagnostics-${SERVER_PID}.json"BASELINE_RSS=$(cat "$DIAG_FILE" 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('rss_bytes',0))" 2>/dev/null || echo "0")BASELINE_FDS=$(cat "$DIAG_FILE" 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('fd_count',0))" 2>/dev/null || echo "0")echo "OK: baseline RSS=${BASELINE_RSS} FDs=${BASELINE_FDS}"@@ -307,16 +523,16 @@ while [ "$(date +%s)" -lt "$END_TIME" ]; do# cbm_mem_collect (mimalloc page return) is NEVER triggered and# cannot sweep a query-only leak. Hammer a VARIETY of read tools to# exercise the store-open + WAL + alloc paths the report implicates.- mcp_call search_graph "{\"project\":\"$PROJ_NAME\",\"name_pattern\":\".*Handle.*\"}"- mcp_call query_graph "{\"project\":\"$PROJ_NAME\",\"query\":\"MATCH (n) RETURN n.name LIMIT 25\"}"- mcp_call trace_path "{\"project\":\"$PROJ_NAME\",\"function_name\":\"handle_1\",\"direction\":\"both\"}"- mcp_call get_code_snippet "{\"project\":\"$PROJ_NAME\",\"qualified_name\":\"handle_1\"}"- mcp_call search_code "{\"project\":\"$PROJ_NAME\",\"pattern\":\"def \"}"+ mcp_call search_graph "{\"project\":\"$PROJ_NAME\",\"name_pattern\":\".*Handle.*\"}" || PASS=false+ mcp_call query_graph "{\"project\":\"$PROJ_NAME\",\"query\":\"MATCH (n) RETURN n.name LIMIT 25\"}" || PASS=false+ mcp_call trace_path "{\"project\":\"$PROJ_NAME\",\"function_name\":\"handle_1\",\"direction\":\"both\"}" || PASS=false+ mcp_call get_code_snippet "{\"project\":\"$PROJ_NAME\",\"qualified_name\":\"handle_1\"}" || PASS=false+ mcp_call search_code "{\"project\":\"$PROJ_NAME\",\"pattern\":\"def \"}" || PASS=falseelse# ── default mode (unchanged) ─────────────────────────────────# Queries every 2 seconds- mcp_call search_graph "{\"project\":\"$PROJ_NAME\",\"name_pattern\":\".*compute.*\"}"- mcp_call trace_path "{\"project\":\"$PROJ_NAME\",\"function_name\":\"compute\",\"direction\":\"both\"}"+ mcp_call search_graph "{\"project\":\"$PROJ_NAME\",\"name_pattern\":\".*handle_.*\"}" || PASS=false+ mcp_call trace_path "{\"project\":\"$PROJ_NAME\",\"function_name\":\"handle_1\",\"direction\":\"both\"}" || PASS=false# File mutation every 2 minutesif [ $((NOW - LAST_MUTATE)) -ge 120 ]; then@@ -328,7 +544,7 @@ while [ "$(date +%s)" -lt "$END_TIME" ]; do# Full reindex every 2 minutes (compressed — simulates 15min real interval)if [ $((NOW - LAST_REINDEX)) -ge 120 ]; then- mcp_call index_repository "{\"repo_path\":\"$SOAK_PROJECT\"}"+ mcp_call index_repository "{\"repo_path\":$SOAK_PROJECT_JSON}" || PASS=falseLAST_REINDEX=$NOWfifi@@ -347,9 +563,17 @@ echo "--- Phase 4: idle (30s) ---"sleep 30collect_snapshot-# Check idle CPU-IDLE_CPU=$(ps -o %cpu= -p "$SERVER_PID" 2>/dev/null | tr -d ' ' || echo "0")-echo "OK: idle CPU=${IDLE_CPU}%"+# Check the actual daemon on platforms where its diagnostics PID shares the+# host process namespace. Wine/native Windows use a different PID namespace,+# so reporting the thin frontend as daemon CPU would be false coverage.+DAEMON_PID=$(diagnostics_json_value pid)+IDLE_CPU=""+if [[ "$BINARY" != *.exe ]] && [[ "$DAEMON_PID" =~ ^[0-9]+$ ]]; then+ IDLE_CPU=$(ps -o %cpu= -p "$DAEMON_PID" 2>/dev/null | tr -d ' ' || true)+ echo "OK: idle daemon CPU=${IDLE_CPU:-unavailable}%"+else+ echo "SKIP: idle daemon CPU is unavailable across the Windows PID boundary"+fi# ── Phase 5: Crash recovery test ────────────────────────────────# Skipped in query-leak mode: crash recovery re-indexes (Phase 5 calls@@ -359,27 +583,50 @@ echo "OK: idle CPU=${IDLE_CPU}%"if [ "$SKIP_CRASH" != "--skip-crash-test" ] && [ "$CBM_SOAK_MODE" != "query-leak" ]; thenecho "--- Phase 5: crash recovery ---"- # Kill server mid-operation, restart, verify clean index- mcp_call index_repository "{\"repo_path\":\"$SOAK_PROJECT\"}"+ # Hand an indexing request to the frontend, then kill it without consuming+ # the response. The last-session disconnect must cancel session work and+ # let the account daemon terminate before a clean restart.+ DIAGNOSTICS_START_COUNT=$(diagnostics_start_count)+ DAEMON_STOP_COUNT=$(daemon_stop_count)+ DIAG_FILE_BEFORE_CRASH="$DIAG_FILE"+ crash_id=$QUERY_ID+ QUERY_ID=$((QUERY_ID + 1))+ echo "{\"jsonrpc\":\"2.0\",\"id\":$crash_id,\"method\":\"tools/call\",\"params\":{\"name\":\"index_repository\",\"arguments\":{\"repo_path\":$SOAK_PROJECT_JSON}}}" >&3+ sleep 0.1kill -9 "$SERVER_PID" 2>/dev/null || truewait "$SERVER_PID" 2>/dev/null || true+ SERVER_PID=""exec 3>&- 4<&-+ if ! wait_for_daemon_stop "$DAEMON_STOP_COUNT"; then+ echo "FAIL: last-session crash did not stop the shared daemon"+ exit 1+ fi# Restart server- CBM_DIAGNOSTICS=1 "$BINARY" < "$SERVER_IN" > "$SERVER_OUT" 2>>"$RESULTS_DIR/server-stderr.log" &+ CBM_CACHE_DIR="$SOAK_CACHE_DIR_VALUE" CBM_DIAGNOSTICS=1 CBM_LOG_LEVEL=info \+ CBM_LOG_FORMAT=text "$BINARY" < "$SERVER_IN" > "$SERVER_OUT" \+ 2>>"$RESULTS_DIR/server-stderr.log" &SERVER_PID=$!exec 3>"$SERVER_IN"exec 4<"$SERVER_OUT"sleep 3if kill -0 "$SERVER_PID" 2>/dev/null; then+ if ! wait_for_diagnostics_snapshot "$DIAGNOSTICS_START_COUNT" "$DIAG_FILE_BEFORE_CRASH"; then+ echo "FAIL: frontend restart did not start a fresh daemon diagnostics generation"+ exit 1+ fiecho "OK: server restarted after kill -9"- echo '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"capabilities":{}}}' >&3- read -t 10 INIT_RESP <&4 || true+ if ! mcp_initialize; then+ echo "FAIL: restarted server did not complete initialize"+ PASS=false+ fi# Verify clean re-index works- mcp_call index_repository "{\"repo_path\":\"$SOAK_PROJECT\"}"- echo "OK: clean re-index after crash recovery"+ mcp_call index_repository "{\"repo_path\":$SOAK_PROJECT_JSON}" || PASS=false+ if $PASS; then+ echo "OK: clean re-index after crash recovery"+ fielseecho "FAIL: server did not restart after kill -9"PASS=false@@ -389,20 +636,20 @@ fi# ── Phase 6: Shutdown + analysis ─────────────────────────────────echo "--- Phase 6: shutdown + analysis ---"+FINAL_DAEMON_STOP_COUNT=$(daemon_stop_count)exec 3>&- # close server stdin → EOF → clean exitsleep 2exec 4<&- # close stdout readerkill "$SERVER_PID" 2>/dev/null || truewait "$SERVER_PID" 2>/dev/null || true-rm -f "$SERVER_IN" "$SERVER_OUT"--# Final diagnostics (written by thread before exit)-FINAL_DIAG="/tmp/cbm-diagnostics-${SERVER_PID}.json"+SERVER_PID=""+if ! wait_for_daemon_stop "$FINAL_DAEMON_STOP_COUNT"; then+ echo "FAIL: final frontend shutdown did not stop the shared daemon"+ PASS=false+fi# ── Analysis ─────────────────────────────────────────────────────-PASS=true-# Check 1: Memory leak detection via RSS trend# This is the primary leak detector on ALL platforms (including Windows# where LeakSanitizer is unavailable). Catches both linear leaks (slope)@@ -456,12 +703,16 @@ if [ "${FD_DRIFT:-0}" -gt 20 ] 2>/dev/null; thenPASS=falsefi-# Check 3: Idle CPU-IDLE_INT=$(echo "$IDLE_CPU" | cut -d. -f1)-echo "Idle CPU: ${IDLE_CPU}%" | tee -a "$SUMMARY"-if [ "${IDLE_INT:-0}" -gt 5 ] 2>/dev/null; then- echo "FAIL: idle CPU ${IDLE_CPU}% > 5%" | tee -a "$SUMMARY"- PASS=false+# Check 3: Idle daemon CPU (where the PID is host-addressable)+if [ -n "$IDLE_CPU" ]; then+ IDLE_INT=$(echo "$IDLE_CPU" | cut -d. -f1)+ echo "Idle daemon CPU: ${IDLE_CPU}%" | tee -a "$SUMMARY"+ if [ "${IDLE_INT:-0}" -gt 5 ] 2>/dev/null; then+ echo "FAIL: idle daemon CPU ${IDLE_CPU}% > 5%" | tee -a "$SUMMARY"+ PASS=false+ fi+else+ echo "Idle daemon CPU: unavailable on Windows (not evaluated)" | tee -a "$SUMMARY"fi# Check 4: Max query latency (exclude index_repository — indexing is legitimately slow)@@ -480,7 +731,8 @@ echo "Total queries: $TOTAL_QUERIES" | tee -a "$SUMMARY"# ── Cleanup ──────────────────────────────────────────────────────-rm -rf "$SOAK_PROJECT"+soak_cleanup+trap - EXIT INT TERMecho ""if $PASS; thendiff --git a/scripts/test-windows.ps1 b/scripts/test-windows.ps1index 06d0f79b5..50188649a 100644--- a/scripts/test-windows.ps1+++ b/scripts/test-windows.ps1@@ -28,11 +28,10 @@* (none currently - test_cli_non_ascii_arg.py was promoted to aguard when the wide-argv fix for #423/#20 landed)- Determinism: the runner sets CBM_INDEX_SUPERVISOR=0 so the path / hook / drive- guards index in-process (the pass-level readers under test, e.g. #700's cbm_fopen- routing, run in-process either way). The non-ASCII CLI guard is the exception - it- drops that override to cross the real supervisor -> worker spawn, where the second- half of #423/#20 lives (CreateProcessW delivering the wide command line).+ Indexing runs through the real supervisor -> worker spawn on every guard:+ under the mandatory coordination daemon CBM_INDEX_SUPERVISOR=0 is a+ fail-closed refusal seam, never an in-process fallback, so the old+ determinism override would turn every indexing guard into a refusal.On native Windows the MinGW/LLVM toolchain ships no libasan/libubsan, so thebuild disables sanitizers (SANITIZE=). Where the toolchain provides@@ -188,7 +187,6 @@ try {$env:TMP = $guardRoot$env:TMPDIR = $guardRoot$env:PYTHONUTF8 = "1" # encode argv/stdio as UTF-8- $env:CBM_INDEX_SUPERVISOR = "0" # in-process indexing (see .DESCRIPTION)# Green regression guards - must stay GREEN (exit 0). RED (exit 1) = the fix for# the referenced issue regressed. The drive-picker guard needs the embedded HTTP@@ -197,6 +195,7 @@ try {$guards = @("tests\windows\test_non_ascii_path.py","tests\windows\test_non_ascii_cache_dump.py",+ "tests\windows\test_daemon_lifecycle.py","tests\windows\test_hook_augment.py","tests\windows\test_ui_drive_listing.py","tests\windows\test_cli_non_ascii_arg.py",diff --git a/scripts/test.sh b/scripts/test.shindex 3e1acc624..ec79ca816 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -37,6 +37,8 @@ done# shellcheck source=env.shsource "$ROOT/scripts/env.sh"+# shellcheck source=path-safety.sh+source "$ROOT/scripts/path-safety.sh"# Forward CC/CXX and collect make-passthrough args. BUILD_DIR is honored for# the explicit target path below so containerized legs can build in their own@@ -58,16 +60,25 @@ print_env "test.sh"# Step 0: fast build/security harness regressions run before the compiler-heavy# suite. The Windows package surface is static here; native launcher behavior is# exercised by scripts/test-windows.ps1.-echo "=== Step 0a: Windows launcher bundle contract ==="-bash "$ROOT/tests/test_windows_bundle_contract.sh"+echo "=== Step 0a: build directory safety contract ==="+bash "$ROOT/tests/test_build_dir_safety.sh"echo "=== Step 0b: Windows VM worktree sync contract ==="bash "$ROOT/tests/test_vm_worktree_manifest.sh"-echo "=== Step 0c: tree-sitter runtime Makefile dependencies ==="+echo "=== Step 0c: UI development proxy security contract ==="+bash "$ROOT/tests/test_ui_dev_proxy_security.sh"++echo "=== Step 0d: daemon soak recovery contract ==="+bash "$ROOT/tests/test_soak_daemon_recovery_contract.sh"++echo "=== Step 0e: Windows launcher bundle contract ==="+bash "$ROOT/tests/test_windows_bundle_contract.sh"++echo "=== Step 0f: tree-sitter runtime Makefile dependencies ==="bash "$ROOT/tests/test_makefile_ts_runtime_dependencies.sh"-echo "=== Step 0d: security fuzz harness self-test ==="+echo "=== Step 0g: security fuzz harness self-test ==="bash "$ROOT/tests/test_security_fuzz_harness.sh"# Verify compiler supports target archdiff --git a/src/cli/activation_transaction.c b/src/cli/activation_transaction.cindex b896080d6..269acacaa 100644--- a/src/cli/activation_transaction.c+++ b/src/cli/activation_transaction.c@@ -9,6 +9,7 @@#include <stdio.h>#include <stdlib.h>#include <string.h>+#include <wchar.h>#include <sys/stat.h>#ifdef _WIN32@@ -188,11 +189,20 @@ static char *activation_unique_path(const char *directory, const char *tag) {if (!path) {return NULL;}- int written = snprintf(- path, needed, "%s%s.cbm-%s-%lu-%" PRIu64, directory,- directory[directory_length - 1U] == '/' || directory[directory_length - 1U] == '\\' ? ""- : "/",- tag, process_id, sequence);+ /* Windows joins use the backslash: extended-length (\\\\?\\) directories+ * reach this composer and that namespace performs no forward-slash+ * translation. POSIX keeps the slash. */+#ifdef _WIN32+ const char *separator = "\\";+#else+ const char *separator = "/";+#endif+ int written =+ snprintf(path, needed, "%s%s.cbm-%s-%lu-%" PRIu64, directory,+ directory[directory_length - 1U] == '/' || directory[directory_length - 1U] == '\\'+ ? ""+ : separator,+ tag, process_id, sequence);if (written <= 0 || (size_t)written >= needed) {free(path);return NULL;@@ -220,7 +230,7 @@ typedef struct {SECURITY_ATTRIBUTES attributes;} activation_windows_security_t;-static wchar_t *activation_utf8_to_wide(const char *value) {+static wchar_t *activation_utf8_to_wide_plain(const char *value) {if (!value) {return NULL;}@@ -236,6 +246,41 @@ static wchar_t *activation_utf8_to_wide(const char *value) {return wide;}+/* File-API path conversion: an absolute drive path beyond the legacy limit is+ * canonicalized and given the extended-length \\?\ prefix so every Win32+ * file call accepts it. Managed-install generation stores and CI-runner paths+ * routinely exceed 260 chars; the prefix also disables the \.\..\ and+ * MAX_PATH parsing that the ancestry validator separately enforces. Non-file+ * strings must not use this. */+static wchar_t *activation_utf8_to_wide(const char *value) {+ wchar_t *wide = activation_utf8_to_wide_plain(value);+ if (!wide) {+ return NULL;+ }+ size_t length = wcslen(wide);+ bool drive_absolute =+ length >= 3 &&+ ((wide[0] >= L'A' && wide[0] <= L'Z') || (wide[0] >= L'a' && wide[0] <= L'z')) &&+ wide[1] == L':' && (wide[2] == L'\\' || wide[2] == L'/');+ if (!drive_absolute || length < 240U) {+ return wide;+ }+ DWORD needed = GetFullPathNameW(wide, 0, NULL, NULL);+ wchar_t *prefixed = needed > 0 ? malloc(((size_t)needed + 5U) * sizeof(*prefixed)) : NULL;+ if (!prefixed) {+ free(wide);+ return NULL;+ }+ wmemcpy(prefixed, L"\\\\?\\", 4);+ DWORD copied = GetFullPathNameW(wide, needed, prefixed + 4, NULL);+ free(wide);+ if (copied == 0 || copied >= needed) {+ free(prefixed);+ return NULL;+ }+ return prefixed;+}+static bool activation_windows_user(void **information_out, PSID *sid_out) {*information_out = NULL;*sid_out = NULL;@@ -318,6 +363,32 @@ static void activation_windows_security_destroy(activation_windows_security_t *smemset(security, 0, sizeof(*security));}+/* Trusted-owner acceptance for SOURCE-side objects: a downloaded release+ * bundle is owned by whatever the machine's default-owner policy dictates+ * (Administrators on GitHub-runner-class images). Its integrity is enforced+ * by identity snapshot/recheck plus the caller's build-fingerprint check,+ * not by exact ownership. Staging targets created by this transaction keep+ * the exact-current-owner rule. */+static bool activation_windows_owner_is_trusted(HANDLE handle) {+ void *information = NULL;+ PSID user_sid = NULL;+ if (!activation_windows_user(&information, &user_sid)) {+ return false;+ }+ PSID owner = NULL;+ PSECURITY_DESCRIPTOR descriptor = NULL;+ DWORD result = GetSecurityInfo(handle, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &owner, NULL,+ NULL, NULL, &descriptor);+ bool trusted = result == ERROR_SUCCESS && owner && IsValidSid(owner) &&+ (EqualSid(owner, user_sid) || IsWellKnownSid(owner, WinLocalSystemSid) ||+ IsWellKnownSid(owner, WinBuiltinAdministratorsSid));+ if (descriptor) {+ (void)LocalFree(descriptor);+ }+ free(information);+ return trusted;+}+static bool activation_windows_owner_is_current(HANDLE handle) {void *information = NULL;PSID user_sid = NULL;@@ -336,7 +407,13 @@ static bool activation_windows_owner_is_current(HANDLE handle) {return same;}+static bool activation_windows_acl_check(HANDLE handle, DWORD tolerated_untrusted_mask);+static bool activation_windows_acl_secure(HANDLE handle) {+ return activation_windows_acl_check(handle, 0U);+}++static bool activation_windows_acl_check(HANDLE handle, DWORD tolerated_untrusted_mask) {void *information = NULL;PSID user_sid = NULL;if (!activation_windows_user(&information, &user_sid)) {@@ -389,7 +466,7 @@ static bool activation_windows_acl_secure(HANDLE handle) {break;}ACCESS_ALLOWED_ACE *ace = opaque_ace;- if ((ace->Mask & mutation_rights) == 0) {+ if ((ace->Mask & mutation_rights & ~tolerated_untrusted_mask) == 0) {continue;}PSID sid = (PSID)&ace->SidStart;@@ -398,7 +475,12 @@ static bool activation_windows_acl_secure(HANDLE handle) {bool trusted = sid_length <= sid_capacity && IsValidSid(sid) &&GetLengthSid(sid) == sid_length &&(EqualSid(sid, user_sid) || IsWellKnownSid(sid, WinLocalSystemSid) ||- IsWellKnownSid(sid, WinBuiltinAdministratorsSid));+ IsWellKnownSid(sid, WinBuiltinAdministratorsSid) ||+ /* OWNER RIGHTS modulates whoever owns the object; the+ * owner is separately validated in every chain that+ * reaches here (same tolerance as the daemon IPC and+ * launcher ancestry validators). */+ IsWellKnownSid(sid, WinCreatorOwnerRightsSid));if (!trusted) {secure = false;}@@ -429,13 +511,20 @@ static bool activation_windows_identity(HANDLE handle, activation_file_identity_}static HANDLE activation_windows_directory_open_no_reparse(const char *directory) {- wchar_t *input = activation_utf8_to_wide(directory);+ /* Canonicalize on the PLAIN wide form so GetFullPathNameW resolves any+ * \.\..\ and slash forms; each ancestor is then opened through the+ * extended-length prefix so a deep component past MAX_PATH still opens. */+ wchar_t *input = activation_utf8_to_wide_plain(directory);if (!input) {return INVALID_HANDLE_VALUE;}- DWORD needed = GetFullPathNameW(input, 0, NULL, NULL);+ /* Managed-install callers hand in extended-length paths already; drop+ * their prefix for canonicalization and the drive-shape check below —+ * the component walk re-adds it for every open. */+ wchar_t *shape = wcsncmp(input, L"\\\\?\\", 4) == 0 ? input + 4 : input;+ DWORD needed = GetFullPathNameW(shape, 0, NULL, NULL);wchar_t *path = needed > 0 ? calloc((size_t)needed + 1U, sizeof(*path)) : NULL;- DWORD length = path ? GetFullPathNameW(input, needed + 1U, path, NULL) : 0;+ DWORD length = path ? GetFullPathNameW(shape, needed + 1U, path, NULL) : 0;free(input);if (!path || length < 3 || length > needed || path[1] != L':' ||(path[2] != L'\\' && path[2] != L'/')) {@@ -447,22 +536,31 @@ static HANDLE activation_windows_directory_open_no_reparse(const char *directorypath[index] = L'\\';}}+ /* prefixed = \\?\ + canonical path; each open truncates this buffer. */+ wchar_t *prefixed = malloc(((size_t)length + 5U) * sizeof(*prefixed));+ if (!prefixed) {+ free(path);+ return INVALID_HANDLE_VALUE;+ }+ wmemcpy(prefixed, L"\\\\?\\", 4);+ wmemcpy(prefixed + 4, path, (size_t)length + 1U);HANDLE final_handle = INVALID_HANDLE_VALUE;for (DWORD boundary = 3; boundary <= length; boundary++) {if (boundary < length && path[boundary] != L'\\') {continue;}if (boundary < length && boundary > 0 && path[boundary - 1] == L'\\') {+ free(prefixed);free(path);return INVALID_HANDLE_VALUE;}- wchar_t saved = path[boundary];- path[boundary] = L'\0';+ wchar_t saved = prefixed[boundary + 4U];+ prefixed[boundary + 4U] = L'\0';HANDLE handle =- CreateFileW(path, FILE_READ_ATTRIBUTES | READ_CONTROL,+ CreateFileW(prefixed, FILE_READ_ATTRIBUTES | READ_CONTROL,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);- path[boundary] = saved;+ prefixed[boundary + 4U] = saved;BY_HANDLE_FILE_INFORMATION information;bool valid = handle != INVALID_HANDLE_VALUE && GetFileType(handle) == FILE_TYPE_DISK &&GetFileInformationByHandle(handle, &information) &&@@ -472,6 +570,7 @@ static HANDLE activation_windows_directory_open_no_reparse(const char *directoryif (handle != INVALID_HANDLE_VALUE) {(void)CloseHandle(handle);}+ free(prefixed);free(path);return INVALID_HANDLE_VALUE;}@@ -481,24 +580,50 @@ static HANDLE activation_windows_directory_open_no_reparse(const char *directory(void)CloseHandle(handle);}}+ free(prefixed);free(path);return final_handle;}+/* SOURCE-side directory rule: trusted owner, and cross-account grants are+ * tolerated only for pure add rights (FILE_ADD_FILE/FILE_ADD_SUBDIRECTORY,+ * standard on Downloads-class locations) — they cannot modify the existing+ * source file, whose bytes are pinned by identity recheck plus the staged+ * copy's build-fingerprint validation. */+static bool activation_source_directory_secure(const char *directory,+ activation_file_identity_t *identity_out) {+ HANDLE handle = activation_windows_directory_open_no_reparse(directory);+ BY_HANDLE_FILE_INFORMATION information;+ bool open_ok = handle != INVALID_HANDLE_VALUE &&+ GetFileInformationByHandle(handle, &information) &&+ (information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&+ (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&+ activation_windows_identity(handle, identity_out, false);+ bool owner_ok = open_ok && activation_windows_owner_is_trusted(handle);+ bool acl_ok = owner_ok && activation_windows_acl_check(+ handle, FILE_ADD_FILE | (DWORD)FILE_ADD_SUBDIRECTORY);+ if (handle != INVALID_HANDLE_VALUE) {+ (void)CloseHandle(handle);+ }+ return acl_ok;+}+static bool activation_directory_secure(const char *directory, int *unused,activation_file_identity_t *identity_out) {(void)unused;HANDLE handle = activation_windows_directory_open_no_reparse(directory);BY_HANDLE_FILE_INFORMATION information;- bool ok = handle != INVALID_HANDLE_VALUE && GetFileInformationByHandle(handle, &information) &&- (information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&- (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&- activation_windows_identity(handle, identity_out, false) &&- activation_windows_owner_is_current(handle) && activation_windows_acl_secure(handle);+ bool open_ok = handle != INVALID_HANDLE_VALUE &&+ GetFileInformationByHandle(handle, &information) &&+ (information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&+ (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&+ activation_windows_identity(handle, identity_out, false);+ bool owner_ok = open_ok && activation_windows_owner_is_current(handle);+ bool acl_ok = owner_ok && activation_windows_acl_secure(handle);if (handle != INVALID_HANDLE_VALUE) {(void)CloseHandle(handle);}- return ok;+ return acl_ok;}#else@@ -807,8 +932,9 @@ static cbm_activation_transaction_status_t activation_create_unique(}#ifdef _WIN32-static bool activation_external_snapshot(const char *path, bool *exists_out,- activation_file_identity_t *identity_out) {+static bool activation_external_snapshot_with_owner(const char *path, bool require_current_owner,+ bool *exists_out,+ activation_file_identity_t *identity_out) {*exists_out = false;wchar_t *wide = activation_utf8_to_wide(path);if (!wide) {@@ -828,9 +954,11 @@ static bool activation_external_snapshot(const char *path, bool *exists_out,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);free(wide);- bool valid =- handle != INVALID_HANDLE_VALUE && activation_windows_identity(handle, identity_out, true) &&- activation_windows_owner_is_current(handle) && activation_windows_acl_secure(handle);+ bool valid = handle != INVALID_HANDLE_VALUE &&+ activation_windows_identity(handle, identity_out, true) &&+ (require_current_owner ? activation_windows_owner_is_current(handle)+ : activation_windows_owner_is_trusted(handle)) &&+ activation_windows_acl_secure(handle);if (handle != INVALID_HANDLE_VALUE) {(void)CloseHandle(handle);}@@ -889,7 +1017,7 @@ static bool activation_entry_snapshot(const cbm_activation_transaction_t *transaactivation_file_identity_t *identity_out) {#ifdef _WIN32return activation_directory_still_valid(transaction) &&- activation_external_snapshot(path, exists_out, identity_out);+ activation_external_snapshot_with_owner(path, true, exists_out, identity_out);#else(void)path;return activation_posix_entry_snapshot_with_links(transaction, name, (nlink_t)1, exists_out,@@ -1075,6 +1203,8 @@ static cbm_activation_transaction_status_t activation_transaction_prepare(}if (!activation_entry_snapshot(transaction, transaction->target_path, transaction->target_name,&transaction->target_existed, &transaction->target_identity)) {+#ifdef _WIN32+#endifactivation_transaction_destroy(transaction);return CBM_ACTIVATION_TRANSACTION_IO;}@@ -1150,12 +1280,18 @@ static bool activation_source_open(const char *path, activation_native_file_t *freturn false;}#ifdef _WIN32- int ignored = 0;activation_file_identity_t directory_identity;activation_file_identity_t expected;bool exists = false;- if (!activation_directory_secure(directory, &ignored, &directory_identity) ||- !activation_external_snapshot(path, &exists, &expected) || !exists) {+ bool src_dir_ok = activation_source_directory_secure(directory, &directory_identity);+ /* The source (a downloaded release bundle) follows the machine's+ * default-owner policy; its bytes are pinned by identity recheck plus the+ * staged copy's build-fingerprint validation, so a trusted owner+ * (user/Administrators/SYSTEM) is sufficient here. Targets keep the+ * exact-current-owner rule. */+ bool snapshot_ok =+ src_dir_ok && activation_external_snapshot_with_owner(path, false, &exists, &expected);+ if (!src_dir_ok || !snapshot_ok || !exists) {free(directory);free(name);return false;@@ -1174,9 +1310,9 @@ static bool activation_source_open(const char *path, activation_native_file_t *factivation_file_identity_t actual;activation_file_identity_t directory_now;bool valid = file != INVALID_HANDLE_VALUE && activation_windows_identity(file, &actual, true) &&- activation_windows_owner_is_current(file) && activation_windows_acl_secure(file) &&+ activation_windows_owner_is_trusted(file) && activation_windows_acl_secure(file) &&activation_identity_equal(&actual, &expected) &&- activation_directory_secure(directory, &ignored, &directory_now) &&+ activation_source_directory_secure(directory, &directory_now) &&activation_identity_equal(&directory_now, &directory_identity);if (!valid) {if (file != INVALID_HANDLE_VALUE) {diff --git a/src/cli/cli.c b/src/cli/cli.cindex 8b7d94868..b9b00f4ef 100644--- a/src/cli/cli.c+++ b/src/cli/cli.c@@ -199,6 +199,9 @@ static const char *g_cli_activation_runtime_parent_for_test = NULL;static cbm_windows_launcher_context_t g_windows_launcher_context;static bool cli_windows_current_path(const wchar_t *canonical_launcher,wchar_t out[CBM_WINDOWS_LAUNCHER_PATH_CAP]);+static bool cli_windows_read_current(const wchar_t *canonical_launcher,+ cbm_windows_current_v1_t *state_out, bool *exists_out);+static bool cli_windows_canonicalize_launcher_path(wchar_t path[CBM_WINDOWS_LAUNCHER_PATH_CAP]);static bool cli_windows_current_process_size(uint64_t *size_out) {if (!size_out) {@@ -316,6 +319,13 @@ int cbm_cli_windows_launcher_startup_authenticate(int argc, char *const argv[])error[0] ? error : "authority acknowledgement failed");return CLI_TRUE;}+ if (context.canonical_launcher_path[0] != L'\0' &&+ !cli_windows_canonicalize_launcher_path(context.canonical_launcher_path)) {+ (void)cbm_windows_launcher_context_complete(&context, false, error, sizeof(error));+ (void)fprintf(stderr, "codebase-memory-mcp: managed Windows launcher path could not "+ "be canonicalized; startup refused\n");+ return CLI_TRUE;+ }g_windows_launcher_context = context;return CLI_OK;}@@ -5685,9 +5695,56 @@ static int cli_ensure_windows_user_path(const char *bin_dir, bool dry_run) {return CLI_OK;}+/* Canonical, file-API-safe wide form: full resolution plus the extended-length+ * prefix once the resolved path nears the legacy MAX_PATH limit (240, matching+ * the activation and foundation converters). Every derived install path+ * (generations, state, patterns) inherits the prefix from its root, which+ * keeps hardlink-identity and backing comparisons form-consistent. */+static bool cli_windows_canonicalize_launcher_path(wchar_t path[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {+ if (!path || !path[0]) {+ return false;+ }+ wchar_t resolved[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ DWORD length = GetFullPathNameW(path, CBM_WINDOWS_LAUNCHER_PATH_CAP, resolved, NULL);+ if (length == 0 || length >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return false;+ }+ bool already_prefixed = wcsncmp(resolved, L"\\\\?\\", 4) == 0;+ bool drive_absolute = !already_prefixed &&+ ((resolved[0] >= L'A' && resolved[0] <= L'Z') ||+ (resolved[0] >= L'a' && resolved[0] <= L'z')) &&+ resolved[1] == L':' && resolved[2] == L'\\';+ /* Always extended-length, not just past a threshold: derived install+ * paths (generations, payloads, transaction temporaries) grow ~145 chars+ * beyond this root, so a conditional prefix would split behavior by+ * install depth. One uniform form also means every install exercises the+ * exact path shape the deep-path guards verify. */+ if (drive_absolute) {+ if (length + 5U >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return false;+ }+ wmemcpy(path, L"\\\\?\\", 4);+ wmemcpy(path + 4, resolved, length + 1U);+ } else {+ wmemcpy(path, resolved, length + 1U);+ }+ return true;+}++/* User-facing form of a canonical wide path: agent configs, PATH advice, and+ * install messages must carry the classic drive form, never the \\?\\+ * namespace the file APIs use internally. */+static char *cli_windows_plain_utf8(const wchar_t *path) {+ if (path && wcsncmp(path, L"\\\\?\\", 4) == 0) {+ path += 4;+ }+ return cbm_wide_to_utf8(path);+}+static bool cli_windows_module_path(wchar_t out[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {DWORD length = GetModuleFileNameW(NULL, out, CBM_WINDOWS_LAUNCHER_PATH_CAP);- return length > 0 && length < CBM_WINDOWS_LAUNCHER_PATH_CAP;+ return length > 0 && length < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ cli_windows_canonicalize_launcher_path(out);}static bool cli_windows_parent_path(const wchar_t *path, wchar_t *out, size_t capacity) {@@ -5723,6 +5780,11 @@ static bool cli_windows_join_path(const wchar_t *directory, const wchar_t *name,out[0] = L'\0';return false;}+ /* Join targets feed file APIs and derived-path builders directly; only+ * the full-capacity launcher buffers can hold the canonical form. */+ if (capacity >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return cli_windows_canonicalize_launcher_path(out);+ }return true;}@@ -5747,16 +5809,23 @@ static bool cli_windows_regular_file_no_reparse(const wchar_t *path, uint64_t *sreturn valid;}-/* A portable release pair provides the source launcher adjacent to the- * payload. A managed reinstall uses the already-authenticated canonical- * launcher because immutable generation payloads intentionally have no- * sibling launcher. */+/* A portable release pair provides a one-link source launcher adjacent to the+ * payload. A managed reinstall must instead validate the canonical launcher's+ * exact two-link identity and copy from the backing that owns that identity.+ * The backing can intentionally differ from current-v1 during a crash-safe ABI+ * transition, so it is discovered by file identity rather than payload SHA. */static bool cli_windows_install_source_launcher(const wchar_t *payload_path, wchar_t launcher_out[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {if (g_windows_launcher_context.present && g_windows_launcher_context.managed) {- int copied = _snwprintf_s(launcher_out, CBM_WINDOWS_LAUNCHER_PATH_CAP, _TRUNCATE, L"%ls",- g_windows_launcher_context.canonical_launcher_path);- return copied > 0 && cli_windows_regular_file_no_reparse(launcher_out, NULL);+ char error[CLI_BUF_512] = {0};+ if (cbm_windows_managed_launcher_backing(g_windows_launcher_context.canonical_launcher_path,+ launcher_out, CBM_WINDOWS_LAUNCHER_PATH_CAP, error,+ sizeof(error))) {+ return true;+ }+ (void)fprintf(stderr, "error: managed launcher backing validation failed: %s\n",+ error[0] ? error : "canonical launcher is not an exact two-link pair");+ return false;}wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];return cli_windows_parent_path(payload_path, directory, CBM_WINDOWS_LAUNCHER_PATH_CAP) &&@@ -5765,200 +5834,343 @@ static bool cli_windows_install_source_launcher(cli_windows_regular_file_no_reparse(launcher_out, NULL);}-static bool cli_windows_remove_tree(const wchar_t *directory) {- DWORD attributes = GetFileAttributesW(directory);- if (attributes == INVALID_FILE_ATTRIBUTES) {- return GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_PATH_NOT_FOUND;+static void cli_windows_remove_empty_managed_state(const wchar_t *canonical_launcher) {+ wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t state[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t generations[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ if (!cli_windows_parent_path(canonical_launcher, directory, CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !cli_windows_join_path(directory, L".cbm", state, CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !cli_windows_join_path(state, L"generations", generations, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ return;}- if ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0 ||- (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {+ /* Rollback already removed the exact generation and current-v1 created by+ * this activation. Remove only now-empty parents: recursive cleanup could+ * erase a pre-existing recovery generation that this attempt did not own. */+ (void)RemoveDirectoryW(generations);+ (void)RemoveDirectoryW(state);+}++static bool cli_windows_stage_private_file(const char *source, const char *target,+ char fingerprint_out[CBM_DAEMON_BUILD_FINGERPRINT_SIZE]);+static bool cli_windows_stage_private_bytes(+ const unsigned char *bytes, size_t bytes_size, const char *target,+ char fingerprint_out[CBM_DAEMON_BUILD_FINGERPRINT_SIZE]);++static bool cli_windows_path_absent(const wchar_t *path) {+ if (!path || !path[0]) {return false;}+ DWORD attributes = GetFileAttributesW(path);+ if (attributes != INVALID_FILE_ATTRIBUTES) {+ return false;+ }+ DWORD error = GetLastError();+ return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND;+}++static bool cli_windows_file_fingerprint_matches(const wchar_t *path,+ const char expected_sha256[65]) {+ char *path_utf8 = cbm_wide_to_utf8(path);+ char observed[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ bool matches = path_utf8 && expected_sha256 &&+ cbm_daemon_build_fingerprint_file(path_utf8, observed) &&+ strcmp(observed, expected_sha256) == 0;+ free(path_utf8);+ return matches;+}++static bool cli_windows_generation_launcher_secure(const wchar_t *canonical_launcher,+ const wchar_t *generation_launcher,+ const char expected_launcher_sha256[65]) {+ wchar_t current_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ char error[CLI_BUF_256] = {0};+ bool managed_backing =+ cbm_windows_managed_launcher_backing(canonical_launcher, current_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, error, sizeof(error)) &&+ _wcsicmp(current_backing, generation_launcher) == 0;+ bool unpublished_backing = !managed_backing && cbm_windows_launcher_file_secure(+ generation_launcher, error, sizeof(error));+ if (!managed_backing && !unpublished_backing) {+ (void)fprintf(stderr, "error: generation launcher backing validation failed: %s (os %lu)\n",+ error[0] ? error : "no matching backing", (unsigned long)GetLastError());+ return false;+ }+ if (!cli_windows_file_fingerprint_matches(generation_launcher, expected_launcher_sha256)) {+ (void)fprintf(stderr, "error: generation launcher fingerprint mismatch (os %lu)\n",+ (unsigned long)GetLastError());+ return false;+ }+ return true;+}- wchar_t pattern[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!cli_windows_join_path(directory, L"*", pattern, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+static bool cli_windows_generation_payload_secure(const wchar_t *payload,+ const cbm_windows_current_v1_t *state) {+ uint64_t payload_size = 0;+ char payload_error[CLI_BUF_256] = {0};+ if (!state || !cli_windows_regular_file_no_reparse(payload, &payload_size)) {+ (void)fprintf(stderr, "error: generation payload open/shape validation failed (os %lu)\n",+ (unsigned long)GetLastError());return false;}- WIN32_FIND_DATAW entry;- HANDLE search = FindFirstFileW(pattern, &entry);- if (search == INVALID_HANDLE_VALUE) {- return GetLastError() == ERROR_FILE_NOT_FOUND && RemoveDirectoryW(directory) != 0;+ if (payload_size != state->payload_size) {+ (void)fprintf(stderr, "error: generation payload size mismatch\n");+ return false;}- bool ok = true;- do {- if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0) {- continue;- }- if ((entry.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {- ok = false;- break;- }- wchar_t child[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!cli_windows_join_path(directory, entry.cFileName, child,- CBM_WINDOWS_LAUNCHER_PATH_CAP)) {- ok = false;- break;- }- if ((entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {- ok = cli_windows_remove_tree(child);- } else {- ok = DeleteFileW(child) != 0;- }- } while (ok && FindNextFileW(search, &entry));- DWORD find_error = GetLastError();- (void)FindClose(search);- return ok && find_error == ERROR_NO_MORE_FILES && RemoveDirectoryW(directory) != 0;+ if (!cbm_windows_launcher_file_secure(payload, payload_error, sizeof(payload_error))) {+ (void)fprintf(stderr, "error: generation payload security validation failed: %s (os %lu)\n",+ payload_error[0] ? payload_error : "unsafe path or policy",+ (unsigned long)GetLastError());+ return false;+ }+ if (!cli_windows_file_fingerprint_matches(payload, state->payload_sha256)) {+ (void)fprintf(stderr, "error: generation payload fingerprint mismatch (os %lu)\n",+ (unsigned long)GetLastError());+ return false;+ }+ return true;}-static bool cli_windows_remove_managed_state(const wchar_t *canonical_launcher) {- wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];- wchar_t state[CBM_WINDOWS_LAUNCHER_PATH_CAP];- return cli_windows_parent_path(canonical_launcher, directory, CBM_WINDOWS_LAUNCHER_PATH_CAP) &&- cli_windows_join_path(directory, L".cbm", state, CBM_WINDOWS_LAUNCHER_PATH_CAP) &&- cli_windows_remove_tree(state);+static bool cli_windows_generation_pair_valid(const wchar_t *canonical_launcher,+ const wchar_t *payload,+ const wchar_t *generation_launcher,+ const cbm_windows_current_v1_t *state,+ const char expected_launcher_sha256[65]) {+ return cli_windows_generation_payload_secure(payload, state) &&+ cli_windows_generation_launcher_secure(canonical_launcher, generation_launcher,+ expected_launcher_sha256);+}++static void cli_windows_generation_pair_cleanup(const wchar_t *payload,+ const wchar_t *generation_launcher,+ const wchar_t *generation_directory,+ bool payload_created, bool launcher_created,+ bool directory_created) {+ if (payload_created && payload && payload[0]) {+ (void)DeleteFileW(payload);+ }+ if (launcher_created && generation_launcher && generation_launcher[0]) {+ (void)DeleteFileW(generation_launcher);+ }+ if (directory_created && generation_directory && generation_directory[0]) {+ (void)RemoveDirectoryW(generation_directory);+ }+}++static bool cli_windows_generation_unreferenced_by_current(const wchar_t *canonical_launcher,+ const char payload_sha256[65]) {+ cbm_windows_current_v1_t current;+ bool exists = false;+ return cli_windows_read_current(canonical_launcher, ¤t, &exists) &&+ (!exists || strcmp(current.payload_sha256, payload_sha256) != 0);}static bool cli_windows_publish_generation(const wchar_t *canonical_launcher,+ const wchar_t *launcher_source,const wchar_t *payload_source,const cbm_windows_current_v1_t *state,bool *created_out) {if (created_out) {*created_out = false;}- wchar_t generation[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!cbm_windows_generation_payload_path(canonical_launcher, state->payload_sha256, generation,- CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ wchar_t payload[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t generation_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ if (!launcher_source || !payload_source || !state ||+ !cbm_windows_generation_payload_path(canonical_launcher, state->payload_sha256, payload,+ CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !cbm_windows_generation_launcher_path(canonical_launcher, state->payload_sha256,+ generation_launcher, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ (void)fprintf(stderr, "error: generation path construction failed (os %lu)\n",+ (unsigned long)GetLastError());+ return false;+ }+ char *launcher_source_utf8 = cbm_wide_to_utf8(launcher_source);+ char expected_launcher_sha256[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ bool launcher_identity =+ launcher_source_utf8 &&+ cbm_daemon_build_fingerprint_file(launcher_source_utf8, expected_launcher_sha256);+ free(launcher_source_utf8);+ if (!launcher_identity) {+ (void)fprintf(stderr, "error: launcher build-identity fingerprint failed (os %lu)\n",+ (unsigned long)GetLastError());return false;}- uint64_t existing_size = 0;- if (cli_windows_regular_file_no_reparse(generation, &existing_size)) {- char *existing_utf8 = cbm_wide_to_utf8(generation);- char fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];- bool valid = existing_utf8 && existing_size == state->payload_size &&- cbm_daemon_build_fingerprint_file(existing_utf8, fingerprint) &&- strcmp(fingerprint, state->payload_sha256) == 0;- free(existing_utf8);- return valid;+ bool payload_absent = cli_windows_path_absent(payload);+ bool launcher_absent = cli_windows_path_absent(generation_launcher);+ if (!payload_absent && !launcher_absent) {+ bool pair_valid = cli_windows_generation_pair_valid(+ canonical_launcher, payload, generation_launcher, state, expected_launcher_sha256);+ if (!pair_valid) {+ (void)fprintf(stderr, "error: existing generation pair failed validation (os %lu)\n",+ (unsigned long)GetLastError());+ }+ return pair_valid;+ }+ bool fresh_generation = payload_absent && launcher_absent;+ if (!cli_windows_generation_unreferenced_by_current(canonical_launcher,+ state->payload_sha256)) {+ (void)fprintf(stderr, "error: generation is still referenced by current state (os %lu)\n",+ (unsigned long)GetLastError());+ return false;+ }+ if (!fresh_generation) {+ bool existing_secure =+ payload_absent ? cli_windows_generation_launcher_secure(+ canonical_launcher, generation_launcher, expected_launcher_sha256)+ : cli_windows_generation_payload_secure(payload, state);+ if (!existing_secure) {+ (void)fprintf(stderr, "error: partial generation failed security validation (os %lu)\n",+ (unsigned long)GetLastError());+ return false;+ }}wchar_t generation_dir[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!cli_windows_parent_path(generation, generation_dir, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ if (!cli_windows_parent_path(payload, generation_dir, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ (void)fprintf(stderr, "error: generation directory path construction failed (os %lu)\n",+ (unsigned long)GetLastError());return false;}char *generation_dir_utf8 = cbm_wide_to_utf8(generation_dir);- char *generation_utf8 = cbm_wide_to_utf8(generation);- char *source_utf8 = cbm_wide_to_utf8(payload_source);- bool prepared = generation_dir_utf8 && generation_utf8 && source_utf8 &&+ char *payload_utf8 = cbm_wide_to_utf8(payload);+ char *generation_launcher_utf8 = cbm_wide_to_utf8(generation_launcher);+ char *payload_source_utf8 = cbm_wide_to_utf8(payload_source);+ launcher_source_utf8 = cbm_wide_to_utf8(launcher_source);+ bool generation_directory_absent = cli_windows_path_absent(generation_dir);+ bool prepared = generation_dir_utf8 && payload_utf8 && generation_launcher_utf8 &&+ payload_source_utf8 && launcher_source_utf8 &&cbm_mkdir_p(generation_dir_utf8, CLI_OCTAL_PERM);- cbm_activation_transaction_t *transaction = NULL;- cbm_activation_transaction_status_t staged =- prepared ? cbm_activation_transaction_stage_file(generation_utf8, source_utf8, &transaction)- : CBM_ACTIVATION_TRANSACTION_IO;- cli_binary_validator_t validator = {{0}};- prepared = staged == CBM_ACTIVATION_TRANSACTION_OK && transaction &&- cli_activation_transaction_expected_build(transaction, &validator) &&- strcmp(validator.fingerprint, state->payload_sha256) == 0 &&- cli_activation_transaction_commit_validated(transaction, &validator,- CLI_OCTAL_PERM) == CLI_OK &&- cli_activation_transaction_finalize_close(&transaction) == CLI_OK;- (void)cli_activation_transaction_abort(&transaction);+ if (!prepared) {+ (void)fprintf(stderr, "error: generation directory creation failed (os %lu)\n",+ (unsigned long)GetLastError());+ }+ char payload_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ char launcher_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ bool payload_created = false;+ bool launcher_created = false;+ if (prepared && payload_absent) {+ payload_created =+ cli_windows_stage_private_file(payload_source_utf8, payload_utf8, payload_fingerprint);+ prepared = payload_created && strcmp(payload_fingerprint, state->payload_sha256) == 0;+ if (payload_created && !prepared) {+ (void)fprintf(stderr, "error: staged payload fingerprint mismatch\n");+ }+ }+ if (prepared && launcher_absent) {+ launcher_created = cli_windows_stage_private_file(+ launcher_source_utf8, generation_launcher_utf8, launcher_fingerprint);+ prepared = launcher_created && strcmp(launcher_fingerprint, expected_launcher_sha256) == 0;+ if (launcher_created && !prepared) {+ (void)fprintf(stderr, "error: staged launcher fingerprint mismatch\n");+ }+ }+ if (prepared) {+ prepared = cli_windows_generation_pair_valid(+ canonical_launcher, payload, generation_launcher, state, expected_launcher_sha256);+ if (!prepared) {+ (void)fprintf(stderr,+ "error: published generation pair failed final validation (os %lu)\n",+ (unsigned long)GetLastError());+ }+ }free(generation_dir_utf8);- free(generation_utf8);- free(source_utf8);- if (prepared && created_out) {- *created_out = true;+ free(payload_utf8);+ free(generation_launcher_utf8);+ free(payload_source_utf8);+ free(launcher_source_utf8);+ if (!prepared) {+ cli_windows_generation_pair_cleanup(payload, generation_launcher, generation_dir,+ payload_created, launcher_created,+ generation_directory_absent);+ return false;+ }+ if (created_out) {+ *created_out = fresh_generation;}return prepared;}static bool cli_windows_publish_generation_bytes(const wchar_t *canonical_launcher,const cbm_windows_current_v1_t *state,- const unsigned char *payload, size_t payload_size,- bool *created_out) {+ const unsigned char *launcher,+ size_t launcher_size, const unsigned char *payload,+ size_t payload_size, bool *created_out) {if (created_out) {*created_out = false;}- if (!payload || payload_size == 0 || payload_size != state->payload_size) {+ if (!state || !launcher || launcher_size == 0 || !payload || payload_size == 0 ||+ payload_size != state->payload_size) {return false;}- wchar_t generation[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!cbm_windows_generation_payload_path(canonical_launcher, state->payload_sha256, generation,- CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ wchar_t generation_payload[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t generation_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ if (!cbm_windows_generation_payload_path(canonical_launcher, state->payload_sha256,+ generation_payload, CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !cbm_windows_generation_launcher_path(canonical_launcher, state->payload_sha256,+ generation_launcher, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {return false;}- uint64_t existing_size = 0;- if (cli_windows_regular_file_no_reparse(generation, &existing_size)) {- char *existing_utf8 = cbm_wide_to_utf8(generation);- char fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];- bool valid = existing_utf8 && existing_size == payload_size &&- cbm_daemon_build_fingerprint_file(existing_utf8, fingerprint) &&- strcmp(fingerprint, state->payload_sha256) == 0;- free(existing_utf8);- return valid;+ char expected_launcher_sha256[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];+ cbm_sha256_hex(launcher, launcher_size, expected_launcher_sha256);+ bool payload_absent = cli_windows_path_absent(generation_payload);+ bool launcher_absent = cli_windows_path_absent(generation_launcher);+ if (!payload_absent && !launcher_absent) {+ return cli_windows_generation_pair_valid(canonical_launcher, generation_payload,+ generation_launcher, state,+ expected_launcher_sha256);+ }+ bool fresh_generation = payload_absent && launcher_absent;+ if (!cli_windows_generation_unreferenced_by_current(canonical_launcher,+ state->payload_sha256)) {+ return false;+ }+ if (!fresh_generation) {+ bool existing_secure =+ payload_absent ? cli_windows_generation_launcher_secure(+ canonical_launcher, generation_launcher, expected_launcher_sha256)+ : cli_windows_generation_payload_secure(generation_payload, state);+ if (!existing_secure) {+ return false;+ }}wchar_t generation_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!cli_windows_parent_path(generation, generation_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ if (!cli_windows_parent_path(generation_payload, generation_directory,+ CBM_WINDOWS_LAUNCHER_PATH_CAP)) {return false;}char *directory_utf8 = cbm_wide_to_utf8(generation_directory);- char *generation_utf8 = cbm_wide_to_utf8(generation);- bool ready = directory_utf8 && generation_utf8 && cbm_mkdir_p(directory_utf8, CLI_OCTAL_PERM);- cbm_activation_transaction_t *transaction = NULL;- cbm_activation_transaction_status_t staged =- ready ? cbm_activation_transaction_stage_bytes(generation_utf8, payload, payload_size,- &transaction)- : CBM_ACTIVATION_TRANSACTION_IO;- cli_binary_validator_t validator = {{0}};- ready = staged == CBM_ACTIVATION_TRANSACTION_OK && transaction &&- cli_activation_transaction_expected_build(transaction, &validator) &&- strcmp(validator.fingerprint, state->payload_sha256) == 0 &&- cli_activation_transaction_commit_validated(transaction, &validator, CLI_OCTAL_PERM) ==- CLI_OK &&- cli_activation_transaction_finalize_close(&transaction) == CLI_OK;- (void)cli_activation_transaction_abort(&transaction);- free(directory_utf8);- free(generation_utf8);- if (ready && created_out) {- *created_out = true;- }- return ready;-}--static bool cli_windows_stage_launcher_candidate(- const wchar_t *canonical_launcher, const char payload_sha256[65], const unsigned char *launcher,- size_t launcher_size, wchar_t candidate_out[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {- wchar_t current[CBM_WINDOWS_LAUNCHER_PATH_CAP];- wchar_t state_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!launcher || launcher_size == 0 || !cli_windows_current_path(canonical_launcher, current) ||- !cli_windows_parent_path(current, state_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {- return false;+ char *payload_utf8 = cbm_wide_to_utf8(generation_payload);+ char *launcher_utf8 = cbm_wide_to_utf8(generation_launcher);+ bool generation_directory_absent = cli_windows_path_absent(generation_directory);+ bool ready = directory_utf8 && payload_utf8 && launcher_utf8 &&+ cbm_mkdir_p(directory_utf8, CLI_OCTAL_PERM);+ char payload_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ char launcher_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ bool payload_created = false;+ bool launcher_created = false;+ if (ready && payload_absent) {+ payload_created = cli_windows_stage_private_bytes(payload, payload_size, payload_utf8,+ payload_fingerprint);+ ready = payload_created && strcmp(payload_fingerprint, state->payload_sha256) == 0;+ }+ if (ready && launcher_absent) {+ launcher_created = cli_windows_stage_private_bytes(launcher, launcher_size, launcher_utf8,+ launcher_fingerprint);+ ready = launcher_created && strcmp(launcher_fingerprint, expected_launcher_sha256) == 0;}- wchar_t name[96];- int name_length = _snwprintf_s(name, sizeof(name) / sizeof(name[0]), _TRUNCATE,- L"launcher-next-%hs.exe", payload_sha256);- if (name_length <= 0 || !cli_windows_join_path(state_directory, name, candidate_out,- CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ ready = ready &&+ cli_windows_generation_pair_valid(canonical_launcher, generation_payload,+ generation_launcher, state, expected_launcher_sha256);+ free(directory_utf8);+ free(payload_utf8);+ free(launcher_utf8);+ if (!ready) {+ cli_windows_generation_pair_cleanup(generation_payload, generation_launcher,+ generation_directory, payload_created, launcher_created,+ generation_directory_absent);return false;}- char *state_utf8 = cbm_wide_to_utf8(state_directory);- char *candidate_utf8 = cbm_wide_to_utf8(candidate_out);- bool ready = state_utf8 && candidate_utf8 && cbm_mkdir_p(state_utf8, CLI_OCTAL_PERM);- cbm_activation_transaction_t *transaction = NULL;- cbm_activation_transaction_status_t staged =- ready ? cbm_activation_transaction_stage_bytes(candidate_utf8, launcher, launcher_size,- &transaction)- : CBM_ACTIVATION_TRANSACTION_IO;- cli_binary_validator_t validator = {{0}};- ready = staged == CBM_ACTIVATION_TRANSACTION_OK && transaction &&- cli_activation_transaction_expected_build(transaction, &validator) &&- cli_activation_transaction_commit_validated(transaction, &validator, CLI_OCTAL_PERM) ==- CLI_OK &&- cli_activation_transaction_finalize_close(&transaction) == CLI_OK;- (void)cli_activation_transaction_abort(&transaction);- free(state_utf8);- free(candidate_utf8);- if (!ready) {- candidate_out[0] = L'\0';+ if (created_out) {+ *created_out = fresh_generation;}return ready;}@@ -9413,11 +9625,13 @@ typedef struct {wchar_t canonical_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP];wchar_t launcher_source[CBM_WINDOWS_LAUNCHER_PATH_CAP];wchar_t payload_source[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t previous_launcher_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];cbm_windows_current_v1_t state;cbm_windows_current_v1_t previous_state;cbm_windows_transition_plan_t transition_plan;bool initial_install;bool previous_state_valid;+ bool previous_launcher_backing_valid;bool delete_indexes;bool skip_config;bool force;@@ -9470,6 +9684,68 @@ static bool cli_windows_read_current(const wchar_t *canonical_launcher,return valid;}+static bool cli_windows_current_equal(const cbm_windows_current_v1_t *left,+ const cbm_windows_current_v1_t *right) {+ return left && right && left->launcher_abi_min == right->launcher_abi_min &&+ left->launcher_abi_max == right->launcher_abi_max &&+ left->payload_size == right->payload_size &&+ strcmp(left->payload_sha256, right->payload_sha256) == 0;+}++static bool cli_windows_remove_current_if_present(const wchar_t *canonical_launcher) {+ cbm_windows_current_v1_t observed;+ bool exists = false;+ wchar_t current[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ if (!cli_windows_read_current(canonical_launcher, &observed, &exists) ||+ !cli_windows_current_path(canonical_launcher, current)) {+ return false;+ }+ if (!exists) {+ return true;+ }+ return DeleteFileW(current) != 0;+}++static bool cli_windows_restore_managed_pair(const wchar_t *canonical_launcher,+ const wchar_t *previous_launcher_backing,+ bool previous_launcher_backing_valid,+ const cbm_windows_current_v1_t *previous_state,+ bool previous_state_valid, char *error,+ size_t error_size) {+ if (error && error_size > 0U) {+ error[0] = '\0';+ }+ char launcher_error[CLI_BUF_256] = {0};+ bool launcher_restored =+ previous_launcher_backing_valid+ ? cbm_windows_launcher_replace_atomic(canonical_launcher, previous_launcher_backing,+ launcher_error, sizeof(launcher_error))+ : (cli_windows_path_absent(canonical_launcher) ||+ cbm_windows_launcher_remove_posix(canonical_launcher, launcher_error,+ sizeof(launcher_error)));+ char current_error[CLI_BUF_256] = {0};+ bool current_restored =+ previous_state_valid+ ? cbm_windows_current_v1_write_atomic(canonical_launcher, previous_state, current_error,+ sizeof(current_error))+ : cli_windows_remove_current_if_present(canonical_launcher);+ if (!launcher_restored || !current_restored) {+ if (error && error_size > 0U) {+ (void)snprintf(+ error, error_size, "%s%s%s",+ !launcher_restored+ ? (launcher_error[0] ? launcher_error : "canonical backing restoration failed")+ : "",+ !launcher_restored && !current_restored ? "; " : "",+ !current_restored+ ? (current_error[0] ? current_error : "current-v1 restoration failed")+ : "");+ }+ return false;+ }+ return true;+}+static bool cli_windows_stage_private_file(const char *source, const char *target,char fingerprint_out[CBM_DAEMON_BUILD_FINGERPRINT_SIZE]) {@@ -9775,53 +10051,78 @@ static int cli_windows_managed_install_activate(void *opaque) {bool launcher_committed = false;bool current_committed = false;char error[CLI_BUF_512] = {0};+ cbm_windows_current_v1_t observed_current;+ bool observed_current_exists = false;+ wchar_t observed_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};+ bool current_unchanged =+ cli_windows_read_current(activation->canonical_launcher, &observed_current,+ &observed_current_exists) &&+ observed_current_exists == activation->previous_state_valid &&+ (!observed_current_exists ||+ cli_windows_current_equal(&observed_current, &activation->previous_state));+ bool backing_unchanged =+ activation->previous_launcher_backing_valid+ ? (cbm_windows_managed_launcher_backing(+ activation->canonical_launcher, observed_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, error, sizeof(error)) &&+ _wcsicmp(observed_backing, activation->previous_launcher_backing) == 0)+ : cli_windows_path_absent(activation->canonical_launcher);+ bool previous_pair_unchanged = current_unchanged && backing_unchanged;+ if (!previous_pair_unchanged) {+ (void)fprintf(stderr, "error: managed Windows launcher/current state changed before "+ "install activation; no generation was published\n");+ return CLI_TRUE;+ }+ wchar_t generation_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};bool generation_ready = cli_windows_publish_generation(- activation->canonical_launcher, activation->payload_source, &activation->state,- &generation_created);+ activation->canonical_launcher, activation->launcher_source, activation->payload_source,+ &activation->state, &generation_created);+ generation_ready = generation_ready &&+ cbm_windows_generation_launcher_path(+ activation->canonical_launcher, activation->state.payload_sha256,+ generation_launcher, CBM_WINDOWS_LAUNCHER_PATH_CAP);if (generation_ready &&activation->transition_plan == CBM_WINDOWS_TRANSITION_CURRENT_FIRST) {current_committed = cbm_windows_current_v1_write_atomic(activation->canonical_launcher, &activation->state, error, sizeof(error));- launcher_committed = current_committed &&- cbm_windows_launcher_replace_atomic(activation->canonical_launcher,- activation->launcher_source,- error, sizeof(error));+ launcher_committed =+ current_committed &&+ cbm_windows_launcher_replace_atomic(activation->canonical_launcher,+ generation_launcher, error, sizeof(error));} else if (generation_ready) {launcher_committed = cbm_windows_launcher_replace_atomic(- activation->canonical_launcher, activation->launcher_source, error, sizeof(error));+ activation->canonical_launcher, generation_launcher, error, sizeof(error));current_committed = launcher_committed && cbm_windows_current_v1_write_atomic(activation->canonical_launcher,&activation->state, error, sizeof(error));}if (!generation_ready || !launcher_committed || !current_committed) {- if (activation->transition_plan == CBM_WINDOWS_TRANSITION_CURRENT_FIRST &&- current_committed && !launcher_committed && activation->previous_state_valid) {- char restore_error[CLI_BUF_256] = {0};- if (!cbm_windows_current_v1_write_atomic(activation->canonical_launcher,- &activation->previous_state, restore_error,- sizeof(restore_error))) {- (void)fprintf(stderr,- "error: managed Windows install could not restore "- "the previous current-v1 after launcher failure: %s\n",- restore_error[0] ? restore_error : "atomic restoration failed");- }- }- if (activation->initial_install) {- char cleanup_error[CLI_BUF_256] = {0};- (void)cbm_windows_launcher_remove_posix(activation->canonical_launcher,- cleanup_error, sizeof(cleanup_error));- (void)cli_windows_remove_managed_state(activation->canonical_launcher);+ char restore_error[CLI_BUF_512] = {0};+ bool restored = cli_windows_restore_managed_pair(+ activation->canonical_launcher, activation->previous_launcher_backing,+ activation->previous_launcher_backing_valid, &activation->previous_state,+ activation->previous_state_valid, restore_error, sizeof(restore_error));+ if (!restored) {+ (void)fprintf(stderr,+ "error: managed Windows install could not restore the "+ "previous launcher/current pair: %s\n",+ restore_error[0] ? restore_error : "atomic restoration failed");}char rollback_error[CLI_BUF_256] = {0};- if (!cbm_windows_generation_rollback_if_unreferenced(- activation->canonical_launcher, activation->state.payload_sha256,- generation_created, rollback_error, sizeof(rollback_error))) {+ bool generation_rolled_back = cbm_windows_generation_rollback_if_unreferenced(+ activation->canonical_launcher, activation->state.payload_sha256,+ generation_created, rollback_error, sizeof(rollback_error));+ if (!generation_rolled_back) {(void)fprintf(stderr,"error: managed Windows install generation rollback ""failed: %s\n",rollback_error[0] ? rollback_error: "generation remains for safe recovery");}+ if (activation->initial_install && !activation->previous_launcher_backing_valid &&+ generation_created && restored && generation_rolled_back) {+ cli_windows_remove_empty_managed_state(activation->canonical_launcher);+ }(void)fprintf(stderr, "error: managed Windows install commit failed: %s\n",error[0] ? error : "generation/launcher/current publish failed");return CLI_TRUE;@@ -9911,7 +10212,7 @@ static int cli_windows_managed_install(const char *home, const char *requested_b}char *bin_dir = cbm_wide_to_utf8(full_directory);- char *bin_target = cbm_wide_to_utf8(canonical_launcher);+ char *bin_target = cli_windows_plain_utf8(canonical_launcher);char *payload_utf8 = cbm_wide_to_utf8(payload_source);char *launcher_utf8 = cbm_wide_to_utf8(launcher_source);char fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};@@ -9947,28 +10248,53 @@ static int cli_windows_managed_install(const char *home, const char *requested_bmemset(&previous, 0, sizeof(previous));bool current_exists = false;bool current_valid = cli_windows_read_current(canonical_launcher, &previous, ¤t_exists);- bool launcher_exists = cli_windows_regular_file_no_reparse(canonical_launcher, NULL);+ DWORD launcher_attributes = GetFileAttributesW(canonical_launcher);+ DWORD launcher_attribute_error =+ launcher_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;+ bool launcher_exists = launcher_attributes != INVALID_FILE_ATTRIBUTES;+ bool launcher_absent = launcher_attributes == INVALID_FILE_ATTRIBUTES &&+ (launcher_attribute_error == ERROR_FILE_NOT_FOUND ||+ launcher_attribute_error == ERROR_PATH_NOT_FOUND);const char *current_version_argv[] = {bin_target, "--version", NULL};- char target_error[CLI_BUF_256] = {0};+ char target_error[CLI_BUF_512] = {0};+ wchar_t target_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};bool current_target_secure =- !launcher_exists ||- cbm_windows_launcher_file_secure(canonical_launcher, target_error, sizeof(target_error));- char installed_launcher_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ launcher_exists && cbm_windows_managed_launcher_backing(canonical_launcher, target_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP,+ target_error, sizeof(target_error));/* A crash between the fresh install's atomic launcher publication and* current-v1 publication leaves one recognizable partial state. Repair it- * only when the visible launcher is still private and byte-identical to- * this candidate; an arbitrary launcher/current mismatch remains a hard- * conflict. The guarded activation republishes the launcher and current-v1- * before it reports success. */+ * only when canonical is the exact second link of this candidate's complete+ * generation. An arbitrary launcher/current mismatch remains a hard+ * conflict. */+ cbm_windows_current_v1_t interrupted_state = {+ .launcher_abi_min = descriptor.payload_launcher_abi_min,+ .launcher_abi_max = descriptor.payload_launcher_abi_max,+ .payload_size = descriptor.payload_size,+ };+ (void)snprintf(interrupted_state.payload_sha256, sizeof(interrupted_state.payload_sha256), "%s",+ fingerprint);bool interrupted_initial_install =current_valid && !current_exists && launcher_exists && current_target_secure &&- cbm_daemon_build_fingerprint_file(bin_target, installed_launcher_fingerprint) &&- strcmp(installed_launcher_fingerprint, launcher_fingerprint) == 0;+ cbm_windows_generation_payload_path(canonical_launcher, fingerprint, prepared_payload,+ CBM_WINDOWS_LAUNCHER_PATH_CAP) &&+ cbm_windows_generation_launcher_path(canonical_launcher, fingerprint, prepared_launcher,+ CBM_WINDOWS_LAUNCHER_PATH_CAP) &&+ _wcsicmp(target_backing, prepared_launcher) == 0 &&+ cli_windows_generation_pair_valid(canonical_launcher, prepared_payload, prepared_launcher,+ &interrupted_state, launcher_fingerprint);+ bool fresh_target = current_valid && !current_exists && launcher_absent;+ bool intact_target = current_valid && current_exists && current_target_secure;+ /* A launcher-first initial-install crash intentionally has no current-v1+ * yet. Executing canonical in that state must fail closed (it cannot select+ * a managed payload and its two-link layout forbids portable mode). The+ * exact generation identities above authenticate that recovery state; the+ * copied source pair is executed again during private staging below. */bool current_pair_runnable =- !current_exists ||- (current_target_secure && cbm_exec_no_shell(current_version_argv) == CLI_OK);- if (!current_valid || (current_exists != launcher_exists && !interrupted_initial_install) ||- !current_target_secure || !current_pair_runnable) {+ fresh_target || interrupted_initial_install ||+ (intact_target && cbm_exec_no_shell(current_version_argv) == CLI_OK);+ if ((!fresh_target && !intact_target && !interrupted_initial_install) ||+ !current_pair_runnable) {(void)fprintf(stderr,"error: target is not an intact compatible managed Windows ""installation; remove the conflicting files before install%s%s\n",@@ -10070,12 +10396,16 @@ static int cli_windows_managed_install(const char *home, const char *requested_b: CBM_WINDOWS_TRANSITION_LAUNCHER_FIRST,.initial_install = !current_exists,.previous_state_valid = current_exists,+ .previous_launcher_backing_valid = launcher_exists,.delete_indexes = delete_indexes,.skip_config = skip_config,.force = force,.dry_run = dry_run,};memcpy(activation.canonical_launcher, canonical_launcher, sizeof(canonical_launcher));+ if (launcher_exists) {+ memcpy(activation.previous_launcher_backing, target_backing, sizeof(target_backing));+ }memcpy(activation.launcher_source, pair_prepared ? prepared_launcher : launcher_source,sizeof(launcher_source));memcpy(activation.payload_source, pair_prepared ? prepared_payload : payload_source,@@ -11579,6 +11909,8 @@ typedef struct {const char *home;const char *canonical_launcher_utf8;wchar_t canonical_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t launcher_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ cbm_windows_current_v1_t state;cbm_detected_agents_t agents;bool delete_indexes;bool dry_run;@@ -11589,6 +11921,22 @@ static int cli_windows_managed_uninstall_activate(void *opaque) {if (!activation || !activation->home || !activation->canonical_launcher_utf8) {return CLI_TRUE;}+ cbm_windows_current_v1_t observed;+ bool observed_exists = false;+ wchar_t observed_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};+ char validation_error[CLI_BUF_512] = {0};+ if (!cli_windows_read_current(activation->canonical_launcher, &observed, &observed_exists) ||+ !observed_exists || !cli_windows_current_equal(&observed, &activation->state) ||+ !cbm_windows_managed_launcher_backing(activation->canonical_launcher, observed_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, validation_error,+ sizeof(validation_error)) ||+ _wcsicmp(observed_backing, activation->launcher_backing) != 0) {+ (void)fprintf(stderr,+ "error: managed Windows launcher/current state changed before "+ "uninstall activation; no configuration was removed%s%s\n",+ validation_error[0] ? ": " : "", validation_error[0] ? validation_error : "");+ return CLI_TRUE;+ }if (activation->agents.claude_code) {uninstall_claude_code(activation->home, activation->dry_run);}@@ -11607,22 +11955,8 @@ static int cli_windows_managed_uninstall_activate(void *opaque) {return CLI_OK;}- char error[CLI_BUF_512] = {0};- if (!cbm_windows_launcher_remove_posix(activation->canonical_launcher, error, sizeof(error))) {- (void)fprintf(stderr, "error: managed launcher removal failed: %s\n",- error[0] ? error : "atomic POSIX unlink unavailable");- return CLI_TRUE;- }- printf("Removed %s\n", activation->canonical_launcher_utf8);-- /* The visible launcher unlink is the uninstall commit point. The private- * launcher/payload copies are not inside this tree, so cleanup is- * synchronous and no installed image remains mapped. */- if (!cli_windows_remove_managed_state(activation->canonical_launcher)) {- (void)fprintf(stderr, "error: launcher was removed, but managed current/generation "- "cleanup did not complete\n");- return CLI_ACTIVATION_PARTIAL;- }+ /* Finish every fallible cleanup before retiring managed state and+ * unlinking the only public retry entry point. */if (activation->delete_indexes) {int expected = count_db_indexes(activation->home);int removed = cbm_remove_indexes(activation->home);@@ -11633,6 +11967,25 @@ static int cli_windows_managed_uninstall_activate(void *opaque) {return CLI_ACTIVATION_PARTIAL;}}++ char error[CLI_BUF_512] = {0};+ if (!cbm_windows_launcher_uninstall_commit(activation->canonical_launcher,+ activation->state.payload_sha256, error,+ sizeof(error))) {+ (void)fprintf(stderr, "error: managed launcher uninstall commit failed: %s\n",+ error[0] ? error : "state retirement or atomic launcher unlink failed");+ (void)fprintf(stderr,+ "error: configuration/index cleanup completed before the failed commit; "+ "retry after reviewing the retained managed state\n");+ return CLI_TRUE;+ }+ printf("Removed %s\n", activation->canonical_launcher_utf8);++ /* The commit moved .cbm to a SHA/PID-qualified sibling before unlinking+ * canonical. The permanent launcher derives that exact authenticated name+ * and removes only that retired tree after both mapped images exit; a+ * concurrent reinstall can safely create a new .cbm immediately. */+ printf("Retired managed generation cleanup will complete after the launcher exits.\n");return CLI_OK;}@@ -11644,16 +11997,21 @@ static int cli_windows_managed_uninstall(const char *home, bool dry_run) {}cbm_windows_current_v1_t current;bool current_exists = false;+ wchar_t launcher_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};+ char validation_error[CLI_BUF_512] = {0};if (!cli_windows_read_current(g_windows_launcher_context.canonical_launcher_path, ¤t,¤t_exists) ||!current_exists ||!cbm_windows_current_v1_supports_launcher_abi(¤t, CBM_WINDOWS_LAUNCHER_ABI_CURRENT) ||current.payload_size != g_windows_launcher_context.payload_size ||strcmp(current.payload_sha256, g_windows_launcher_context.expected_payload_sha256) != 0 ||- !cli_windows_regular_file_no_reparse(g_windows_launcher_context.canonical_launcher_path,- NULL)) {- (void)fprintf(stderr, "error: authenticated managed launcher state changed before "- "uninstall; no sessions were stopped\n");+ !cbm_windows_managed_launcher_backing(g_windows_launcher_context.canonical_launcher_path,+ launcher_backing, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ validation_error, sizeof(validation_error))) {+ (void)fprintf(stderr,+ "error: authenticated managed launcher state changed before "+ "uninstall; no sessions were stopped%s%s\n",+ validation_error[0] ? ": " : "", validation_error[0] ? validation_error : "");return CLI_TRUE;}wchar_t target_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];@@ -11697,12 +12055,14 @@ static int cli_windows_managed_uninstall(const char *home, bool dry_run) {cli_windows_uninstall_activation_t activation = {.home = home,.canonical_launcher_utf8 = canonical_utf8,+ .state = current,.agents = cbm_detect_agents(home),.delete_indexes = delete_indexes,.dry_run = dry_run,};memcpy(activation.canonical_launcher, g_windows_launcher_context.canonical_launcher_path,sizeof(activation.canonical_launcher));+ memcpy(activation.launcher_backing, launcher_backing, sizeof(launcher_backing));int result = dry_run? cli_windows_managed_uninstall_activate(&activation): cli_activation_guard(CBM_DAEMON_RUNTIME_ACTIVATION_UNINSTALL, NULL, NULL,@@ -11844,6 +12204,7 @@ typedef struct {const char *home;const char *canonical_launcher_utf8;wchar_t canonical_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t previous_launcher_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];cbm_windows_release_pair_t pair;cbm_windows_current_v1_t state;cbm_windows_current_v1_t previous_state;@@ -11859,61 +12220,53 @@ static int cli_windows_managed_update_activate(void *opaque) {}cbm_windows_current_v1_t observed;bool observed_exists = false;+ wchar_t observed_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};+ char error[CLI_BUF_512] = {0};if (!cli_windows_read_current(activation->canonical_launcher, &observed, &observed_exists) ||- !observed_exists ||- observed.launcher_abi_min != activation->previous_state.launcher_abi_min ||- observed.launcher_abi_max != activation->previous_state.launcher_abi_max ||- observed.payload_size != activation->previous_state.payload_size ||- strcmp(observed.payload_sha256, activation->previous_state.payload_sha256) != 0 ||+ !observed_exists || !cli_windows_current_equal(&observed, &activation->previous_state) ||+ !cbm_windows_managed_launcher_backing(activation->canonical_launcher, observed_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, error,+ sizeof(error)) ||+ _wcsicmp(observed_backing, activation->previous_launcher_backing) != 0 ||activation->transition_plan == CBM_WINDOWS_TRANSITION_INCOMPATIBLE) {(void)fprintf(stderr, "error: managed Windows state changed before update ""activation; no generation was published\n");return CLI_TRUE;}- wchar_t candidate[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};- char error[CLI_BUF_512] = {0};- bool candidate_ready = cli_windows_stage_launcher_candidate(- activation->canonical_launcher, activation->state.payload_sha256, activation->pair.launcher,- (size_t)activation->pair.launcher_len, candidate);+ wchar_t generation_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};bool generation_created = false;- bool generation_ready =- candidate_ready &&- cli_windows_publish_generation_bytes(- activation->canonical_launcher, &activation->state, activation->pair.payload,- (size_t)activation->pair.payload_len, &generation_created);+ bool generation_ready = cli_windows_publish_generation_bytes(+ activation->canonical_launcher, &activation->state, activation->pair.launcher,+ (size_t)activation->pair.launcher_len, activation->pair.payload,+ (size_t)activation->pair.payload_len, &generation_created);+ generation_ready =+ generation_ready && cbm_windows_generation_launcher_path(+ activation->canonical_launcher, activation->state.payload_sha256,+ generation_launcher, CBM_WINDOWS_LAUNCHER_PATH_CAP);bool launcher_committed = false;bool current_committed = false;if (generation_ready && activation->transition_plan == CBM_WINDOWS_TRANSITION_CURRENT_FIRST) {current_committed = cbm_windows_current_v1_write_atomic(activation->canonical_launcher, &activation->state, error, sizeof(error));- launcher_committed = current_committed &&- cbm_windows_launcher_replace_atomic(activation->canonical_launcher,- candidate, error, sizeof(error));+ launcher_committed = current_committed && cbm_windows_launcher_replace_atomic(+ activation->canonical_launcher,+ generation_launcher, error, sizeof(error));} else if (generation_ready) {- launcher_committed = cbm_windows_launcher_replace_atomic(activation->canonical_launcher,- candidate, error, sizeof(error));+ launcher_committed = cbm_windows_launcher_replace_atomic(+ activation->canonical_launcher, generation_launcher, error, sizeof(error));current_committed = launcher_committed && cbm_windows_current_v1_write_atomic(activation->canonical_launcher,&activation->state, error, sizeof(error));}- if (candidate[0] != L'\0') {- DWORD attributes = GetFileAttributesW(candidate);- if (attributes != INVALID_FILE_ATTRIBUTES) {- (void)DeleteFileW(candidate);- }- }if (!generation_ready || !launcher_committed || !current_committed) {- if (activation->transition_plan == CBM_WINDOWS_TRANSITION_CURRENT_FIRST &&- current_committed && !launcher_committed) {- char restore_error[CLI_BUF_256] = {0};- if (!cbm_windows_current_v1_write_atomic(activation->canonical_launcher,- &activation->previous_state, restore_error,- sizeof(restore_error))) {- (void)fprintf(stderr,- "error: managed Windows update could not restore the "- "previous current-v1 after launcher failure: %s\n",- restore_error[0] ? restore_error : "atomic restoration failed");- }+ char restore_error[CLI_BUF_512] = {0};+ if (!cli_windows_restore_managed_pair(+ activation->canonical_launcher, activation->previous_launcher_backing, true,+ &activation->previous_state, true, restore_error, sizeof(restore_error))) {+ (void)fprintf(stderr,+ "error: managed Windows update could not restore the previous "+ "launcher/current pair: %s\n",+ restore_error[0] ? restore_error : "atomic restoration failed");}char rollback_error[CLI_BUF_256] = {0};if (!cbm_windows_generation_rollback_if_unreferenced(@@ -12004,18 +12357,25 @@ static int cli_windows_extract_and_activate_update(const char *archive_path, concbm_windows_current_v1_t current;memset(¤t, 0, sizeof(current));bool current_exists = false;+ wchar_t previous_launcher_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};+ char backing_error[CLI_BUF_512] = {0};bool current_compatible =cli_windows_read_current(g_windows_launcher_context.canonical_launcher_path, ¤t,¤t_exists) &¤t_exists &&- cbm_windows_current_v1_supports_launcher_abi(¤t, CBM_WINDOWS_LAUNCHER_ABI_CURRENT);+ cbm_windows_current_v1_supports_launcher_abi(¤t, CBM_WINDOWS_LAUNCHER_ABI_CURRENT) &&+ cbm_windows_managed_launcher_backing(+ g_windows_launcher_context.canonical_launcher_path, previous_launcher_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, backing_error, sizeof(backing_error));char *canonical_utf8 =current_compatible ? cbm_wide_to_utf8(g_windows_launcher_context.canonical_launcher_path): NULL;if (!canonical_utf8) {cbm_windows_release_pair_free(&pair);- (void)fprintf(stderr, "error: old/new managed launcher ABI compatibility check "- "failed before update activation\n");+ (void)fprintf(stderr,+ "error: old/new managed launcher ABI or two-link backing check "+ "failed before update activation%s%s\n",+ backing_error[0] ? ": " : "", backing_error[0] ? backing_error : "");return CLI_TRUE;}wchar_t prepared_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};@@ -12077,6 +12437,8 @@ static int cli_windows_extract_and_activate_update(const char *archive_path, con};memcpy(activation.canonical_launcher, g_windows_launcher_context.canonical_launcher_path,sizeof(activation.canonical_launcher));+ memcpy(activation.previous_launcher_backing, previous_launcher_backing,+ sizeof(previous_launcher_backing));int result =cli_activation_guard(CBM_DAEMON_RUNTIME_ACTIVATION_UPDATE, NULL, next.payload_sha256,cli_windows_managed_update_activate, &activation);@@ -12088,6 +12450,8 @@ static int cli_windows_extract_and_activate_update(const char *archive_path, constatic bool cli_windows_managed_update_preflight(bool probe_capability) {cbm_windows_current_v1_t current;bool current_exists = false;+ wchar_t launcher_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};+ char error[CLI_BUF_512] = {0};if (!g_windows_launcher_context.present || !g_windows_launcher_context.managed ||!g_windows_launcher_context.private_activation ||g_windows_launcher_context.action != CBM_WINDOWS_LAUNCHER_ACTION_UPDATE ||@@ -12096,17 +12460,20 @@ static bool cli_windows_managed_update_preflight(bool probe_capability) {!current_exists || current.payload_size != g_windows_launcher_context.payload_size ||strcmp(current.payload_sha256, g_windows_launcher_context.expected_payload_sha256) != 0 ||!cbm_windows_current_v1_supports_launcher_abi(¤t, CBM_WINDOWS_LAUNCHER_ABI_CURRENT) ||- !cli_windows_regular_file_no_reparse(g_windows_launcher_context.canonical_launcher_path,- NULL)) {- (void)fprintf(stderr, "error: authenticated managed launcher state changed before "- "update; no network or daemon operation was started\n");+ !cbm_windows_managed_launcher_backing(g_windows_launcher_context.canonical_launcher_path,+ launcher_backing, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ error, sizeof(error))) {+ (void)fprintf(stderr,+ "error: authenticated managed launcher state changed before "+ "update; no network or daemon operation was started%s%s\n",+ error[0] ? ": " : "", error[0] ? error : "");return false;}if (!probe_capability) {return true;}wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];- char error[CLI_BUF_512] = {0};+ error[0] = '\0';if (!cli_windows_parent_path(g_windows_launcher_context.canonical_launcher_path, directory,CBM_WINDOWS_LAUNCHER_PATH_CAP) ||!cbm_windows_launcher_capability_probe(diff --git a/src/cli/windows_launcher_state.c b/src/cli/windows_launcher_state.cindex 0c5746e45..2219866b3 100644--- a/src/cli/windows_launcher_state.c+++ b/src/cli/windows_launcher_state.c@@ -182,14 +182,14 @@ cbm_windows_transition_plan_t cbm_windows_transition_plan(return CBM_WINDOWS_TRANSITION_INCOMPATIBLE;}-bool cbm_windows_generation_payload_path(const wchar_t *canonical_launcher_path,- const char payload_sha256[65], wchar_t *path_out,- size_t path_capacity) {+static bool windows_generation_file_path(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], const wchar_t *leaf,+ wchar_t *path_out, size_t path_capacity) {if (path_out && path_capacity > 0U) {path_out[0] = L'\0';}- if (!canonical_launcher_path || !lowercase_sha256_valid(payload_sha256) || !path_out ||- path_capacity == 0U) {+ if (!canonical_launcher_path || !lowercase_sha256_valid(payload_sha256) || !leaf || !leaf[0] ||+ wcschr(leaf, L'\\') || wcschr(leaf, L'/') || !path_out || path_capacity == 0U) {return false;}const wchar_t *last_backslash = wcsrchr(canonical_launcher_path, L'\\');@@ -207,13 +207,13 @@ bool cbm_windows_generation_payload_path(const wchar_t *canonical_launcher_path,directory_length = 3U; /* Preserve C:\ rather than producing C:.cbm. */}static const wchar_t middle[] = L".cbm\\generations\\";- static const wchar_t leaf[] = L"\\codebase-memory-mcp.payload.exe";size_t middle_length = sizeof(middle) / sizeof(middle[0]) - 1U;- size_t leaf_length = sizeof(leaf) / sizeof(leaf[0]) - 1U;+ size_t leaf_length = wcslen(leaf);bool root = directory_length == 3U && canonical_launcher_path[1] == L':' &&(canonical_launcher_path[2] == L'\\' || canonical_launcher_path[2] == L'/');size_t separator_count = root ? 0U : 1U;- size_t needed = directory_length + separator_count + middle_length + 64U + leaf_length + 1U;+ size_t needed =+ directory_length + separator_count + middle_length + 64U + 1U + leaf_length + 1U;if (needed > path_capacity) {return false;}@@ -230,6 +230,91 @@ bool cbm_windows_generation_payload_path(const wchar_t *canonical_launcher_path,for (size_t index = 0; index < 64U; index++) {path_out[offset++] = (wchar_t)(unsigned char)payload_sha256[index];}+ path_out[offset++] = L'\\';+ memcpy(path_out + offset, leaf, (leaf_length + 1U) * sizeof(*path_out));+ return true;+}++bool cbm_windows_generation_payload_path(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], wchar_t *path_out,+ size_t path_capacity) {+ return windows_generation_file_path(canonical_launcher_path, payload_sha256,+ L"codebase-memory-mcp.payload.exe", path_out,+ path_capacity);+}++bool cbm_windows_generation_launcher_path(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], wchar_t *path_out,+ size_t path_capacity) {+ return windows_generation_file_path(canonical_launcher_path, payload_sha256,+ L"codebase-memory-mcp.exe", path_out, path_capacity);+}++bool cbm_windows_retired_state_path(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], uint32_t payload_pid,+ wchar_t *path_out, size_t path_capacity) {+ if (path_out && path_capacity > 0U) {+ path_out[0] = L'\0';+ }+ if (!canonical_launcher_path || !lowercase_sha256_valid(payload_sha256) || payload_pid == 0U ||+ !path_out || path_capacity == 0U) {+ return false;+ }+ const wchar_t *last_backslash = wcsrchr(canonical_launcher_path, L'\\');+ const wchar_t *last_slash = wcsrchr(canonical_launcher_path, L'/');+ const wchar_t *separator = last_backslash;+ if (!separator || (last_slash && last_slash > separator)) {+ separator = last_slash;+ }+ if (!separator || separator == canonical_launcher_path ||+ (separator == canonical_launcher_path + 2 && canonical_launcher_path[1] != L':')) {+ return false;+ }+ size_t directory_length = (size_t)(separator - canonical_launcher_path);+ if (directory_length == 2U && canonical_launcher_path[1] == L':') {+ directory_length = 3U;+ }+ bool root = directory_length == 3U && canonical_launcher_path[1] == L':' &&+ (canonical_launcher_path[2] == L'\\' || canonical_launcher_path[2] == L'/');+ static const wchar_t retired_prefix[] = L".cbm-retired-v1-";+ wchar_t pid_text[16];+ int pid_written = swprintf(pid_text, sizeof(pid_text) / sizeof(pid_text[0]), L"%u",+ (unsigned int)payload_pid);+ size_t prefix_length = sizeof(retired_prefix) / sizeof(retired_prefix[0]) - 1U;+ if (pid_written <= 0 || (size_t)pid_written >= sizeof(pid_text) / sizeof(pid_text[0])) {+ return false;+ }+ size_t leaf_length = prefix_length + CBM_WINDOWS_RETIRED_TAG_HEX + 1U + (size_t)pid_written;+ wchar_t leaf[128];+ if (leaf_length + 1U > sizeof(leaf) / sizeof(leaf[0])) {+ return false;+ }+ memcpy(leaf, retired_prefix, prefix_length * sizeof(*leaf));+ size_t leaf_offset = prefix_length;+ /* A 16-hex-char (64-bit) prefix of the payload digest keeps the retired+ * directory uniquely identifiable while staying inside the directory-+ * rename length limit for the deepest managed-install ancestries. The+ * managed uninstall renames the state tree with FileRenameInfoEx on an+ * already-DELETE-opened handle (MoveFileExW cannot: it needs+ * FILE_DELETE_CHILD on the parent, which the add-only managed ancestor+ * withholds), and that call caps the absolute target near MAX_PATH. */+ for (size_t index = 0U; index < CBM_WINDOWS_RETIRED_TAG_HEX; index++) {+ leaf[leaf_offset++] = (wchar_t)(unsigned char)payload_sha256[index];+ }+ leaf[leaf_offset++] = L'-';+ memcpy(leaf + leaf_offset, pid_text, ((size_t)pid_written + 1U) * sizeof(*leaf));+ size_t separator_count = root ? 0U : 1U;+ size_t needed = directory_length + separator_count + leaf_length + 1U;+ if (needed > path_capacity) {+ return false;+ }+ memcpy(path_out, canonical_launcher_path, directory_length * sizeof(*path_out));+ size_t offset = directory_length;+ if (!root) {+ path_out[offset++] = L'\\';+ } else {+ path_out[2] = L'\\';+ }memcpy(path_out + offset, leaf, (leaf_length + 1U) * sizeof(*path_out));return true;}@@ -324,6 +409,17 @@ bool cbm_windows_launcher_file_secure(const wchar_t *launcher_path, char *error,return false;}+bool cbm_windows_managed_launcher_backing(const wchar_t *canonical_launcher_path,+ wchar_t *backing_path_out, size_t backing_path_capacity,+ char *error, size_t error_size) {+ (void)canonical_launcher_path;+ if (backing_path_out && backing_path_capacity > 0U) {+ backing_path_out[0] = L'\0';+ }+ launcher_error(error, error_size, "Windows launcher support is unavailable");+ return false;+}+bool cbm_windows_release_descriptor_probe(const wchar_t *launcher_candidate,cbm_windows_release_descriptor_v1_t *descriptor_out,char *error, size_t error_size) {@@ -344,10 +440,10 @@ bool cbm_windows_current_v1_write_atomic(const wchar_t *canonical_launcher_path,return false;}-bool cbm_windows_launcher_replace_atomic(const wchar_t *target_path, const wchar_t *candidate_path,+bool cbm_windows_launcher_replace_atomic(const wchar_t *target_path, const wchar_t *backing_path,char *error, size_t error_size) {(void)target_path;- (void)candidate_path;+ (void)backing_path;launcher_error(error, error_size, "Windows launcher support is unavailable");return false;}@@ -358,6 +454,15 @@ bool cbm_windows_launcher_remove_posix(const wchar_t *target_path, char *error,return false;}+bool cbm_windows_launcher_uninstall_commit(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], char *error,+ size_t error_size) {+ (void)canonical_launcher_path;+ (void)payload_sha256;+ launcher_error(error, error_size, "Windows launcher support is unavailable");+ return false;+}+bool cbm_windows_generation_rollback_if_unreferenced(const wchar_t *canonical_launcher_path,const char payload_sha256[65],bool created_by_activation, char *error,@@ -485,12 +590,21 @@ static bool windows_pipe_wait_available(HANDLE pipe, size_t needed, uint64_t deareturn false;}-static bool windows_file_identity(HANDLE file, BY_HANDLE_FILE_INFORMATION *information) {+static bool windows_file_information(HANDLE file, BY_HANDLE_FILE_INFORMATION *information) {return file && file != INVALID_HANDLE_VALUE && GetFileType(file) == FILE_TYPE_DISK &&GetFileInformationByHandle(file, information) != 0 &&(information->dwFileAttributes &- (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0 &&- information->nNumberOfLinks == 1U;+ (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0;+}++static bool windows_file_identity_links(HANDLE file, BY_HANDLE_FILE_INFORMATION *information,+ DWORD expected_links) {+ return windows_file_information(file, information) &&+ information->nNumberOfLinks == expected_links;+}++static bool windows_file_identity(HANDLE file, BY_HANDLE_FILE_INFORMATION *information) {+ return windows_file_identity_links(file, information, 1U);}static bool windows_same_identity(const BY_HANDLE_FILE_INFORMATION *first,@@ -549,7 +663,15 @@ static bool windows_bounded_ace_sid_is_trusted(const ACE_HEADER *header, PSID cuGetLengthSid((PSID)sid) == (DWORD)sid_length &&(windows_sid_is_trusted((PSID)sid, current_user) ||(((header->AceFlags & INHERIT_ONLY_ACE) != 0U) &&- IsWellKnownSid((PSID)sid, WinCreatorOwnerSid)));+ IsWellKnownSid((PSID)sid, WinCreatorOwnerSid)) ||+ /* OWNER RIGHTS (S-1-3-4) modulates the rights of whoever OWNS the+ * object; the owner is separately validated by+ * windows_owner_secure in every chain that reaches here, so such+ * an ACE only ever grants to an already-trusted identity. Default+ * Windows profile/temp ACLs (and GitHub runner profiles) carry+ * it; the daemon IPC ancestry validator documents the same+ * tolerance. */+ IsWellKnownSid((PSID)sid, WinCreatorOwnerRightsSid));}static bool windows_owner_secure(HANDLE file, bool require_current_user) {@@ -657,32 +779,47 @@ static bool windows_acl_secure(HANDLE file) {static bool windows_path_tree_plain(const wchar_t *file_path) {size_t length = file_path ? wcslen(file_path) : 0U;+ /* Accept the extended-length prefix for local drive paths: launchers may+ * legitimately resolve their image through \\?\C:\... (>MAX_PATH-safe+ * form). The prefix is dropped for shape checks and the component walk;+ * \\?\UNC\... stays rejected with every other non-local namespace. */+ if (length >= 4U && file_path[0] == L'\\' && file_path[1] == L'\\' && file_path[2] == L'?' &&+ file_path[3] == L'\\') {+ file_path += 4;+ length -= 4U;+ }if (length < 4U || length >= CBM_WINDOWS_LAUNCHER_PATH_CAP || file_path[1] != L':' ||(file_path[2] != L'\\' && file_path[2] != L'/')) {return false;}- wchar_t *path = malloc((length + 1U) * sizeof(*path));+ /* Walk in the extended-length namespace: the cumulative ancestor paths of+ * a >MAX_PATH target overflow the legacy limit even though the full path+ * itself opens, so every component open below carries the \\?\\ prefix.+ * Boundary offsets stay relative to the plain form (component index i is+ * prefixed-buffer index i + 4). */+ wchar_t *path = malloc((length + 5U) * sizeof(*path));if (!path) {return false;}- memcpy(path, file_path, (length + 1U) * sizeof(*path));+ wmemcpy(path, L"\\\\?\\", 4);+ memcpy(path + 4, file_path, (length + 1U) * sizeof(*path));for (size_t index = 0U; index < length; index++) {- if (path[index] == L'/')- path[index] = L'\\';+ if (path[4U + index] == L'/')+ path[4U + index] = L'\\';}- wchar_t *last = wcsrchr(path, L'\\');- if (!last || last <= path + 2) {+ wchar_t *last = wcsrchr(path + 4, L'\\');+ if (!last || last <= path + 6) {free(path);return false;}*last = L'\0';- size_t directory_length = wcslen(path);+ size_t directory_length = wcslen(path + 4);bool valid = true;for (size_t index = 3U; valid && index <= directory_length; index++) {- if (index < directory_length && path[index] != L'\\')+ if (index < directory_length && path[4U + index] != L'\\')continue;- wchar_t saved = path[index];- path[index] = L'\0';+ wchar_t saved = path[4U + index];+ path[4U + index] = L'\0';HANDLE component =CreateFileW(path, FILE_READ_ATTRIBUTES | READ_CONTROL,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,@@ -695,27 +832,31 @@ static bool windows_path_tree_plain(const wchar_t *file_path) {* immediate parent remains fully private. */mutation &= ~((DWORD)FILE_ADD_SUBDIRECTORY);}- valid = component != INVALID_HANDLE_VALUE && GetFileType(component) == FILE_TYPE_DISK &&- GetFileInformationByHandle(component, &information) != 0 &&- (information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&- (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&- windows_owner_secure(component, false) &&- windows_acl_secure_for_mutation(component, mutation);+ bool open_ok =+ component != INVALID_HANDLE_VALUE && GetFileType(component) == FILE_TYPE_DISK;+ bool info_ok = open_ok && GetFileInformationByHandle(component, &information) != 0 &&+ (information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&+ (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0;+ bool owner_ok = info_ok && windows_owner_secure(component, false);+ bool acl_ok = owner_ok && windows_acl_secure_for_mutation(component, mutation);+ valid = acl_ok;if (component != INVALID_HANDLE_VALUE)(void)CloseHandle(component);- path[index] = saved;+ path[4U + index] = saved;}free(path);return valid;}-static HANDLE windows_open_regular_no_reparse(const wchar_t *path, DWORD access) {+static HANDLE windows_open_regular_no_reparse_links(const wchar_t *path, DWORD access,+ DWORD expected_links) {HANDLE file =CreateFileW(path, access | FILE_READ_ATTRIBUTES | READ_CONTROL,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, NULL);BY_HANDLE_FILE_INFORMATION information;- if (!windows_path_tree_plain(path) || !windows_file_identity(file, &information) ||+ if (!windows_path_tree_plain(path) || !windows_file_information(file, &information) ||+ (expected_links != 0U && information.nNumberOfLinks != expected_links) ||!windows_owner_is_current(file) || !windows_acl_secure(file)) {if (file != INVALID_HANDLE_VALUE) {(void)CloseHandle(file);@@ -725,9 +866,39 @@ static HANDLE windows_open_regular_no_reparse(const wchar_t *path, DWORD access)return file;}-static HANDLE windows_open_directory_secure(const wchar_t *path) {+static HANDLE windows_open_regular_no_reparse(const wchar_t *path, DWORD access) {+ return windows_open_regular_no_reparse_links(path, access, 1U);+}++/* The launcher may be owned by the installing user or by one of the bounded+ * privileged principals accepted by the permanent launcher. Keep this+ * context-only opener separate from the exact-current-owner opener above:+ * mutable transaction files must never inherit this broader owner policy. */+static HANDLE windows_open_launcher_context_file(const wchar_t *path, DWORD expected_links) {+ HANDLE file =+ CreateFileW(path, GENERIC_READ | FILE_READ_ATTRIBUTES | READ_CONTROL,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, NULL);+ BY_HANDLE_FILE_INFORMATION information;+ bool tree_ok = windows_path_tree_plain(path);+ bool links_ok = tree_ok && windows_file_identity_links(file, &information, expected_links);+ bool owner_ok = links_ok && windows_owner_secure(file, false);+ bool acl_ok = owner_ok && windows_acl_secure(file);+ if (!acl_ok) {+ if (file != INVALID_HANDLE_VALUE) {+ (void)CloseHandle(file);+ }+ return INVALID_HANDLE_VALUE;+ }+ return file;+}++static bool windows_create_directory_private(const wchar_t *path);+static bool windows_stamp_current_owner_private(HANDLE file);++static HANDLE windows_open_directory_secure_access(const wchar_t *path, DWORD access) {HANDLE directory =- CreateFileW(path, FILE_READ_ATTRIBUTES | READ_CONTROL,+ CreateFileW(path, access | FILE_READ_ATTRIBUTES | READ_CONTROL,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);BY_HANDLE_FILE_INFORMATION information;@@ -744,6 +915,10 @@ static HANDLE windows_open_directory_secure(const wchar_t *path) {return directory;}+static HANDLE windows_open_directory_secure(const wchar_t *path) {+ return windows_open_directory_secure_access(path, 0U);+}+static bool windows_process_creation(HANDLE process, FILETIME *creation_out) {FILETIME exit_time;FILETIME kernel_time;@@ -829,15 +1004,39 @@ bool cbm_windows_launcher_context_consume(cbm_windows_launcher_context_t *contexif (server) {(void)CloseHandle(server);}- HANDLE actual_file =- valid ? windows_open_regular_no_reparse(actual_path, GENERIC_READ) : INVALID_HANDLE_VALUE;- HANDLE claimed_file =- valid ? windows_open_regular_no_reparse(claimed_path, GENERIC_READ) : INVALID_HANDLE_VALUE;+ const char *context_error = "invalid or unauthenticated Windows launcher context";+ DWORD expected_launcher_links = (flags & CBM_LAUNCH_CONTEXT_FLAG_MANAGED) != 0U ? 2U : 1U;+ HANDLE actual_file = INVALID_HANDLE_VALUE;+ HANDLE claimed_file = INVALID_HANDLE_VALUE;BY_HANDLE_FILE_INFORMATION actual_info;BY_HANDLE_FILE_INFORMATION claimed_info;- valid = valid && windows_file_identity(actual_file, &actual_info) &&- windows_file_identity(claimed_file, &claimed_info) &&- windows_same_identity(&actual_info, &claimed_info);+ if (valid) {+ actual_file = windows_open_launcher_context_file(actual_path, expected_launcher_links);+ if (actual_file == INVALID_HANDLE_VALUE) {+ context_error = "Windows launcher context actual image failed secure open";+ valid = false;+ }+ }+ if (valid) {+ claimed_file = windows_open_launcher_context_file(claimed_path, expected_launcher_links);+ if (claimed_file == INVALID_HANDLE_VALUE) {+ context_error = "Windows launcher context claimed path failed secure open";+ valid = false;+ }+ }+ if (valid && !windows_file_identity_links(actual_file, &actual_info, expected_launcher_links)) {+ context_error = "Windows launcher context actual image failed secure open";+ valid = false;+ }+ if (valid &&+ !windows_file_identity_links(claimed_file, &claimed_info, expected_launcher_links)) {+ context_error = "Windows launcher context claimed path failed secure open";+ valid = false;+ }+ if (valid && !windows_same_identity(&actual_info, &claimed_info)) {+ context_error = "Windows launcher context actual/claimed file identity mismatch";+ valid = false;+ }if (actual_file != INVALID_HANDLE_VALUE) {(void)CloseHandle(actual_file);}@@ -846,7 +1045,7 @@ bool cbm_windows_launcher_context_consume(cbm_windows_launcher_context_t *contex}if (!valid) {(void)CloseHandle(pipe);- launcher_error(error, error_size, "invalid or unauthenticated Windows launcher context");+ launcher_error(error, error_size, context_error);memset(context_out, 0, sizeof(*context_out));return false;}@@ -940,27 +1139,80 @@ static bool windows_posix_remove_handle(HANDLE file) {sizeof(disposition)) != 0;}-static bool windows_posix_rename_handle(HANDLE file, const wchar_t *target_path) {+static bool windows_posix_rename_handle_flags(HANDLE file, const wchar_t *target_path,+ bool replace_existing) {+ /* The rename target travels to NtSetInformationFile. A bare drive path is+ * converted internally with the legacy MAX_PATH bound (deep targets fail+ * with ERROR_FILENAME_EXCED_RANGE), and the Win32 \\\\?\\ prefix is not a+ * valid NT name — the NT namespace form \\??\\ is, at any length. */size_t chars = wcslen(target_path);if (chars == 0U || chars > (size_t)UINT32_MAX / sizeof(wchar_t)) {return false;}++ /* The rename TARGET must be the bare Win32 path — harness-proven on this+ * kernel: FileRenameInfoEx submits the name to NtSetInformationFile, which+ * rejects the \\\\?\\ extended-length prefix (ERROR_INVALID_NAME, os 123)+ * AND the NT \\??\\ form (os 123), while accepting a bare drive path up to+ * the legacy limit. Strip any inherited prefix; never add one. */+ if (chars >= 4U && wcsncmp(target_path, L"\\\\?\\", 4) == 0) {+ target_path += 4;+ chars -= 4U;+ }size_t bytes = chars * sizeof(wchar_t);- size_t allocation = offsetof(cbm_file_rename_info_ex_t, FileName) + bytes;+ /* Allocate one extra WCHAR and NUL-terminate the name. FileNameLength governs+ * per the contract, but antivirus/filter drivers on this kernel read the+ * FileName as NUL-terminated: with an exactly-sized buffer they append+ * adjacent heap bytes to the created name (a flaky, garbage-suffixed rename+ * target). The terminator bounds them to the intended name. */+ size_t allocation = offsetof(cbm_file_rename_info_ex_t, FileName) + bytes + sizeof(wchar_t);cbm_file_rename_info_ex_t *rename = calloc(1U, allocation);if (!rename) {return false;}- rename->Flags = CBM_FILE_RENAME_REPLACE | CBM_FILE_RENAME_POSIX;+ rename->Flags = CBM_FILE_RENAME_POSIX | (replace_existing ? CBM_FILE_RENAME_REPLACE : 0U);rename->RootDirectory = NULL;rename->FileNameLength = (DWORD)bytes;- memcpy(rename->FileName, target_path, bytes);- bool renamed = SetFileInformationByHandle(file, CBM_FILE_RENAME_INFO_EX_CLASS, rename,- (DWORD)allocation) != 0;+ memcpy(rename->FileName, target_path, chars * sizeof(wchar_t));+ rename->FileName[chars] = L'\0';+ /* First-touch antivirus scanning (Defender filter drivers) transiently+ * vetoes renames of trees holding a just-created executable — observed as+ * ERROR_INVALID_NAME on a name that is provably valid moments later, and+ * classically as ACCESS_DENIED/SHARING_VIOLATION. Freshly built or+ * downloaded binaries are always cold, so first-run installs must absorb+ * the scan window with a bounded backoff. */+ bool renamed = false;+ DWORD last_error = ERROR_SUCCESS;+ for (DWORD wait_ms = 0U, waited_ms = 0U;; waited_ms += wait_ms) {+ renamed = SetFileInformationByHandle(file, CBM_FILE_RENAME_INFO_EX_CLASS, rename,+ (DWORD)allocation) != 0;+ if (renamed) {+ break;+ }+ last_error = GetLastError();+ bool transient = last_error == ERROR_INVALID_NAME || last_error == ERROR_ACCESS_DENIED ||+ last_error == ERROR_SHARING_VIOLATION;+ if (!transient || waited_ms >= 2000U) {+ break;+ }+ wait_ms = wait_ms == 0U ? 100U : (wait_ms < 1000U ? wait_ms * 2U : wait_ms);+ Sleep(wait_ms);+ }free(rename);+ if (!renamed) {+ SetLastError(last_error);+ }return renamed;}+static bool windows_posix_rename_handle(HANDLE file, const wchar_t *target_path) {+ return windows_posix_rename_handle_flags(file, target_path, true);+}++static bool windows_posix_rename_handle_no_replace(HANDLE file, const wchar_t *target_path) {+ return windows_posix_rename_handle_flags(file, target_path, false);+}+static bool windows_parent_path(const wchar_t *path, wchar_t *parent, size_t capacity) {if (!path || !parent || capacity == 0U) {return false;@@ -983,7 +1235,10 @@ static bool windows_parent_path(const wchar_t *path, wchar_t *parent, size_t cap}static bool windows_copy_flush_private(const wchar_t *candidate, const wchar_t *stage) {- HANDLE source = windows_open_regular_no_reparse(candidate, GENERIC_READ);+ /* Capability probes may copy the already-managed canonical launcher+ * (exact two links); candidate publication validation separately requires+ * an unpublished generation launcher to have exactly one link. */+ HANDLE source = windows_open_regular_no_reparse_links(candidate, GENERIC_READ, 0U);if (source == INVALID_HANDLE_VALUE || !windows_path_tree_plain(stage) ||!CopyFileW(candidate, stage, TRUE)) {if (source != INVALID_HANDLE_VALUE)@@ -992,12 +1247,18 @@ static bool windows_copy_flush_private(const wchar_t *candidate, const wchar_t *}(void)CloseHandle(source);HANDLE file =- CreateFileW(stage, GENERIC_READ | GENERIC_WRITE | DELETE,+ CreateFileW(stage, GENERIC_READ | GENERIC_WRITE | DELETE | WRITE_OWNER | WRITE_DAC,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH, NULL);BY_HANDLE_FILE_INFORMATION information;- bool ok = windows_file_identity(file, &information) && windows_owner_is_current(file) &&- windows_acl_secure(file) && FlushFileBuffers(file) != 0;+ /* CopyFileW's destination inherits the machine's default owner (e.g.+ * Administrators on runner-class images); re-stamp the exact current user+ * as owner and re-apply the owner-only protected DACL so the probe's own+ * exact-owner validation accepts the freshly staged image. */+ bool stamped = windows_stamp_current_owner_private(file);+ bool ok = stamped && windows_file_identity(file, &information) &&+ windows_owner_is_current(file) && windows_acl_secure(file) &&+ FlushFileBuffers(file) != 0;if (file != INVALID_HANDLE_VALUE) {(void)CloseHandle(file);}@@ -1016,67 +1277,124 @@ static bool windows_unique_sibling(const wchar_t *target, const wchar_t *tag, wcreturn written > 0 && (size_t)written < capacity;}-bool cbm_windows_launcher_replace_atomic(const wchar_t *target_path, const wchar_t *candidate_path,+static bool windows_generation_layout_exact(const wchar_t *generation_directory,+ DWORD expected_launcher_links,+ BY_HANDLE_FILE_INFORMATION *launcher_information_out);++static bool windows_backing_generation_layout_exact(const wchar_t *backing_path,+ DWORD expected_launcher_links) {+ wchar_t generation_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ return windows_parent_path(backing_path, generation_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP) &&+ windows_generation_layout_exact(generation_directory, expected_launcher_links, NULL);+}++bool cbm_windows_launcher_replace_atomic(const wchar_t *target_path, const wchar_t *backing_path,char *error, size_t error_size) {if (error && error_size > 0U)error[0] = '\0';- if (!target_path || !candidate_path || !target_path[0] || !candidate_path[0]) {+ if (!target_path || !backing_path || !target_path[0] || !backing_path[0]) {launcher_error(error, error_size, "invalid launcher replacement paths");return false;}- HANDLE candidate = windows_open_regular_no_reparse(candidate_path, GENERIC_READ);+ HANDLE backing = windows_open_regular_no_reparse_links(backing_path, GENERIC_READ, 0U);DWORD target_attributes = GetFileAttributesW(target_path);DWORD target_error =target_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;HANDLE target = target_attributes == INVALID_FILE_ATTRIBUTES? INVALID_HANDLE_VALUE- : windows_open_regular_no_reparse(target_path, GENERIC_READ);+ : windows_open_regular_no_reparse_links(target_path, GENERIC_READ, 0U);bool target_absent =target_attributes == INVALID_FILE_ATTRIBUTES &&(target_error == ERROR_FILE_NOT_FOUND || target_error == ERROR_PATH_NOT_FOUND);- if (candidate == INVALID_HANDLE_VALUE || (!target_absent && target == INVALID_HANDLE_VALUE) ||- !windows_path_tree_plain(target_path)) {- if (candidate != INVALID_HANDLE_VALUE)- (void)CloseHandle(candidate);+ BY_HANDLE_FILE_INFORMATION backing_before;+ BY_HANDLE_FILE_INFORMATION target_before;+ bool backing_valid = windows_file_information(backing, &backing_before);+ bool target_valid = target_absent || windows_file_information(target, &target_before);+ bool already_published = backing_valid && target_valid && !target_absent &&+ windows_same_identity(&backing_before, &target_before) &&+ backing_before.nNumberOfLinks == 2U &&+ target_before.nNumberOfLinks == 2U;+ if (already_published) {+ bool exact_layout = windows_backing_generation_layout_exact(backing_path, 2U);+ (void)CloseHandle(backing);+ (void)CloseHandle(target);+ if (!exact_layout) {+ launcher_error(error, error_size,+ "published launcher generation has extra or missing entries");+ }+ return exact_layout;+ }+ if (!backing_valid || backing_before.nNumberOfLinks != 1U || !target_valid ||+ (!target_absent && target_before.nNumberOfLinks != 2U) ||+ !windows_path_tree_plain(target_path) ||+ !windows_backing_generation_layout_exact(backing_path, 1U)) {+ if (backing != INVALID_HANDLE_VALUE)+ (void)CloseHandle(backing);if (target != INVALID_HANDLE_VALUE)(void)CloseHandle(target);- launcher_error(error, error_size, "launcher candidate or existing target is unsafe");+ launcher_error(error, error_size,+ "launcher backing or existing managed target has an unsafe link layout");return false;}- (void)CloseHandle(candidate);+ (void)CloseHandle(backing);if (target != INVALID_HANDLE_VALUE)(void)CloseHandle(target);wchar_t stage[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!windows_unique_sibling(target_path, L"replace", stage, CBM_WINDOWS_LAUNCHER_PATH_CAP) ||- !windows_copy_flush_private(candidate_path, stage)) {- launcher_error(error, error_size, "could not stage launcher replacement");- return false;- }- HANDLE file =- CreateFileW(stage, DELETE | FILE_READ_ATTRIBUTES | READ_CONTROL,- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,- FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH, NULL);- BY_HANDLE_FILE_INFORMATION information;- bool ok = windows_file_identity(file, &information) && windows_owner_is_current(file) &&- windows_acl_secure(file) && windows_posix_rename_handle(file, target_path);- if (file != INVALID_HANDLE_VALUE)- (void)CloseHandle(file);+ if (!windows_unique_sibling(target_path, L"hardlink", stage, CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !CreateHardLinkW(stage, backing_path, NULL)) {+ launcher_error(error, error_size, "could not create launcher hard-link stage");+ return false;+ }+ HANDLE stage_file = windows_open_regular_no_reparse_links(stage, DELETE, 2U);+ HANDLE backing_after_link =+ windows_open_regular_no_reparse_links(backing_path, GENERIC_READ, 2U);+ BY_HANDLE_FILE_INFORMATION stage_information;+ BY_HANDLE_FILE_INFORMATION backing_information;+ bool ok = windows_file_identity_links(stage_file, &stage_information, 2U) &&+ windows_file_identity_links(backing_after_link, &backing_information, 2U) &&+ windows_same_identity(&stage_information, &backing_information) &&+ windows_posix_rename_handle(stage_file, target_path);+ if (stage_file != INVALID_HANDLE_VALUE)+ (void)CloseHandle(stage_file);+ if (backing_after_link != INVALID_HANDLE_VALUE)+ (void)CloseHandle(backing_after_link);if (!ok) {(void)DeleteFileW(stage);- launcher_error(error, error_size, "atomic launcher replacement is unsupported or failed");+ launcher_error(error, error_size,+ "atomic hard-link launcher replacement is unsupported or failed");+ return false;+ }++ HANDLE canonical_check = windows_open_regular_no_reparse_links(target_path, GENERIC_READ, 2U);+ HANDLE backing_check = windows_open_regular_no_reparse_links(backing_path, GENERIC_READ, 2U);+ BY_HANDLE_FILE_INFORMATION canonical_information;+ BY_HANDLE_FILE_INFORMATION final_backing_information;+ bool committed = windows_file_identity_links(canonical_check, &canonical_information, 2U) &&+ windows_file_identity_links(backing_check, &final_backing_information, 2U) &&+ windows_same_identity(&canonical_information, &final_backing_information);+ if (canonical_check != INVALID_HANDLE_VALUE)+ (void)CloseHandle(canonical_check);+ if (backing_check != INVALID_HANDLE_VALUE)+ (void)CloseHandle(backing_check);+ if (!committed) {+ launcher_error(error, error_size,+ "published launcher did not retain its exact hard-link identity");}- return ok;+ return committed;}-bool cbm_windows_launcher_remove_posix(const wchar_t *target_path, char *error, size_t error_size) {+static bool cbm_windows_launcher_remove_posix_links(const wchar_t *target_path,+ DWORD expected_links, char *error,+ size_t error_size) {if (error && error_size > 0U)error[0] = '\0';if (!target_path || !target_path[0]) {launcher_error(error, error_size, "invalid launcher removal path");return false;}- HANDLE file = windows_open_regular_no_reparse(target_path, DELETE);- if (file == INVALID_HANDLE_VALUE) {+ HANDLE original =+ windows_open_regular_no_reparse_links(target_path, GENERIC_READ, expected_links);+ if (original == INVALID_HANDLE_VALUE) {DWORD attributes = GetFileAttributesW(target_path);DWORD remove_error = attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;if (attributes == INVALID_FILE_ATTRIBUTES &&@@ -1086,14 +1404,108 @@ bool cbm_windows_launcher_remove_posix(const wchar_t *target_path, char *error,launcher_error(error, error_size, "could not securely open launcher for removal");return false;}- bool removed = windows_posix_remove_handle(file);- (void)CloseHandle(file);+ (void)CloseHandle(original);++ /* Windows refuses a delete disposition on a mapped image. Uninstall uses+ * the same transaction proven by update: replace the mapped canonical+ * link with an unmapped two-link tombstone, then unlink only that fresh+ * name. The mapped generation backing remains as its safe sole link. */+ wchar_t tombstone[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t stage[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ if (!windows_unique_sibling(target_path, L"unlink-backing", tombstone,+ CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !windows_unique_sibling(target_path, L"unlink-stage", stage,+ CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ launcher_error(error, error_size, "launcher unlink staging path is too long");+ return false;+ }+ HANDLE tombstone_file = CreateFileW(+ tombstone,+ GENERIC_READ | GENERIC_WRITE | DELETE | WRITE_OWNER | WRITE_DAC | FILE_READ_ATTRIBUTES |+ READ_CONTROL,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, CREATE_NEW,+ FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH, NULL);+ bool tombstone_created = tombstone_file != INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION tombstone_information;+ /* CREATE_NEW inherits the parent directory's default owner (Administrators+ * on runner-class images); re-stamp the exact current user so the unlink+ * transaction's own owner validation accepts this fresh tombstone. */+ bool tombstone_ready = windows_stamp_current_owner_private(tombstone_file) &&+ windows_file_identity(tombstone_file, &tombstone_information) &&+ windows_owner_is_current(tombstone_file) &&+ windows_acl_secure(tombstone_file) && FlushFileBuffers(tombstone_file);+ if (tombstone_file != INVALID_HANDLE_VALUE)+ (void)CloseHandle(tombstone_file);+ bool stage_created = tombstone_ready && CreateHardLinkW(stage, tombstone, NULL) != 0;+ HANDLE stage_file = stage_created ? windows_open_regular_no_reparse_links(stage, DELETE, 2U)+ : INVALID_HANDLE_VALUE;+ HANDLE tombstone_link = stage_created+ ? windows_open_regular_no_reparse_links(tombstone, GENERIC_READ, 2U)+ : INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION stage_information;+ BY_HANDLE_FILE_INFORMATION tombstone_link_information;+ bool renamed = windows_file_identity_links(stage_file, &stage_information, 2U) &&+ windows_file_identity_links(tombstone_link, &tombstone_link_information, 2U) &&+ windows_same_identity(&stage_information, &tombstone_link_information) &&+ windows_posix_rename_handle(stage_file, target_path);+ if (stage_file != INVALID_HANDLE_VALUE)+ (void)CloseHandle(stage_file);+ if (tombstone_link != INVALID_HANDLE_VALUE)+ (void)CloseHandle(tombstone_link);++ HANDLE replacement = renamed ? windows_open_regular_no_reparse_links(target_path, DELETE, 2U)+ : INVALID_HANDLE_VALUE;+ HANDLE tombstone_after =+ renamed ? windows_open_regular_no_reparse_links(tombstone, GENERIC_READ, 2U)+ : INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION replacement_information;+ BY_HANDLE_FILE_INFORMATION tombstone_after_information;+ bool target_removed =+ windows_file_identity_links(replacement, &replacement_information, 2U) &&+ windows_file_identity_links(tombstone_after, &tombstone_after_information, 2U) &&+ windows_same_identity(&replacement_information, &tombstone_after_information) &&+ windows_posix_remove_handle(replacement);+ if (replacement != INVALID_HANDLE_VALUE)+ (void)CloseHandle(replacement);+ if (tombstone_after != INVALID_HANDLE_VALUE)+ (void)CloseHandle(tombstone_after);++ HANDLE tombstone_final =+ target_removed ? windows_open_regular_no_reparse(tombstone, DELETE) : INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION tombstone_final_information;+ bool tombstone_removed = windows_file_identity(tombstone_final, &tombstone_final_information) &&+ windows_posix_remove_handle(tombstone_final);+ if (tombstone_final != INVALID_HANDLE_VALUE)+ (void)CloseHandle(tombstone_final);++ if (!renamed && stage_created) {+ (void)DeleteFileW(stage);+ } else if (!target_removed) {+ /* Rename already committed: target now names only our unmapped+ * tombstone, never the original launcher, so cleanup is safe. */+ (void)DeleteFileW(target_path);+ }+ if (!tombstone_removed && tombstone_created)+ (void)DeleteFileW(tombstone);+ DWORD attributes = GetFileAttributesW(target_path);+ DWORD remove_error = attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;+ bool removed = renamed && target_removed && tombstone_removed &&+ attributes == INVALID_FILE_ATTRIBUTES &&+ (remove_error == ERROR_FILE_NOT_FOUND || remove_error == ERROR_PATH_NOT_FOUND);if (!removed) {- launcher_error(error, error_size, "POSIX launcher deletion is unsupported or failed");+ launcher_error(error, error_size,+ "transactional POSIX launcher unlink is unsupported or failed");}return removed;}+bool cbm_windows_launcher_remove_posix(const wchar_t *target_path, char *error, size_t error_size) {+ /* The canonical launcher is the managed two-link file (canonical name ++ * generation backing). Callers that have not intentionally dropped the+ * backing keep that invariant. */+ return cbm_windows_launcher_remove_posix_links(target_path, 2U, error, error_size);+}+/* 1 = valid current, 0 = absent, -1 = unsafe/corrupt. */static int windows_current_v1_read(const wchar_t *canonical_launcher_path,cbm_windows_current_v1_t *state_out) {@@ -1137,6 +1549,349 @@ static int windows_current_v1_read(const wchar_t *canonical_launcher_path,return valid ? 1 : -1;}+/* Relocate every generation backing executable OUT of the managed state tree so+ * the tree can be renamed aside during uninstall. The active generation's+ * launcher backing is hardlinked to the still-running managed launcher image; a+ * mapped file pins its directory against rename. A running image's LAST+ * directory name cannot be deleted, but the image CAN be renamed — so we MOVE+ * each backing to an `activation-<pid>-N.retired` tombstone beside the install.+ * That unpins the state tree while keeping the canonical the exact two-link+ * managed file for its own unlink; the moved name survives as the mapped+ * inode's link until this process exits, and the launcher's liveness-guarded+ * stale sweep reclaims the tombstone afterwards. Best-effort by design. */+/* A record of one generation backing moved aside to an activation-*.retired+ * tombstone during an unpin relocation. A FAILED uninstall must be able to+ * reverse every such move so the restored .cbm keeps its generation backings.+ * The full extended-length path cap is too large to hold on the stack per+ * record, so each path is heap-duplicated. */+typedef struct {+ wchar_t *from; /* the activation-*.retired tombstone the backing now lives at */+ wchar_t *to; /* the original generation backing path to restore it to */+} windows_backing_move_t;++typedef struct {+ windows_backing_move_t *moves;+ size_t count;+ size_t capacity;+} windows_backing_relocation_log_t;++static void windows_backing_relocation_log_record(windows_backing_relocation_log_t *log,+ const wchar_t *from, const wchar_t *to) {+ if (!log) {+ return;+ }+ if (log->count == log->capacity) {+ size_t next_capacity = log->capacity == 0U ? 8U : log->capacity * 2U;+ windows_backing_move_t *grown =+ (windows_backing_move_t *)realloc(log->moves, next_capacity * sizeof(*grown));+ if (!grown) {+ return; /* best-effort: an unrecorded move cannot be reversed, but the+ * commit still proceeds correctly on the success path */+ }+ log->moves = grown;+ log->capacity = next_capacity;+ }+ size_t from_bytes = (wcslen(from) + 1U) * sizeof(wchar_t);+ size_t to_bytes = (wcslen(to) + 1U) * sizeof(wchar_t);+ wchar_t *from_copy = (wchar_t *)malloc(from_bytes);+ wchar_t *to_copy = (wchar_t *)malloc(to_bytes);+ if (!from_copy || !to_copy) {+ free(from_copy);+ free(to_copy);+ return;+ }+ (void)memcpy(from_copy, from, from_bytes);+ (void)memcpy(to_copy, to, to_bytes);+ log->moves[log->count].from = from_copy;+ log->moves[log->count].to = to_copy;+ log->count++;+}++/* Reverse every recorded unpin relocation, moving each tombstone back to its+ * original generation backing path. Called only on the uninstall failure paths+ * after .cbm has been restored, so the target generation directories exist+ * again. The generation backing path routinely exceeds MAX_PATH, which the+ * handle-based FileRenameInfoEx cannot reach (its bare full-path target is+ * bounded by the legacy limit, and SetFileInformationByHandle rejects a+ * RootDirectory-relative form with ERROR_INVALID_PARAMETER, os 87 —+ * VM-proven). MoveFileExW converts both arguments through the DOS→NT path+ * routine itself, so the \\?\ extended-length form works at any depth, and a+ * mapped image may be renamed (only deletion is blocked) — the same property+ * the relocation itself relies on. Without MOVEFILE_REPLACE_EXISTING this+ * keeps the no-replace semantics of the outbound move. Best-effort per move:+ * a rename the kernel refuses leaves that tombstone for the launcher's+ * liveness-guarded stale sweep rather than aborting the restore. */+static void windows_restore_relocated_backings(const windows_backing_relocation_log_t *log) {+ if (!log) {+ return;+ }+ for (size_t index = 0U; index < log->count; index++) {+ (void)MoveFileExW(log->moves[index].from, log->moves[index].to, 0U);+ }+}++static void windows_backing_relocation_log_free(windows_backing_relocation_log_t *log) {+ if (!log) {+ return;+ }+ for (size_t index = 0U; index < log->count; index++) {+ free(log->moves[index].from);+ free(log->moves[index].to);+ }+ free(log->moves);+ log->moves = NULL;+ log->count = 0U;+ log->capacity = 0U;+}++static void windows_relocate_generation_backings(const wchar_t *state_directory,+ windows_backing_relocation_log_t *log) {+ if (!state_directory || !state_directory[0]) {+ return;+ }+ /* A generation backing path — a 64-hex generation directory nested under a+ * possibly-deep managed install — routinely exceeds MAX_PATH. Open it (and+ * enumerate) in the extended-length namespace, or CreateFileW fails with+ * ERROR_PATH_NOT_FOUND and the pin is never dropped. Normalize to a single+ * \\?\ prefix regardless of the caller's form. */+ const wchar_t *bare_state =+ wcsncmp(state_directory, L"\\\\?\\", 4) == 0 ? state_directory + 4 : state_directory;+ wchar_t install_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ if (!windows_parent_path(bare_state, install_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ return;+ }+ wchar_t pattern[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int written =+ swprintf(pattern, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"\\\\?\\%ls\\generations\\*", bare_state);+ if (written <= 0 || (size_t)written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return;+ }+ WIN32_FIND_DATAW entry;+ HANDLE search = FindFirstFileW(pattern, &entry);+ if (search == INVALID_HANDLE_VALUE) {+ return;+ }+ static const wchar_t *const backings[] = {L"codebase-memory-mcp.exe",+ L"codebase-memory-mcp.payload.exe"};+ unsigned int tombstone_index = 0U;+ do {+ if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0 ||+ (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {+ continue;+ }+ for (size_t index = 0U; index < sizeof(backings) / sizeof(backings[0]); index++) {+ wchar_t backing_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int backing_written = swprintf(backing_path, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"\\\\?\\%ls\\generations\\%ls\\%ls", bare_state,+ entry.cFileName, backings[index]);+ if (backing_written <= 0 || (size_t)backing_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ continue;+ }+ HANDLE handle = CreateFileW(backing_path, DELETE,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);+ if (handle == INVALID_HANDLE_VALUE) {+ continue; /* absent (e.g. no payload backing) or already relocated */+ }+ wchar_t tombstone[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int tombstone_written = swprintf(+ tombstone, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"\\\\?\\%ls\\activation-%lu-%u.retired",+ install_directory, (unsigned long)GetCurrentProcessId(), tombstone_index++);+ if (tombstone_written > 0 &&+ (size_t)tombstone_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ windows_posix_rename_handle_no_replace(handle, tombstone)) {+ windows_backing_relocation_log_record(log, tombstone, backing_path);+ }+ (void)CloseHandle(handle);+ }+ } while (FindNextFileW(search, &entry));+ (void)FindClose(search);+}++bool cbm_windows_launcher_uninstall_commit(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], char *error,+ size_t error_size) {+ if (error && error_size > 0U)+ error[0] = '\0';+ cbm_windows_current_v1_t current;+ wchar_t backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ char backing_error[128] = {0};+ if (!canonical_launcher_path || !lowercase_sha256_valid(payload_sha256) ||+ windows_current_v1_read(canonical_launcher_path, ¤t) != 1 ||+ strcmp(current.payload_sha256, payload_sha256) != 0 ||+ !cbm_windows_managed_launcher_backing(canonical_launcher_path, backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, backing_error,+ sizeof(backing_error))) {+ launcher_error(error, error_size,+ "managed launcher/current/backing validation failed before uninstall");+ return false;+ }++ wchar_t install_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t state_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t retired_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int state_written = windows_parent_path(canonical_launcher_path, install_directory,+ CBM_WINDOWS_LAUNCHER_PATH_CAP)+ ? swprintf(state_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\.cbm",+ install_directory)+ : -1;+ if (state_written <= 0 || (size_t)state_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||+ !cbm_windows_retired_state_path(canonical_launcher_path, payload_sha256,+ (uint32_t)GetCurrentProcessId(), retired_directory,+ CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ launcher_error(error, error_size, "managed retired-state path could not be derived");+ return false;+ }+ /* Normalize both paths to the bare Win32 form. FileRenameInfoEx accepts+ * only a bare target (the \\?\\ prefix is rejected NT-side), so the+ * retirement rename lands the tree at the bare path; every secure open and+ * restore below must resolve the same bare path, not the \\?\\ form the+ * canonical launcher path was canonicalized into. These paths are always+ * within the legacy limit. */+ if (wcsncmp(state_directory, L"\\\\?\\", 4) == 0) {+ (void)wmemmove(state_directory, state_directory + 4, wcslen(state_directory + 4) + 1U);+ }+ if (wcsncmp(retired_directory, L"\\\\?\\", 4) == 0) {+ (void)wmemmove(retired_directory, retired_directory + 4,+ wcslen(retired_directory + 4) + 1U);+ }+ DWORD retired_attributes = GetFileAttributesW(retired_directory);+ DWORD retired_error =+ retired_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;+ if (retired_attributes != INVALID_FILE_ATTRIBUTES ||+ (retired_error != ERROR_FILE_NOT_FOUND && retired_error != ERROR_PATH_NOT_FOUND)) {+ launcher_error(error, error_size,+ "unique retired-state destination already exists or is inaccessible");+ return false;+ }++ HANDLE original_backing = windows_open_regular_no_reparse_links(backing, GENERIC_READ, 2U);+ BY_HANDLE_FILE_INFORMATION original_backing_information;+ if (!windows_file_identity_links(original_backing, &original_backing_information, 2U)) {+ if (original_backing != INVALID_HANDLE_VALUE)+ (void)CloseHandle(original_backing);+ launcher_error(error, error_size,+ "managed launcher backing changed before state retirement");+ return false;+ }+ HANDLE state = windows_open_directory_secure_access(state_directory, DELETE);+ bool rename_succeeded = false;+ /* Records every backing an unpin relocation moves aside, so a failed+ * uninstall can reverse the moves and hand back a .cbm with its generation+ * backings intact. Empty (and its restore/free no-ops) when the rename never+ * needed to unpin. */+ windows_backing_relocation_log_t reloc_log = {0};+ if (state != INVALID_HANDLE_VALUE) {+ /* Retire the state tree by renaming it aside. Two transient forces can+ * veto the rename; both are absorbed inside one bounded budget:+ * 1. When the running managed launcher maps its generation backings,+ * those hardlinks pin the tree against rename (ACCESS_DENIED). Drop+ * that pin ONCE, only on the first failure, by relocating the+ * backings to activation-*.retired tombstones (a mapped image can be+ * renamed but not deleted; the inode survives via the canonical+ * link). Relocating only when the rename actually needs it keeps a+ * recoverable, unpinned tree undisturbed until the commit is+ * certain — a FAILED uninstall below must restore .cbm with its+ * generation backings intact.+ * 2. First-touch antivirus scanning transiently vetoes a provably valid+ * target as ERROR_INVALID_NAME; the loop keeps retrying. */+ DWORD settled_total_ms = 0U;+ bool backings_released = false;+ for (DWORD settle_ms = 0U;; settled_total_ms += settle_ms) {+ rename_succeeded = windows_posix_rename_handle_no_replace(state, retired_directory);+ if (rename_succeeded || settled_total_ms >= 30000U) {+ break;+ }+ if (!backings_released) {+ windows_relocate_generation_backings(state_directory, &reloc_log);+ backings_released = true;+ }+ settle_ms = settle_ms == 0U ? 200U : (settle_ms < 1600U ? settle_ms * 2U : settle_ms);+ Sleep(settle_ms);+ }+ }+ DWORD state_attributes = rename_succeeded ? GetFileAttributesW(state_directory) : 0U;+ DWORD state_error = rename_succeeded && state_attributes == INVALID_FILE_ATTRIBUTES+ ? GetLastError()+ : ERROR_SUCCESS;+ HANDLE retired_check =+ rename_succeeded ? windows_open_directory_secure(retired_directory) : INVALID_HANDLE_VALUE;+ bool retired = rename_succeeded && state_attributes == INVALID_FILE_ATTRIBUTES &&+ (state_error == ERROR_FILE_NOT_FOUND || state_error == ERROR_PATH_NOT_FOUND) &&+ retired_check != INVALID_HANDLE_VALUE;+ if (retired_check != INVALID_HANDLE_VALUE)+ (void)CloseHandle(retired_check);+ if (!retired) {+ bool restored =+ rename_succeeded && windows_posix_rename_handle_no_replace(state, state_directory);+ /* .cbm is back at its canonical path when the rename never moved it or was+ * moved back — reverse any unpin relocation so its generation backings+ * return. If the tree is stuck aside (restored == false), the tombstones+ * stay for manual recovery alongside it. */+ if (!rename_succeeded || restored) {+ windows_restore_relocated_backings(&reloc_log);+ }+ windows_backing_relocation_log_free(&reloc_log);+ if (state != INVALID_HANDLE_VALUE)+ (void)CloseHandle(state);+ (void)CloseHandle(original_backing);+ launcher_error(error, error_size,+ restored ? "managed state retirement validation failed and was restored"+ : "managed state could not be retired atomically; inspect the "+ "retired state directory before retrying");+ return false;+ }++ /* The canonical is still the exact two-link managed file — its second link is+ * the generation backing inside the retired tree, or the activation-*.retired+ * tombstone it was relocated to if the tree had to be unpinned — so its+ * unlink follows the proven two-link transaction and the surviving link keeps+ * the mapped inode alive until the process exits. */+ char unlink_error[256] = {0};+ bool unlinked = cbm_windows_launcher_remove_posix(canonical_launcher_path, unlink_error,+ sizeof(unlink_error));+ if (!unlinked) {+ HANDLE canonical =+ windows_open_regular_no_reparse_links(canonical_launcher_path, GENERIC_READ, 2U);+ BY_HANDLE_FILE_INFORMATION canonical_information;+ bool original_canonical_survived =+ windows_file_identity_links(canonical, &canonical_information, 2U) &&+ windows_same_identity(&canonical_information, &original_backing_information);+ if (canonical != INVALID_HANDLE_VALUE)+ (void)CloseHandle(canonical);+ bool restored = original_canonical_survived &&+ windows_posix_rename_handle_no_replace(state, state_directory);+ (void)CloseHandle(state);+ (void)CloseHandle(original_backing);+ if (restored) {+ /* .cbm is back — reverse any unpin relocation so the restored tree+ * keeps its generation backings. */+ windows_restore_relocated_backings(&reloc_log);+ if (error && error_size > 0U) {+ (void)snprintf(error, error_size,+ "canonical unlink failed; retired state was restored: %s",+ unlink_error[0] ? unlink_error : "transaction failed");+ }+ } else {+ launcher_error(error, error_size,+ "canonical unlink failed after state retirement; retired state was kept "+ "for manual recovery");+ }+ windows_backing_relocation_log_free(&reloc_log);+ return false;+ }+ (void)CloseHandle(state);+ (void)CloseHandle(original_backing);+ /* Commit succeeded. Relocate any generation backings still inside the retired+ * tree to activation-*.retired tombstones beside the install so the tree is+ * shallow enough for the detached cleanup's non-long-path-aware rd — a 64-hex+ * generation path exceeds MAX_PATH. Deferred to the commit path on purpose: a+ * failed uninstall restores .cbm with its backings intact and recoverable. */+ windows_relocate_generation_backings(retired_directory, NULL);+ windows_backing_relocation_log_free(&reloc_log);+ return true;+}+static bool windows_generation_directory_path(const wchar_t *canonical_launcher_path, const char payload_sha256[65],wchar_t directory_out[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {@@ -1150,8 +1905,9 @@ bool cbm_windows_launcher_file_secure(const wchar_t *launcher_path, char *error,size_t error_size) {if (error && error_size > 0U)error[0] = '\0';- HANDLE launcher = launcher_path ? windows_open_regular_no_reparse(launcher_path, GENERIC_READ)- : INVALID_HANDLE_VALUE;+ HANDLE launcher = launcher_path+ ? windows_open_regular_no_reparse_links(launcher_path, GENERIC_READ, 1U)+ : INVALID_HANDLE_VALUE;if (launcher == INVALID_HANDLE_VALUE) {launcher_error(error, error_size, "launcher path, owner, or access policy is unsafe");return false;@@ -1172,15 +1928,13 @@ static bool windows_generation_name_valid(const wchar_t *name) {return true;}-static bool windows_remove_generation_directory(const wchar_t *generation_directory) {- DWORD attributes = GetFileAttributesW(generation_directory);- if (attributes == INVALID_FILE_ATTRIBUTES) {- DWORD missing_error = GetLastError();- return missing_error == ERROR_FILE_NOT_FOUND || missing_error == ERROR_PATH_NOT_FOUND;- }+static bool windows_generation_layout_exact(const wchar_t *generation_directory,+ DWORD expected_launcher_links,+ BY_HANDLE_FILE_INFORMATION *launcher_information_out) {HANDLE directory = windows_open_directory_secure(generation_directory);- if (directory == INVALID_HANDLE_VALUE)+ if (directory == INVALID_HANDLE_VALUE) {return false;+ }(void)CloseHandle(directory);wchar_t pattern[CBM_WINDOWS_LAUNCHER_PATH_CAP];@@ -1191,39 +1945,233 @@ static bool windows_remove_generation_directory(const wchar_t *generation_direct}WIN32_FIND_DATAW entry;HANDLE search = FindFirstFileW(pattern, &entry);- if (search == INVALID_HANDLE_VALUE)+ if (search == INVALID_HANDLE_VALUE) {return false;+ }bool exact = true;size_t payload_entries = 0U;+ size_t launcher_entries = 0U;do {if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0) {continue;}- bool payload = wcscmp(entry.cFileName, L"codebase-memory-mcp.payload.exe") == 0 &&- (entry.dwFileAttributes &+ bool regular = (entry.dwFileAttributes &(FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0;- if (!payload) {+ if (regular && wcscmp(entry.cFileName, L"codebase-memory-mcp.payload.exe") == 0) {+ payload_entries++;+ } else if (regular && wcscmp(entry.cFileName, L"codebase-memory-mcp.exe") == 0) {+ launcher_entries++;+ } else {exact = false;break;}- payload_entries++;} while (FindNextFileW(search, &entry));DWORD find_error = GetLastError();(void)FindClose(search);- exact = exact && find_error == ERROR_NO_MORE_FILES && payload_entries == 1U;- if (!exact)+ if (!exact || find_error != ERROR_NO_MORE_FILES || payload_entries != 1U ||+ launcher_entries != 1U) {return false;+ }wchar_t payload_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t launcher_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];int payload_written = swprintf(payload_path, CBM_WINDOWS_LAUNCHER_PATH_CAP,L"%ls\\codebase-memory-mcp.payload.exe", generation_directory);- HANDLE payload = payload_written > 0 && (size_t)payload_written < CBM_WINDOWS_LAUNCHER_PATH_CAP- ? windows_open_regular_no_reparse(payload_path, DELETE)- : INVALID_HANDLE_VALUE;- bool removed = payload != INVALID_HANDLE_VALUE && windows_posix_remove_handle(payload);+ int launcher_written = swprintf(launcher_path, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\codebase-memory-mcp.exe", generation_directory);+ if (payload_written <= 0 || launcher_written <= 0 ||+ (size_t)payload_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||+ (size_t)launcher_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return false;+ }+ HANDLE payload = windows_open_regular_no_reparse(payload_path, GENERIC_READ);+ HANDLE launcher =+ windows_open_regular_no_reparse_links(launcher_path, GENERIC_READ, expected_launcher_links);+ BY_HANDLE_FILE_INFORMATION payload_information;+ BY_HANDLE_FILE_INFORMATION launcher_information;+ bool valid =+ windows_file_identity(payload, &payload_information) &&+ windows_file_identity_links(launcher, &launcher_information, expected_launcher_links);+ if (valid && launcher_information_out) {+ *launcher_information_out = launcher_information;+ }if (payload != INVALID_HANDLE_VALUE)(void)CloseHandle(payload);- return removed && RemoveDirectoryW(generation_directory) != 0;+ if (launcher != INVALID_HANDLE_VALUE)+ (void)CloseHandle(launcher);+ return valid;+}++bool cbm_windows_managed_launcher_backing(const wchar_t *canonical_launcher_path,+ wchar_t *backing_path_out, size_t backing_path_capacity,+ char *error, size_t error_size) {+ if (backing_path_out && backing_path_capacity > 0U) {+ backing_path_out[0] = L'\0';+ }+ if (error && error_size > 0U) {+ error[0] = '\0';+ }+ if (!canonical_launcher_path || !backing_path_out || backing_path_capacity == 0U) {+ launcher_error(error, error_size, "invalid managed launcher validation request");+ return false;+ }+ HANDLE canonical =+ windows_open_regular_no_reparse_links(canonical_launcher_path, GENERIC_READ, 2U);+ BY_HANDLE_FILE_INFORMATION canonical_information;+ if (!windows_file_identity_links(canonical, &canonical_information, 2U)) {+ if (canonical != INVALID_HANDLE_VALUE)+ (void)CloseHandle(canonical);+ launcher_error(error, error_size, "canonical launcher is not an exact two-link file");+ return false;+ }++ wchar_t install_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t generations_root[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int root_written = windows_parent_path(canonical_launcher_path, install_directory,+ CBM_WINDOWS_LAUNCHER_PATH_CAP)+ ? swprintf(generations_root, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\.cbm\\generations", install_directory)+ : -1;+ HANDLE root = root_written > 0 && (size_t)root_written < CBM_WINDOWS_LAUNCHER_PATH_CAP+ ? windows_open_directory_secure(generations_root)+ : INVALID_HANDLE_VALUE;+ if (root == INVALID_HANDLE_VALUE) {+ (void)CloseHandle(canonical);+ launcher_error(error, error_size, "managed generation root is missing or unsafe");+ return false;+ }+ (void)CloseHandle(root);++ wchar_t pattern[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int pattern_written =+ swprintf(pattern, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\*", generations_root);+ WIN32_FIND_DATAW entry;+ HANDLE search = pattern_written > 0 && (size_t)pattern_written < CBM_WINDOWS_LAUNCHER_PATH_CAP+ ? FindFirstFileW(pattern, &entry)+ : INVALID_HANDLE_VALUE;+ if (search == INVALID_HANDLE_VALUE) {+ (void)CloseHandle(canonical);+ launcher_error(error, error_size, "managed generation root could not be enumerated");+ return false;+ }++ size_t matches = 0U;+ wchar_t match[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ match[0] = L'\0';+ do {+ if (!windows_generation_name_valid(entry.cFileName) ||+ (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 ||+ (entry.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {+ continue;+ }+ wchar_t candidate[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int candidate_written =+ swprintf(candidate, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\%ls\\codebase-memory-mcp.exe",+ generations_root, entry.cFileName);+ if (candidate_written <= 0 || (size_t)candidate_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ continue;+ }+ HANDLE backing = windows_open_regular_no_reparse_links(candidate, GENERIC_READ, 2U);+ BY_HANDLE_FILE_INFORMATION backing_information;+ bool same = windows_file_identity_links(backing, &backing_information, 2U) &&+ windows_same_identity(&canonical_information, &backing_information);+ if (backing != INVALID_HANDLE_VALUE)+ (void)CloseHandle(backing);+ if (!same) {+ continue;+ }+ size_t candidate_length = wcslen(candidate);+ if (++matches != 1U || candidate_length + 1U > backing_path_capacity) {+ continue;+ }+ memcpy(match, candidate, (candidate_length + 1U) * sizeof(*match));+ } while (FindNextFileW(search, &entry));+ DWORD find_error = GetLastError();+ (void)FindClose(search);+ (void)CloseHandle(canonical);++ wchar_t generation_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ BY_HANDLE_FILE_INFORMATION backing_information;+ bool valid = find_error == ERROR_NO_MORE_FILES && matches == 1U && match[0] != L'\0' &&+ windows_parent_path(match, generation_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP) &&+ windows_generation_layout_exact(generation_directory, 2U, &backing_information) &&+ windows_same_identity(&canonical_information, &backing_information);+ if (!valid) {+ launcher_error(error, error_size,+ "canonical launcher has no unique exact generation backing");+ return false;+ }+ size_t match_length = wcslen(match);+ memcpy(backing_path_out, match, (match_length + 1U) * sizeof(*backing_path_out));+ return true;+}++typedef enum {+ WINDOWS_GENERATION_REMOVE_INVALID = 0,+ WINDOWS_GENERATION_REMOVE_REMOVED = 1,+ WINDOWS_GENERATION_REMOVE_BUSY = 2,+} windows_generation_remove_result_t;++static windows_generation_remove_result_t windows_remove_generation_directory(+ const wchar_t *generation_directory) {+ DWORD attributes = GetFileAttributesW(generation_directory);+ if (attributes == INVALID_FILE_ATTRIBUTES) {+ DWORD missing_error = GetLastError();+ return missing_error == ERROR_FILE_NOT_FOUND || missing_error == ERROR_PATH_NOT_FOUND+ ? WINDOWS_GENERATION_REMOVE_REMOVED+ : WINDOWS_GENERATION_REMOVE_INVALID;+ }+ if (!windows_generation_layout_exact(generation_directory, 1U, NULL))+ return WINDOWS_GENERATION_REMOVE_INVALID;++ wchar_t payload_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t launcher_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int payload_written = swprintf(payload_path, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\codebase-memory-mcp.payload.exe", generation_directory);+ int launcher_written = swprintf(launcher_path, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\codebase-memory-mcp.exe", generation_directory);+ if (payload_written <= 0 || launcher_written <= 0 ||+ (size_t)payload_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||+ (size_t)launcher_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return WINDOWS_GENERATION_REMOVE_INVALID;+ }++ /* Acquire DELETE handles for both exact-one-link files before mutating+ * either. Their symmetric share checks prevent a new deny-delete handle+ * from racing between the two dispositions. A live old launcher image+ * predictably refuses the first disposition, leaving the exact pair+ * untouched for a later prune. */+ HANDLE launcher = windows_open_regular_no_reparse(launcher_path, DELETE);+ DWORD launcher_open_error = launcher == INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS;+ HANDLE payload = windows_open_regular_no_reparse(payload_path, DELETE);+ DWORD payload_open_error = payload == INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS;+ if (launcher == INVALID_HANDLE_VALUE || payload == INVALID_HANDLE_VALUE) {+ if (launcher != INVALID_HANDLE_VALUE)+ (void)CloseHandle(launcher);+ if (payload != INVALID_HANDLE_VALUE)+ (void)CloseHandle(payload);+ DWORD open_error =+ launcher == INVALID_HANDLE_VALUE ? launcher_open_error : payload_open_error;+ return open_error == ERROR_ACCESS_DENIED || open_error == ERROR_SHARING_VIOLATION ||+ open_error == ERROR_LOCK_VIOLATION+ ? WINDOWS_GENERATION_REMOVE_BUSY+ : WINDOWS_GENERATION_REMOVE_INVALID;+ }+ bool launcher_removed = windows_posix_remove_handle(launcher);+ DWORD launcher_error_code = launcher_removed ? ERROR_SUCCESS : GetLastError();+ bool payload_removed = launcher_removed && windows_posix_remove_handle(payload);+ (void)CloseHandle(launcher);+ (void)CloseHandle(payload);+ if (!launcher_removed) {+ return launcher_error_code == ERROR_ACCESS_DENIED ||+ launcher_error_code == ERROR_SHARING_VIOLATION ||+ launcher_error_code == ERROR_LOCK_VIOLATION+ ? WINDOWS_GENERATION_REMOVE_BUSY+ : WINDOWS_GENERATION_REMOVE_INVALID;+ }+ return payload_removed && RemoveDirectoryW(generation_directory) != 0+ ? WINDOWS_GENERATION_REMOVE_REMOVED+ : WINDOWS_GENERATION_REMOVE_INVALID;}bool cbm_windows_generation_rollback_if_unreferenced(const wchar_t *canonical_launcher_path,@@ -1248,8 +2196,30 @@ bool cbm_windows_generation_rollback_if_unreferenced(const wchar_t *canonical_lareturn true;}wchar_t generation[CBM_WINDOWS_LAUNCHER_PATH_CAP];- if (!windows_generation_directory_path(canonical_launcher_path, payload_sha256, generation) ||- !windows_remove_generation_directory(generation)) {+ wchar_t canonical_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ char backing_error[128] = {0};+ DWORD canonical_attributes = GetFileAttributesW(canonical_launcher_path);+ DWORD canonical_error =+ canonical_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;+ bool canonical_absent =+ canonical_attributes == INVALID_FILE_ATTRIBUTES &&+ (canonical_error == ERROR_FILE_NOT_FOUND || canonical_error == ERROR_PATH_NOT_FOUND);+ bool backing_valid = canonical_absent ||+ cbm_windows_managed_launcher_backing(+ canonical_launcher_path, canonical_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, backing_error, sizeof(backing_error));+ wchar_t backing_generation[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ bool is_backing_generation =+ !canonical_absent && backing_valid &&+ windows_parent_path(canonical_backing, backing_generation, CBM_WINDOWS_LAUNCHER_PATH_CAP) &&+ windows_generation_directory_path(canonical_launcher_path, payload_sha256, generation) &&+ _wcsicmp(generation, backing_generation) == 0;+ if (is_backing_generation) {+ return true;+ }+ if (!backing_valid ||+ !windows_generation_directory_path(canonical_launcher_path, payload_sha256, generation) ||+ windows_remove_generation_directory(generation) != WINDOWS_GENERATION_REMOVE_REMOVED) {launcher_error(error, error_size,"new unreferenced generation could not be rolled back safely");return false;@@ -1277,6 +2247,22 @@ bool cbm_windows_generations_prune(const wchar_t *canonical_launcher_path, size_launcher_error(error, error_size, "generation root path could not be resolved");return false;}+ wchar_t canonical_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t backing_generation[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ char backing_error[128] = {0};+ if (!cbm_windows_managed_launcher_backing(canonical_launcher_path, canonical_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, backing_error,+ sizeof(backing_error)) ||+ !windows_parent_path(canonical_backing, backing_generation,+ CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ launcher_error(error, error_size, "canonical launcher backing is missing during pruning");+ return false;+ }+ bool current_is_backing = _wcsicmp(current_generation, backing_generation) == 0;+ if (!windows_generation_layout_exact(current_generation, current_is_backing ? 2U : 1U, NULL)) {+ launcher_error(error, error_size, "current generation layout is incomplete or unsafe");+ return false;+ }HANDLE root = windows_open_directory_secure(generations_root);if (root == INVALID_HANDLE_VALUE) {launcher_error(error, error_size, "generation root is missing or unsafe");@@ -1302,6 +2288,12 @@ bool cbm_windows_generations_prune(const wchar_t *canonical_launcher_path, size_current_name[index] = (wchar_t)(unsigned char)current.payload_sha256[index];}current_name[64] = L'\0';+ const wchar_t *backing_name = wcsrchr(backing_generation, L'\\');+ const wchar_t *backing_slash = wcsrchr(backing_generation, L'/');+ if (!backing_name || (backing_slash && backing_slash > backing_name)) {+ backing_name = backing_slash;+ }+ backing_name = backing_name ? backing_name + 1 : backing_generation;bool ok = true;size_t removed = 0U;do {@@ -1316,6 +2308,14 @@ bool cbm_windows_generations_prune(const wchar_t *canonical_launcher_path, size_ok = false;continue;}+ if (_wcsicmp(entry.cFileName, backing_name) == 0) {+ bool backing_entry_valid = wcscmp(entry.cFileName, backing_name) == 0 &&+ (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&+ (entry.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0;+ if (!backing_entry_valid)+ ok = false;+ continue;+ }if (!windows_generation_name_valid(entry.cFileName) ||(entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 ||(entry.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {@@ -1325,9 +2325,17 @@ bool cbm_windows_generations_prune(const wchar_t *canonical_launcher_path, size_wchar_t generation[CBM_WINDOWS_LAUNCHER_PATH_CAP];int generation_written = swprintf(generation, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\%ls",generations_root, entry.cFileName);- if (generation_written <= 0 ||- (size_t)generation_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||- !windows_remove_generation_directory(generation)) {+ windows_generation_remove_result_t removal =+ generation_written > 0 && (size_t)generation_written < CBM_WINDOWS_LAUNCHER_PATH_CAP+ ? windows_remove_generation_directory(generation)+ : WINDOWS_GENERATION_REMOVE_INVALID;+ if (removal == WINDOWS_GENERATION_REMOVE_BUSY) {+ /* A launcher mapped by an older live session keeps its sole+ * generation link until that process exits. Retaining the exact+ * layout is safe; the next activation prunes it. */+ continue;+ }+ if (removal != WINDOWS_GENERATION_REMOVE_REMOVED) {ok = false;continue;}@@ -1352,9 +2360,10 @@ bool cbm_windows_current_v1_write_atomic(const wchar_t *canonical_launcher_path,error[0] = '\0';uint8_t record[CBM_WINDOWS_CURRENT_V1_SIZE];wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];- HANDLE canonical = canonical_launcher_path- ? windows_open_regular_no_reparse(canonical_launcher_path, GENERIC_READ)- : INVALID_HANDLE_VALUE;+ HANDLE canonical =+ canonical_launcher_path+ ? windows_open_regular_no_reparse_links(canonical_launcher_path, GENERIC_READ, 2U)+ : INVALID_HANDLE_VALUE;if (!canonical_launcher_path || canonical == INVALID_HANDLE_VALUE ||!cbm_windows_current_v1_encode(state, record) ||!windows_parent_path(canonical_launcher_path, directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {@@ -1373,7 +2382,8 @@ bool cbm_windows_current_v1_write_atomic(const wchar_t *canonical_launcher_path,if (state_written <= 0 || current_written <= 0 ||(size_t)state_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||(size_t)current_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||- (!CreateDirectoryW(state_directory, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)) {+ (!windows_create_directory_private(state_directory) &&+ GetLastError() != ERROR_ALREADY_EXISTS)) {launcher_error(error, error_size, "could not create launcher state directory");return false;}@@ -1405,12 +2415,17 @@ bool cbm_windows_current_v1_write_atomic(const wchar_t *canonical_launcher_path,return false;}HANDLE file = CreateFileW(- stage, GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES | READ_CONTROL,+ stage,+ GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES | READ_CONTROL | WRITE_OWNER | WRITE_DAC,FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, CREATE_NEW,FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_WRITE_THROUGH, NULL);DWORD written = 0U;BY_HANDLE_FILE_INFORMATION information;- bool ok = file != INVALID_HANDLE_VALUE &&+ /* Stamp before the owner check: under an Administrators-default-owner+ * policy (GitHub runners, Windows Server) a NULL-security CREATE_NEW file+ * is Administrators-owned and the exact-owner validation below would+ * refuse our own staged record. */+ bool ok = file != INVALID_HANDLE_VALUE && windows_stamp_current_owner_private(file) &&WriteFile(file, record, sizeof(record), &written, NULL) != 0 &&written == sizeof(record) && FlushFileBuffers(file) != 0 &&windows_file_identity(file, &information) && windows_owner_is_current(file) &&@@ -1683,23 +2698,122 @@ static bool windows_created_directories_push(windows_created_directories_t *creareturn true;}+/* Directories this launcher creates must be owner-stamped explicitly: under+ * the Administrators-default-owner policy (GitHub runners, mirrored by the+ * local VM), CreateDirectoryW with a NULL descriptor yields an+ * Administrators-owned directory that this file's own exact-owner+ * validation then rejects. Same pattern as win_mkdtemp_private_create. */+static bool windows_stamp_current_owner_private(HANDLE file) {+ if (file == INVALID_HANDLE_VALUE) {+ return false;+ }+ HANDLE token = NULL;+ TOKEN_USER *user = NULL;+ PACL acl = NULL;+ DWORD needed = 0U;+ bool stamped = false;+ if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&+ !GetTokenInformation(token, TokenUser, NULL, 0U, &needed) &&+ GetLastError() == ERROR_INSUFFICIENT_BUFFER && (user = malloc(needed)) != NULL &&+ GetTokenInformation(token, TokenUser, user, needed, &needed) && user->User.Sid &&+ IsValidSid(user->User.Sid)) {+ EXPLICIT_ACCESSW access;+ memset(&access, 0, sizeof(access));+ access.grfAccessPermissions = GENERIC_ALL;+ access.grfAccessMode = SET_ACCESS;+ access.grfInheritance = NO_INHERITANCE;+ access.Trustee.TrusteeForm = TRUSTEE_IS_SID;+ access.Trustee.TrusteeType = TRUSTEE_IS_USER;+ access.Trustee.ptstrName = (LPWSTR)user->User.Sid;+ if (SetEntriesInAclW(1U, &access, NULL, &acl) == ERROR_SUCCESS &&+ SetSecurityInfo(file, SE_FILE_OBJECT,+ OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION |+ PROTECTED_DACL_SECURITY_INFORMATION,+ user->User.Sid, NULL, acl, NULL) == ERROR_SUCCESS) {+ stamped = true;+ }+ }+ if (acl) {+ (void)LocalFree(acl);+ }+ free(user);+ if (token) {+ (void)CloseHandle(token);+ }+ return stamped;+}++static bool windows_create_directory_private(const wchar_t *path) {+ bool created = false;+ HANDLE token = NULL;+ TOKEN_USER *user = NULL;+ PACL acl = NULL;+ DWORD needed = 0U;+ if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&+ !GetTokenInformation(token, TokenUser, NULL, 0U, &needed) &&+ GetLastError() == ERROR_INSUFFICIENT_BUFFER && (user = malloc(needed)) != NULL &&+ GetTokenInformation(token, TokenUser, user, needed, &needed) && user->User.Sid &&+ IsValidSid(user->User.Sid)) {+ EXPLICIT_ACCESSW access;+ memset(&access, 0, sizeof(access));+ access.grfAccessPermissions = GENERIC_ALL;+ access.grfAccessMode = SET_ACCESS;+ access.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;+ access.Trustee.TrusteeForm = TRUSTEE_IS_SID;+ access.Trustee.TrusteeType = TRUSTEE_IS_USER;+ access.Trustee.ptstrName = (LPWSTR)user->User.Sid;+ SECURITY_DESCRIPTOR descriptor;+ if (SetEntriesInAclW(1U, &access, NULL, &acl) == ERROR_SUCCESS &&+ InitializeSecurityDescriptor(&descriptor, SECURITY_DESCRIPTOR_REVISION) &&+ SetSecurityDescriptorDacl(&descriptor, TRUE, acl, FALSE) &&+ SetSecurityDescriptorOwner(&descriptor, user->User.Sid, FALSE) &&+ SetSecurityDescriptorControl(&descriptor, SE_DACL_PROTECTED, SE_DACL_PROTECTED)) {+ SECURITY_ATTRIBUTES attributes;+ attributes.nLength = sizeof(attributes);+ attributes.lpSecurityDescriptor = &descriptor;+ attributes.bInheritHandle = FALSE;+ created = CreateDirectoryW(path, &attributes) != 0;+ }+ }+ DWORD create_error = created ? ERROR_SUCCESS : GetLastError();+ if (acl) {+ (void)LocalFree(acl);+ }+ free(user);+ if (token) {+ (void)CloseHandle(token);+ }+ /* Callers distinguish ERROR_ALREADY_EXISTS; keep the creation error alive+ * across the cleanup calls above. */+ SetLastError(create_error);+ return created;+}+static bool windows_prepare_probe_directory(const wchar_t *target,windows_created_directories_t *created) {memset(created, 0, sizeof(*created));size_t length = target ? wcslen(target) : 0U;- if (length < 3U || length >= CBM_WINDOWS_LAUNCHER_PATH_CAP || target[1] != L':' ||- (target[2] != L'\\' && target[2] != L'/')) {+ /* Managed-install targets arrive in the extended-length form; the walk+ * keeps the prefix on every cumulative open and only the drive-shape+ * check and root guards shift by its four characters. */+ size_t root = 0U;+ if (length >= 4U && target[0] == L'\\' && target[1] == L'\\' && target[2] == L'?' &&+ target[3] == L'\\') {+ root = 4U;+ }+ if (length < root + 3U || length >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||+ target[root + 1U] != L':' || (target[root + 2U] != L'\\' && target[root + 2U] != L'/')) {return false;}wchar_t *cursor = malloc((length + 1U) * sizeof(*cursor));if (!cursor)return false;memcpy(cursor, target, (length + 1U) * sizeof(*cursor));- for (size_t index = 0U; index < length; index++) {+ for (size_t index = root; index < length; index++) {if (cursor[index] == L'/')cursor[index] = L'\\';}- while (length > 3U && cursor[length - 1U] == L'\\') {+ while (length > root + 3U && cursor[length - 1U] == L'\\') {cursor[--length] = L'\0';}bool valid = true;@@ -1711,13 +2825,14 @@ static bool windows_prepare_probe_directory(const wchar_t *target,FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);BY_HANDLE_FILE_INFORMATION information;- DWORD mutation = windows_private_mutation_rights();- if (created->count > 0U) {- /* Only a missing descendant will be created below this- * existing ancestor; sibling-directory creation is sufficient- * and cannot replace an existing component. */- mutation &= ~((DWORD)FILE_ADD_SUBDIRECTORY);- }+ /* Sibling-directory creation cannot replace an existing path+ * component at any ancestry level, and the descendant chain this+ * probe creates below here uses CreateDirectoryW without+ * OPEN_ALWAYS — a squatted component fails creation instead of+ * being adopted. Standard profile ancestors (and the launcher+ * guard's fixture) legitimately carry cross-account+ * add-subdirectory grants. */+ DWORD mutation = windows_private_mutation_rights() & ~((DWORD)FILE_ADD_SUBDIRECTORY);valid = ancestor != INVALID_HANDLE_VALUE && GetFileType(ancestor) == FILE_TYPE_DISK &&GetFileInformationByHandle(ancestor, &information) != 0 &&(information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&@@ -1734,8 +2849,8 @@ static bool windows_prepare_probe_directory(const wchar_t *target,valid = false;break;}- wchar_t *separator = wcsrchr(cursor, L'\\');- if (!separator || separator <= cursor + 2) {+ wchar_t *separator = wcsrchr(cursor + root, L'\\');+ if (!separator || separator <= cursor + root + 2) {valid = false;break;}@@ -1743,7 +2858,7 @@ static bool windows_prepare_probe_directory(const wchar_t *target,}for (size_t remaining = created->count; valid && remaining > 0U; remaining--) {const wchar_t *directory = created->paths[remaining - 1U];- if (!CreateDirectoryW(directory, NULL)) {+ if (!windows_create_directory_private(directory)) {valid = false;break;}@@ -1759,9 +2874,9 @@ static bool windows_prepare_probe_directory(const wchar_t *target,return valid;}-bool cbm_windows_launcher_capability_probe(const wchar_t *target_directory,- const wchar_t *launcher_candidate, char *error,- size_t error_size) {+static bool windows_launcher_capability_probe_once(const wchar_t *target_directory,+ const wchar_t *launcher_candidate, char *error,+ size_t error_size) {if (error && error_size > 0U)error[0] = '\0';if (!target_directory || !target_directory[0] || !launcher_candidate ||@@ -1794,19 +2909,151 @@ bool cbm_windows_launcher_capability_probe(const wchar_t *target_directory,ok ? CreateMutexW(NULL, FALSE, L"Local\\CBMWindowsLauncherCapabilityProbe-v1") : NULL;DWORD mutex_wait = mutex ? WaitForSingleObject(mutex, 30000U) : WAIT_FAILED;ok = ok && mutex_wait == WAIT_OBJECT_0;- wchar_t probe_a[CBM_WINDOWS_LAUNCHER_PATH_CAP];- wchar_t probe_b[CBM_WINDOWS_LAUNCHER_PATH_CAP];- int a_written =- swprintf(probe_a, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\.cbm-launcher-probe-a-%lu.exe",- target_directory, (unsigned long)GetCurrentProcessId());- int b_written =- swprintf(probe_b, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\.cbm-launcher-probe-b-%lu.exe",- target_directory, (unsigned long)GetCurrentProcessId());- ok = ok && a_written > 0 && b_written > 0 &&- (size_t)a_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&- (size_t)b_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&- windows_copy_flush_private(launcher_candidate, probe_a) &&- windows_copy_flush_private(launcher_candidate, probe_b);+ unsigned long probe_pid = (unsigned long)GetCurrentProcessId();+ unsigned long long probe_nonce = (unsigned long long)GetTickCount64();+ enum { WINDOWS_PROBE_PATH_COUNT = 12 };+ wchar_t *path_storage =+ calloc(WINDOWS_PROBE_PATH_COUNT * CBM_WINDOWS_LAUNCHER_PATH_CAP, sizeof(*path_storage));+ wchar_t *canonical = path_storage;+ wchar_t *old_generation = path_storage ? path_storage + CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *old_payload = path_storage ? path_storage + 2U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *old_backing = path_storage ? path_storage + 3U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *new_generation =+ path_storage ? path_storage + 4U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *new_payload = path_storage ? path_storage + 5U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *new_backing = path_storage ? path_storage + 6U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *state_directory =+ path_storage ? path_storage + 7U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *retired_directory =+ path_storage ? path_storage + 8U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *mapped_image = path_storage ? path_storage + 9U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *retired_mapped_image =+ path_storage ? path_storage + 10U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ wchar_t *state_mapped_link =+ path_storage ? path_storage + 11U * CBM_WINDOWS_LAUNCHER_PATH_CAP : NULL;+ int canonical_written = path_storage+ ? swprintf(canonical, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\.cbm-launcher-probe-canonical-%lu-%llu.exe",+ target_directory, probe_pid, probe_nonce)+ : -1;+ int old_generation_written = path_storage+ ? swprintf(old_generation, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\.cbm-launcher-probe-old-generation-%lu-%llu",+ target_directory, probe_pid, probe_nonce)+ : -1;+ int old_payload_written =+ path_storage ? swprintf(old_payload, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\codebase-memory-mcp.payload.exe", old_generation)+ : -1;+ int old_backing_written = path_storage+ ? swprintf(old_backing, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\codebase-memory-mcp.exe", old_generation)+ : -1;+ int new_generation_written = path_storage+ ? swprintf(new_generation, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\.cbm-launcher-probe-new-generation-%lu-%llu",+ target_directory, probe_pid, probe_nonce)+ : -1;+ int new_payload_written =+ path_storage ? swprintf(new_payload, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\codebase-memory-mcp.payload.exe", new_generation)+ : -1;+ int new_backing_written = path_storage+ ? swprintf(new_backing, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\codebase-memory-mcp.exe", new_generation)+ : -1;+ int state_directory_written = path_storage+ ? swprintf(state_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\.cbm-launcher-probe-state-%lu-%llu",+ target_directory, probe_pid, probe_nonce)+ : -1;+ int retired_directory_written = path_storage+ ? swprintf(retired_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\.cbm-launcher-probe-retired-%lu-%llu",+ target_directory, probe_pid, probe_nonce)+ : -1;+ int mapped_image_written = path_storage+ ? swprintf(mapped_image, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\.cbm-launcher-probe-mapped-%lu-%llu.exe",+ target_directory, probe_pid, probe_nonce)+ : -1;+ int retired_mapped_image_written =+ path_storage ? swprintf(retired_mapped_image, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\mapped-launcher.exe", retired_directory)+ : -1;+ int state_mapped_link_written = path_storage+ ? swprintf(state_mapped_link, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\mapped-launcher.exe", state_directory)+ : -1;+ ok = ok && canonical_written > 0 && old_generation_written > 0 && old_payload_written > 0 &&+ old_backing_written > 0 && new_generation_written > 0 && new_payload_written > 0 &&+ new_backing_written > 0 && state_directory_written > 0 && retired_directory_written > 0 &&+ mapped_image_written > 0 && retired_mapped_image_written > 0 &&+ state_mapped_link_written > 0 &&+ (size_t)state_mapped_link_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)canonical_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)old_generation_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)old_payload_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)old_backing_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)new_generation_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)new_payload_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)new_backing_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)state_directory_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)retired_directory_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)mapped_image_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&+ (size_t)retired_mapped_image_written < CBM_WINDOWS_LAUNCHER_PATH_CAP;+ bool old_generation_created = false;+ bool old_payload_created = false;+ bool old_backing_created = false;+ bool new_generation_created = false;+ bool new_payload_created = false;+ bool new_backing_created = false;+ bool canonical_created = false;+ if (ok)+ old_generation_created = windows_create_directory_private(old_generation);+ ok = ok && old_generation_created;+ if (ok)+ new_generation_created = windows_create_directory_private(new_generation);+ ok = ok && new_generation_created;+ if (ok)+ old_payload_created = windows_copy_flush_private(launcher_candidate, old_payload);+ ok = ok && old_payload_created;+ if (ok)+ old_backing_created = windows_copy_flush_private(launcher_candidate, old_backing);+ ok = ok && old_backing_created;+ if (ok)+ new_payload_created = windows_copy_flush_private(launcher_candidate, new_payload);+ ok = ok && new_payload_created;+ if (ok)+ new_backing_created = windows_copy_flush_private(launcher_candidate, new_backing);+ ok = ok && new_backing_created && windows_generation_layout_exact(old_generation, 1U, NULL) &&+ windows_generation_layout_exact(new_generation, 1U, NULL);+ if (ok)+ canonical_created = CreateHardLinkW(canonical, old_backing, NULL) != 0;+ ok = ok && canonical_created && windows_generation_layout_exact(old_generation, 2U, NULL);+ if (!ok) {+ (void)fprintf(stderr, "error: probe middle stage %d refused (os %lu)\n", 1,+ (unsigned long)GetLastError());+ }++ HANDLE canonical_before =+ ok ? windows_open_regular_no_reparse_links(canonical, GENERIC_READ, 2U)+ : INVALID_HANDLE_VALUE;+ HANDLE old_before = ok ? windows_open_regular_no_reparse_links(old_backing, GENERIC_READ, 2U)+ : INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION canonical_before_information;+ BY_HANDLE_FILE_INFORMATION old_before_information;+ ok = ok && windows_file_identity_links(canonical_before, &canonical_before_information, 2U) &&+ windows_file_identity_links(old_before, &old_before_information, 2U) &&+ windows_same_identity(&canonical_before_information, &old_before_information);+ if (!ok) {+ (void)fprintf(stderr, "error: probe M1-identity-before refused (os %lu)\n",+ (unsigned long)GetLastError());+ }+ if (canonical_before != INVALID_HANDLE_VALUE)+ (void)CloseHandle(canonical_before);+ if (old_before != INVALID_HANDLE_VALUE)+ (void)CloseHandle(old_before);SECURITY_ATTRIBUTES security = {.nLength = sizeof(security),@@ -1817,57 +3064,232 @@ bool cbm_windows_launcher_capability_probe(const wchar_t *target_directory,HANDLE release_a = ok ? CreateEventW(&security, TRUE, FALSE, NULL) : NULL;PROCESS_INFORMATION child_a;memset(&child_a, 0, sizeof(child_a));- ok = ok && ready_a && release_a && windows_probe_spawn(probe_a, ready_a, release_a, &child_a) &&- WaitForSingleObject(ready_a, 10000U) == WAIT_OBJECT_0;+ ok = ok && ready_a && release_a &&+ windows_probe_spawn(canonical, ready_a, release_a, &child_a) &&+ WaitForSingleObject(ready_a, 30000U) == WAIT_OBJECT_0;+ if (!ok) {+ (void)fprintf(stderr, "error: probe M2-spawnA refused (os %lu)\n",+ (unsigned long)GetLastError());+ }++ char transaction_error[256] = {0};+ bool replace_ok =+ ok && cbm_windows_launcher_replace_atomic(canonical, new_backing, transaction_error,+ sizeof(transaction_error));+ bool child_a_alive = replace_ok && WaitForSingleObject(child_a.hProcess, 0U) == WAIT_TIMEOUT;+ if (ok && !replace_ok) {+ (void)fprintf(stderr, "error: probe M3 replace_atomic refused (os %lu): %s\n",+ (unsigned long)GetLastError(),+ transaction_error[0] ? transaction_error : "no detail");+ }+ if (replace_ok && !child_a_alive) {+ DWORD child_code = 0U;+ (void)GetExitCodeProcess(child_a.hProcess, &child_code);+ (void)fprintf(stderr, "error: probe M3 child A exited early (code %lu)\n",+ (unsigned long)child_code);+ }+ ok = child_a_alive;++ HANDLE canonical_after = ok ? windows_open_regular_no_reparse_links(canonical, GENERIC_READ, 2U)+ : INVALID_HANDLE_VALUE;+ HANDLE new_after = ok ? windows_open_regular_no_reparse_links(new_backing, GENERIC_READ, 2U)+ : INVALID_HANDLE_VALUE;+ HANDLE old_after =+ ok ? windows_open_regular_no_reparse(old_backing, GENERIC_READ) : INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION canonical_after_information;+ BY_HANDLE_FILE_INFORMATION new_after_information;+ BY_HANDLE_FILE_INFORMATION old_after_information;+ ok = ok && windows_file_identity_links(canonical_after, &canonical_after_information, 2U) &&+ windows_file_identity_links(new_after, &new_after_information, 2U) &&+ windows_same_identity(&canonical_after_information, &new_after_information) &&+ windows_file_identity(old_after, &old_after_information) &&+ !windows_same_identity(&old_after_information, &new_after_information);+ if (!ok) {+ (void)fprintf(stderr, "error: probe M4-identity-after refused (os %lu)\n",+ (unsigned long)GetLastError());+ }+ if (canonical_after != INVALID_HANDLE_VALUE)+ (void)CloseHandle(canonical_after);+ if (new_after != INVALID_HANDLE_VALUE)+ (void)CloseHandle(new_after);+ if (old_after != INVALID_HANDLE_VALUE)+ (void)CloseHandle(old_after);++ /* Unlink the fresh, unmapped canonical name while the old generation's+ * sole backing remains mapped. This is the real managed transaction;+ * direct deletion of the mapped image is intentionally never probed. */+ ok = ok &&+ cbm_windows_launcher_remove_posix(canonical, transaction_error, sizeof(transaction_error));+ if (!ok) {+ (void)fprintf(stderr, "error: probe M5-remove refused (os %lu)\n",+ (unsigned long)GetLastError());+ }+ DWORD canonical_attributes = ok ? GetFileAttributesW(canonical) : INVALID_FILE_ATTRIBUTES;+ DWORD canonical_error =+ canonical_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;+ HANDLE new_final =+ ok ? windows_open_regular_no_reparse(new_backing, GENERIC_READ) : INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION new_final_information;+ ok = ok && canonical_attributes == INVALID_FILE_ATTRIBUTES &&+ (canonical_error == ERROR_FILE_NOT_FOUND || canonical_error == ERROR_PATH_NOT_FOUND) &&+ windows_file_identity(new_final, &new_final_information) &&+ WaitForSingleObject(child_a.hProcess, 0U) == WAIT_TIMEOUT;+ if (!ok) {+ (void)fprintf(stderr, "error: probe M6-final refused (os %lu)\n",+ (unsigned long)GetLastError());+ }+ if (new_final != INVALID_HANDLE_VALUE)+ (void)CloseHandle(new_final);- HANDLE source = ok ? CreateFileW(probe_b, DELETE | FILE_READ_ATTRIBUTES | READ_CONTROL,- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,- OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL)- : INVALID_HANDLE_VALUE;- BY_HANDLE_FILE_INFORMATION source_info;- ok = ok && windows_file_identity(source, &source_info) && windows_owner_is_current(source) &&- windows_posix_rename_handle(source, probe_a) &&- GetFileAttributesW(probe_a) != INVALID_FILE_ATTRIBUTES;- if (source != INVALID_HANDLE_VALUE)- (void)CloseHandle(source);windows_probe_child_stop(&child_a, release_a);if (ready_a)(void)CloseHandle(ready_a);if (release_a)(void)CloseHandle(release_a);- /* The replacement at probe_a is now a fresh candidate. Map it and prove- * POSIX deletion removes the visible name while the image remains live. */+ /* Also prove that a private state tree containing a mapped launcher can+ * be retired to a no-replace sibling and restored before any sessions are+ * drained. Uninstall relies on exactly this namespace transaction. */+ bool state_directory_created = false;+ bool mapped_image_created = false;+ if (ok) {+ state_directory_created = windows_create_directory_private(state_directory);+ if (!state_directory_created) {+ (void)fprintf(stderr, "error: probe state directory creation refused (os %lu): %ls\n",+ (unsigned long)GetLastError(), state_directory);+ }+ }+ ok = ok && state_directory_created;+ if (ok)+ mapped_image_created = windows_copy_flush_private(launcher_candidate, mapped_image);+ ok = ok && mapped_image_created;+ /* Mirror the real uninstall layout: the EXECUTING name lives outside the+ * state tree (like the canonical launcher and the retired staged copy);+ * the tree carries only a hardlink (like a generation backing). Renaming+ * a tree that merely links a mapped image is the capability uninstall+ * actually needs — and first-touch antivirus scanning pins only the+ * executing path, so this shape is immune to the cold-scan veto that a+ * directly-mapped inside file provokes. */+ bool state_link_created = ok && CreateHardLinkW(state_mapped_link, mapped_image, NULL) != 0;+ ok = ok && state_link_created;+ HANDLE state =+ ok ? windows_open_directory_secure_access(state_directory, DELETE) : INVALID_HANDLE_VALUE;HANDLE ready_b = ok ? CreateEventW(&security, TRUE, FALSE, NULL) : NULL;HANDLE release_b = ok ? CreateEventW(&security, TRUE, FALSE, NULL) : NULL;PROCESS_INFORMATION child_b;memset(&child_b, 0, sizeof(child_b));- ok = ok && ready_b && release_b && windows_probe_spawn(probe_a, ready_b, release_b, &child_b) &&- WaitForSingleObject(ready_b, 10000U) == WAIT_OBJECT_0;- HANDLE mapped = ok ? windows_open_regular_no_reparse(probe_a, DELETE) : INVALID_HANDLE_VALUE;- ok = ok && mapped != INVALID_HANDLE_VALUE && windows_posix_remove_handle(mapped) &&- GetFileAttributesW(probe_a) == INVALID_FILE_ATTRIBUTES &&- GetLastError() == ERROR_FILE_NOT_FOUND;- if (mapped != INVALID_HANDLE_VALUE)- (void)CloseHandle(mapped);+ bool probe_spawned = ok && state != INVALID_HANDLE_VALUE && ready_b && release_b &&+ windows_probe_spawn(mapped_image, ready_b, release_b, &child_b);+ bool probe_ready = probe_spawned && WaitForSingleObject(ready_b, 30000U) == WAIT_OBJECT_0;+ bool probe_retired =+ probe_ready && windows_posix_rename_handle_no_replace(state, retired_directory);+ if (ok && !probe_retired) {+ (void)fprintf(stderr,+ "error: capability probe stage failed: spawned=%d ready=%d "+ "retire-rename refused (os %lu)\n",+ probe_spawned ? 1 : 0, probe_ready ? 1 : 0, (unsigned long)GetLastError());+ (void)fprintf(stderr, "error: probe retire target was: %ls\n", retired_directory);+ (void)fprintf(stderr, "error: probe state source was: %ls\n", state_directory);+ }+ ok = probe_retired;+ DWORD state_attributes = ok ? GetFileAttributesW(state_directory) : 0U;+ DWORD state_missing_error =+ ok && state_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;+ HANDLE retired_check =+ ok ? windows_open_directory_secure(retired_directory) : INVALID_HANDLE_VALUE;+ ok = ok && state_attributes == INVALID_FILE_ATTRIBUTES &&+ (state_missing_error == ERROR_FILE_NOT_FOUND ||+ state_missing_error == ERROR_PATH_NOT_FOUND) &&+ retired_check != INVALID_HANDLE_VALUE &&+ WaitForSingleObject(child_b.hProcess, 0U) == WAIT_TIMEOUT &&+ windows_posix_rename_handle_no_replace(state, state_directory);+ if (retired_check != INVALID_HANDLE_VALUE)+ (void)CloseHandle(retired_check);+ DWORD retired_attributes = ok ? GetFileAttributesW(retired_directory) : 0U;+ DWORD retired_missing_error =+ ok && retired_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;+ HANDLE state_check = ok ? windows_open_directory_secure(state_directory) : INVALID_HANDLE_VALUE;+ ok = ok && retired_attributes == INVALID_FILE_ATTRIBUTES &&+ (retired_missing_error == ERROR_FILE_NOT_FOUND ||+ retired_missing_error == ERROR_PATH_NOT_FOUND) &&+ state_check != INVALID_HANDLE_VALUE &&+ WaitForSingleObject(child_b.hProcess, 0U) == WAIT_TIMEOUT;+ if (state_check != INVALID_HANDLE_VALUE)+ (void)CloseHandle(state_check);windows_probe_child_stop(&child_b, release_b);if (ready_b)(void)CloseHandle(ready_b);if (release_b)(void)CloseHandle(release_b);-- (void)DeleteFileW(probe_a);- (void)DeleteFileW(probe_b);+ if (state != INVALID_HANDLE_VALUE)+ (void)CloseHandle(state);++ if (canonical_created)+ (void)DeleteFileW(canonical);+ if (old_backing_created)+ (void)DeleteFileW(old_backing);+ if (old_payload_created)+ (void)DeleteFileW(old_payload);+ if (old_generation_created)+ (void)RemoveDirectoryW(old_generation);+ if (new_backing_created)+ (void)DeleteFileW(new_backing);+ if (new_payload_created)+ (void)DeleteFileW(new_payload);+ if (new_generation_created)+ (void)RemoveDirectoryW(new_generation);+ if (mapped_image_created) {+ (void)DeleteFileW(mapped_image);+ (void)DeleteFileW(retired_mapped_image);+ (void)DeleteFileW(state_mapped_link);+ }+ if (state_directory_created) {+ (void)RemoveDirectoryW(state_directory);+ (void)RemoveDirectoryW(retired_directory);+ }if (mutex_wait == WAIT_OBJECT_0)(void)ReleaseMutex(mutex);if (mutex)(void)CloseHandle(mutex);+ free(path_storage);windows_created_directories_close(&created, true);+ if (!ok) {+ /* Failure-path observability: name the phase that refused. */+ (void)fprintf(stderr,+ "error: capability probe flags: oldgen=%d newgen=%d oldpay=%d "+ "oldback=%d newpay=%d newback=%d canon=%d statedir=%d mapped=%d link=%d\n",+ old_generation_created ? 1 : 0, new_generation_created ? 1 : 0,+ old_payload_created ? 1 : 0, old_backing_created ? 1 : 0,+ new_payload_created ? 1 : 0, new_backing_created ? 1 : 0,+ canonical_created ? 1 : 0, state_directory_created ? 1 : 0,+ mapped_image_created ? 1 : 0, state_link_created ? 1 : 0);+ }if (!ok && (!error || error_size == 0U || error[0] == '\0')) {launcher_error(error, error_size,- "mapped-image POSIX replace/delete capability probe failed");+ "mapped-image hard-link and state-retirement capability probe failed");}return ok;}+bool cbm_windows_launcher_capability_probe(const wchar_t *target_directory,+ const wchar_t *launcher_candidate, char *error,+ size_t error_size) {+ /* First-touch antivirus scanning pins a never-seen executable for the+ * lifetime of the process mapped from it, which vetoes the probe's+ * state-retirement rename no matter how long that one call retries. The+ * first attempt's staged copies get scanned while it runs, so a single+ * full re-run is warm by construction. Freshly built or downloaded+ * binaries — every first install — hit this. */+ for (int attempt = 0;; attempt++) {+ if (windows_launcher_capability_probe_once(target_directory, launcher_candidate, error,+ error_size)) {+ return true;+ }+ if (attempt >= 1) {+ return false;+ }+ Sleep(500U);+ }+}+#endif /* _WIN32 */diff --git a/src/cli/windows_launcher_state.h b/src/cli/windows_launcher_state.hindex ee75ddb67..2948ff8b7 100644--- a/src/cli/windows_launcher_state.h+++ b/src/cli/windows_launcher_state.h@@ -27,6 +27,12 @@#endif#define CBM_WINDOWS_LAUNCHER_PATH_CAP 32768U+/* Hex-char count of the payload digest embedded in a retired-state directory+ * name. 16 chars (64 bits) uniquely identifies the retired generation while+ * keeping the retired path short enough for the managed uninstall's+ * handle-based directory rename at the deepest supported install depth. */+#define CBM_WINDOWS_RETIRED_TAG_HEX 16U+typedef struct {uint32_t launcher_abi_min;uint32_t launcher_abi_max;@@ -68,10 +74,20 @@ bool cbm_windows_release_descriptor_v1_decode(const uint8_t *record, size_t recocbm_windows_transition_plan_t cbm_windows_transition_plan(const cbm_windows_current_v1_t *current, const cbm_windows_release_descriptor_v1_t *candidate);-/* Resolve the immutable payload using the canonical launcher's directory. */+/* Resolve the immutable generation pair using the canonical launcher's+ * directory. A managed generation contains exactly these two executables:+ * the payload and the launcher's hard-link backing. */bool cbm_windows_generation_payload_path(const wchar_t *canonical_launcher_path,const char payload_sha256[65], wchar_t *path_out,size_t path_capacity);+bool cbm_windows_generation_launcher_path(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], wchar_t *path_out,+ size_t path_capacity);+/* Derive the race-free retired state sibling shared by the uninstall payload+ * (its own PID) and supervising launcher (the authenticated child PID). */+bool cbm_windows_retired_state_path(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], uint32_t payload_pid,+ wchar_t *path_out, size_t path_capacity);/* Match main's top-level dispatch. Tokens after a mode selector (cli,* install, config, hook-augment, help/version) are opaque user input. */@@ -107,15 +123,30 @@ bool cbm_windows_launcher_capability_probe(const wchar_t *target_directory,const wchar_t *launcher_candidate, char *error,size_t error_size);bool cbm_windows_launcher_file_secure(const wchar_t *launcher_path, char *error, size_t error_size);+/* Find the unique managed-generation backing for canonical_launcher_path.+ * The canonical name and backing must be the same file identity with exactly+ * two links. The backing need not be in the current payload generation while+ * a crash-safe cross-ABI transition is between its two publication steps. */+bool cbm_windows_managed_launcher_backing(const wchar_t *canonical_launcher_path,+ wchar_t *backing_path_out, size_t backing_path_capacity,+ char *error, size_t error_size);bool cbm_windows_release_descriptor_probe(const wchar_t *launcher_candidate,cbm_windows_release_descriptor_v1_t *descriptor_out,char *error, size_t error_size);bool cbm_windows_current_v1_write_atomic(const wchar_t *canonical_launcher_path,const cbm_windows_current_v1_t *state, char *error,size_t error_size);-bool cbm_windows_launcher_replace_atomic(const wchar_t *target_path, const wchar_t *candidate_path,+/* Publish an exact-one-link immutable generation backing at the canonical+ * name by hard-linking a same-directory stage and POSIX-renaming that stage.+ * Success leaves canonical and backing as the same exact-two-link file. */+bool cbm_windows_launcher_replace_atomic(const wchar_t *target_path, const wchar_t *backing_path,char *error, size_t error_size);bool cbm_windows_launcher_remove_posix(const wchar_t *target_path, char *error, size_t error_size);+/* Retire .cbm to its generation/PID-qualified sibling, then unlink canonical+ * as the final uninstall commit. A failed unlink restores .cbm. */+bool cbm_windows_launcher_uninstall_commit(const wchar_t *canonical_launcher_path,+ const char payload_sha256[65], char *error,+ size_t error_size);bool cbm_windows_generation_rollback_if_unreferenced(const wchar_t *canonical_launcher_path,const char payload_sha256[65],bool created_by_activation, char *error,diff --git a/src/daemon/application.c b/src/daemon/application.cindex 845c5c212..20ecbb6ad 100644--- a/src/daemon/application.c+++ b/src/daemon/application.c@@ -179,6 +179,8 @@ struct cbm_daemon_application {bool update_thread_done;bool update_thread_joining;bool stopping;+ /* See cbm_daemon_application_set_permanent. */+ bool permanent;};typedef struct {@@ -455,11 +457,19 @@ static void application_refresh_watch_locked(cbm_daemon_application_session_t *s}return;}+ /* Physical registration is the commit point. Never publish a logical+ * subscription that the shared watcher failed to install. */+ if (!cbm_watcher_watch(application->watcher, project, root)) {+ cbm_log_warn("daemon.watch.registration_failed", "project", project, "action", "retry");+ free(watch->project);+ free(watch->root);+ free(watch);+ return;+ }watch->subscribers = 1;watch->next = application->watches;application->watches = watch;session->watch = watch;- cbm_watcher_watch(application->watcher, project, root);}static void application_refresh_watch(cbm_daemon_application_session_t *session) {@@ -2694,10 +2704,12 @@ static void application_session_cancel(void *context,final_live_session = false;}}- if (final_live_session) {+ if (final_live_session && !application->permanent) {/* The daemon runtime cannot close this allocation until an* in-flight callback joins. Stop new admission now and cancel- * watcher/UI jobs that are not owned by session->active_job. */+ * watcher/UI jobs that are not owned by session->active_job.+ * A PERMANENT generation deliberately outlives its sessions and+ * keeps admitting new ones; only the stop/drain paths latch it. */application->stopping = true;application_cancel_jobs_locked(application);application_update_cancel_locked(application);@@ -2757,6 +2769,15 @@ static void application_session_close(void *context,free(session);}+void cbm_daemon_application_set_permanent(cbm_daemon_application_t *application, bool permanent) {+ if (!application) {+ return;+ }+ cbm_mutex_lock(&application->mutex);+ application->permanent = permanent;+ cbm_mutex_unlock(&application->mutex);+}+cbm_daemon_application_t *cbm_daemon_application_new(const cbm_daemon_application_config_t *config) {cbm_daemon_application_t *application = calloc(1, sizeof(*application));diff --git a/src/daemon/application.h b/src/daemon/application.hindex f23dc38b6..ed35c750b 100644--- a/src/daemon/application.h+++ b/src/daemon/application.h@@ -96,6 +96,11 @@ typedef enum {cbm_daemon_application_t *cbm_daemon_application_new(const cbm_daemon_application_config_t *config);+/* A PERMANENT application layer (backing a `daemon start` generation) keeps+ * admitting new sessions after its last live session ends; only the explicit+ * stop/drain paths latch it stopping. */+void cbm_daemon_application_set_permanent(cbm_daemon_application_t *application, bool permanent);+/* Cancel and reap all daemon-owned operations within timeout_ms. Normal final* client shutdown calls this before watcher/store teardown. Idempotent. */bool cbm_daemon_application_shutdown(cbm_daemon_application_t *application, uint32_t timeout_ms);diff --git a/src/daemon/bootstrap.c b/src/daemon/bootstrap.cindex 8115572d2..de4656a1f 100644--- a/src/daemon/bootstrap.c+++ b/src/daemon/bootstrap.c@@ -139,8 +139,17 @@ cbm_daemon_process_role_t cbm_daemon_process_role(int argc, char *const argv[])int daemon_arg = bootstrap_find_arg(argc, argv, CBM_DAEMON_INTERNAL_ARG);if (daemon_arg >= 0) {- return argc == 2 && daemon_arg == 1 ? CBM_DAEMON_PROCESS_DAEMON- : CBM_DAEMON_PROCESS_INVALID;+ /* Byte-exact daemon-role grammar, deliberately unforgiving: the bare+ * internal marker, or the marker followed by exactly the permanent+ * flag. Every other shape — reordered, repeated, or extended — is+ * INVALID, so argv smuggling cannot reach the daemon role. */+ if (argc == 2 && daemon_arg == 1) {+ return CBM_DAEMON_PROCESS_DAEMON;+ }+ if (argc == 3 && daemon_arg == 1 && bootstrap_arg_is(argv[2], CBM_DAEMON_PERMANENT_ARG)) {+ return CBM_DAEMON_PROCESS_DAEMON;+ }+ return CBM_DAEMON_PROCESS_INVALID;}int worker_arg = bootstrap_find_arg(argc, argv, "--index-worker");@@ -171,6 +180,12 @@ cbm_daemon_process_role_t cbm_daemon_process_role(int argc, char *const argv[])return bootstrap_has_help_after(argc, argv, arg + 1) ? CBM_DAEMON_PROCESS_STATELESS: CBM_DAEMON_PROCESS_LOCAL_CLI;}+ /* Placed after the `cli` check on purpose: `cbm cli search "daemon+ * start"` is opaque tool input and must stay LOCAL_CLI. */+ if (bootstrap_arg_is(argv[arg], "daemon")) {+ return bootstrap_has_help_after(argc, argv, arg + 1) ? CBM_DAEMON_PROCESS_STATELESS+ : CBM_DAEMON_PROCESS_DAEMON_CTL;+ }if (bootstrap_arg_is(argv[arg], "--version") || bootstrap_arg_is(argv[arg], "--help") ||bootstrap_arg_is(argv[arg], "-h")) {return CBM_DAEMON_PROCESS_STATELESS;@@ -206,13 +221,23 @@ bool cbm_daemon_bootstrap_launch_spec_init(const char *executable_path,spec_out->executable_path = executable_path;spec_out->argv[0] = executable_path;spec_out->argv[1] = CBM_DAEMON_INTERNAL_ARG;- spec_out->argc = CBM_DAEMON_BOOTSTRAP_LAUNCH_ARGC;+ spec_out->argc = 2U;spec_out->detached = true;spec_out->inherit_standard_handles = false;spec_out->use_shell = false;return true;}+bool cbm_daemon_bootstrap_launch_spec_init_permanent(const char *executable_path,+ cbm_daemon_bootstrap_launch_spec_t *spec_out) {+ if (!cbm_daemon_bootstrap_launch_spec_init(executable_path, spec_out)) {+ return false;+ }+ spec_out->argv[2] = CBM_DAEMON_PERMANENT_ARG;+ spec_out->argc = 3U;+ return true;+}+static uint64_t bootstrap_deadline_after(uint32_t timeout_ms) {uint64_t now = cbm_now_ms();return UINT64_MAX - now < timeout_ms ? UINT64_MAX : now + (uint64_t)timeout_ms;@@ -286,7 +311,9 @@ static cbm_daemon_bootstrap_status_t bootstrap_finish_probe(connect_result && connect_result->message[0]? connect_result->message: "CBM could not start because a conflicting CBM process is active; "- "close all CBM sessions and commands, then retry");+ "close all CBM sessions and commands, then retry. If a permanent "+ "daemon from another build is running, `codebase-memory-mcp daemon "+ "stop` retires it");if (ops->visible_diagnostic) {ops->visible_diagnostic(ops->context, result->message);}@@ -437,8 +464,11 @@ cbm_daemon_bootstrap_status_t cbm_daemon_bootstrap_execute_with_ops(}cbm_daemon_bootstrap_launch_spec_t spec;- if (!cbm_daemon_bootstrap_launch_spec_init(config->executable_path, &spec) ||- !ops->startup_lock_prepare_handoff(ops->context, startup_lock) ||+ bool spec_ready =+ config->spawn_permanent+ ? cbm_daemon_bootstrap_launch_spec_init_permanent(config->executable_path, &spec)+ : cbm_daemon_bootstrap_launch_spec_init(config->executable_path, &spec);+ if (!spec_ready || !ops->startup_lock_prepare_handoff(ops->context, startup_lock) ||!ops->spawn_daemon(ops->context, &spec)) {probe = CBM_DAEMON_BOOTSTRAP_PROBE_ERROR;break;diff --git a/src/daemon/bootstrap.h b/src/daemon/bootstrap.hindex 17cdc7dec..acb6c657b 100644--- a/src/daemon/bootstrap.h+++ b/src/daemon/bootstrap.h@@ -17,7 +17,8 @@#include <stdint.h>#define CBM_DAEMON_INTERNAL_ARG "--cbm-daemon-internal"-#define CBM_DAEMON_BOOTSTRAP_LAUNCH_ARGC 2U+#define CBM_DAEMON_PERMANENT_ARG "--cbm-daemon-permanent"+#define CBM_DAEMON_BOOTSTRAP_LAUNCH_ARGC 3Utypedef enum {CBM_DAEMON_PROCESS_INVALID = 0,@@ -27,6 +28,7 @@ typedef enum {CBM_DAEMON_PROCESS_MCP_CLIENT,CBM_DAEMON_PROCESS_LOCAL_CLI,CBM_DAEMON_PROCESS_HOOK_CLIENT,+ CBM_DAEMON_PROCESS_DAEMON_CTL,} cbm_daemon_process_role_t;/* Pure argv classifier. argv[0] is the executable. The hidden daemon role is@@ -59,6 +61,12 @@ typedef struct {bool cbm_daemon_bootstrap_launch_spec_init(const char *executable_path,cbm_daemon_bootstrap_launch_spec_t *spec_out);+/* Same launch policy, but the child is born PERMANENT: it survives its last+ * client disconnect and stops only via `daemon stop`, the install/update+ * drain, or an explicit process kill. Only `daemon start` uses this. */+bool cbm_daemon_bootstrap_launch_spec_init_permanent(const char *executable_path,+ cbm_daemon_bootstrap_launch_spec_t *spec_out);+typedef enum {CBM_DAEMON_BOOTSTRAP_FAILED = 0,CBM_DAEMON_BOOTSTRAP_BYPASSED,@@ -73,6 +81,10 @@ typedef struct {const char *executable_path;uint32_t connect_timeout_ms;uint32_t startup_timeout_ms;+ /* `daemon start` only: an absent endpoint is replaced by a PERMANENT+ * generation instead of an ephemeral one. Client bootstraps leave this+ * false — they must never mint permanence implicitly. */+ bool spawn_permanent;} cbm_daemon_bootstrap_config_t;typedef struct {diff --git a/src/daemon/daemon.c b/src/daemon/daemon.cindex e228e84e0..ae26ba36b 100644--- a/src/daemon/daemon.c+++ b/src/daemon/daemon.c@@ -45,6 +45,8 @@ struct cbm_daemon_coordinator {cbm_daemon_job_t *jobs;cbm_daemon_watch_t *watches;size_t client_count;+ /* See cbm_daemon_coordinator_set_permanent. */+ bool permanent;size_t job_count;size_t watch_count;size_t callback_count;@@ -289,7 +291,7 @@ static void release_client_locked(cbm_daemon_coordinator_t *coordinator,release_client_resources_locked(coordinator, client->id, batch);free(client);coordinator->client_count--;- if (coordinator->client_count == 0) {+ if (coordinator->client_count == 0 && !coordinator->permanent) {coordinator->state = CBM_DAEMON_COORDINATOR_STOPPING;}}@@ -318,6 +320,15 @@ static bool terminal_job_locked(cbm_daemon_coordinator_t *coordinator, const chareturn true;}+void cbm_daemon_coordinator_set_permanent(cbm_daemon_coordinator_t *coordinator, bool permanent) {+ if (!coordinator) {+ return;+ }+ cbm_mutex_lock(&coordinator->mutex);+ coordinator->permanent = permanent;+ cbm_mutex_unlock(&coordinator->mutex);+}+cbm_daemon_coordinator_t *cbm_daemon_coordinator_new(uint64_t lease_timeout_ms) {cbm_daemon_coordinator_t *coordinator = calloc(1, sizeof(*coordinator));if (!coordinator) {diff --git a/src/daemon/daemon.h b/src/daemon/daemon.hindex cf1f0074e..6357cb151 100644--- a/src/daemon/daemon.h+++ b/src/daemon/daemon.h@@ -69,6 +69,11 @@ typedef struct {/* lease_timeout_ms is fixed for the coordinator lifetime. All timestamps must* come from the same monotonic clock domain. */cbm_daemon_coordinator_t *cbm_daemon_coordinator_new(uint64_t lease_timeout_ms);++/* A PERMANENT coordinator (backing a `daemon start` generation) never+ * self-transitions to STOPPING when its client count reaches zero; only the+ * explicit stop/drain paths end it. */+void cbm_daemon_coordinator_set_permanent(cbm_daemon_coordinator_t *coordinator, bool permanent);/* The caller must first quiesce coordinator calls and hook invocations. */void cbm_daemon_coordinator_free(cbm_daemon_coordinator_t *coordinator);diff --git a/src/daemon/host.c b/src/daemon/host.cindex efd865e67..61dcf14af 100644--- a/src/daemon/host.c+++ b/src/daemon/host.c@@ -68,13 +68,15 @@ typedef struct {cbm_http_server_t *(*server_new)(void *context, int port);void (*server_configure)(void *context, cbm_http_server_t *server, host_state_t *host);void (*server_stop)(void *context, cbm_http_server_t *server);- void (*server_free)(void *context, cbm_http_server_t *server);+ bool (*server_free)(void *context, cbm_http_server_t *server);int (*thread_start)(void *context, cbm_thread_t *thread, void *(*entry)(void *),void *entry_context);int (*thread_join)(void *context, cbm_thread_t *thread);} host_http_ops_t;struct host_state {+ /* Mirrors cbm_daemon_host_config_t.permanent for prepare-time consumers. */+ bool permanent;cbm_daemon_application_t *application;cbm_watcher_t *watcher;cbm_store_t *watch_store;@@ -85,6 +87,7 @@ struct host_state {cbm_thread_t http_thread;bool watcher_started;bool http_started;+ bool http_retiring;bool http_config_loaded;bool http_config_enabled;bool http_assets_available;@@ -337,15 +340,37 @@ static void host_http_server_stop_default(void *context, cbm_http_server_t *servcbm_http_server_stop(server);}-static void host_http_server_free_default(void *context, cbm_http_server_t *server) {+static bool host_http_server_free_default(void *context, cbm_http_server_t *server) {(void)context;- cbm_http_server_free(server);+ return cbm_http_server_free(server);+}++typedef int (*host_http_thread_create_fn)(void *context, cbm_thread_t *thread,+ void *(*entry)(void *), void *entry_context);++static int host_http_thread_create_default(void *context, cbm_thread_t *thread,+ void *(*entry)(void *), void *entry_context) {+ (void)context;+ return cbm_thread_create(thread, 0, entry, entry_context);+}++static int host_http_thread_schedule_create(cbm_thread_t *thread, void *(*entry)(void *),+ cbm_http_server_t *server,+ host_http_thread_create_fn create,+ void *create_context) {+ if (!server || !create || !cbm_http_server_schedule_run(server))+ return -1;+ int rc = create(create_context, thread, entry, server);+ if (rc != 0 && !cbm_http_server_cancel_scheduled_run(server))+ return -1;+ return rc;}static int host_http_thread_start_default(void *context, cbm_thread_t *thread,void *(*entry)(void *), void *entry_context) {(void)context;- return cbm_thread_create(thread, 0, entry, entry_context);+ return host_http_thread_schedule_create(thread, entry, entry_context,+ host_http_thread_create_default, NULL);}static int host_http_thread_join_default(void *context, cbm_thread_t *thread) {@@ -364,17 +389,22 @@ static const host_http_ops_t g_host_http_default_ops = {.thread_join = host_http_thread_join_default,};-static void host_http_stop_join_free(host_state_t *host) {+static bool host_http_stop_join_free(host_state_t *host) {const host_http_ops_t *ops = host->http_ops;- if (host->http) {+ if (host->http && host->http_started) {ops->server_stop(ops->context, host->http);}if (host->http_started) {- (void)ops->thread_join(ops->context, &host->http_thread);+ if (ops->thread_join(ops->context, &host->http_thread) != 0) {+ return false;+ }host->http_started = false;}- ops->server_free(ops->context, host->http);+ if (!ops->server_free(ops->context, host->http)) {+ return false;+ }host->http = NULL;+ return true;}static uint64_t host_deadline_from(uint64_t now_ms, uint32_t delay_ms) {@@ -409,8 +439,22 @@ static void host_http_reconcile_at(host_state_t *host, uint64_t now_ms, bool forbool config_changed = !host->http_config_loaded ||desired.ui_enabled != host->http_config_enabled ||desired.ui_port != host->http_config_port;+ if (config_changed && !host->http_retiring) {+ host->http_retiring = true;+ host->http_retry_at_ms = now_ms;+ host->http_retry_delay_ms = HOST_HTTP_RETRY_INITIAL_MS;+ }+ if (host->http_retiring) {+ if (now_ms < host->http_retry_at_ms) {+ return;+ }+ if (!host_http_stop_join_free(host)) {+ host_http_schedule_retry(host, now_ms, "server_retire");+ return;+ }+ host->http_retiring = false;+ }if (config_changed) {- host_http_stop_join_free(host);host->http_config_loaded = true;host->http_config_enabled = desired.ui_enabled;host->http_config_port = desired.ui_port;@@ -446,14 +490,16 @@ static void host_http_reconcile_at(host_state_t *host, uint64_t now_ms, bool forhost->http_retry_at_ms = 0;host->http_retry_delay_ms = HOST_HTTP_RETRY_INITIAL_MS;} else {- ops->server_free(ops->context, host->http);- host->http = NULL;+ host->http_retiring = true;+ if (host_http_stop_join_free(host)) {+ host->http_retiring = false;+ }host_http_schedule_retry(host, now_ms, "thread_start");}}static void host_background_stop(host_state_t *host) {- if (host->http) {+ if (host->http && host->http_started) {host->http_ops->server_stop(host->http_ops->context, host->http);}if (host->watcher) {@@ -461,15 +507,20 @@ static void host_background_stop(host_state_t *host) {}}-static void host_background_join(host_state_t *host) {+static bool host_background_join(host_state_t *host) {if (host->http_started) {- (void)host->http_ops->thread_join(host->http_ops->context, &host->http_thread);+ if (host->http_ops->thread_join(host->http_ops->context, &host->http_thread) != 0) {+ return false;+ }host->http_started = false;}if (host->watcher_started) {- (void)cbm_thread_join(&host->watcher_thread);+ if (cbm_thread_join(&host->watcher_thread) != 0) {+ return false;+ }host->watcher_started = false;}+ return true;}static bool host_project_lock_manager_free_once(void *context) {@@ -482,7 +533,11 @@ static bool host_project_lock_manager_free_once(void *context) {}static void host_state_free(host_state_t *host) {- host_http_stop_join_free(host);+ if (!host_http_stop_join_free(host)) {+ /* The retained server or one of its callbacks can still borrow every+ * dependency below. Process containment is the only safe teardown. */+ host_force_terminate("http_cleanup");+ }if (host->application) {if (!cbm_daemon_application_free(host->application)) {/* The application still owns work or a borrowed callback context.@@ -528,6 +583,9 @@ static bool host_state_prepare(host_state_t *host, const cbm_daemon_ipc_endpoint.project_locks = host->project_locks,};host->application = cbm_daemon_application_new(&application_config);+ if (host->application && host->permanent) {+ cbm_daemon_application_set_permanent(host->application, true);+ }if (!host->watch_store || !host->watcher || !host->project_locks || !host->application) {return false;}@@ -547,6 +605,8 @@ bool cbm_daemon_host_state_prepare_for_test(const cbm_daemon_ipc_endpoint_t *endtypedef struct {size_t create_failures;size_t thread_start_failures;+ size_t server_free_failures;+ size_t config_change_after_load;size_t config_loads;size_t server_create_attempts;size_t thread_start_attempts;@@ -559,7 +619,9 @@ static void host_http_test_config_load(void *opaque, cbm_ui_config_t *config_outhost_http_reconcile_test_context_t *context = opaque;context->config_loads++;config_out->ui_enabled = true;- config_out->ui_port = CBM_UI_DEFAULT_PORT;+ bool change_port = context->config_change_after_load > 0 &&+ context->config_loads == context->config_change_after_load;+ config_out->ui_port = change_port ? CBM_UI_DEFAULT_PORT + 1 : CBM_UI_DEFAULT_PORT;}static cbm_http_server_t *host_http_test_server_new(void *opaque, int port) {@@ -591,10 +653,12 @@ static void host_http_test_server_stop(void *opaque, cbm_http_server_t *server)/* WHY: See host_http_test_server_stop; changing only this implementation to a* pointer-to-const parameter would make it incompatible with host_http_ops_t. */// cppcheck-suppress constParameterCallback-static void host_http_test_server_free(void *opaque, cbm_http_server_t *server) {+static bool host_http_test_server_free(void *opaque, cbm_http_server_t *server) {+ host_http_reconcile_test_context_t *context = opaque;if (server) {- ((host_http_reconcile_test_context_t *)opaque)->server_frees++;+ context->server_frees++;}+ return !server || context->server_frees > context->server_free_failures;}static int host_http_test_thread_start(void *opaque, cbm_thread_t *thread, void *(*entry)(void *),@@ -650,7 +714,9 @@ bool cbm_daemon_host_http_reconcile_sequence_for_test(bool active = host.http_started;uint32_t largest_retry = host.http_largest_scheduled_retry_ms;uint64_t next_retry = host.http_retry_at_ms;- host_http_stop_join_free(&host);+ if (!host_http_stop_join_free(&host)) {+ return false;+ }*result_out = (cbm_daemon_host_http_reconcile_test_result_t){.config_loads = context.config_loads,@@ -666,6 +732,85 @@ bool cbm_daemon_host_http_reconcile_sequence_for_test(return true;}+bool cbm_daemon_host_http_reconcile_free_refusal_for_test(+ cbm_daemon_host_http_free_refusal_test_result_t *result_out) {+ if (!result_out) {+ return false;+ }+ host_http_reconcile_test_context_t context = {+ .server_free_failures = 1,+ .config_change_after_load = 2,+ };+ const host_http_ops_t ops = {+ .context = &context,+ .config_load = host_http_test_config_load,+ .server_new = host_http_test_server_new,+ .server_configure = host_http_test_server_configure,+ .server_stop = host_http_test_server_stop,+ .server_free = host_http_test_server_free,+ .thread_start = host_http_test_thread_start,+ .thread_join = host_http_test_thread_join,+ };+ host_state_t host = {+ .http_assets_available = true,+ .http_ops = &ops,+ };++ host_http_reconcile_at(&host, 0, true);+ host_http_reconcile_at(&host, HOST_HTTP_CONFIG_POLL_MS, false);+ bool retained_after_refusal =+ host.http != NULL && !host.http_started && context.server_create_attempts == 1;+ size_t creates_after_refusal = context.server_create_attempts;+ host_http_reconcile_at(&host, HOST_HTTP_CONFIG_POLL_MS * 2U, false);+ bool replacement_active = host.http != NULL && host.http_started;++ *result_out = (cbm_daemon_host_http_free_refusal_test_result_t){+ .server_create_attempts_after_refusal = creates_after_refusal,+ .server_create_attempts = context.server_create_attempts,+ .thread_start_attempts = context.thread_start_attempts,+ .server_stops = context.server_stops,+ .server_free_attempts = context.server_frees,+ .thread_joins = context.thread_joins,+ .retained_after_refusal = retained_after_refusal,+ .replacement_active_after_retry = replacement_active,+ };+ return host_http_stop_join_free(&host);+}++typedef struct {+ cbm_http_server_t *server;+ bool free_refused_while_scheduled;+} host_http_thread_create_failure_test_t;++/* WHY: the signature is fixed by the host_http_ops_t thread_start hook type;+ * a const pointee would make the function-pointer types incompatible. */+static int host_http_thread_create_failure_for_test(+ void *opaque, cbm_thread_t *thread, void *(*entry)(void *),+ void *entry_context) { // cppcheck-suppress constParameterCallback+ (void)thread;+ (void)entry;+ host_http_thread_create_failure_test_t *test = opaque;+ if (!test || entry_context != test->server)+ return -1;+ test->free_refused_while_scheduled = !cbm_http_server_free(test->server);+ return -1;+}++bool cbm_daemon_host_http_thread_create_failure_lifecycle_for_test(void) {+ cbm_http_server_t *server = cbm_http_server_new(0);+ if (!server)+ return false;+ host_http_thread_create_failure_test_t test = {+ .server = server,+ };+ cbm_thread_t unused_thread = {0};+ int rc = host_http_thread_schedule_create(&unused_thread, host_http_thread, server,+ host_http_thread_create_failure_for_test, &test);+ bool free_refused = test.free_refused_while_scheduled;+ bool final_free_succeeded = free_refused && cbm_http_server_free(server);+ return rc != 0 && free_refused && final_free_succeeded;+}+static bool host_background_start(host_state_t *host) {if (cbm_thread_create(&host->watcher_thread, 0, host_watcher_thread, host->watcher) != 0) {return false;@@ -677,7 +822,7 @@ static bool host_background_start(host_state_t *host) {}static bool host_wait_for_lifetime(cbm_daemon_runtime_service_t *service,- atomic_int *stop_requested, host_state_t *host) {+ atomic_int *stop_requested, host_state_t *host, bool permanent) {uint64_t initial_deadline = cbm_now_ms() + HOST_INITIAL_CLIENT_TIMEOUT_MS;uint64_t stopping_deadline = 0;for (;;) {@@ -703,7 +848,10 @@ static bool host_wait_for_lifetime(cbm_daemon_runtime_service_t *service,* mid-conversation between per-request connections. */bool admitted = cbm_daemon_runtime_service_clients_admitted_total(service) > 0;bool stop = stop_requested && atomic_load(stop_requested);- if (stop || (!admitted && cbm_now_ms() >= initial_deadline)) {+ /* A permanent generation (`daemon start`) skips the nobody-ever-+ * connected window — it exists precisely to idle ahead of clients.+ * Explicit stop requests (signals) are still honored. */+ if (stop || (!permanent && !admitted && cbm_now_ms() >= initial_deadline)) {cbm_log_info("daemon.lifetime_end", "reason",stop ? "stop_requested" : "initial_window_expired");return cbm_daemon_runtime_service_stop(service, HOST_RUNTIME_SHUTDOWN_MS);@@ -842,6 +990,7 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) {cbm_index_supervisor_mark_host();host_state_t host = {0};+ host.permanent = config->permanent;if (!host_state_prepare(&host, config->endpoint)) {cbm_log_error("daemon.start_failed", "component", "application");host_state_free(&host);@@ -864,6 +1013,7 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) {.request_timeout_ms = HOST_REQUEST_TIMEOUT_MS,.shutdown_timeout_ms = HOST_RUNTIME_SHUTDOWN_MS,.application = callbacks,+ .permanent = config->permanent,};cbm_daemon_runtime_service_t *service =cbm_daemon_runtime_service_start_reserved(&runtime_config, &lifetime_reservation);@@ -884,7 +1034,9 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) {host_force_terminate("operations");}host_background_stop(&host);- host_background_join(&host);+ if (!host_background_join(&host)) {+ host_force_terminate("background");+ }if (!host_runtime_stop_free(service)) {host_force_terminate("runtime");}@@ -914,7 +1066,7 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) {: "unavailable","memory_budget_bytes", memory_budget, "physical_job_limit", physical_job_limit,"worker_memory_budget_bytes", worker_memory_budget);- if (!host_wait_for_lifetime(service, config->stop_requested, &host)) {+ if (!host_wait_for_lifetime(service, config->stop_requested, &host, config->permanent)) {host_force_terminate("runtime");}@@ -924,7 +1076,9 @@ int cbm_daemon_host_run(const cbm_daemon_host_config_t *config) {host_force_terminate("operations");}host_background_stop(&host);- host_background_join(&host);+ if (!host_background_join(&host)) {+ host_force_terminate("background");+ }if (!host_runtime_stop_free(service)) {host_force_terminate("runtime");}diff --git a/src/daemon/host.h b/src/daemon/host.hindex da760417d..037882381 100644--- a/src/daemon/host.h+++ b/src/daemon/host.h@@ -14,6 +14,10 @@ typedef struct {cbm_daemon_build_identity_t identity;const char *executable_path;atomic_int *stop_requested;+ /* Born via `daemon start`: the generation survives its last client+ * disconnect and the no-client initial window; it stops only through the+ * stop/drain ops or an explicit process kill. */+ bool permanent;} cbm_daemon_host_config_t;/* Blocks for the complete daemon generation. The first admitted frontend ownsdiff --git a/src/daemon/host_internal.h b/src/daemon/host_internal.hindex dfe4cb9ff..dd8856161 100644--- a/src/daemon/host_internal.h+++ b/src/daemon/host_internal.h@@ -40,10 +40,32 @@ typedef struct {bool active_after_sequence;} cbm_daemon_host_http_reconcile_test_result_t;+typedef struct {+ size_t server_create_attempts_after_refusal;+ size_t server_create_attempts;+ size_t thread_start_attempts;+ size_t server_stops;+ size_t server_free_attempts;+ size_t thread_joins;+ bool retained_after_refusal;+ bool replacement_active_after_retry;+} cbm_daemon_host_http_free_refusal_test_result_t;+/* Drive the production HTTP reconciliation state machine at explicit* monotonic timestamps with deterministic transient failures. */bool cbm_daemon_host_http_reconcile_sequence_for_test(const uint64_t *timestamps_ms, size_t timestamp_count, size_t create_failures,size_t thread_start_failures, cbm_daemon_host_http_reconcile_test_result_t *result_out);+/* Change the configured UI port for one poll under an active fake server,+ * inject one server-free refusal, revert the desired port, then drive the+ * next retry. */+bool cbm_daemon_host_http_reconcile_free_refusal_for_test(+ cbm_daemon_host_http_free_refusal_test_result_t *result_out);++/* Exercise the production HTTP schedule/create/cancel adapter with an injected+ * create failure. The callback verifies free is refused while SCHEDULED; after+ * the failure, the adapter must cancel so the final free succeeds. */+bool cbm_daemon_host_http_thread_create_failure_lifecycle_for_test(void);+#endif /* CBM_DAEMON_HOST_INTERNAL_H */diff --git a/src/daemon/ipc.c b/src/daemon/ipc.cindex 12e6a5b7b..349a7d553 100644--- a/src/daemon/ipc.c+++ b/src/daemon/ipc.c@@ -2959,6 +2959,13 @@ void cbm_daemon_ipc_connection_close(cbm_daemon_ipc_connection_t *connection) {free(connection);}+void cbm_daemon_ipc_connection_drain(cbm_daemon_ipc_connection_t *connection, uint32_t timeout_ms) {+ /* POSIX stream sockets deliver buffered data after close; the final+ * response cannot be lost to an immediate close, so no wait is needed. */+ (void)connection;+ (void)timeout_ms;+}+void cbm_daemon_ipc_connection_interrupt(cbm_daemon_ipc_connection_t *connection) {if (connection && connection->fd >= 0) {(void)shutdown(connection->fd, SHUT_RDWR);@@ -3345,6 +3352,14 @@ struct cbm_daemon_ipc_listener {wchar_t *pipe_name;HANDLE pipe;bool first_instance;+ /* The pending overlapped ConnectNamedPipe persists across accept-poll+ * timeouts. Destroying a listening instance on every poll timeout races+ * clients attaching in the teardown window: they end up severed or,+ * worse, attached to an orphaned pipe object no server will ever read,+ * silently absorbing their HELLO until their own timeout expires. */+ HANDLE connect_event;+ OVERLAPPED connect_overlapped;+ bool connect_pending;cbm_daemon_ipc_lifetime_reservation_t *lifetime_reservation;cbm_daemon_ipc_participant_guard_t *participant_guard;};@@ -5091,6 +5106,9 @@ void cbm_daemon_ipc_listener_close(cbm_daemon_ipc_listener_t *listener) {(void)DisconnectNamedPipe(listener->pipe);(void)CloseHandle(listener->pipe);}+ if (listener->connect_event) {+ (void)CloseHandle(listener->connect_event);+ }cbm_daemon_ipc_lifetime_reservation_release(listener->lifetime_reservation);ipc_participant_guard_release_complete(&listener->participant_guard);free(listener->pipe_name);@@ -5221,34 +5239,57 @@ int cbm_daemon_ipc_accept(cbm_daemon_ipc_listener_t *listener, uint32_t timeout_if (listener->pipe == INVALID_HANDLE_VALUE) {listener->pipe = win_pipe_instance_new(listener->pipe_name, listener->first_instance);listener->first_instance = false;+ listener->connect_pending = false;if (listener->pipe == INVALID_HANDLE_VALUE) {return -1;}}- OVERLAPPED overlapped;- memset(&overlapped, 0, sizeof(overlapped));- overlapped.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL);- if (!overlapped.hEvent) {- return -1;- }- BOOL connected = ConnectNamedPipe(listener->pipe, &overlapped);- int result = 1;- if (!connected) {- DWORD connect_error = GetLastError();+ if (!listener->connect_pending) {+ if (!listener->connect_event) {+ listener->connect_event = CreateEventW(NULL, TRUE, FALSE, NULL);+ if (!listener->connect_event) {+ return -1;+ }+ }+ if (!ResetEvent(listener->connect_event)) {+ return -1;+ }+ memset(&listener->connect_overlapped, 0, sizeof(listener->connect_overlapped));+ listener->connect_overlapped.hEvent = listener->connect_event;+ BOOL connected = ConnectNamedPipe(listener->pipe, &listener->connect_overlapped);+ DWORD connect_error = connected ? ERROR_PIPE_CONNECTED : GetLastError();if (connect_error == ERROR_IO_PENDING) {- DWORD transferred = 0;- result = win_overlapped_wait(listener->pipe, &overlapped, timeout_ms, &transferred);+ listener->connect_pending = true;} else if (connect_error != ERROR_PIPE_CONNECTED) {- result = -1;+ (void)DisconnectNamedPipe(listener->pipe);+ (void)CloseHandle(listener->pipe);+ listener->pipe = INVALID_HANDLE_VALUE;+ return -1;}}- (void)CloseHandle(overlapped.hEvent);- if (result != 1) {- (void)DisconnectNamedPipe(listener->pipe);- (void)CloseHandle(listener->pipe);- listener->pipe = INVALID_HANDLE_VALUE;- return result;++ if (listener->connect_pending) {+ DWORD wait = WaitForSingleObject(listener->connect_event, timeout_ms);+ if (wait == WAIT_TIMEOUT) {+ /* Keep the instance and its pending connect armed: a listening+ * pipe must stay available for clients between polls. */+ return 0;+ }+ DWORD transferred = 0;+ if (wait != WAIT_OBJECT_0 ||+ !GetOverlappedResult(listener->pipe, &listener->connect_overlapped, &transferred,+ FALSE)) {+ DWORD connect_error = GetLastError();+ listener->connect_pending = false;+ if (connect_error != ERROR_PIPE_CONNECTED) {+ (void)DisconnectNamedPipe(listener->pipe);+ (void)CloseHandle(listener->pipe);+ listener->pipe = INVALID_HANDLE_VALUE;+ return -1;+ }+ }+ listener->connect_pending = false;}cbm_daemon_ipc_connection_t *connection = malloc(sizeof(*connection));if (!connection) {@@ -5525,6 +5566,33 @@ void cbm_daemon_ipc_connection_close(cbm_daemon_ipc_connection_t *connection) {free(connection);}+static int win_io_once(cbm_daemon_ipc_connection_t *connection, void *buffer, DWORD length,+ bool writing, uint64_t deadline_ms, DWORD *transferred_out);++void cbm_daemon_ipc_connection_drain(cbm_daemon_ipc_connection_t *connection, uint32_t timeout_ms) {+ if (!connection || connection->handle == INVALID_HANDLE_VALUE ||+ connection->role != CBM_DAEMON_IPC_PIPE_ROLE_ACCEPTED_SERVER ||+ atomic_load_explicit(&connection->poisoned, memory_order_acquire)) {+ return;+ }+ /* Closing the server end of a named pipe discards data the client has not+ * read yet, so a final response followed by an immediate close races the+ * client's decode. Reading until peer EOF proves consumption: clients+ * close only after draining their pending response. A poisoned or+ * interrupted connection returns immediately above/below, so ordinary+ * EOF-triggered teardown pays nothing here. */+ uint64_t deadline_ms = ipc_deadline_after(timeout_ms);+ for (;;) {+ uint8_t discard[256];+ DWORD transferred = 0;+ int result =+ win_io_once(connection, discard, sizeof(discard), false, deadline_ms, &transferred);+ if (result != 1 || transferred == 0) {+ return;+ }+ }+}+void cbm_daemon_ipc_connection_interrupt(cbm_daemon_ipc_connection_t *connection) {if (!connection || connection->handle == INVALID_HANDLE_VALUE) {return;diff --git a/src/daemon/ipc.h b/src/daemon/ipc.hindex 05d68faf2..a4f0c4331 100644--- a/src/daemon/ipc.h+++ b/src/daemon/ipc.h@@ -150,6 +150,16 @@ cbm_daemon_ipc_connection_t *cbm_daemon_ipc_connect(const cbm_daemon_ipc_endpoinuint32_t timeout_ms);void cbm_daemon_ipc_connection_close(cbm_daemon_ipc_connection_t *connection);+/* Bounded wait for the peer to consume everything already sent, by reading+ * (and discarding) until peer EOF or the timeout. On POSIX this is a no-op:+ * closing a stream socket leaves buffered data deliverable, so the final+ * response survives an immediate close. On Windows named pipes, closing the+ * server handle discards data the client has not yet read; a server that+ * sends a final response and closes immediately races the client's decode.+ * Peer EOF is proof of consumption because clients close only after reading+ * their pending response. Callers close the connection afterwards. */+void cbm_daemon_ipc_connection_drain(cbm_daemon_ipc_connection_t *connection, uint32_t timeout_ms);+/* Interrupt pending I/O without freeing the connection object. This is* idempotent and may be called from a supervisor thread; the connection's* owning worker must still call connection_close after its I/O unwinds. */diff --git a/src/daemon/runtime.c b/src/daemon/runtime.cindex 48686864b..c98ba6e23 100644--- a/src/daemon/runtime.c+++ b/src/daemon/runtime.c@@ -40,6 +40,13 @@ enum {RUNTIME_ACCEPT_POLL_MS = 20,RUNTIME_WAIT_POLL_NS = 1000000,RUNTIME_WORKER_STACK_SIZE = 256 * 1024,+ /* Bounds the drain-before-close wait for a peer consuming its final+ * response; interrupted or already-poisoned connections skip it. */+ RUNTIME_WORKER_DRAIN_TIMEOUT_MS = 2000,+ /* Inline rejections run on the accept thread, so their drain stays short:+ * a local cooperative peer is already blocked in read and consumes the+ * rejection within milliseconds. */+ RUNTIME_REJECT_DRAIN_TIMEOUT_MS = 250,RUNTIME_PATH_CAP = 4096,RENDEZVOUS_REQUEST_ABI_OFFSET = 0,@@ -148,6 +155,9 @@ struct cbm_daemon_runtime_service {* entirely between two host polls, and a sampled count then reads zero* forever, stopping a daemon whose client is mid-conversation. */uint64_t admitted_total;+ /* Born via `daemon start`: last-client-disconnect does not begin stopping.+ * The stop/drain ops and process kill remain the only exits. */+ bool permanent;cbm_thread_t accept_thread;bool accept_thread_started;@@ -1093,10 +1103,12 @@ static void runtime_worker_disconnect(cbm_daemon_runtime_worker_t *worker) {if (service->committed_clients > 0) {service->committed_clients--;}- if (service->committed_clients == 0) {+ if (service->committed_clients == 0 && !service->permanent) {/* A HELLO whose application session is still opening is only a* provisional coordinator client. It cannot keep the generation- * alive after the final fully committed frontend disconnects. */+ * alive after the final fully committed frontend disconnects.+ * A permanent generation (`daemon start`) deliberately survives+ * this: only the stop/drain ops or a process kill end it. */runtime_service_begin_stopping_locked(service, shutdown_deadline, false,"last_committed_client_disconnected");}@@ -1330,6 +1342,18 @@ static bool runtime_worker_handle_application_cancel(cbm_daemon_runtime_worker_treturn true;}+static bool runtime_worker_handle_close_intent(cbm_daemon_runtime_worker_t *worker,+ uint32_t length) {+ if (length != 0) {+ return false;+ }+ /* Terminal for the session (admission, coordinator registration, session+ * cancel), but not for the connection: the worker keeps reading so the+ * in-flight response tail and the eventual EOF unwind normally. */+ runtime_worker_disconnect(worker);+ return true;+}+static bool runtime_worker_handle_disconnect(cbm_daemon_runtime_worker_t *worker, uint32_t length) {if (length != 0) {return false;@@ -1361,6 +1385,12 @@ static void runtime_worker_finish(cbm_daemon_runtime_worker_t *worker) {worker->application_session = NULL;worker->application_session_opened = false;}+ if (worker->connection) {+ /* Off the service mutex: a peer that just received its final response+ * (hello rejection, disconnect acknowledgement) must be able to read+ * it before the handle closes; see cbm_daemon_ipc_connection_drain. */+ cbm_daemon_ipc_connection_drain(worker->connection, RUNTIME_WORKER_DRAIN_TIMEOUT_MS);+ }cbm_mutex_lock(&service->mutex);if (worker->connection) {cbm_daemon_ipc_connection_close(worker->connection);@@ -1388,6 +1418,159 @@ static bool runtime_activation_peer_matches_claim(cbm_daemon_runtime_service_t *strcmp(peer_fingerprint, claimed_build) == 0;}+static bool runtime_control_request_decode(const uint8_t *payload, uint32_t length,+ char build_out[CBM_DAEMON_BUILD_FINGERPRINT_SIZE]) {+ if (!payload || length != CBM_DAEMON_CONTROL_REQUEST_SIZE ||+ payload[CBM_DAEMON_CONTROL_REQUEST_SIZE - 1U] != 0U) {+ return false;+ }+ memcpy(build_out, payload, CBM_DAEMON_BUILD_FINGERPRINT_SIZE);+ return strlen(build_out) == CBM_DAEMON_BUILD_FINGERPRINT_SIZE - 1U;+}++static void runtime_control_collect_clients_locked(cbm_daemon_runtime_service_t *service,+ cbm_daemon_runtime_worker_t *except,+ uint8_t *count_out,+ uint32_t pids[CBM_DAEMON_CONTROL_CLIENT_CAP]) {+ uint8_t count = 0U;+ for (size_t index = 0; index < service->worker_capacity; index++) {+ cbm_daemon_runtime_worker_t *candidate = &service->workers[index];+ if (!candidate->in_use || !candidate->admission_committed || candidate == except) {+ continue;+ }+ if (count < CBM_DAEMON_CONTROL_CLIENT_CAP) {+ pids[count] = (uint32_t)candidate->peer_process_id;+ }+ count++;+ }+ *count_out =+ count > CBM_DAEMON_CONTROL_CLIENT_CAP ? (uint8_t)CBM_DAEMON_CONTROL_CLIENT_CAP : count;+}++static void runtime_worker_handle_status(cbm_daemon_runtime_worker_t *worker,+ const uint8_t *payload, uint32_t length) {+ cbm_daemon_runtime_service_t *service = worker->service;+ char requested_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ bool peer_verified =+ runtime_control_request_decode(payload, length, requested_build) &&+ runtime_activation_peer_matches_claim(service, worker->peer_process_id, requested_build);+ uint8_t response[CBM_DAEMON_STATUS_RESPONSE_SIZE];+ memset(response, 0, sizeof(response));+ if (peer_verified) {+ uint8_t count = 0U;+ uint32_t pids[CBM_DAEMON_CONTROL_CLIENT_CAP] = {0};+ cbm_mutex_lock(&service->mutex);+ response[0] = 1U;+ response[1] =+ (uint8_t)((service->permanent ? 0x01U : 0U) |+ (service->state != CBM_DAEMON_RUNTIME_SERVICE_RUNNING ? 0x02U : 0U));+ uint16_t committed = service->committed_clients > UINT16_MAX+ ? UINT16_MAX+ : (uint16_t)service->committed_clients;+ response[2] = (uint8_t)(committed >> 8);+ response[3] = (uint8_t)(committed & 0xFFU);+ uint32_t daemon_pid = (uint32_t)runtime_current_process_id();+ response[4] = (uint8_t)(daemon_pid >> 24);+ response[5] = (uint8_t)(daemon_pid >> 16);+ response[6] = (uint8_t)(daemon_pid >> 8);+ response[7] = (uint8_t)(daemon_pid & 0xFFU);+ runtime_control_collect_clients_locked(service, worker, &count, pids);+ response[8] = count;+ for (size_t index = 0; index < CBM_DAEMON_CONTROL_CLIENT_CAP; index++) {+ size_t offset = 12U + index * 4U;+ response[offset] = (uint8_t)(pids[index] >> 24);+ response[offset + 1U] = (uint8_t)(pids[index] >> 16);+ response[offset + 2U] = (uint8_t)(pids[index] >> 8);+ response[offset + 3U] = (uint8_t)(pids[index] & 0xFFU);+ }+ (void)snprintf((char *)response + 44U, CBM_DAEMON_BUILD_FINGERPRINT_SIZE, "%s",+ service->identity.build_fingerprint);+ (void)snprintf((char *)response + 109U, 12U, "%s",+ service->identity.semantic_version ? service->identity.semantic_version+ : "");+ cbm_mutex_unlock(&service->mutex);+ }+ (void)runtime_worker_send_frame(worker, CBM_DAEMON_FRAME_RESPONSE, CBM_DAEMON_RUNTIME_OP_STATUS,+ response, (uint32_t)sizeof(response));+ runtime_worker_finish(worker);+}++static void runtime_worker_handle_stop(cbm_daemon_runtime_worker_t *worker, const uint8_t *payload,+ uint32_t length) {+ cbm_daemon_runtime_service_t *service = worker->service;+ char requested_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ bool peer_verified =+ runtime_control_request_decode(payload, length, requested_build) &&+ runtime_activation_peer_matches_claim(service, worker->peer_process_id, requested_build);+ uint8_t response[CBM_DAEMON_STOP_RESPONSE_SIZE];+ memset(response, 0, sizeof(response));+ bool accepted = false;+ if (peer_verified) {+ uint8_t count = 0U;+ uint32_t pids[CBM_DAEMON_CONTROL_CLIENT_CAP] = {0};+ uint64_t deadline = runtime_deadline_after(service->shutdown_timeout_ms);+ cbm_mutex_lock(&service->mutex);+ response[0] = 1U;+ uint16_t committed = service->committed_clients > UINT16_MAX+ ? UINT16_MAX+ : (uint16_t)service->committed_clients;+ runtime_control_collect_clients_locked(service, worker, &count, pids);+ if (service->committed_clients > 0) {+ /* Refuse-if-busy: the caller reports these pids to the user as+ * the processes that must exit before a graceful stop. */+ response[1] = 0x02U;+ } else if (service->state == CBM_DAEMON_RUNTIME_SERVICE_RUNNING) {+ /* Explicit stop is the sanctioned exit for PERMANENT generations+ * as well — begin_stopping here overrides the permanence gate.+ * Mirror the activation-shutdown ACK protocol: the stopping+ * teardown must not consume this requester's response slot before+ * the acceptance byte leaves. */+ runtime_service_begin_stopping_locked(service, deadline, false,+ "daemon_stop_requested");+ /* Same exit criterion as an activation drain: a permanent+ * coordinator never reports client-terminal, so resource+ * emptiness must be allowed to complete this stop promptly. */+ service->activation_shutdown_requested = true;+ service->activation_response_inflight = true;+ worker->final_response_inflight = true;+ response[1] = 0x01U;+ accepted = true;+ }+ response[2] = (uint8_t)(committed >> 8);+ response[3] = (uint8_t)(committed & 0xFFU);+ response[4] = count;+ for (size_t index = 0; index < CBM_DAEMON_CONTROL_CLIENT_CAP; index++) {+ size_t offset = 8U + index * 4U;+ response[offset] = (uint8_t)(pids[index] >> 24);+ response[offset + 1U] = (uint8_t)(pids[index] >> 16);+ response[offset + 2U] = (uint8_t)(pids[index] >> 8);+ response[offset + 3U] = (uint8_t)(pids[index] & 0xFFU);+ }+ cbm_mutex_unlock(&service->mutex);+ }+ if (accepted) {+ char requester_pid[32];+ (void)snprintf(requester_pid, sizeof(requester_pid), "%llu",+ (unsigned long long)worker->peer_process_id);+ cbm_log_info("daemon.stop_requested", "requester_pid", requester_pid, "requester_build",+ requested_build);+ runtime_service_interrupt_connections_except(worker->service, worker, true);+ }+ (void)runtime_worker_send_frame(worker, CBM_DAEMON_FRAME_RESPONSE, CBM_DAEMON_RUNTIME_OP_STOP,+ response, (uint32_t)sizeof(response));+ if (accepted) {+ cbm_daemon_runtime_service_t *stop_service = worker->service;+ runtime_worker_finish(worker);+ cbm_mutex_lock(&stop_service->mutex);+ worker->final_response_inflight = false;+ stop_service->activation_response_inflight = false;+ cbm_mutex_unlock(&stop_service->mutex);+ runtime_service_interrupt_connections(stop_service);+ return;+ }+ runtime_worker_finish(worker);+}+static void runtime_worker_handle_activation_shutdown(cbm_daemon_runtime_worker_t *worker,const uint8_t *payload, uint32_t length) {cbm_daemon_runtime_service_t *service = worker->service;@@ -1434,6 +1617,13 @@ static void runtime_worker_handle_activation_shutdown(cbm_daemon_runtime_worker_"requester_build", requested_build, "action",runtime_activation_action_text(action), "active_clients", active_clients,"active_connections", active_connections);+ /* Interrupt every other connection BEFORE the ACK leaves: the ACK is+ * the requester's license to act on "snapshotted and draining", so+ * every drain must already be initiated when it arrives. Acking first+ * left a window where a session could still get one request serviced+ * after the requester observed the ACK. The requester itself is+ * excepted and its response path stays protected. */+ runtime_service_interrupt_connections_except(service, worker, true);}bool response_sent =encoded && runtime_worker_send_frame(worker, CBM_DAEMON_FRAME_RESPONSE,@@ -1446,10 +1636,8 @@ static void runtime_worker_handle_activation_shutdown(cbm_daemon_runtime_worker_}if (result.accepted) {- /* Keep the activation ACK protected while interrupting every other- * connection. Close this requester normally, then release the global- * ACK gate so the accept loop can finish any stragglers. */- runtime_service_interrupt_connections_except(service, worker, true);+ /* Close this requester normally, then release the global ACK gate so+ * the accept loop can finish any stragglers. */runtime_worker_finish(worker);cbm_mutex_lock(&service->mutex);worker->final_response_inflight = false;@@ -1482,6 +1670,16 @@ static void *runtime_connection_worker(void *opaque) {free(payload);return NULL;}+ if (frame.flags == CBM_DAEMON_RUNTIME_OP_STATUS) {+ runtime_worker_handle_status(worker, payload, frame.length);+ free(payload);+ return NULL;+ }+ if (frame.flags == CBM_DAEMON_RUNTIME_OP_STOP) {+ runtime_worker_handle_stop(worker, payload, frame.length);+ free(payload);+ return NULL;+ }if (frame.flags != CBM_DAEMON_RUNTIME_OP_HELLO ||frame.length != CBM_DAEMON_RENDEZVOUS_REQUEST_SIZE ||!runtime_rendezvous_request_decode(payload, requested_version, requested_build)) {@@ -1626,6 +1824,9 @@ static void *runtime_connection_worker(void *opaque) {case CBM_DAEMON_RUNTIME_OP_APPLICATION_CANCEL:keep_running = runtime_worker_handle_application_cancel(worker, payload, frame.length);break;+ case CBM_DAEMON_RUNTIME_OP_CLOSE_INTENT:+ keep_running = runtime_worker_handle_close_intent(worker, frame.length);+ break;case CBM_DAEMON_RUNTIME_OP_DISCONNECT:keep_running = false;(void)runtime_worker_handle_disconnect(worker, frame.length);@@ -1704,6 +1905,9 @@ static void runtime_reject_inline(cbm_daemon_ipc_connection_t *connection, constcbm_daemon_runtime_connect_result_t result;runtime_result_rejected(&result, message);(void)runtime_send_hello_response(connection, &result);+ /* Same Windows named-pipe discard hazard as runtime_worker_finish: the+ * peer must get to read the rejection before the handle closes. */+ cbm_daemon_ipc_connection_drain(connection, RUNTIME_REJECT_DRAIN_TIMEOUT_MS);cbm_daemon_ipc_connection_close(connection);}@@ -1948,6 +2152,9 @@ cbm_daemon_runtime_service_t *cbm_daemon_runtime_service_start_reserved(service->worker_capacity = config->max_clients;service->workers = calloc(service->worker_capacity, sizeof(*service->workers));service->coordinator = cbm_daemon_coordinator_new(config->lease_timeout_ms);+ if (service->coordinator && config->permanent) {+ cbm_daemon_coordinator_set_permanent(service->coordinator, true);+ }service->conflict_log_path =runtime_string_copy_bounded(config->conflict_log_path, RUNTIME_PATH_CAP);size_t version_length = 0;@@ -1971,6 +2178,7 @@ cbm_daemon_runtime_service_t *cbm_daemon_runtime_service_start_reserved(service->request_timeout_ms = config->request_timeout_ms;service->shutdown_timeout_ms = config->shutdown_timeout_ms;service->application = config->application;+ service->permanent = config->permanent;service->state = CBM_DAEMON_RUNTIME_SERVICE_STARTING;if (!service->workers || !service->coordinator || !service->conflict_log_path ||@@ -2254,6 +2462,105 @@ bool cbm_daemon_runtime_request_activation_shutdown(return valid;}+static bool runtime_control_request_send(const cbm_daemon_ipc_endpoint_t *endpoint,+ const cbm_daemon_build_identity_t *identity,+ cbm_daemon_runtime_operation_t operation,+ uint32_t timeout_ms, uint32_t response_size,+ uint8_t **payload_out) {+ *payload_out = NULL;+ if (!endpoint || !identity || !identity->build_fingerprint ||+ timeout_ms == CBM_DAEMON_IPC_WAIT_FOREVER) {+ return false;+ }+ uint8_t request[CBM_DAEMON_CONTROL_REQUEST_SIZE];+ memset(request, 0, sizeof(request));+ int written = snprintf((char *)request, sizeof(request), "%s", identity->build_fingerprint);+ if (written <= 0 || (size_t)written != CBM_DAEMON_BUILD_FINGERPRINT_SIZE - 1U) {+ return false;+ }+ cbm_daemon_ipc_connection_t *connection = cbm_daemon_ipc_connect(endpoint, timeout_ms);+ bool sent =+ connection && cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_REQUEST, operation,+ request, (uint32_t)sizeof(request));+ cbm_daemon_frame_t frame = {0};+ uint8_t *payload = NULL;+ int received = sent ? cbm_daemon_ipc_receive_frame_bounded(connection, timeout_ms,+ response_size, &frame, &payload)+ : 0;+ bool valid = received == 1 && frame.type == CBM_DAEMON_FRAME_RESPONSE &&+ frame.flags == operation && frame.length == response_size && payload &&+ payload[0] == 1U;+ cbm_daemon_ipc_connection_close(connection);+ if (!valid) {+ free(payload);+ return false;+ }+ *payload_out = payload;+ return true;+}++static uint32_t runtime_control_read_u32(const uint8_t *bytes) {+ return ((uint32_t)bytes[0] << 24) | ((uint32_t)bytes[1] << 16) | ((uint32_t)bytes[2] << 8) |+ (uint32_t)bytes[3];+}++bool cbm_daemon_runtime_request_status(const cbm_daemon_ipc_endpoint_t *endpoint,+ const cbm_daemon_build_identity_t *identity,+ uint32_t timeout_ms,+ cbm_daemon_runtime_status_t *status_out) {+ if (!status_out) {+ return false;+ }+ memset(status_out, 0, sizeof(*status_out));+ uint8_t *payload = NULL;+ if (!runtime_control_request_send(endpoint, identity, CBM_DAEMON_RUNTIME_OP_STATUS, timeout_ms,+ CBM_DAEMON_STATUS_RESPONSE_SIZE, &payload)) {+ return false;+ }+ status_out->permanent = (payload[1] & 0x01U) != 0U;+ status_out->stopping = (payload[1] & 0x02U) != 0U;+ status_out->committed_clients = (uint16_t)(((uint16_t)payload[2] << 8) | payload[3]);+ status_out->daemon_pid = runtime_control_read_u32(payload + 4);+ status_out->client_count = payload[8] > CBM_DAEMON_CONTROL_CLIENT_CAP+ ? (uint8_t)CBM_DAEMON_CONTROL_CLIENT_CAP+ : payload[8];+ for (size_t index = 0; index < CBM_DAEMON_CONTROL_CLIENT_CAP; index++) {+ status_out->client_pids[index] = runtime_control_read_u32(payload + 12U + index * 4U);+ }+ memcpy(status_out->build_fingerprint, payload + 44U, CBM_DAEMON_BUILD_FINGERPRINT_SIZE);+ status_out->build_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE - 1U] = '\0';+ memcpy(status_out->semantic_version, payload + 109U, sizeof(status_out->semantic_version));+ status_out->semantic_version[sizeof(status_out->semantic_version) - 1U] = '\0';+ free(payload);+ return true;+}++bool cbm_daemon_runtime_request_stop(const cbm_daemon_ipc_endpoint_t *endpoint,+ const cbm_daemon_build_identity_t *identity,+ uint32_t timeout_ms,+ cbm_daemon_runtime_stop_result_t *result_out) {+ if (!result_out) {+ return false;+ }+ memset(result_out, 0, sizeof(*result_out));+ uint8_t *payload = NULL;+ if (!runtime_control_request_send(endpoint, identity, CBM_DAEMON_RUNTIME_OP_STOP, timeout_ms,+ CBM_DAEMON_STOP_RESPONSE_SIZE, &payload)) {+ return false;+ }+ result_out->accepted = (payload[1] & 0x01U) != 0U;+ result_out->busy = (payload[1] & 0x02U) != 0U;+ result_out->committed_clients = (uint16_t)(((uint16_t)payload[2] << 8) | payload[3]);+ result_out->client_count = payload[4] > CBM_DAEMON_CONTROL_CLIENT_CAP+ ? (uint8_t)CBM_DAEMON_CONTROL_CLIENT_CAP+ : payload[4];+ for (size_t index = 0; index < CBM_DAEMON_CONTROL_CLIENT_CAP; index++) {+ result_out->client_pids[index] = runtime_control_read_u32(payload + 8U + index * 4U);+ }+ free(payload);+ return true;+}+cbm_daemon_runtime_client_t *cbm_daemon_runtime_client_connect(const cbm_daemon_ipc_endpoint_t *endpoint, const cbm_daemon_build_identity_t *identity,uint32_t timeout_ms, cbm_daemon_runtime_connect_result_t *result_out) {@@ -2570,9 +2877,15 @@ cbm_daemon_runtime_application_status_t cbm_daemon_runtime_client_application_reuint8_t cancel_wire[APPLICATION_CANCEL_REQUEST_SIZE];runtime_put_u64(cancel_wire, request_token);cbm_mutex_lock(&client->send_mutex);- bool sent = cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_REQUEST,- CBM_DAEMON_RUNTIME_OP_APPLICATION_REQUEST, wire,- (uint32_t)wire_length);+ cbm_mutex_lock(&client->state_mutex);+ bool request_can_send = client->usable && !client->closing &&+ client->connection == connection &&+ client->active_application_token == request_token;+ cbm_mutex_unlock(&client->state_mutex);+ bool sent =+ request_can_send && cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_REQUEST,+ CBM_DAEMON_RUNTIME_OP_APPLICATION_REQUEST,+ wire, (uint32_t)wire_length);bool send_cancel = false;cbm_mutex_lock(&client->state_mutex);client->application_request_sent = sent;@@ -2680,18 +2993,45 @@ bool cbm_daemon_runtime_client_close_begin(cbm_daemon_runtime_client_t *client)if (!client) {return false;}+ /* Serialize with request publication. If the request won send_mutex, its+ * exact token is visible here and cancellation is ordered after REQUEST;+ * if close won, the request path's closing recheck refuses the late send. */+ cbm_mutex_lock(&client->send_mutex);cbm_mutex_lock(&client->state_mutex);if (client->closing) {cbm_mutex_unlock(&client->state_mutex);+ cbm_mutex_unlock(&client->send_mutex);return false;}client->closing = true;client->close_interrupted_exchange = client->exchange_active;cbm_daemon_ipc_connection_t *connection = client->connection;+ cbm_daemon_runtime_application_token_t cancel_token = client->active_application_token;+ bool send_cancel = client->close_interrupted_exchange && connection &&+ client->application_request_sent && !client->application_cancel_sent &&+ cancel_token != CBM_DAEMON_RUNTIME_APPLICATION_TOKEN_INVALID;+ if (send_cancel) {+ client->application_cancel_sent = true;+ }+ cbm_mutex_unlock(&client->state_mutex);++ if (send_cancel) {+ uint8_t wire[APPLICATION_CANCEL_REQUEST_SIZE];+ runtime_put_u64(wire, cancel_token);+ (void)cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_REQUEST,+ CBM_DAEMON_RUNTIME_OP_APPLICATION_CANCEL, wire,+ (uint32_t)sizeof(wire));+ }if (client->close_interrupted_exchange && connection) {+ /* The interrupted-exchange close cannot run the DISCONNECT handshake,+ * so announce the departure explicitly (ordered after the cancel);+ * the server releases this client's admission on receipt instead of+ * waiting for the handle to close. Mirrors POSIX shutdown() timing. */+ (void)cbm_daemon_ipc_send_frame(connection, CBM_DAEMON_FRAME_REQUEST,+ CBM_DAEMON_RUNTIME_OP_CLOSE_INTENT, NULL, 0);cbm_daemon_ipc_connection_interrupt(connection);}- cbm_mutex_unlock(&client->state_mutex);+ cbm_mutex_unlock(&client->send_mutex);return true;}diff --git a/src/daemon/runtime.h b/src/daemon/runtime.hindex 4647f99d2..6de58f3b2 100644--- a/src/daemon/runtime.h+++ b/src/daemon/runtime.h@@ -46,6 +46,14 @@* requester excludes itself). */#define CBM_DAEMON_ACTIVATION_SHUTDOWN_REQUEST_SIZE 137U#define CBM_DAEMON_ACTIVATION_SHUTDOWN_RESPONSE_SIZE 24U++/* STATUS/STOP wire sizes. Requests carry only the requester's claimed build+ * fingerprint (kernel-peer-verified, cross-build by design). Responses are+ * fixed-size with a capped committed-client pid table. */+#define CBM_DAEMON_CONTROL_REQUEST_SIZE 65U+#define CBM_DAEMON_CONTROL_CLIENT_CAP 8U+#define CBM_DAEMON_STATUS_RESPONSE_SIZE 121U+#define CBM_DAEMON_STOP_RESPONSE_SIZE 40U#define CBM_DAEMON_RUNTIME_PROJECT_KEY_MAX 4096U#define CBM_DAEMON_RUNTIME_APPLICATION_PAYLOAD_MAX (CBM_DAEMON_MAX_FRAME_SIZE - 16U)@@ -62,6 +70,21 @@ typedef enum {CBM_DAEMON_RUNTIME_OP_APPLICATION_REQUEST = 6,CBM_DAEMON_RUNTIME_OP_APPLICATION_CANCEL = 7,CBM_DAEMON_RUNTIME_OP_ACTIVATION_SHUTDOWN = 8,+ /* Fire-and-forget departure notice sent by close_begin when it interrupts+ * an in-flight exchange. POSIX peers additionally signal departure via+ * shutdown()/EOF; Windows named pipes have no client half-close, so this+ * frame is what releases admission before the handle closes. No response+ * is sent: the client's receive path is already interrupted. */+ CBM_DAEMON_RUNTIME_OP_CLOSE_INTENT = 9,+ /* `daemon status` observability probe. Like ACTIVATION_SHUTDOWN this is a+ * one-shot authenticated first frame — no cohort, no HELLO, no admission —+ * so it works across build skew, which is exactly when status matters. */+ CBM_DAEMON_RUNTIME_OP_STATUS = 10,+ /* `daemon stop`. Same authentication shape as STATUS. Refuses while+ * committed clients exist (their pids come back in the response) and+ * otherwise begins the normal stopping sequence — including for a+ * PERMANENT generation, which this op and process kill alone may end. */+ CBM_DAEMON_RUNTIME_OP_STOP = 11,} cbm_daemon_runtime_operation_t;typedef enum {@@ -170,6 +193,10 @@ typedef struct {* required. Function pointers and context are copied; the context's owner* must keep it alive until service_free returns true. */cbm_daemon_runtime_application_callbacks_t application;+ /* Born via `daemon start`: the service does not begin stopping when its+ * last committed client disconnects; only the stop/drain ops or an+ * explicit process kill end it. */+ bool permanent;} cbm_daemon_runtime_service_config_t;typedef enum {@@ -227,6 +254,40 @@ bool cbm_daemon_runtime_request_activation_shutdown(cbm_daemon_runtime_activation_action_t action, uint32_t timeout_ms,cbm_daemon_runtime_activation_result_t *result_out);+typedef struct {+ bool permanent;+ bool stopping;+ uint16_t committed_clients;+ uint32_t daemon_pid;+ uint8_t client_count; /* entries in client_pids, capped at the wire limit */+ uint32_t client_pids[CBM_DAEMON_CONTROL_CLIENT_CAP];+ char build_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];+ char semantic_version[12];+} cbm_daemon_runtime_status_t;++typedef struct {+ bool accepted; /* stopping was initiated */+ bool busy; /* refused: committed clients hold the daemon */+ uint16_t committed_clients;+ uint8_t client_count;+ uint32_t client_pids[CBM_DAEMON_CONTROL_CLIENT_CAP];+} cbm_daemon_runtime_stop_result_t;++/* One-shot authenticated status probe (no cohort, no HELLO, no admission).+ * Works across build skew. A true return means a valid response arrived. */+bool cbm_daemon_runtime_request_status(const cbm_daemon_ipc_endpoint_t *endpoint,+ const cbm_daemon_build_identity_t *identity,+ uint32_t timeout_ms,+ cbm_daemon_runtime_status_t *status_out);++/* One-shot authenticated stop request. Refuses while committed clients exist+ * (result_out lists their pids); otherwise begins the stopping sequence, for+ * permanent generations too. */+bool cbm_daemon_runtime_request_stop(const cbm_daemon_ipc_endpoint_t *endpoint,+ const cbm_daemon_build_identity_t *identity,+ uint32_t timeout_ms,+ cbm_daemon_runtime_stop_result_t *result_out);+/* Performs the complete guarded first-participant handoff, starts listening* synchronously, then owns both that participant claim and its* accept/connection threads. All config scalar/text data is copied. endpointdiff --git a/src/daemon/service.c b/src/daemon/service.cindex 284922641..777700f88 100644--- a/src/daemon/service.c+++ b/src/daemon/service.c@@ -740,7 +740,7 @@ bool cbm_daemon_build_fingerprint_file(const char *path,if (!bounded_length(path, DAEMON_SERVICE_PATH_CAP, &path_length) || path_length == 0) {return false;}- wchar_t *wide = cbm_utf8_to_wide(path);+ wchar_t *wide = cbm_path_to_wide(path);if (!wide) {return false;}@@ -829,7 +829,7 @@ static bool windows_log_path_open(const char *log_path, windows_log_path_t *pathreturn false;}- path->wide = cbm_utf8_to_wide(log_path);+ path->wide = cbm_path_to_wide(log_path);if (!path->wide) {return false;}@@ -851,15 +851,22 @@ static bool windows_private_file_prepare(const char *directory, const char *base/* cbm_daemon_ipc_private_log_open supplies the same explicit protected* current-SID DACL and reparse/owner checks as the daemon's operation log.* Its brief FILE_SHARE_READ handle can collide with a concurrent opener,- * so retry that transient window rather than dropping a conflict event. */- for (unsigned int attempt = 0; attempt < 100; attempt++) {+ * so retry that transient window rather than dropping a conflict event.+ * The retry budget is a short deadline, not a count: Sleep(2) rounds up+ * to the ~16 ms timer granularity, and a permanently obstructed path+ * (e.g. a directory squatting on it) must fail fast — a rejected client+ * is waiting behind this on the hello path with its own timeout. */+ ULONGLONG deadline = GetTickCount64() + 250;+ for (;;) {FILE *file = cbm_daemon_ipc_private_log_open(directory, base, SIZE_MAX);if (file) {return fclose(file) == 0;}+ if (GetTickCount64() >= deadline) {+ return false;+ }Sleep(2);}- return false;}static HANDLE windows_lock_open(const wchar_t *path) {diff --git a/src/discover/discover.c b/src/discover/discover.cindex c82a6bdf0..832cc1f5a 100644--- a/src/discover/discover.c+++ b/src/discover/discover.c@@ -690,7 +690,7 @@ static CBMLanguage detect_file_language(const char *entry_name, const char *abs_/* UTF-8-safe stat: wide API on Windows, regular stat on POSIX. */static int wide_stat(const char *path, struct stat *st) {#ifdef _WIN32- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return CBM_NOT_FOUND;}@@ -715,7 +715,7 @@ static int wide_stat(const char *path, struct stat *st) {* root, mirroring the POSIX S_ISLNK skip. */static int safe_stat(const char *abs_path, struct stat *st) {#ifdef _WIN32- wchar_t *wpath = cbm_utf8_to_wide(abs_path);+ wchar_t *wpath = cbm_path_to_wide(abs_path);if (wpath) {DWORD attr = GetFileAttributesW(wpath);free(wpath);diff --git a/src/foundation/compat.c b/src/foundation/compat.cindex 27862fe2d..2ebddb13a 100644--- a/src/foundation/compat.c+++ b/src/foundation/compat.c@@ -75,7 +75,7 @@ static bool win_mkdtemp_private_create(const char *path) {TOKEN_USER *user = NULL;PACL acl = NULL;DWORD needed = 0;- wchar_t *wide = cbm_utf8_to_wide(path);+ wchar_t *wide = cbm_path_to_wide(path);if (wide && OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&!GetTokenInformation(token, TokenUser, NULL, 0, &needed) &&GetLastError() == ERROR_INSUFFICIENT_BUFFER && (user = malloc(needed)) != NULL &&@@ -127,15 +127,31 @@ char *cbm_mkdtemp(char *tmpl) {} else {snprintf(buf, sizeof(buf), "%s", tmpl);}- if (!_mktemp(buf))+ /* Wide-API template expansion: the ANSI CRT interprets the UTF-8 bytes of+ * non-ASCII cache/temp components in the local codepage and fails. */+ wchar_t *wide_template = cbm_utf8_to_wide(buf);+ if (!wide_template || !_wmktemp(wide_template)) {+ free(wide_template);return NULL;+ }+ char *expanded = cbm_wide_to_utf8(wide_template);+ free(wide_template);+ if (!expanded || strlen(expanded) >= sizeof(buf)) {+ free(expanded);+ return NULL;+ }+ strcpy(buf, expanded);+ free(expanded);if (!win_mkdtemp_private_create(buf)) {/* One-time note: every private-namespace validation downstream* depends on the explicit descriptor, so a silent fallback turns* into unexplained owner/DACL refusals far from this call site. */static bool fallback_reported;DWORD create_error = GetLastError();- if (_mkdir(buf) != 0)+ wchar_t *wide_directory = cbm_utf8_to_wide(buf);+ int mkdir_result = wide_directory ? _wmkdir(wide_directory) : -1;+ free(wide_directory);+ if (mkdir_result != 0)return NULL;if (!fallback_reported) {fallback_reported = true;@@ -159,6 +175,34 @@ char *cbm_mkdtemp(char *tmpl) {}#endif+bool cbm_path_for_file_api(const char *path, char *out, size_t out_size) {+ if (!path || !out || out_size == 0) {+ return false;+ }+#ifdef _WIN32+ wchar_t *wide = cbm_path_to_wide(path);+ char *narrow = wide ? cbm_wide_to_utf8(wide) : NULL;+ free(wide);+ if (!narrow) {+ return false;+ }+ size_t needed = strlen(narrow);+ bool fits = needed < out_size;+ if (fits) {+ memcpy(out, narrow, needed + 1U);+ }+ free(narrow);+ return fits;+#else+ size_t needed = strlen(path);+ if (needed >= out_size) {+ return false;+ }+ memcpy(out, path, needed + 1U);+ return true;+#endif+}+/* ── mkstemp (Windows lacks it) ───────────────────────────────── */#ifdef _WIN32@@ -182,11 +226,35 @@ int cbm_mkstemp(char *tmpl) {errno = ENAMETOOLONG;return CBM_NOT_FOUND;}- if (!_mktemp(buf))+ /* Wide-API expansion and open: worker staging files land inside+ * CBM_CACHE_DIR, which users may place at non-ASCII paths; the ANSI CRT+ * (_mktemp/_open) mangles those bytes in the local codepage. */+ wchar_t *wide_template = cbm_utf8_to_wide(buf);+ if (!wide_template || !_wmktemp(wide_template)) {+ free(wide_template);+ return CBM_NOT_FOUND;+ }+ char *expanded_for_open = cbm_wide_to_utf8(wide_template);+ wchar_t *wide_open = expanded_for_open ? cbm_path_to_wide(expanded_for_open) : NULL;+ free(expanded_for_open);+ if (!wide_open) {+ free(wide_template);return CBM_NOT_FOUND;- int fd = _open(buf, _O_CREAT | _O_EXCL | _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE);- if (fd >= 0)- strcpy(tmpl, buf);+ }+ int fd = _wopen(wide_open, _O_CREAT | _O_EXCL | _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE);+ free(wide_open);+ if (fd >= 0) {+ char *expanded = cbm_wide_to_utf8(wide_template);+ if (!expanded || strlen(expanded) >= sizeof(buf)) {+ free(expanded);+ free(wide_template);+ (void)_close(fd);+ return CBM_NOT_FOUND;+ }+ strcpy(tmpl, expanded);+ free(expanded);+ }+ free(wide_template);return fd;}#endifdiff --git a/src/foundation/compat.h b/src/foundation/compat.hindex 38886f0ad..055a45687 100644--- a/src/foundation/compat.h+++ b/src/foundation/compat.h@@ -117,10 +117,19 @@ char *cbm_mkdtemp(char *tmpl);/* ── mkstemp (Windows lacks it) ──────────────────────────────── */#ifdef _WIN32int cbm_mkstemp(char *tmpl);+#else#define cbm_mkstemp mkstemp#endif+/* Rewrite an absolute path into the form the platform's file APIs accept at+ * any length. On Windows, absolute drive paths beyond the legacy 260-char+ * limit are canonicalized and given the extended-length \\?\ prefix+ * (SQLite passes such UTF-8 paths through to CreateFileW unchanged). On+ * POSIX, the path is copied verbatim. Returns false if the buffer is too+ * small or the path cannot be canonicalized. */+bool cbm_path_for_file_api(const char *path, char *out, size_t out_size);+/* ── setenv / unsetenv (Windows lacks them) ──────────────────── */#ifdef _WIN32static inline int cbm_setenv(const char *name, const char *value, int overwrite) {diff --git a/src/foundation/compat_fs.c b/src/foundation/compat_fs.cindex e62db8574..09392097d 100644--- a/src/foundation/compat_fs.c+++ b/src/foundation/compat_fs.c@@ -20,6 +20,8 @@#define WIN32_LEAN_AND_MEAN#endif#include <windows.h>++#include <aclapi.h>#include <direct.h> /* _wmkdir */#include <errno.h> /* errno for spawn-failure logging */#include <fcntl.h> /* _O_RDONLY */@@ -41,7 +43,7 @@ cbm_dir_t *cbm_opendir(const char *path) {if (!path) {return NULL;}- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return NULL;}@@ -377,7 +379,7 @@ int cbm_pclose(FILE *f) {}FILE *cbm_fopen(const char *path, const char *mode) {- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return NULL;}@@ -392,13 +394,66 @@ FILE *cbm_fopen(const char *path, const char *mode) {return f;}+/* Stamp the exact current user as owner and apply an owner-only protected+ * DACL on a directory cbm just created. Under the Administrators-default-owner+ * policy (server/runner images), a plain _wmkdir yields an Administrators-owned+ * directory that the launcher/activation exact-owner validators reject. Only+ * freshly created directories are stamped; pre-existing ones keep their owner. */+static void cbm_windows_stamp_dir_owner(const wchar_t *path) {+ HANDLE token = NULL;+ TOKEN_USER *user = NULL;+ PACL acl = NULL;+ DWORD needed = 0U;+ if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&+ !GetTokenInformation(token, TokenUser, NULL, 0U, &needed) &&+ GetLastError() == ERROR_INSUFFICIENT_BUFFER && (user = malloc(needed)) != NULL &&+ GetTokenInformation(token, TokenUser, user, needed, &needed) && user->User.Sid &&+ IsValidSid(user->User.Sid)) {+ EXPLICIT_ACCESSW access;+ memset(&access, 0, sizeof(access));+ access.grfAccessPermissions = GENERIC_ALL;+ access.grfAccessMode = SET_ACCESS;+ access.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;+ access.Trustee.TrusteeForm = TRUSTEE_IS_SID;+ access.Trustee.TrusteeType = TRUSTEE_IS_USER;+ access.Trustee.ptstrName = (LPWSTR)user->User.Sid;+ HANDLE directory =+ CreateFileW(path, WRITE_OWNER | WRITE_DAC | READ_CONTROL,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);+ if (directory != INVALID_HANDLE_VALUE) {+ if (SetEntriesInAclW(1U, &access, NULL, &acl) == ERROR_SUCCESS) {+ (void)SetSecurityInfo(directory, SE_FILE_OBJECT,+ OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION |+ PROTECTED_DACL_SECURITY_INFORMATION,+ user->User.Sid, NULL, acl, NULL);+ }+ (void)CloseHandle(directory);+ }+ }+ if (acl) {+ (void)LocalFree(acl);+ }+ free(user);+ if (token) {+ (void)CloseHandle(token);+ }+}+static bool cbm_windows_mkdir_component(wchar_t *path) {- if (_wmkdir(path) != 0 && errno != EEXIST) {+ bool created = _wmkdir(path) == 0;+ if (!created && errno != EEXIST) {return false;}DWORD attributes = GetFileAttributesW(path);- return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0U &&- (attributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0U;+ if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0U ||+ (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0U) {+ return false;+ }+ if (created) {+ cbm_windows_stamp_dir_owner(path);+ }+ return true;}bool cbm_mkdir_p(const char *path, int mode) {@@ -406,7 +461,7 @@ bool cbm_mkdir_p(const char *path, int mode) {if (!path || path[0] == '\0') {return false;}- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return false;}@@ -453,7 +508,7 @@ bool cbm_mkdir_p(const char *path, int mode) {}int cbm_unlink(const char *path) {- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return CBM_NOT_FOUND;}@@ -463,7 +518,7 @@ int cbm_unlink(const char *path) {}int cbm_rmdir(const char *path) {- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return CBM_NOT_FOUND;}@@ -815,7 +870,7 @@ int cbm_canonical_path(const char *path, char *out, size_t out_sz) {return 0;}#ifdef _WIN32- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return 0;}@@ -882,8 +937,8 @@ int cbm_canonical_path(const char *path, char *out, size_t out_sz) {* (wide paths — raw MoveFileExA would re-mangle non-ASCII cache paths). */int cbm_rename_replace(const char *src, const char *dst) {#ifdef _WIN32- wchar_t *wsrc = cbm_utf8_to_wide(src);- wchar_t *wdst = cbm_utf8_to_wide(dst);+ wchar_t *wsrc = cbm_path_to_wide(src);+ wchar_t *wdst = cbm_path_to_wide(dst);int ret = CBM_NOT_FOUND;if (wsrc && wdst) {ret = MoveFileExW(wsrc, wdst, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)diff --git a/src/foundation/diagnostics.c b/src/foundation/diagnostics.cindex 9bd3129f9..1971c0f1a 100644--- a/src/foundation/diagnostics.c+++ b/src/foundation/diagnostics.c@@ -1,48 +1,82 @@/** diagnostics.c — Periodic diagnostics file writer.*- * Writes JSON to /tmp/cbm-diagnostics-<pid>.json every 5 seconds.- * Atomic: writes .tmp then renames to avoid partial reads.+ * Every enabled process writes below a fresh owner-private directory. Files+ * are created exclusively without following links, and POSIX I/O remains+ * anchored to the validated directory descriptor. Diagnostics are strictly+ * best-effort: shutdown is interruptible and bounded, so a stuck filesystem+ * can never retain the daemon.*/-#include "foundation/constants.h"#include "foundation/diagnostics.h"-#include <stdatomic.h>-#include "foundation/mem.h"+#include "foundation/compat.h"-#include "foundation/compat_thread.h"#include "foundation/compat_fs.h"+#include "foundation/compat_thread.h"+#include "foundation/constants.h"+#include "foundation/log.h"+#include "foundation/macos_acl.h"+#include "foundation/mem.h"#include "foundation/platform.h"+#include "foundation/private_file_lock.h"+#include "foundation/private_file_lock_internal.h"#include <mimalloc.h>+#include <stdatomic.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>#ifdef _WIN32+#include "foundation/win_utf8.h"#include <process.h>+#include <windows.h>#define getpid _getpid#else#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <sys/stat.h>+#include <sys/types.h>#include <unistd.h>#endif-/* ── Globals ─────────────────────────────────────────────────────── */+enum {+ DIAG_INTERVAL_MS = 5000,+ DIAG_WAIT_SLICE_MS = 10,+ DIAG_STOP_TIMEOUT_MS = 500,+};++#define DIAG_NDJSON_CAP_BYTES (8u * 1024u * 1024u)+#define DIAG_SNAPSHOT_NAME "snapshot.json"+#define DIAG_SNAPSHOT_TMP_NAME "snapshot.json.tmp"+#define DIAG_TRAJECTORY_NAME "trajectory.ndjson"+#define DIAG_TRAJECTORY_ROTATED_NAME "trajectory.ndjson.1"++/* ── Globals ────────────────────────────────────────────────────────────── */cbm_query_stats_t g_query_stats = {0};-static atomic_int g_diag_stop = 0;+static atomic_bool g_diag_stop = false;+static atomic_bool g_diag_done = false;static cbm_thread_t g_diag_thread;static bool g_diag_started = false;+static bool g_diag_abandoned = false;static time_t g_start_time = 0;-static char g_diag_path[CBM_SZ_256] = "";-/* Persistent NDJSON time-series (the memory TRAJECTORY users send us to diagnose- * slow leaks like #581). Unlike g_diag_path (a latest-snapshot file overwritten- * every interval and deleted on stop), this is appended-to and KEPT on exit. */-static char g_diag_ndjson_path[CBM_SZ_256] = "";+static cbm_private_lock_directory_t *g_diag_directory = NULL;+#ifndef _WIN32+static int g_diag_directory_fd = -1;+#endif+static char g_diag_directory_path[CBM_PATH_MAX] = "";+static char g_diag_path[CBM_PATH_MAX] = "";+static char g_diag_ndjson_path[CBM_PATH_MAX] = "";static size_t g_diag_ndjson_size = 0;-#define DIAG_NDJSON_CAP_BYTES (8u * 1024u * 1024u) /* rotate to .1 past this */-/* ── Query stats ─────────────────────────────────────────────────── */+#ifdef CBM_DIAGNOSTICS_ENABLE_TEST_API+static atomic_bool g_diag_test_hold_writer = false;+static atomic_bool g_diag_test_writer_reached = false;+#endif++/* ── Query stats ────────────────────────────────────────────────────────── */void cbm_diag_record_query(long long duration_us, bool is_error) {atomic_fetch_add(&g_query_stats.count, 1);@@ -50,7 +84,6 @@ void cbm_diag_record_query(long long duration_us, bool is_error) {if (is_error) {atomic_fetch_add(&g_query_stats.errors, 1);}- /* Update max (lock-free CAS loop) */long long old_max = atomic_load(&g_query_stats.max_us);while (duration_us > old_max) {if (atomic_compare_exchange_weak(&g_query_stats.max_us, &old_max, duration_us)) {@@ -59,7 +92,7 @@ void cbm_diag_record_query(long long duration_us, bool is_error) {}}-/* ── FD count (platform-specific) ────────────────────────────────── */+/* ── FD count (platform-specific) ──────────────────────────────────────── */static int count_open_fds(void) {#ifdef __linux__@@ -72,9 +105,8 @@ static int count_open_fds(void) {free(entries[i]);}free(entries);- return n - PAIR_LEN; /* . and .. */+ return n - PAIR_LEN;#elif defined(__APPLE__)- /* Count via /dev/fd using scandir (MT-safe) */struct dirent **entries = NULL;int n = scandir("/dev/fd", &entries, NULL, NULL);if (n < 0) {@@ -84,48 +116,312 @@ static int count_open_fds(void) {free(entries[i]);}free(entries);- return n - PAIR_LEN; /* . and .. */+ return n - PAIR_LEN;#else- return CBM_NOT_FOUND; /* Not available on Windows */+ return CBM_NOT_FOUND;#endif}-/* ── Writer ──────────────────────────────────────────────────────── */+/* ── Private output directory ────────────────────────────────────────────── */-#define DIAG_INTERVAL_S 5-#define DIAG_PATH_EXTRA 24 /* ".tmp" + safety margin */+static bool diag_set_output_paths(void) {+ int snapshot = snprintf(g_diag_path, sizeof(g_diag_path), "%s/%s", g_diag_directory_path,+ DIAG_SNAPSHOT_NAME);+ int trajectory = snprintf(g_diag_ndjson_path, sizeof(g_diag_ndjson_path), "%s/%s",+ g_diag_directory_path, DIAG_TRAJECTORY_NAME);+ return snapshot > 0 && (size_t)snapshot < sizeof(g_diag_path) && trajectory > 0 &&+ (size_t)trajectory < sizeof(g_diag_ndjson_path);+}-/* Append one compact JSON line to the persistent NDJSON trajectory, rotating to- * <path>.1 once it passes the cap. Best-effort: a failed append never disrupts- * the server. The trajectory (a monotonic rss/committed climb over hours) is- * what reveals a slow leak like #581 — the single latest-snapshot file cannot. */-static void append_trajectory(long uptime, size_t rss, size_t peak_rss, size_t commit,- size_t peak_commit, size_t page_faults, int fds, int qcount) {- if (g_diag_ndjson_path[0] == '\0') {+static void diag_directory_close(bool remove_directory) {+#ifndef _WIN32+ if (g_diag_directory_fd >= 0) {+ (void)close(g_diag_directory_fd);+ g_diag_directory_fd = -1;+ }+#endif+ cbm_private_lock_directory_close(g_diag_directory);+ g_diag_directory = NULL;+ if (remove_directory && g_diag_directory_path[0] != '\0') {+ (void)cbm_rmdir(g_diag_directory_path);+ }+}++/* Diagnostics placement honors the documented contract ($TMPDIR, /tmp+ * fallback) without touching cbm_tmpdir(), whose many other callers keep+ * their established behavior. Windows already resolves the real user temp. */+static const char *diag_tmp_base(char *buffer, size_t size) {+#ifdef _WIN32+ (void)buffer;+ (void)size;+ return cbm_tmpdir();+#else+ cbm_safe_getenv("TMPDIR", buffer, size, NULL);+ if (buffer[0] != '\0') {+ return buffer;+ }+ return "/tmp";+#endif+}++static bool diag_directory_prepare(void) {+ char tmp_base[CBM_PATH_MAX];+ char directory_template[CBM_PATH_MAX];+ int written =+ snprintf(directory_template, sizeof(directory_template), "%s/cbm-diagnostics-%d-XXXXXX",+ diag_tmp_base(tmp_base, sizeof(tmp_base)), (int)getpid());+ if (written <= 0 || (size_t)written >= sizeof(directory_template) ||+ !cbm_mkdtemp(directory_template)) {+ return false;+ }+ written =+ snprintf(g_diag_directory_path, sizeof(g_diag_directory_path), "%s", directory_template);+ if (written <= 0 || (size_t)written >= sizeof(g_diag_directory_path)) {+ (void)cbm_rmdir(directory_template);+ return false;+ }++#ifdef _WIN32+ wchar_t *wide_directory = cbm_path_to_wide(g_diag_directory_path);+ HANDLE handle =+ wide_directory+ ? CreateFileW(wide_directory, FILE_READ_ATTRIBUTES | READ_CONTROL,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,+ NULL)+ : INVALID_HANDLE_VALUE;+ free(wide_directory);+ cbm_private_file_lock_status_t status = CBM_PRIVATE_FILE_LOCK_IO;+ if (handle != INVALID_HANDLE_VALUE) {+ status = cbm_private_lock_directory_adopt_windows(handle, g_diag_directory_path,+ &g_diag_directory);+ if (status != CBM_PRIVATE_FILE_LOCK_OK) {+ (void)CloseHandle(handle);+ }+ }+#else+ int flags = O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW;+ int validation_fd = open(g_diag_directory_path, flags);+ int output_fd = open(g_diag_directory_path, flags);+ struct stat validation_state;+ struct stat output_state;+ bool same_directory =+ validation_fd >= 0 && output_fd >= 0 && fstat(validation_fd, &validation_state) == 0 &&+ fstat(output_fd, &output_state) == 0 && validation_state.st_dev == output_state.st_dev &&+ validation_state.st_ino == output_state.st_ino;+ cbm_private_file_lock_status_t status = CBM_PRIVATE_FILE_LOCK_IO;+ if (same_directory) {+ status = cbm_private_lock_directory_adopt_posix(validation_fd, g_diag_directory_path,+ &g_diag_directory);+ if (status == CBM_PRIVATE_FILE_LOCK_OK) {+ validation_fd = -1;+ g_diag_directory_fd = output_fd;+ output_fd = -1;+ }+ }+ if (validation_fd >= 0) {+ (void)close(validation_fd);+ }+ if (output_fd >= 0) {+ (void)close(output_fd);+ }+#endif++ if (status != CBM_PRIVATE_FILE_LOCK_OK || !diag_set_output_paths()) {+ diag_directory_close(true);+ return false;+ }+ return true;+}++#ifdef _WIN32++static bool diag_full_path(const char *base_name, char *path, size_t path_size) {+ int written = snprintf(path, path_size, "%s/%s", g_diag_directory_path, base_name);+ return written > 0 && (size_t)written < path_size;+}++static bool diag_win_handle_valid(HANDLE handle) {+ BY_HANDLE_FILE_INFORMATION information;+ return handle != INVALID_HANDLE_VALUE && GetFileType(handle) == FILE_TYPE_DISK &&+ GetFileInformationByHandle(handle, &information) != 0 &&+ (information.dwFileAttributes &+ (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0 &&+ information.nNumberOfLinks == 1 &&+ SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) != 0;+}++static bool diag_write_file(const char *base_name, const char *data, size_t length, bool append) {+ char path[CBM_PATH_MAX];+ if (!diag_full_path(base_name, path, sizeof(path))) {+ return false;+ }+ wchar_t *wide_path = cbm_path_to_wide(path);+ DWORD access = append ? FILE_APPEND_DATA : GENERIC_WRITE;+ HANDLE handle = wide_path+ ? CreateFileW(wide_path, access, FILE_SHARE_READ, NULL, CREATE_NEW,+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, NULL)+ : INVALID_HANDLE_VALUE;+ DWORD creation_error = handle == INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS;+ if (handle == INVALID_HANDLE_VALUE && wide_path &&+ (creation_error == ERROR_FILE_EXISTS || creation_error == ERROR_ALREADY_EXISTS)) {+ handle = CreateFileW(wide_path, access, FILE_SHARE_READ, NULL,+ append ? OPEN_EXISTING : TRUNCATE_EXISTING,+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, NULL);+ }+ free(wide_path);+ if (!diag_win_handle_valid(handle)) {+ if (handle != INVALID_HANDLE_VALUE) {+ (void)CloseHandle(handle);+ }+ return false;+ }+ bool ok = true;+ size_t offset = 0;+ while (offset < length) {+ DWORD chunk = length - offset > MAXDWORD ? MAXDWORD : (DWORD)(length - offset);+ DWORD bytes_written = 0;+ if (!WriteFile(handle, data + offset, chunk, &bytes_written, NULL) || bytes_written == 0) {+ ok = false;+ break;+ }+ offset += bytes_written;+ }+ return CloseHandle(handle) != 0 && ok;+}++static bool diag_native_rename(const char *source_name, const char *destination_name) {+ char source[CBM_PATH_MAX];+ char destination[CBM_PATH_MAX];+ return diag_full_path(source_name, source, sizeof(source)) &&+ diag_full_path(destination_name, destination, sizeof(destination)) &&+ cbm_rename_replace(source, destination) == 0;+}++static void diag_native_unlink(const char *base_name) {+ char path[CBM_PATH_MAX];+ if (diag_full_path(base_name, path, sizeof(path))) {+ (void)cbm_unlink(path);+ }+}++#else++static bool diag_posix_file_valid(int descriptor) {+ struct stat state;+ return descriptor >= 0 && fstat(descriptor, &state) == 0 && S_ISREG(state.st_mode) &&+ state.st_uid == geteuid() && state.st_nlink == 1 && (state.st_mode & 07777) == 0600 &&+ cbm_macos_extended_acl_fd_is_empty(descriptor);+}++static bool diag_write_file(const char *base_name, const char *data, size_t length, bool append) {+ int flags = O_WRONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK;+ flags |= append ? O_APPEND : O_TRUNC;+ int descriptor = openat(g_diag_directory_fd, base_name, flags | O_CREAT | O_EXCL, 0600);+ bool created = descriptor >= 0;+ if (descriptor < 0 && errno == EEXIST) {+ descriptor = openat(g_diag_directory_fd, base_name, flags);+ }+ if (created && fchmod(descriptor, 0600) != 0) {+ (void)close(descriptor);+ return false;+ }+ if (!diag_posix_file_valid(descriptor)) {+ if (descriptor >= 0) {+ (void)close(descriptor);+ }+ return false;+ }+ bool ok = true;+ size_t offset = 0;+ while (offset < length) {+ ssize_t bytes_written = write(descriptor, data + offset, length - offset);+ if (bytes_written > 0) {+ offset += (size_t)bytes_written;+ } else if (bytes_written < 0 && errno == EINTR) {+ continue;+ } else {+ ok = false;+ break;+ }+ }+ return close(descriptor) == 0 && ok;+}++static bool diag_native_rename(const char *source_name, const char *destination_name) {+ return renameat(g_diag_directory_fd, source_name, g_diag_directory_fd, destination_name) == 0;+}++static void diag_native_unlink(const char *base_name) {+ (void)unlinkat(g_diag_directory_fd, base_name, 0);+}++#endif++/* ── Writer ─────────────────────────────────────────────────────────────────────── */++static void diag_sleep_ms(unsigned int milliseconds) {+ struct timespec delay = {+ .tv_sec = (time_t)(milliseconds / 1000U),+ .tv_nsec = (long)((milliseconds % 1000U) * 1000000U),+ };+ (void)cbm_nanosleep(&delay, NULL);+}++static void diag_wait_for_interval(void) {+ uint64_t deadline = cbm_now_ms() + DIAG_INTERVAL_MS;+ while (!atomic_load_explicit(&g_diag_stop, memory_order_acquire)) {+ uint64_t now = cbm_now_ms();+ if (now >= deadline) {+ return;+ }+ uint64_t remaining = deadline - now;+ unsigned int slice =+ remaining < DIAG_WAIT_SLICE_MS ? (unsigned int)remaining : DIAG_WAIT_SLICE_MS;+ diag_sleep_ms(slice > 0 ? slice : 1);+ }+}++#ifdef CBM_DIAGNOSTICS_ENABLE_TEST_API+static void diag_test_pause_writer(void) {+ if (!atomic_load_explicit(&g_diag_test_hold_writer, memory_order_acquire)) {return;}+ atomic_store_explicit(&g_diag_test_writer_reached, true, memory_order_release);+ while (atomic_load_explicit(&g_diag_test_hold_writer, memory_order_acquire)) {+ diag_sleep_ms(DIAG_WAIT_SLICE_MS);+ }+}+#endif++static void append_trajectory(long uptime, size_t rss, size_t peak_rss, size_t commit,+ size_t peak_commit, size_t page_faults, int fds, int qcount) {if (g_diag_ndjson_size > DIAG_NDJSON_CAP_BYTES) {- char rot[sizeof(g_diag_ndjson_path) + DIAG_PATH_EXTRA];- snprintf(rot, sizeof(rot), "%s.1", g_diag_ndjson_path);- (void)rename(g_diag_ndjson_path, rot); /* keep one previous generation */+ if (!diag_native_rename(DIAG_TRAJECTORY_NAME, DIAG_TRAJECTORY_ROTATED_NAME)) {+ return;+ }g_diag_ndjson_size = 0;}- FILE *f = fopen(g_diag_ndjson_path, "a");- if (!f) {+ char line[CBM_SZ_512];+ int length = snprintf(line, sizeof(line),+ "{\"uptime_s\":%ld,\"rss\":%zu,\"peak_rss\":%zu,\"committed\":%zu,"+ "\"peak_committed\":%zu,\"page_faults\":%zu,\"fd\":%d,\"queries\":%d}\n",+ uptime, rss, peak_rss, commit, peak_commit, page_faults, fds, qcount);+ if (length <= 0 || (size_t)length >= sizeof(line) ||+ !diag_write_file(DIAG_TRAJECTORY_NAME, line, (size_t)length, true)) {return;}- int n = fprintf(f,- "{\"uptime_s\":%ld,\"rss\":%zu,\"peak_rss\":%zu,\"committed\":%zu,"- "\"peak_committed\":%zu,\"page_faults\":%zu,\"fd\":%d,\"queries\":%d}\n",- uptime, rss, peak_rss, commit, peak_commit, page_faults, fds, qcount);- if (n > 0) {- g_diag_ndjson_size += (size_t)n;- }- (void)fclose(f);+ g_diag_ndjson_size += (size_t)length;}static void write_diagnostics(void) {- /* Collect mimalloc stats */+#ifdef CBM_DIAGNOSTICS_ENABLE_TEST_API+ diag_test_pause_writer();+#endif+ if (atomic_load_explicit(&g_diag_stop, memory_order_acquire)) {+ return;+ }+size_t elapsed_ms = 0;size_t user_ms = 0;size_t sys_ms = 0;@@ -136,8 +432,6 @@ static void write_diagnostics(void) {size_t page_faults = 0;mi_process_info(&elapsed_ms, &user_ms, &sys_ms, ¤t_rss, &peak_rss, ¤t_commit,&peak_commit, &page_faults);-- /* Fallback RSS for ASan builds */if (current_rss == 0) {current_rss = cbm_mem_rss();}@@ -145,91 +439,92 @@ static void write_diagnostics(void) {int fds = count_open_fds();time_t now = time(NULL);long uptime = (long)(now - g_start_time);-int qcount = atomic_load(&g_query_stats.count);int qerrors = atomic_load(&g_query_stats.errors);long long qtime = atomic_load(&g_query_stats.time_us);long long qmax = atomic_load(&g_query_stats.max_us);long long qavg = qcount > 0 ? qtime / qcount : 0;- /* Write to .tmp then rename (atomic) */- char tmp_path[sizeof(g_diag_path) + DIAG_PATH_EXTRA];- snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", g_diag_path);-- FILE *f = fopen(tmp_path, "w");- if (!f) {+ char snapshot[CBM_SZ_1K];+ int length = snprintf(snapshot, sizeof(snapshot),+ "{\n"+ " \"uptime_s\": %ld,\n"+ " \"rss_bytes\": %zu,\n"+ " \"peak_rss_bytes\": %zu,\n"+ " \"heap_committed_bytes\": %zu,\n"+ " \"peak_committed_bytes\": %zu,\n"+ " \"page_faults\": %zu,\n"+ " \"fd_count\": %d,\n"+ " \"query_count\": %d,\n"+ " \"query_errors\": %d,\n"+ " \"query_total_us\": %lld,\n"+ " \"query_avg_us\": %lld,\n"+ " \"query_max_us\": %lld,\n"+ " \"pid\": %d\n"+ "}\n",+ uptime, current_rss, peak_rss, current_commit, peak_commit, page_faults,+ fds, qcount, qerrors, qtime, qavg, qmax, (int)getpid());+ if (length <= 0 || (size_t)length >= sizeof(snapshot) ||+ !diag_write_file(DIAG_SNAPSHOT_TMP_NAME, snapshot, (size_t)length, false) ||+ !diag_native_rename(DIAG_SNAPSHOT_TMP_NAME, DIAG_SNAPSHOT_NAME)) {+ diag_native_unlink(DIAG_SNAPSHOT_TMP_NAME);return;}-- if (fprintf(f,- "{\n"- " \"uptime_s\": %ld,\n"- " \"rss_bytes\": %zu,\n"- " \"peak_rss_bytes\": %zu,\n"- " \"heap_committed_bytes\": %zu,\n"- " \"peak_committed_bytes\": %zu,\n"- " \"page_faults\": %zu,\n"- " \"fd_count\": %d,\n"- " \"query_count\": %d,\n"- " \"query_errors\": %d,\n"- " \"query_total_us\": %lld,\n"- " \"query_avg_us\": %lld,\n"- " \"query_max_us\": %lld,\n"- " \"pid\": %d\n"- "}\n",- uptime, current_rss, peak_rss, current_commit, peak_commit, page_faults, fds,- qcount, qerrors, qtime, qavg, qmax, (int)getpid()) < 0) {- (void)fclose(f);- return;+ if (!atomic_load_explicit(&g_diag_stop, memory_order_acquire)) {+ append_trajectory(uptime, current_rss, peak_rss, current_commit, peak_commit, page_faults,+ fds, qcount);}- if (fclose(f) != 0) {- return;- }- (void)rename(tmp_path, g_diag_path);-- /* Also append to the persistent trajectory (kept on exit for users to send). */- append_trajectory(uptime, current_rss, peak_rss, current_commit, peak_commit, page_faults, fds,- qcount);}static void *diag_thread_fn(void *arg) {(void)arg;- while (!atomic_load(&g_diag_stop)) {+ while (!atomic_load_explicit(&g_diag_stop, memory_order_acquire)) {write_diagnostics();- struct timespec ts = {DIAG_INTERVAL_S, 0};- cbm_nanosleep(&ts, NULL);+ if (!atomic_load_explicit(&g_diag_stop, memory_order_acquire)) {+ diag_wait_for_interval();+ }}- /* Final write before exit */- write_diagnostics();+ atomic_store_explicit(&g_diag_done, true, memory_order_release);return NULL;}-/* ── Public API ──────────────────────────────────────────────────── */+static void diag_cleanup_live_files(void) {+ diag_native_unlink(DIAG_SNAPSHOT_NAME);+ diag_native_unlink(DIAG_SNAPSHOT_TMP_NAME);+}++/* ── Public API ──────────────────────────────────────────────────────── */bool cbm_diag_start(void) {char env_buf[CBM_SZ_32] = "";cbm_safe_getenv("CBM_DIAGNOSTICS", env_buf, sizeof(env_buf), NULL);- if (env_buf[0] == '\0' || (strcmp(env_buf, "1") != 0 && strcmp(env_buf, "true") != 0)) {+ if (env_buf[0] == '\0' || (strcmp(env_buf, "1") != 0 && strcmp(env_buf, "true") != 0) ||+ g_diag_started || g_diag_abandoned) {return false;}g_start_time = time(NULL);- atomic_store(&g_diag_stop, 0);-- snprintf(g_diag_path, sizeof(g_diag_path), "%s/cbm-diagnostics-%d.json", cbm_tmpdir(),- (int)getpid());- snprintf(g_diag_ndjson_path, sizeof(g_diag_ndjson_path), "%s/cbm-diagnostics-%d.ndjson",- cbm_tmpdir(), (int)getpid());g_diag_ndjson_size = 0;-+ atomic_store_explicit(&g_diag_stop, false, memory_order_release);+ atomic_store_explicit(&g_diag_done, false, memory_order_release);+#ifdef CBM_DIAGNOSTICS_ENABLE_TEST_API+ atomic_store_explicit(&g_diag_test_writer_reached, false, memory_order_release);+#endif+ if (!diag_directory_prepare()) {+ return false;+ }if (cbm_thread_create(&g_diag_thread, 0, diag_thread_fn, NULL) != 0) {+ diag_directory_close(true);return false;}g_diag_started = true;- (void)fprintf(stderr,- "level=info msg=diagnostics.start snapshot=%s trajectory=%s interval=%ds\n",- g_diag_path, g_diag_ndjson_path, DIAG_INTERVAL_S);+ char interval[CBM_SZ_32];+ (void)snprintf(interval, sizeof(interval), "%d", DIAG_INTERVAL_MS / 1000);+ /* Discovery must survive CBM_LOG_LEVEL suppression and paths containing+ * spaces: a control record is the only announced copy of these paths. */+ cbm_log_control("diagnostics.start", "snapshot", g_diag_path, "trajectory", g_diag_ndjson_path,+ "interval_s", interval);return true;}@@ -237,18 +532,69 @@ void cbm_diag_stop(void) {if (!g_diag_started) {return;}- atomic_store(&g_diag_stop, 1);- cbm_thread_join(&g_diag_thread);+ atomic_store_explicit(&g_diag_stop, true, memory_order_release);++ uint64_t deadline = cbm_now_ms() + DIAG_STOP_TIMEOUT_MS;+ while (!atomic_load_explicit(&g_diag_done, memory_order_acquire) && cbm_now_ms() < deadline) {+ diag_sleep_ms(DIAG_WAIT_SLICE_MS);+ }+ bool completed = atomic_load_explicit(&g_diag_done, memory_order_acquire);+ if (completed) {+ /* The completion publication is the final access to diagnostics+ * state. Detaching avoids turning an already-complete best-effort+ * writer into an unbounded native join during daemon teardown. */+ (void)cbm_thread_detach(&g_diag_thread);+ diag_cleanup_live_files();+ diag_directory_close(false);+ } else {+ /* The thread may still hold a native file or directory descriptor.+ * Detach it and intentionally retain all static state until process+ * exit; closing or reusing those handles would create an fd/handle+ * reuse race if the stalled operation later resumes. */+ (void)cbm_thread_detach(&g_diag_thread);+ g_diag_abandoned = true;+ }g_diag_started = false;+}++#ifdef CBM_DIAGNOSTICS_ENABLE_TEST_API++static bool diag_test_copy(char *destination, size_t destination_size, const char *source) {+ if (!destination || destination_size == 0) {+ return false;+ }+ int written = snprintf(destination, destination_size, "%s", source);+ return written >= 0 && (size_t)written < destination_size;+}++bool cbm_diag_test_copy_paths(char *directory, size_t directory_size, char *snapshot,+ size_t snapshot_size, char *trajectory, size_t trajectory_size) {+ return diag_test_copy(directory, directory_size, g_diag_directory_path) &&+ diag_test_copy(snapshot, snapshot_size, g_diag_path) &&+ diag_test_copy(trajectory, trajectory_size, g_diag_ndjson_path);+}++void cbm_diag_test_hold_writer(bool hold) {+ atomic_store_explicit(&g_diag_test_hold_writer, hold, memory_order_release);+}++bool cbm_diag_test_writer_reached(void) {+ return atomic_load_explicit(&g_diag_test_writer_reached, memory_order_acquire);+}++bool cbm_diag_test_abandoned(void) {+ return g_diag_abandoned;+}- /* Remove the live latest-snapshot file (and its .tmp), but KEEP the- * trajectory NDJSON so the user can send it after the server exits. */- cbm_unlink(g_diag_path);- char tmp_path[sizeof(g_diag_path) + DIAG_PATH_EXTRA];- snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", g_diag_path);- cbm_unlink(tmp_path);- if (g_diag_ndjson_path[0] != '\0') {- (void)fprintf(stderr, "level=info msg=diagnostics.trajectory_kept path=%s\n",- g_diag_ndjson_path);+bool cbm_diag_test_reset_abandoned(void) {+ if (!g_diag_abandoned || g_diag_started ||+ !atomic_load_explicit(&g_diag_done, memory_order_acquire)) {+ return false;}+ diag_cleanup_live_files();+ diag_directory_close(false);+ g_diag_abandoned = false;+ return true;}++#endifdiff --git a/src/foundation/diagnostics.h b/src/foundation/diagnostics.hindex b34511927..4f0049148 100644--- a/src/foundation/diagnostics.h+++ b/src/foundation/diagnostics.h@@ -1,13 +1,15 @@/** diagnostics.h — Periodic diagnostics file writer.*- * When CBM_DIAGNOSTICS=1, writes /tmp/cbm-diagnostics-<pid>.json every 5s.- * Soak tests read this file to track memory, FDs, query stats over time.+ * When CBM_DIAGNOSTICS=1, writes a snapshot and retained trajectory below a+ * fresh owner-private temporary directory every 5s. The start diagnostic+ * reports both randomized paths for soak-test and support tooling.*/#ifndef CBM_DIAGNOSTICS_H#define CBM_DIAGNOSTICS_H#include <stdbool.h>+#include <stddef.h>#include <stdint.h>#include <stdatomic.h>@@ -29,7 +31,18 @@ void cbm_diag_record_query(long long duration_us, bool is_error);* Call once from main(). Returns true if started. */bool cbm_diag_start(void);-/* Stop the writer thread and delete the diagnostics file. */+/* Stop the writer within a bounded deadline and delete the live snapshot.+ * The trajectory remains for post-mortem support. */void cbm_diag_stop(void);+#ifdef CBM_DIAGNOSTICS_ENABLE_TEST_API+/* Focused lifecycle/security seams; absent from production builds. */+bool cbm_diag_test_copy_paths(char *directory, size_t directory_size, char *snapshot,+ size_t snapshot_size, char *trajectory, size_t trajectory_size);+void cbm_diag_test_hold_writer(bool hold);+bool cbm_diag_test_writer_reached(void);+bool cbm_diag_test_abandoned(void);+bool cbm_diag_test_reset_abandoned(void);+#endif+#endif /* CBM_DIAGNOSTICS_H */diff --git a/src/foundation/log.c b/src/foundation/log.cindex fc4bb6c9e..4d4477928 100644--- a/src/foundation/log.c+++ b/src/foundation/log.c@@ -255,6 +255,35 @@ void cbm_log(CBMLogLevel level, const char *msg, ...) {emit_line(line_buf);}+void cbm_log_control_record(const char *msg, ...) {+ /* No threshold check: a control record's whole purpose is surviving+ * CBM_LOG_LEVEL suppression. Always JSON, independent of CBM_LOG_FORMAT,+ * so consumers get one stable, fully escaped representation. */+ char line_buf[CBM_SZ_4K];+ size_t pos = 0;+ va_list args;+ va_start(args, msg);+ append_raw(line_buf, sizeof(line_buf), &pos, "{\"level\":");+ append_json_string(line_buf, sizeof(line_buf), &pos, "control");+ append_raw(line_buf, sizeof(line_buf), &pos, ",\"event\":");+ append_json_string(line_buf, sizeof(line_buf), &pos, msg ? msg : "");+ for (;;) {+ const char *key = va_arg(args, const char *);+ if (!key) {+ break;+ }+ const char *val = va_arg(args, const char *);+ append_char(line_buf, sizeof(line_buf), &pos, ',');+ append_json_string(line_buf, sizeof(line_buf), &pos, key);+ append_char(line_buf, sizeof(line_buf), &pos, ':');+ append_json_string(line_buf, sizeof(line_buf), &pos, val ? val : "");+ }+ append_char(line_buf, sizeof(line_buf), &pos, '}');+ va_end(args);+ finish_line(line_buf, sizeof(line_buf), pos);+ emit_line(line_buf);+}+void cbm_log_int(CBMLogLevel level, const char *msg, const char *key, int64_t value) {char value_buf[CBM_SZ_32];snprintf(value_buf, sizeof(value_buf), "%" PRId64, value);diff --git a/src/foundation/log.h b/src/foundation/log.hindex 7f247f086..baad71d14 100644--- a/src/foundation/log.h+++ b/src/foundation/log.h@@ -70,6 +70,15 @@ void cbm_log(CBMLogLevel level, const char *msg, ...);/* Convenience macros. */#define cbm_log_debug(msg, ...) cbm_log(CBM_LOG_DEBUG, msg, ##__VA_ARGS__, NULL)#define cbm_log_info(msg, ...) cbm_log(CBM_LOG_INFO, msg, ##__VA_ARGS__, NULL)++/* Always-delivered internal control/discovery record. It bypasses the level+ * threshold and always uses the JSON encoding, so exact values (paths with+ * spaces or control bytes) survive unambiguously; it flows through the+ * configured sink like every other record. Reserve it for the rare+ * discovery/control events that ordinary log filtering must never suppress+ * (e.g. diagnostics.start path announcement). */+void cbm_log_control_record(const char *msg, ...);+#define cbm_log_control(msg, ...) cbm_log_control_record(msg, ##__VA_ARGS__, NULL)#define cbm_log_warn(msg, ...) cbm_log(CBM_LOG_WARN, msg, ##__VA_ARGS__, NULL)#define cbm_log_error(msg, ...) cbm_log(CBM_LOG_ERROR, msg, ##__VA_ARGS__, NULL)diff --git a/src/foundation/platform.c b/src/foundation/platform.cindex 9d69b0c99..ce4c43dc6 100644--- a/src/foundation/platform.c+++ b/src/foundation/platform.c@@ -91,7 +91,7 @@ void *cbm_mmap_read(const char *path, size_t *out_size) {}*out_size = 0;- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return NULL;}@@ -152,7 +152,7 @@ int cbm_nprocs(void) {}bool cbm_file_exists(const char *path) {- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return false;}@@ -162,7 +162,7 @@ bool cbm_file_exists(const char *path) {}bool cbm_is_dir(const char *path) {- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return false;}@@ -172,7 +172,7 @@ bool cbm_is_dir(const char *path) {}int64_t cbm_file_size(const char *path) {- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return CBM_NOT_FOUND;}diff --git a/src/foundation/subprocess.c b/src/foundation/subprocess.cindex 6c2c9ad43..5532c33af 100644--- a/src/foundation/subprocess.c+++ b/src/foundation/subprocess.c@@ -295,6 +295,96 @@ bool cbm_build_win_cmdline(char *buf, size_t cap, const char *const *argv) {return true;}+static bool cbm_ascii_case_equal(const char *left, const char *right) {+ if (!left || !right) {+ return false;+ }+ while (*left && *right) {+ unsigned char left_ch = (unsigned char)*left++;+ unsigned char right_ch = (unsigned char)*right++;+ if (left_ch >= 'A' && left_ch <= 'Z') {+ left_ch = (unsigned char)(left_ch + ('a' - 'A'));+ }+ if (right_ch >= 'A' && right_ch <= 'Z') {+ right_ch = (unsigned char)(right_ch + ('a' - 'A'));+ }+ if (left_ch != right_ch) {+ return false;+ }+ }+ return *left == '\0' && *right == '\0';+}++static bool cbm_win_cmd_path_is_absolute(const char *path) {+ if (!path) {+ return false;+ }+ size_t path_len = strlen(path);+ if (path_len < 3) {+ return false;+ }+ bool drive_absolute =+ ((path[0] >= 'A' && path[0] <= 'Z') || (path[0] >= 'a' && path[0] <= 'z')) &&+ path[1] == ':' && (path[2] == '\\' || path[2] == '/');+ bool unc_absolute = (path[0] == '\\' || path[0] == '/') && path[1] == path[0] && path[2];+ if (!drive_absolute && !unc_absolute) {+ return false;+ }++ const char *basename = path;+ for (const char *cursor = path; *cursor; cursor++) {+ if (*cursor == '"' || *cursor == '\r' || *cursor == '\n') {+ return false;+ }+ if (*cursor == '\\' || *cursor == '/') {+ basename = cursor + 1;+ }+ }+ return cbm_ascii_case_equal(basename, "cmd.exe");+}++bool cbm_build_win_cmd_payload(char *buf, size_t cap, const char *cmd_executable,+ const char *payload) {+ if (!buf || cap == 0) {+ return false;+ }+ buf[0] = '\0';+ if (!cbm_win_cmd_path_is_absolute(cmd_executable) || !payload || !payload[0]) {+ return false;+ }++ static const char prefix[] = "\" /D /S /V:OFF /C ";+ size_t executable_len = strlen(cmd_executable);+ size_t payload_len = strlen(payload);+ size_t remaining = cap - 1; /* reserve the final NUL */+ if (remaining < 1) {+ return false;+ }+ remaining--; /* opening quote */+ if (executable_len > remaining) {+ return false;+ }+ remaining -= executable_len;+ if (sizeof(prefix) - 1 > remaining) {+ return false;+ }+ remaining -= sizeof(prefix) - 1;+ if (payload_len > remaining) {+ return false;+ }++ size_t pos = 0;+ buf[pos++] = '"';+ memcpy(buf + pos, cmd_executable, executable_len);+ pos += executable_len;+ memcpy(buf + pos, prefix, sizeof(prefix) - 1);+ pos += sizeof(prefix) - 1;+ memcpy(buf + pos, payload, payload_len);+ pos += payload_len;+ buf[pos] = '\0';+ return true;+}+/* ── Nonblocking contained-process supervisor ─────────────────────────────── */enum { CBM_SUBPROCESS_ARGV_LIMIT = 4096 };@@ -310,6 +400,7 @@ struct cbm_subprocess {char *bin;char **argv;size_t argc;+ char *windows_cmd_payload;char *log_file;cbm_proc_log_cb on_log_line;void *log_ud;@@ -361,6 +452,7 @@ static void cbm_subprocess_free_config(cbm_subprocess_t *process) {}free(process->argv);free(process->bin);+ free(process->windows_cmd_payload);free(process->log_file);free(process);}@@ -369,6 +461,16 @@ static cbm_subprocess_t *cbm_subprocess_copy_opts(const cbm_proc_opts_t *opts) {if (!opts || !opts->bin || !opts->bin[0]) {return NULL;}+#ifdef _WIN32+ if (opts->windows_cmd_payload &&+ (!opts->windows_cmd_payload[0] || opts->argv || !cbm_win_cmd_path_is_absolute(opts->bin))) {+ return NULL;+ }+#else+ if (opts->windows_cmd_payload) {+ return NULL;+ }+#endifsize_t argc = 1;if (opts->argv) {@@ -386,9 +488,12 @@ static cbm_subprocess_t *cbm_subprocess_copy_opts(const cbm_proc_opts_t *opts) {return NULL;}process->bin = cbm_strdup(opts->bin);+ process->windows_cmd_payload =+ opts->windows_cmd_payload ? cbm_strdup(opts->windows_cmd_payload) : NULL;process->argv = (char **)calloc(argc + 1, sizeof(*process->argv));process->argc = argc;- if (!process->bin || !process->argv) {+ if (!process->bin || !process->argv ||+ (opts->windows_cmd_payload && !process->windows_cmd_payload)) {cbm_subprocess_free_config(process);return NULL;}@@ -440,7 +545,7 @@ static void cbm_subprocess_delete_log(cbm_subprocess_t *process) {return;}#ifdef _WIN32- wchar_t *path = cbm_utf8_to_wide(process->log_file);+ wchar_t *path = cbm_path_to_wide(process->log_file);if (path) {(void)DeleteFileW(path);free(path);@@ -529,7 +634,12 @@ static void cbm_win_close_spawn_handles(HANDLE nul, HANDLE log, LPPROC_THREAD_ATstatic int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {char cmdline[8192];- if (!cbm_build_win_cmdline(cmdline, sizeof(cmdline), (const char *const *)process->argv)) {+ bool built =+ process->windows_cmd_payload+ ? cbm_build_win_cmd_payload(cmdline, sizeof(cmdline), process->bin,+ process->windows_cmd_payload)+ : cbm_build_win_cmdline(cmdline, sizeof(cmdline), (const char *const *)process->argv);+ if (!built) {return -1;}wchar_t *wbin = cbm_utf8_to_wide(process->bin);@@ -568,7 +678,7 @@ static int cbm_subprocess_spawn_win(cbm_subprocess_t *process) {return -1;}if (process->log_file) {- wchar_t *wlog = cbm_utf8_to_wide(process->log_file);+ wchar_t *wlog = cbm_path_to_wide(process->log_file);if (wlog) {log = CreateFileW(wlog, GENERIC_WRITE, FILE_SHARE_READ, &security, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL, NULL);diff --git a/src/foundation/subprocess.h b/src/foundation/subprocess.hindex df02f1e86..f6ff7f7fd 100644--- a/src/foundation/subprocess.h+++ b/src/foundation/subprocess.h@@ -53,18 +53,22 @@ typedef struct {typedef 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 *log_file; /* child stdout+stderr are redirected here and tailed;- * NULL => discard child output, 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 */- bool delete_log_on_exit; /* unlink log_file after reaping */+ 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; /* child stdout+stderr are redirected here and tailed;+ * NULL => discard child output, 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 */+ bool delete_log_on_exit; /* unlink log_file after reaping */} cbm_proc_opts_t;#define CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS 1000@@ -159,4 +163,18 @@ const char *cbm_proc_outcome_str(cbm_proc_outcome_t o);* the UI http_server index spawn) escape through one shared, tested implementation. */bool cbm_build_win_cmdline(char *buf, size_t cap, const char *const *argv);+/* Build the special CreateProcess command line needed to invoke cmd.exe with a+ * command-language payload. Unlike cbm_build_win_cmdline(), payload is not a C+ * runtime argv element: cmd.exe must receive its embedded quotes and backslashes+ * unchanged. cmd_executable must be an absolute Windows path whose basename is+ * cmd.exe. The result is:+ *+ * "<absolute-cmd.exe>" /D /S /V:OFF /C <payload-verbatim>+ *+ * Returns false for invalid input or overflow and leaves a valid empty string+ * whenever buf/cap permit one. Pure string logic, available on every platform+ * so the Windows serialization contract is unit-testable everywhere. */+bool cbm_build_win_cmd_payload(char *buf, size_t cap, const char *cmd_executable,+ const char *payload);+#endif /* CBM_SUBPROCESS_H */diff --git a/src/foundation/win_utf8.h b/src/foundation/win_utf8.hindex 8a3530a57..65f70d4b6 100644--- a/src/foundation/win_utf8.h+++ b/src/foundation/win_utf8.h@@ -25,6 +25,41 @@ static inline wchar_t *cbm_utf8_to_wide(const char *utf8) {return w;}+/* Path-aware conversion for FILE-SYSTEM paths: absolute drive paths longer+ * than the legacy limit are canonicalized (GetFullPathNameW) and given the+ * extended-length \\?\ prefix so every Win32 file API accepts them+ * regardless of the machine's LongPathsEnabled policy. Never use this for+ * non-file strings (command lines, pipe names, registry paths). */+static inline wchar_t *cbm_path_to_wide(const char *utf8_path) {+ wchar_t *wide = cbm_utf8_to_wide(utf8_path);+ if (!wide) {+ return NULL;+ }+ size_t length = wcslen(wide);+ int drive_absolute =+ length >= 3 &&+ ((wide[0] >= L'A' && wide[0] <= L'Z') || (wide[0] >= L'a' && wide[0] <= L'z')) &&+ wide[1] == L':' && (wide[2] == L'\\' || wide[2] == L'/');+ if (!drive_absolute || length < 240U) {+ return wide;+ }+ DWORD needed = GetFullPathNameW(wide, 0, NULL, NULL);+ wchar_t *prefixed =+ needed > 0 ? (wchar_t *)malloc(((size_t)needed + 5U) * sizeof(wchar_t)) : NULL;+ if (!prefixed) {+ free(wide);+ return NULL;+ }+ wmemcpy(prefixed, L"\\\\?\\", 4);+ DWORD copied = GetFullPathNameW(wide, needed, prefixed + 4, NULL);+ free(wide);+ if (copied == 0 || copied >= needed) {+ free(prefixed);+ return NULL;+ }+ return prefixed;+}+static inline char *cbm_wide_to_utf8(const wchar_t *wide) {if (!wide) {return NULL;diff --git a/src/launcher/windows_launcher.c b/src/launcher/windows_launcher.cindex 46620375f..348589daa 100644--- a/src/launcher/windows_launcher.c+++ b/src/launcher/windows_launcher.c@@ -150,9 +150,18 @@ static bool launcher_file_information(HANDLE file, BY_HANDLE_FILE_INFORMATION *i(unsigned long)information->dwFileAttributes);return false;}- if (information->nNumberOfLinks != 1U) {- launcher_refusal_set(L"hard-link count %lu, expected 1",- (unsigned long)information->nNumberOfLinks);+ return true;+}++static bool launcher_file_information_links(HANDLE file, BY_HANDLE_FILE_INFORMATION *information,+ DWORD expected_links) {+ if (!launcher_file_information(file, information)) {+ return false;+ }+ if (information->nNumberOfLinks != expected_links) {+ launcher_refusal_set(L"hard-link count %lu, expected %lu",+ (unsigned long)information->nNumberOfLinks,+ (unsigned long)expected_links);return false;}return true;@@ -333,14 +342,21 @@ static bool launcher_security_is_trusted(HANDLE file) {return launcher_security_is_safe(file, false, launcher_private_mutation_rights());}-static HANDLE launcher_open_regular(const wchar_t *path, DWORD access, bool require_private) {+static HANDLE launcher_open_regular_links(const wchar_t *path, DWORD access, bool require_private,+ DWORD expected_links) {HANDLE file =CreateFileW(path, access | FILE_READ_ATTRIBUTES | (require_private ? READ_CONTROL : 0U),FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, NULL);BY_HANDLE_FILE_INFORMATION information;- if (!launcher_file_information(file, &information) ||- (require_private && !launcher_security_is_trusted(file))) {+ bool valid = launcher_file_information(file, &information);+ if (valid && expected_links != 0U && information.nNumberOfLinks != expected_links) {+ launcher_refusal_set(L"hard-link count %lu, expected %lu",+ (unsigned long)information.nNumberOfLinks,+ (unsigned long)expected_links);+ valid = false;+ }+ if (!valid || (require_private && !launcher_security_is_trusted(file))) {if (file != INVALID_HANDLE_VALUE)(void)CloseHandle(file);return INVALID_HANDLE_VALUE;@@ -348,6 +364,10 @@ static HANDLE launcher_open_regular(const wchar_t *path, DWORD access, bool requreturn file;}+static HANDLE launcher_open_regular(const wchar_t *path, DWORD access, bool require_private) {+ return launcher_open_regular_links(path, access, require_private, 1U);+}+static HANDLE launcher_open_directory_private(const wchar_t *path) {HANDLE directory =CreateFileW(path, FILE_READ_ATTRIBUTES | READ_CONTROL,@@ -445,10 +465,37 @@ static bool launcher_path_tree_plain(const wchar_t *file_path) {return valid;}+/* Canonical, file-API-safe self path: drive-absolute module paths always get+ * the extended-length prefix. A managed install can live past MAX_PATH, and+ * every derived path (generations, current-v1, payload spawn) plus the+ * ancestry walk inherits this form, exactly like the CLI side. */+static bool launcher_self_path_canonicalize(wchar_t path[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {+ wchar_t resolved[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ DWORD length = GetFullPathNameW(path, CBM_WINDOWS_LAUNCHER_PATH_CAP, resolved, NULL);+ if (length == 0 || length >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return false;+ }+ bool already_prefixed = wcsncmp(resolved, L"\\\\?\\", 4) == 0;+ bool drive_absolute = !already_prefixed &&+ ((resolved[0] >= L'A' && resolved[0] <= L'Z') ||+ (resolved[0] >= L'a' && resolved[0] <= L'z')) &&+ resolved[1] == L':' && resolved[2] == L'\\';+ if (drive_absolute) {+ if (length + 5U >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return false;+ }+ wmemcpy(path, L"\\\\?\\", 4);+ wmemcpy(path + 4, resolved, length + 1U);+ } else {+ wmemcpy(path, resolved, length + 1U);+ }+ return true;+}+static bool launcher_self_path(wchar_t output[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {DWORD length = GetModuleFileNameW(NULL, output, CBM_WINDOWS_LAUNCHER_PATH_CAP);return length > 3U && length < CBM_WINDOWS_LAUNCHER_PATH_CAP &&- launcher_path_tree_plain(output);+ launcher_self_path_canonicalize(output) && launcher_path_tree_plain(output);}static bool launcher_parent_path(const wchar_t *path, wchar_t *output, size_t capacity) {@@ -466,6 +513,133 @@ static bool launcher_parent_path(const wchar_t *path, wchar_t *output, size_t careturn true;}+/* The uninstall payload atomically retires .cbm to one authenticated+ * SHA/PID-qualified sibling before unlinking canonical. Delete only that+ * immutable basename after the payload and this mapped launcher have exited;+ * a concurrent reinstall's new .cbm is never named by this command. */+static bool launcher_schedule_managed_cleanup(const wchar_t *canonical_launcher,+ const cbm_windows_current_v1_t *state,+ DWORD payload_pid) {+ wchar_t install_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t retired_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t retired_parent[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ if (!state || payload_pid == 0U ||+ !launcher_parent_path(canonical_launcher, install_directory,+ CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !cbm_windows_retired_state_path(canonical_launcher, state->payload_sha256,+ (uint32_t)payload_pid, retired_directory,+ CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !launcher_parent_path(retired_directory, retired_parent, CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ _wcsicmp(install_directory, retired_parent) != 0) {+ launcher_refusal_set(L"could not resolve the install directory for cleanup");+ return false;+ }+ const wchar_t *retired_basename = wcsrchr(retired_directory, L'\\');+ const wchar_t *retired_slash = wcsrchr(retired_directory, L'/');+ if (!retired_basename || (retired_slash && retired_slash > retired_basename))+ retired_basename = retired_slash;+ retired_basename = retired_basename ? retired_basename + 1 : NULL;+ DWORD canonical_attributes = GetFileAttributesW(canonical_launcher);+ DWORD canonical_error =+ canonical_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;+ bool canonical_absent =+ canonical_attributes == INVALID_FILE_ATTRIBUTES &&+ (canonical_error == ERROR_FILE_NOT_FOUND || canonical_error == ERROR_PATH_NOT_FOUND);+ wchar_t replacement_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ char replacement_error[128] = {0};+ bool canonical_is_new_managed =+ canonical_attributes != INVALID_FILE_ATTRIBUTES &&+ cbm_windows_managed_launcher_backing(canonical_launcher, replacement_backing,+ CBM_WINDOWS_LAUNCHER_PATH_CAP, replacement_error,+ sizeof(replacement_error));+ HANDLE install = launcher_open_directory_private(install_directory);+ HANDLE retired = launcher_open_directory_private(retired_directory);+ bool private_cwd =+ retired_basename && retired_basename[0] && wcschr(retired_basename, L'\\') == NULL &&+ wcschr(retired_basename, L'/') == NULL && (canonical_absent || canonical_is_new_managed) &&+ install != INVALID_HANDLE_VALUE && retired != INVALID_HANDLE_VALUE;+ if (install != INVALID_HANDLE_VALUE)+ (void)CloseHandle(install);+ if (retired != INVALID_HANDLE_VALUE)+ (void)CloseHandle(retired);+ if (!private_cwd) {+ launcher_refusal_set(+ L"retired cleanup tree or concurrent managed reinstall validation failed");+ return false;+ }++ wchar_t system_directory[MAX_PATH + 1U];+ UINT system_length = GetSystemDirectoryW(system_directory, MAX_PATH + 1U);+ wchar_t command_path[MAX_PATH + 16U];+ wchar_t delay_path[MAX_PATH + 16U];+ int command_path_written =+ system_length > 0U && system_length <= MAX_PATH+ ? swprintf(command_path, sizeof(command_path) / sizeof(command_path[0]),+ L"%ls\\cmd.exe", system_directory)+ : -1;+ int delay_path_written = system_length > 0U && system_length <= MAX_PATH+ ? swprintf(delay_path, sizeof(delay_path) / sizeof(delay_path[0]),+ L"%ls\\ping.exe", system_directory)+ : -1;+ HANDLE command_file =+ command_path_written > 0 &&+ (size_t)command_path_written < sizeof(command_path) / sizeof(command_path[0])+ ? launcher_open_regular_links(command_path, GENERIC_READ, true, 0U)+ : INVALID_HANDLE_VALUE;+ HANDLE delay_file = delay_path_written > 0 && (size_t)delay_path_written <+ sizeof(delay_path) / sizeof(delay_path[0])+ ? launcher_open_regular_links(delay_path, GENERIC_READ, true, 0U)+ : INVALID_HANDLE_VALUE;+ if (command_file == INVALID_HANDLE_VALUE || delay_file == INVALID_HANDLE_VALUE) {+ if (command_file != INVALID_HANDLE_VALUE)+ (void)CloseHandle(command_file);+ if (delay_file != INVALID_HANDLE_VALUE)+ (void)CloseHandle(delay_file);+ launcher_refusal_set(L"trusted absolute System32 cleanup utilities failed validation");+ return false;+ }+ (void)CloseHandle(command_file);+ (void)CloseHandle(delay_file);++ wchar_t mutable_command[2048];+ int cleanup_written =+ swprintf(mutable_command, sizeof(mutable_command) / sizeof(mutable_command[0]),+ L"\"%ls\" /d /q /e:on /c \"for /l %%i in (1,1,120) do @(rd /s /q %ls "+ L"2>nul&if not exist %ls exit /b 0&\"%ls\" -n 2 -w 1000 127.0.0.1 "+ L">nul)&exit /b 1\"",+ command_path, retired_basename, retired_basename, delay_path);+ if (cleanup_written <= 0 ||+ (size_t)cleanup_written >= sizeof(mutable_command) / sizeof(mutable_command[0])) {+ launcher_refusal_set(L"detached retired-state cleanup command is too long");+ return false;+ }+ STARTUPINFOW startup;+ PROCESS_INFORMATION child;+ memset(&startup, 0, sizeof(startup));+ memset(&child, 0, sizeof(child));+ startup.cb = sizeof(startup);+ DWORD flags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_UNICODE_ENVIRONMENT;+ /* CreateProcessW's lpCurrentDirectory is a Win32 path and does NOT accept the+ * \\?\ extended-length prefix. install_directory is canonicalized with that+ * prefix, so passing it verbatim leaves the detached process in an+ * unintended working directory — the relative `rd <basename>` then deletes+ * nothing while `if not exist <basename>` trivially succeeds. Strip it. */+ const wchar_t *cleanup_cwd =+ wcsncmp(install_directory, L"\\\\?\\", 4) == 0 ? install_directory + 4 : install_directory;+ bool spawned = CreateProcessW(command_path, mutable_command, NULL, NULL, FALSE, flags, NULL,+ cleanup_cwd, &startup, &child) != 0;+ DWORD spawn_error = spawned ? ERROR_SUCCESS : GetLastError();+ if (child.hThread)+ (void)CloseHandle(child.hThread);+ if (child.hProcess)+ (void)CloseHandle(child.hProcess);+ if (!spawned) {+ launcher_refusal_set(L"detached System32 cleanup spawn failed (error %lu)",+ (unsigned long)spawn_error);+ }+ return spawned;+}+static bool launcher_read_all(HANDLE file, void *buffer, size_t size) {size_t offset = 0U;while (offset < size) {@@ -809,6 +983,108 @@ static bool launcher_posix_remove(HANDLE file) {sizeof(disposition)) != 0;}+typedef struct {+ DWORD Flags;+ HANDLE RootDirectory;+ DWORD FileNameLength;+ WCHAR FileName[1];+} launcher_rename_info_ex_t;++#define LAUNCHER_FILE_RENAME_INFO_EX ((FILE_INFO_BY_HANDLE_CLASS)22)+#define LAUNCHER_FILE_RENAME_REPLACE 0x00000001U+#define LAUNCHER_FILE_RENAME_POSIX 0x00000002U++/* POSIX-semantics rename by handle. Renaming a MAPPED (executing) image is+ * legal even though deleting one is not — the retirement path below relies on+ * this to free the staged activation name while the payload still runs. */+static bool launcher_posix_rename(HANDLE file, const wchar_t *target_path) {+ /* The name travels verbatim to NtSetInformationFile, where the Win32+ * \\?\\ prefix is not a valid name; a plain drive path is accepted at+ * any length (no MAX_PATH at the NT layer). */+ if (wcsncmp(target_path, L"\\\\?\\", 4) == 0) {+ target_path += 4;+ }+ size_t chars = wcslen(target_path);+ if (chars == 0U || chars > (size_t)UINT32_MAX / sizeof(wchar_t)) {+ return false;+ }++ size_t bytes = chars * sizeof(wchar_t);+ /* Allocate one extra WCHAR and NUL-terminate the name. FileNameLength+ * governs per the contract, but antivirus/filter drivers on this kernel+ * read the FileName as NUL-terminated: with an exactly-sized buffer they+ * append adjacent heap bytes to the created name (a flaky, garbage-suffixed+ * or ERROR_INVALID_NAME rename). The terminator bounds them to the name. */+ size_t allocation = offsetof(launcher_rename_info_ex_t, FileName) + bytes + sizeof(wchar_t);+ launcher_rename_info_ex_t *rename = calloc(1U, allocation);+ if (!rename) {+ return false;+ }+ rename->Flags = LAUNCHER_FILE_RENAME_POSIX | LAUNCHER_FILE_RENAME_REPLACE;+ rename->RootDirectory = NULL;+ rename->FileNameLength = (DWORD)bytes;+ memcpy(rename->FileName, target_path, bytes);+ rename->FileName[chars] = L'\0';+ /* First-touch antivirus scanning (Defender filter drivers) transiently+ * vetoes renames of trees holding a just-created executable — observed as+ * ERROR_INVALID_NAME on a name that is provably valid moments later, and+ * classically as ACCESS_DENIED/SHARING_VIOLATION. Freshly built or+ * downloaded binaries are always cold, so first-run installs must absorb+ * the scan window with a bounded backoff. */+ bool renamed = false;+ DWORD last_error = ERROR_SUCCESS;+ for (DWORD wait_ms = 0U, waited_ms = 0U;; waited_ms += wait_ms) {+ renamed = SetFileInformationByHandle(file, LAUNCHER_FILE_RENAME_INFO_EX, rename,+ (DWORD)allocation) != 0;+ if (renamed) {+ break;+ }+ last_error = GetLastError();+ bool transient = last_error == ERROR_INVALID_NAME || last_error == ERROR_ACCESS_DENIED ||+ last_error == ERROR_SHARING_VIOLATION;+ if (!transient || waited_ms >= 2000U) {+ break;+ }+ wait_ms = wait_ms == 0U ? 100U : (wait_ms < 1000U ? wait_ms * 2U : wait_ms);+ Sleep(wait_ms);+ }+ free(rename);+ if (!renamed) {+ SetLastError(last_error);+ }+ return renamed;+}++/* Retire the running staged image: direct POSIX delete succeeds only for an+ * unmapped file — Windows refuses a delete disposition on a mapped image. A+ * mapped image is instead renamed OUT of the .cbm state tree to the install+ * root: a mapped file blocks the rename of every ancestor directory, so a+ * retired image left inside .cbm\runtime would wedge the uninstall's atomic+ * state retirement. The install root stays on the same volume (rename-info+ * cannot cross volumes) and later launcher runs sweep *.retired there. */+static bool launcher_retire_running_image(HANDLE file, const wchar_t *image_path) {+ if (launcher_posix_remove(file)) {+ return true;+ }+ wchar_t runtime_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t state_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ wchar_t install_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ if (!launcher_parent_path(image_path, runtime_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !launcher_parent_path(runtime_directory, state_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP) ||+ !launcher_parent_path(state_directory, install_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {+ return false;+ }+ wchar_t retired[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int written =+ swprintf(retired, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\activation-%lu-%llu.retired",+ install_directory, (unsigned long)GetCurrentProcessId(),+ (unsigned long long)GetTickCount64());+ if (written <= 0 || (size_t)written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ return false;+ }+ return launcher_posix_rename(file, retired);+}+static int launcher_spawn_payload(const wchar_t *execution_path, const wchar_t *canonical_launcher,bool managed, bool private_activation,cbm_windows_launcher_action_t action,@@ -876,6 +1152,7 @@ static int launcher_spawn_payload(const wchar_t *execution_path, const wchar_t *environment_set &&CreateProcessW(execution_path, command, NULL, NULL, TRUE, flags, NULL, NULL,&startup.StartupInfo, &child) != 0;+ DWORD payload_pid = created ? child.dwProcessId : 0U;(void)SetEnvironmentVariableW(LAUNCHER_CONTEXT_ENV, NULL);if (attribute_initialized)DeleteProcThreadAttributeList(attributes);@@ -899,10 +1176,27 @@ static int launcher_spawn_payload(const wchar_t *execution_path, const wchar_t *HANDLE private_file = INVALID_HANDLE_VALUE;bool private_removed = true;if (payload_ready && private_activation) {- private_file =- launcher_open_regular(execution_path, GENERIC_READ | GENERIC_WRITE | DELETE, true);- private_removed =- private_file != INVALID_HANDLE_VALUE && launcher_posix_remove(private_file);+ /* DELETE only, never GENERIC_WRITE: the payload is RUNNING from this+ * staged image, and the image section always denies write sharing+ * (ERROR_SHARING_VIOLATION). */+ private_file = launcher_open_regular(execution_path, GENERIC_READ | DELETE, true);+ if (private_file == INVALID_HANDLE_VALUE) {+ /* Surfaced on the inherited stderr: the payload's generic+ * completion error cannot say WHICH launcher-side step refused. */+ (void)fwprintf(stderr,+ L"codebase-memory-mcp-launcher: private staged copy failed secure "+ L"open (%ls; error %lu): %ls\n",+ launcher_refusal_detail[0] ? launcher_refusal_detail : L"no detail",+ (unsigned long)GetLastError(), execution_path);+ }+ private_removed = private_file != INVALID_HANDLE_VALUE &&+ launcher_retire_running_image(private_file, execution_path);+ if (private_file != INVALID_HANDLE_VALUE && !private_removed) {+ (void)fwprintf(stderr,+ L"codebase-memory-mcp-launcher: private staged copy retirement failed "+ L"(error %lu): %ls\n",+ (unsigned long)GetLastError(), execution_path);+ }}uint8_t handshake_result = private_removed ? (uint8_t)'G' : (uint8_t)'F';bool authenticated = payload_ready &&@@ -937,6 +1231,14 @@ static int launcher_spawn_payload(const wchar_t *execution_path, const wchar_t *if (job)(void)CloseHandle(job);launcher_context_pipe_close(&context_pipe);+ if (exit_valid && exit_code == 0U && managed &&+ action == CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL &&+ !launcher_schedule_managed_cleanup(canonical_launcher, state, payload_pid)) {+ return launcher_failure(+ L"uninstall removed the canonical launcher, but detached retired-state cleanup could "+ L"not be scheduled; after this process exits, remove the matching .cbm-retired-v1 "+ L"directory manually");+ }return exit_valid ? (int)exit_code : 1;}@@ -1024,6 +1326,93 @@ static bool launcher_private_payload_path(const wchar_t *canonical_launcher, con(void)CloseHandle(state_handle);if (runtime_handle != INVALID_HANDLE_VALUE)(void)CloseHandle(runtime_handle);+ if (directories_valid) {+ /* Best-effort stale sweep: earlier activations' staged copies and+ * .retired images become deletable once their payload exits. Entries+ * whose embedded pid is still alive are skipped (a concurrent+ * activation owns them); still-mapped leftovers fail the delete+ * harmlessly and are retried on the next run. */+ wchar_t sweep_pattern[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ WIN32_FIND_DATAW stale;+ int sweep_written =+ swprintf(sweep_pattern, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\activation-*", runtime);+ HANDLE search = sweep_written > 0 && (size_t)sweep_written < CBM_WINDOWS_LAUNCHER_PATH_CAP+ ? FindFirstFileW(sweep_pattern, &stale)+ : INVALID_HANDLE_VALUE;+ if (search != INVALID_HANDLE_VALUE) {+ do {+ unsigned long stale_pid = 0U;+ if ((stale.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ||+ swscanf(stale.cFileName, L"activation-%lu-", &stale_pid) != 1 ||+ stale_pid == (unsigned long)GetCurrentProcessId()) {+ continue;+ }+ HANDLE owner =+ OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)stale_pid);+ bool owner_alive = owner && WaitForSingleObject(owner, 0U) == WAIT_TIMEOUT;+ if (owner)+ (void)CloseHandle(owner);+ if (owner_alive) {+ continue;+ }+ wchar_t stale_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int stale_written = swprintf(stale_path, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\%ls",+ runtime, stale.cFileName);+ if (stale_written <= 0 || (size_t)stale_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ continue;+ }+ HANDLE stale_file =+ CreateFileW(stale_path, DELETE | FILE_READ_ATTRIBUTES,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);+ if (stale_file != INVALID_HANDLE_VALUE) {+ (void)launcher_posix_remove(stale_file);+ (void)CloseHandle(stale_file);+ }+ } while (FindNextFileW(search, &stale));+ (void)FindClose(search);+ }+ /* Second pass: retired mapped images live at the INSTALL root (see+ * launcher_retire_running_image); same liveness-guarded delete. */+ sweep_written = swprintf(sweep_pattern, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ L"%ls\\activation-*.retired", directory);+ search = sweep_written > 0 && (size_t)sweep_written < CBM_WINDOWS_LAUNCHER_PATH_CAP+ ? FindFirstFileW(sweep_pattern, &stale)+ : INVALID_HANDLE_VALUE;+ if (search != INVALID_HANDLE_VALUE) {+ do {+ unsigned long stale_pid = 0U;+ if ((stale.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ||+ swscanf(stale.cFileName, L"activation-%lu-", &stale_pid) != 1 ||+ stale_pid == (unsigned long)GetCurrentProcessId()) {+ continue;+ }+ HANDLE owner =+ OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD)stale_pid);+ bool owner_alive = owner && WaitForSingleObject(owner, 0U) == WAIT_TIMEOUT;+ if (owner)+ (void)CloseHandle(owner);+ if (owner_alive) {+ continue;+ }+ wchar_t stale_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ int stale_written = swprintf(stale_path, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\%ls",+ directory, stale.cFileName);+ if (stale_written <= 0 || (size_t)stale_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {+ continue;+ }+ HANDLE stale_file =+ CreateFileW(stale_path, DELETE | FILE_READ_ATTRIBUTES,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);+ if (stale_file != INVALID_HANDLE_VALUE) {+ (void)launcher_posix_remove(stale_file);+ (void)CloseHandle(stale_file);+ }+ } while (FindNextFileW(search, &stale));+ (void)FindClose(search);+ }+ }if (!directories_valid || !CopyFileW(payload, output, TRUE)) {if (runtime_created)(void)RemoveDirectoryW(runtime);@@ -1176,26 +1565,58 @@ int wmain(void) {(void)LocalFree(argv);return launcher_failure(L"could not securely resolve the launcher path");}- HANDLE canonical_file = launcher_open_regular(canonical, GENERIC_READ, true);+ HANDLE canonical_file = launcher_open_regular_links(canonical, GENERIC_READ, true, 0U);if (canonical_file == INVALID_HANDLE_VALUE) {(void)LocalFree(argv);return launcher_failure(L"launcher ownership or access policy is unsafe");}- (void)CloseHandle(canonical_file);+ BY_HANDLE_FILE_INFORMATION canonical_information;+ if (!launcher_file_information(canonical_file, &canonical_information)) {+ (void)CloseHandle(canonical_file);+ (void)LocalFree(argv);+ return launcher_failure(L"launcher file identity is unavailable");+ }cbm_windows_current_v1_t state;memset(&state, 0, sizeof(state));int state_status = launcher_load_current(canonical, &state);if (state_status < 0) {+ (void)CloseHandle(canonical_file);(void)LocalFree(argv);return launcher_failure(L"current-v1 launcher state is corrupt or unsafe");}bool managed = state_status == 1;if (managed &&!cbm_windows_current_v1_supports_launcher_abi(&state, CBM_WINDOWS_LAUNCHER_ABI_CURRENT)) {+ (void)CloseHandle(canonical_file);(void)LocalFree(argv);return launcher_failure(L"current-v1 requires an incompatible launcher ABI");}+ bool launcher_layout_valid = canonical_information.nNumberOfLinks == 1U;+ if (managed) {+ wchar_t backing[CBM_WINDOWS_LAUNCHER_PATH_CAP];+ char backing_error[256] = {0};+ bool backing_path_valid =+ cbm_windows_managed_launcher_backing(canonical, backing, CBM_WINDOWS_LAUNCHER_PATH_CAP,+ backing_error, sizeof(backing_error));+ HANDLE backing_file = backing_path_valid+ ? launcher_open_regular_links(backing, GENERIC_READ, true, 2U)+ : INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION backing_information;+ launcher_layout_valid =+ canonical_information.nNumberOfLinks == 2U &&+ launcher_file_information_links(backing_file, &backing_information, 2U) &&+ launcher_same_identity(&canonical_information, &backing_information);+ if (backing_file != INVALID_HANDLE_VALUE)+ (void)CloseHandle(backing_file);+ }+ (void)CloseHandle(canonical_file);+ if (!launcher_layout_valid) {+ (void)LocalFree(argv);+ return launcher_failure(managed+ ? L"managed launcher hard-link backing is missing or unsafe"+ : L"portable launcher must have exactly one file-system link");+ }cbm_windows_launcher_action_t action = launcher_wide_action(argc, argv);if (!cbm_windows_launcher_action_allowed(action, managed)) {(void)LocalFree(argv);diff --git a/src/main.c b/src/main.cindex d63bb7d93..c47ebd998 100644--- a/src/main.c+++ b/src/main.c@@ -40,9 +40,9 @@ enum {MAIN_MCP_STARTUP_TIMEOUT_MS = 30000,MAIN_REQUEST_TIMEOUT_MS = 24 * 60 * 60 * 1000,MAIN_HOOK_CONNECT_TIMEOUT_MS = 250,- MAIN_HOOK_STARTUP_TIMEOUT_MS = 1500,MAIN_HOOK_REQUEST_TIMEOUT_MS = 1500,MAIN_HOOK_CLOSE_TIMEOUT_MS = 250,+ MAIN_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 */@@ -64,6 +64,7 @@ enum {#endif#include "ui/http_server.h"#include "ui/embedded_assets.h"+#include "ui/config.h"#include <yyjson/yyjson.h>#include <errno.h>@@ -591,10 +592,7 @@ static bool cli_first_nonspace_is_brace(const char *s) {return *s == '{';}-static void cli_progress_worker_log(const char *line, void *context) {- (void)context;- cbm_progress_sink_fn(line);-}+static char *main_local_cli_daemon_execute(const char *tool_name, const char *args_json);static int run_cli(int argc, char **argv, cbm_project_lock_manager_t *project_locks,main_local_maintenance_context_t *maintenance_context) {@@ -711,78 +709,52 @@ static int run_cli(int argc, char **argv, cbm_project_lock_manager_t *project_locbm_cli_progress_start(stderr, tool_name);}- if (!index_worker && strcmp(tool_name, "index_repository") == 0) {- char self_path[MAIN_PATH_CAP] = {0};- if (!cbm_http_server_resolve_binary_path(NULL, self_path, sizeof(self_path)) ||- !cbm_index_supervisor_capture_build_fingerprint()) {- (void)fprintf(stderr, "error: exact CLI worker identity could not be verified\n");- if (progress) {- cbm_progress_sink_fini();- cbm_cli_progress_finish(stderr, tool_name, false,- cbm_now_ms() - progress_started_ms);- }- free(heap_args);- return SKIP_ONE;- }- cbm_http_server_set_binary_path(self_path);- cbm_index_supervisor_mark_host();- }-- cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ /* Indexing always executes daemon-side now (the daemon's supervisor+ * spawns and budgets the worker); no local supervision prep remains for+ * one-shot commands. */+ cbm_mcp_server_t *srv = NULL;char *result = NULL;main_local_cli_mutation_t mutation = {.manager = project_locks,.feedback = progress ? stderr : NULL,.index_worker = index_worker,};- if (srv) {- /* Both the one-shot parent and its in-process worker are standalone- * instances: neither may launch MCP-session background tasks. The- * worker receives project_locks from its own process-level- * coordination setup and therefore owns the mutation lease while it- * performs the physical write. */- cbm_mcp_server_set_background_tasks(srv, false);- if (project_locks) {- cbm_mcp_server_set_project_mutation_guard(srv, main_local_cli_mutation_begin,- main_local_cli_mutation_end, &mutation);- }- }- if (srv && !index_worker) {- char session_root[MAIN_PATH_CAP];- char allowed_root[MAIN_PATH_CAP];- const char *allowed_root_ptr = NULL;- if (progress) {- cbm_mcp_server_set_index_log_callback(srv, cli_progress_worker_log, NULL);+ bool maintenance_binding_failed = false;+ bool maintenance_cancelled = false;+ if (!index_worker) {+ result = main_local_cli_daemon_execute(tool_name, args_json);+ } else {+ srv = cbm_mcp_server_new(NULL);+ if (srv) {+ /* The in-process worker is a standalone instance: it may not+ * launch MCP-session background tasks. It receives project_locks+ * from its own process-level coordination setup and therefore+ * owns the mutation lease while it performs the physical write. */+ cbm_mcp_server_set_background_tasks(srv, false);+ if (project_locks) {+ cbm_mcp_server_set_project_mutation_guard(srv, main_local_cli_mutation_begin,+ main_local_cli_mutation_end, &mutation);+ }}- if (!main_session_context(NULL, session_root, allowed_root, &allowed_root_ptr) ||- !cbm_mcp_server_set_session_context(srv, session_root, allowed_root_ptr)) {- cbm_mcp_server_free(srv);- srv = NULL;+ maintenance_binding_failed = srv && !maintenance_context;+ if (srv && maintenance_context) {+ main_local_maintenance_server_bind(maintenance_context, srv);+ result = cbm_mcp_handle_tool(srv, tool_name, args_json);+ /* Unbind under the same mutex used by cancellation before any+ * server teardown. The process-level monitor remains active+ * across all parsing and cleanup, but can no longer race a freed+ * server. */+ main_local_maintenance_server_bind(maintenance_context, NULL);+ maintenance_cancelled = main_local_maintenance_was_cancelled(maintenance_context);}}- bool maintenance_binding_failed = srv && !maintenance_context;- bool maintenance_cancelled = false;- if (srv && maintenance_context) {- main_local_maintenance_server_bind(maintenance_context, srv);- result = cbm_mcp_handle_tool(srv, tool_name, args_json);- /* Unbind under the same mutex used by cancellation before any server- * teardown. The process-level monitor remains active across all- * parsing and cleanup, but can no longer race a freed server. */- main_local_maintenance_server_bind(maintenance_context, NULL);- maintenance_cancelled = main_local_maintenance_was_cancelled(maintenance_context);- }- if (maintenance_cancelled && !index_worker) {- (void)fprintf(stderr, "codebase-memory-mcp: active CLI command is stopping for "- "install/update/uninstall\n");- }if (!result) {if (maintenance_binding_failed) {(void)fprintf(stderr,"error: local %s maintenance cancellation could not bind safely\n",index_worker ? "worker" : "CLI");- } else {- (void)fprintf(stderr, "error: failed to run local %s server\n",- index_worker ? "worker" : "CLI");+ } else if (index_worker) {+ (void)fprintf(stderr, "error: failed to run local worker server\n");}cbm_mcp_server_free(srv);main_local_cli_mutation_release_all(&mutation);@@ -1242,6 +1214,144 @@ static bool main_set_client_context(cbm_daemon_runtime_client_t *client, const cCBM_DAEMON_RUNTIME_APPLICATION_OK;}+/* Parse a strict MAJOR.MINOR.PATCH triple; false for anything else (dev+ * builds and prereleases never participate in auto-drain decisions). */+static bool main_semver_triple(const char *text, long out[3]) {+ if (!text || !text[0]) {+ return false;+ }+ char *cursor = NULL;+ out[0] = strtol(text, &cursor, 10);+ if (!cursor || *cursor != '.') {+ return false;+ }+ out[1] = strtol(cursor + 1, &cursor, 10);+ if (!cursor || *cursor != '.') {+ return false;+ }+ out[2] = strtol(cursor + 1, &cursor, 10);+ return cursor && *cursor == '\0';+}++static bool main_semver_newer(const char *candidate, const char *active) {+ long candidate_triple[3];+ long active_triple[3];+ if (!main_semver_triple(candidate, candidate_triple) ||+ !main_semver_triple(active, active_triple)) {+ return false;+ }+ for (int part = 0; part < 3; part++) {+ if (candidate_triple[part] != active_triple[part]) {+ return candidate_triple[part] > active_triple[part];+ }+ }+ return false;+}++/* Client bootstrap with the upgrade policy: a CONFLICT against a PERMANENT+ * daemon of a strictly OLDER release is resolved by draining that daemon+ * (the same authenticated path install/update use) and retrying once. A+ * manual binary swap therefore self-heals exactly like the ephemeral+ * lifecycle used to, instead of deadlocking behind the pinned daemon. Same-+ * or newer-build daemons and dev builds are never auto-drained. */+static cbm_daemon_bootstrap_status_t main_client_bootstrap_with_upgrade(+ const cbm_daemon_bootstrap_config_t *config, cbm_daemon_bootstrap_result_t *result) {+ cbm_daemon_bootstrap_status_t status = cbm_daemon_bootstrap_execute(config, result);+ if (status != CBM_DAEMON_BOOTSTRAP_CONFLICT) {+ return status;+ }+ cbm_daemon_runtime_status_t active;+ if (!cbm_daemon_runtime_request_status(config->endpoint, config->identity,+ MAIN_CONNECT_TIMEOUT_MS, &active) ||+ !active.permanent ||+ !main_semver_newer(config->identity->semantic_version, active.semantic_version)) {+ return status;+ }+ (void)fprintf(stderr,+ "codebase-memory-mcp: retiring the active permanent daemon (%s, pid %lu) for "+ "this newer build (%s)\n",+ active.semantic_version, (unsigned long)active.daemon_pid,+ config->identity->semantic_version);+ cbm_daemon_runtime_activation_result_t drain;+ if (!cbm_daemon_runtime_request_activation_shutdown(config->endpoint, config->identity,+ CBM_DAEMON_RUNTIME_ACTIVATION_UPDATE,+ MAIN_MCP_STARTUP_TIMEOUT_MS, &drain) ||+ !drain.accepted) {+ (void)fprintf(stderr, "codebase-memory-mcp: the active daemon did not accept the "+ "upgrade drain; run `codebase-memory-mcp daemon stop`\n");+ return status;+ }+ return cbm_daemon_bootstrap_execute(config, result);+}++/* One-shot CLI commands execute through the shared daemon, exactly like MCP+ * sessions and hooks: an active daemon (any starter) is recycled, an absent+ * one is spawned for this command — with a hint that `daemon start` removes+ * that per-command cost. Only supervised index workers stay in-process. */+static char *main_local_cli_daemon_execute(const char *tool_name, const char *args_json) {+ cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_bootstrap_endpoint_new(NULL);+ char executable_path[MAIN_PATH_CAP] = {0};+ cbm_daemon_build_identity_t identity;+ bool prepared =+ endpoint &&+ cbm_http_server_resolve_binary_path(NULL, executable_path, sizeof(executable_path)) &&+ main_build_identity(&identity) == MAIN_BUILD_IDENTITY_OK;+ if (!prepared) {+ (void)fprintf(stderr, "error: daemon-backed CLI coordination could not be prepared\n");+ cbm_daemon_ipc_endpoint_free(endpoint);+ return NULL;+ }+ cbm_daemon_bootstrap_config_t config = {+ .role = CBM_DAEMON_PROCESS_MCP_CLIENT,+ .endpoint = endpoint,+ .identity = &identity,+ .executable_path = executable_path,+ .connect_timeout_ms = MAIN_CONNECT_TIMEOUT_MS,+ .startup_timeout_ms = MAIN_MCP_STARTUP_TIMEOUT_MS,+ };+ cbm_daemon_bootstrap_result_t bootstrap;+ cbm_daemon_bootstrap_status_t status = main_client_bootstrap_with_upgrade(&config, &bootstrap);+ cbm_daemon_ipc_endpoint_free(endpoint);+ if (status != CBM_DAEMON_BOOTSTRAP_CONNECTED || !bootstrap.client) {+ (void)fprintf(stderr, "error: %s\n",+ bootstrap.message[0] ? bootstrap.message+ : "no CBM daemon connection for CLI execution");+ return NULL;+ }+ if (bootstrap.daemon_spawned) {+ (void)fprintf(stderr, "hint: this command started a temporary CBM daemon. "+ "`codebase-memory-mcp daemon start` keeps one warm and removes this "+ "startup cost from every CLI command.\n");+ }+ char session_root[MAIN_PATH_CAP];+ char allowed_root[MAIN_PATH_CAP];+ const char *allowed_root_ptr = NULL;+ char *result = NULL;+ uint8_t *response = NULL;+ uint32_t response_length = 0;+ bool context_ok =+ main_session_context(NULL, session_root, allowed_root, &allowed_root_ptr) &&+ main_set_client_context(bootstrap.client, session_root, CBM_MCP_TOOL_PROFILE_ALL, NULL,+ NULL, MAIN_CONNECT_TIMEOUT_MS);+ if (context_ok &&+ cbm_daemon_application_client_tool(bootstrap.client, tool_name, args_json, &response,+ &response_length, MAIN_REQUEST_TIMEOUT_MS) ==+ CBM_DAEMON_RUNTIME_APPLICATION_OK &&+ response && response_length > 0) {+ result = malloc((size_t)response_length + 1U);+ if (result) {+ memcpy(result, response, response_length);+ result[response_length] = '\0';+ }+ }+ free(response);+ if (!result) {+ (void)fprintf(stderr, "error: daemon-backed CLI execution failed\n");+ }+ (void)cbm_daemon_runtime_client_close(bootstrap.client, MAIN_CLOSE_TIMEOUT_MS);+ return result;+}+static char *main_hook_cwd(const char *input_json) {if (!input_json) {return NULL;@@ -1264,33 +1374,57 @@ static char *main_hook_cwd(const char *input_json) {return copy;}-static bool main_hook_options(int argc, char **argv, const char **event_out,- const char **dialect_out) {- if (!argv || !event_out || !dialect_out) {+/* Hooks never spawn a daemon (a cold spawn livelocks against the fail-open+ * budget), so augmentation is absent until an MCP session or `daemon start`+ * brings one up. That state must be VISIBLE, not silent — but a notice per+ * tool call would nag, so a cache-scoped marker rate-limits it. */+static bool main_hook_absent_notice_due(void) {+ const char *cache_dir = cbm_resolve_cache_dir();+ if (!cache_dir) {return false;}- *event_out = NULL;- *dialect_out = NULL;- int hook_index = -1;- for (int index = 1; index < argc; index++) {- if (argv[index] && strcmp(argv[index], "hook-augment") == 0) {- hook_index = index;- break;+ char marker[MAIN_PATH_CAP];+ int written = snprintf(marker, sizeof(marker), "%s/.hook-daemon-absent-notice", cache_dir);+ if (written <= 0 || (size_t)written >= sizeof(marker)) {+ return false;+ }+ uint64_t now_seconds = cbm_now_ms() / 1000U;+ uint64_t stamp_seconds = 0;+ FILE *stamp = cbm_fopen(marker, "r");+ if (stamp) {+ char text[32] = {0};+ if (fgets(text, sizeof(text), stamp)) {+ stamp_seconds = strtoull(text, NULL, 10);}+ (void)fclose(stamp);}- if (hook_index < 0) {+ if (stamp_seconds != 0 && now_seconds >= stamp_seconds &&+ now_seconds - stamp_seconds < MAIN_HOOK_NOTICE_INTERVAL_SECONDS) {return false;}- for (int index = hook_index + 1; index < argc; index++) {- if (strcmp(argv[index], "--event") == 0 && index + 1 < argc) {- *event_out = argv[++index];- } else if (strcmp(argv[index], "--dialect") == 0 && index + 1 < argc) {- *dialect_out = argv[++index];- } else {- return false;- }+ FILE *update = cbm_fopen(marker, "w");+ if (update) {+ (void)fprintf(update, "%llu\n", (unsigned long long)now_seconds);+ (void)fclose(update);+ }+ return true;+}++static void main_hook_report_absent_daemon(const char *hook_dialect) {+ if (!main_hook_absent_notice_due()) {+ return;+ }+ (void)fprintf(stderr, "codebase-memory-mcp: no CBM daemon is running, so graph "+ "augmentation is skipped. Start an MCP session or run "+ "`codebase-memory-mcp daemon start` to enable it.\n");+ if (!hook_dialect) {+ /* Claude hook output: a systemMessage is surfaced to the user. */+ (void)fputs("{\"systemMessage\":\"codebase-memory-mcp: no CBM daemon is running, so "+ "graph augmentation is currently skipped. Run `codebase-memory-mcp daemon "+ "start` (or open an MCP session) to enable it.\"}",+ stdout);+ (void)fflush(stdout);}- return cbm_hook_augment_invocation_supported(*event_out, *dialect_out);}static int main_run_hook_frontend(cbm_daemon_runtime_client_t *client, const char *hook_event,@@ -1321,6 +1455,247 @@ static int main_run_hook_frontend(cbm_daemon_runtime_client_t *client, const chareturn 0; /* hooks always fail open */}+static bool main_hook_options(int argc, char **argv, const char **event_out,+ const char **dialect_out) {+ if (!argv || !event_out || !dialect_out) {+ return false;+ }+ *event_out = NULL;+ *dialect_out = NULL;+ int hook_index = -1;+ for (int index = 1; index < argc; index++) {+ if (argv[index] && strcmp(argv[index], "hook-augment") == 0) {+ hook_index = index;+ break;+ }+ }+ if (hook_index < 0) {+ return false;+ }+ for (int index = hook_index + 1; index < argc; index++) {+ if (strcmp(argv[index], "--event") == 0 && index + 1 < argc) {+ *event_out = argv[++index];+ } else if (strcmp(argv[index], "--dialect") == 0 && index + 1 < argc) {+ *dialect_out = argv[++index];+ } else {+ return false;+ }+ }+ return cbm_hook_augment_invocation_supported(*event_out, *dialect_out);+}++enum {+ MAIN_DAEMON_CTL_PROBE_TIMEOUT_MS = 3000,+ MAIN_DAEMON_CTL_STOP_TIMEOUT_MS = 10000,+ MAIN_DAEMON_CTL_START_TIMEOUT_MS = 30000,+};++static void main_daemon_ctl_print_clients(const uint32_t *pids, uint8_t count, uint16_t committed) {+ printf(" committed clients: %u\n", (unsigned)committed);+ for (uint8_t index = 0; index < count; index++) {+ printf(" - pid %lu\n", (unsigned long)pids[index]);+ }+ if (committed > count) {+ printf(" - (%u more not listed)\n", (unsigned)(committed - count));+ }+}++static void main_daemon_ctl_print_ui(void) {+ if (CBM_EMBEDDED_FILE_COUNT == 0) {+ return;+ }+ cbm_ui_config_t ui_config;+ cbm_ui_config_load(&ui_config);+ if (ui_config.ui_enabled) {+ printf(" ui: http://127.0.0.1:%d\n", ui_config.ui_port);+ } else {+ printf(" ui: disabled (enable with `daemon start` in a UI build)\n");+ }+}++static void main_daemon_ctl_open_browser(int port) {+ char url[64];+ (void)snprintf(url, sizeof(url), "http://127.0.0.1:%d", port);+#if defined(_WIN32)+ char command[96];+ (void)snprintf(command, sizeof(command), "start \"\" %s", url);+#elif defined(__APPLE__)+ char command[96];+ (void)snprintf(command, sizeof(command), "open %s", url);+#else+ char command[96];+ (void)snprintf(command, sizeof(command), "xdg-open %s >/dev/null 2>&1", url);+#endif+ if (system(command) != 0) {+ (void)fprintf(stderr, "hint: could not open a browser automatically; visit %s\n", url);+ }+}++static int main_run_daemon_ctl(int argc, char **argv, const cbm_daemon_ipc_endpoint_t *endpoint,+ const cbm_daemon_build_identity_t *identity,+ const char *executable_path) {+ const char *subcommand = NULL;+ bool open_browser = false;+ int requested_port = 0;+ bool arguments_valid = true;+ for (int index = 1; index < argc; index++) {+ if (strcmp(argv[index], "daemon") == 0) {+ continue;+ }+ if (strcmp(argv[index], "start") == 0 || strcmp(argv[index], "stop") == 0 ||+ strcmp(argv[index], "status") == 0) {+ subcommand = argv[index];+ } else if (strcmp(argv[index], "--open") == 0) {+ open_browser = true;+ } else if (strncmp(argv[index], "--port=", 7) == 0) {+ requested_port = atoi(argv[index] + 7);+ if (requested_port <= 0 || requested_port >= MAIN_MAX_PORT) {+ (void)fprintf(stderr, "error: --port requires a value between 1 and 65535\n");+ return EXIT_FAILURE;+ }+ } else {+ (void)fprintf(stderr, "error: unknown daemon option: %s\n", argv[index]);+ arguments_valid = false;+ break;+ }+ }+ if (!arguments_valid || !subcommand) {+ (void)fprintf(stderr, "usage: codebase-memory-mcp daemon <start|stop|status> "+ "[--open] [--port=N]\n");+ return EXIT_FAILURE;+ }++ cbm_daemon_runtime_status_t status;+ bool active = cbm_daemon_runtime_request_status(endpoint, identity,+ MAIN_DAEMON_CTL_PROBE_TIMEOUT_MS, &status);++ if (strcmp(subcommand, "status") == 0) {+ if (!active) {+ printf("daemon: not running\n");+ printf("hint: `codebase-memory-mcp daemon start` keeps a daemon warm so CLI "+ "commands and hooks skip the per-command startup cost.\n");+ return EXIT_FAILURE;+ }+ printf("daemon: active (%s)\n", status.permanent ? "permanent" : "session-managed");+ printf(" pid: %lu\n", (unsigned long)status.daemon_pid);+ printf(" build: %s (%.12s...)\n", status.semantic_version, status.build_fingerprint);+ if (status.stopping) {+ printf(" state: stopping\n");+ }+ main_daemon_ctl_print_clients(status.client_pids, status.client_count,+ status.committed_clients);+ main_daemon_ctl_print_ui();+ return EXIT_SUCCESS;+ }++ if (strcmp(subcommand, "stop") == 0) {+ if (!active) {+ printf("daemon: not running (nothing to stop)\n");+ return EXIT_SUCCESS;+ }+ cbm_daemon_runtime_stop_result_t stop_result;+ if (!cbm_daemon_runtime_request_stop(endpoint, identity, MAIN_DAEMON_CTL_STOP_TIMEOUT_MS,+ &stop_result)) {+ (void)fprintf(stderr,+ "error: the active daemon did not answer the stop request; "+ "if it is stuck, terminate pid %lu directly\n",+ (unsigned long)status.daemon_pid);+ return EXIT_FAILURE;+ }+ if (stop_result.busy) {+ printf("daemon: NOT stopped — %u committed client(s) still use it.\n",+ (unsigned)stop_result.committed_clients);+ main_daemon_ctl_print_clients(stop_result.client_pids, stop_result.client_count,+ stop_result.committed_clients);+ printf("Close these sessions/commands first, then retry `daemon stop`.\n");+ return EXIT_FAILURE;+ }+ if (!stop_result.accepted) {+ printf("daemon: already stopping\n");+ return EXIT_SUCCESS;+ }+ printf("daemon: stopping (pid %lu)\n", (unsigned long)status.daemon_pid);+ return EXIT_SUCCESS;+ }++ /* start */+ if (active) {+ if (status.permanent) {+ printf("daemon: already active (permanent, pid %lu)\n",+ (unsigned long)status.daemon_pid);+ } else {+ printf("daemon: already active (session-managed, pid %lu) — it stops with its "+ "last session; run `daemon stop` first if you want a permanent one\n",+ (unsigned long)status.daemon_pid);+ }+ main_daemon_ctl_print_ui();+ return EXIT_SUCCESS;+ }++ cbm_daemon_bootstrap_config_t start_config = {+ .role = CBM_DAEMON_PROCESS_MCP_CLIENT,+ .endpoint = endpoint,+ .identity = identity,+ .executable_path = executable_path,+ .connect_timeout_ms = MAIN_CONNECT_TIMEOUT_MS,+ .startup_timeout_ms = MAIN_DAEMON_CTL_START_TIMEOUT_MS,+ .spawn_permanent = true,+ };+ cbm_daemon_bootstrap_result_t start_result;+ cbm_daemon_bootstrap_status_t start_status =+ main_client_bootstrap_with_upgrade(&start_config, &start_result);+ if (start_status != CBM_DAEMON_BOOTSTRAP_CONNECTED || !start_result.client) {+ (void)fprintf(stderr, "error: %s\n",+ start_result.message[0] ? start_result.message+ : "the permanent daemon could not be started");+ if (start_status == CBM_DAEMON_BOOTSTRAP_CONFLICT) {+ (void)fprintf(stderr, "hint: a daemon of a different build is active; "+ "`codebase-memory-mcp daemon stop` retires it.\n");+ }+ return EXIT_FAILURE;+ }++ /* The committed control connection satisfied the daemon's no-client+ * startup window; configure the UI before departing. */+ int ui_port = 0;+ if (CBM_EMBEDDED_FILE_COUNT > 0) {+ cbm_ui_config_t ui_config;+ cbm_ui_config_load(&ui_config);+ ui_port = requested_port > 0 ? requested_port : ui_config.ui_port;+ uint8_t update_mask = 0x03U; /* enabled + port */+ if (cbm_daemon_application_client_set_ui_config(start_result.client, update_mask, true,+ ui_port, MAIN_CONNECT_TIMEOUT_MS) !=+ CBM_DAEMON_RUNTIME_APPLICATION_OK) {+ (void)fprintf(stderr, "warning: the daemon did not accept the UI configuration; "+ "check `daemon status` and the daemon log\n");+ }+ } else if (requested_port > 0 || open_browser) {+ (void)fprintf(stderr, "warning: this binary was built without the embedded UI; "+ "--port/--open have no effect\n");+ }++ cbm_daemon_runtime_status_t started;+ bool started_ok = cbm_daemon_runtime_request_status(endpoint, identity,+ MAIN_DAEMON_CTL_PROBE_TIMEOUT_MS, &started);+ if (started_ok) {+ printf("daemon: started (permanent, pid %lu)\n", (unsigned long)started.daemon_pid);+ } else {+ printf("daemon: started (permanent)\n");+ }+ printf("It survives idle periods and session ends; `codebase-memory-mcp daemon stop` "+ "retires it.\n");+ if (CBM_EMBEDDED_FILE_COUNT > 0) {+ printf(" ui: http://127.0.0.1:%d\n", ui_port);+ printf(" If this port is unavailable the daemon keeps retrying and logs the "+ "conflict; pass --port=N for a different port.\n");+ if (open_browser) {+ main_daemon_ctl_open_browser(ui_port);+ }+ }+ (void)cbm_daemon_runtime_client_close(start_result.client, MAIN_CLOSE_TIMEOUT_MS);+ return EXIT_SUCCESS;+}+int main(int argc, char **argv) {/* Must remain the first statement: see allocator binding contract above. */cbm_alloc_init();@@ -1373,12 +1748,12 @@ int main(int argc, char **argv) {return EXIT_SUCCESS; /* hook adapters are contractually fail-open */}- /* Hook augmentation is contractually fail-open and time-bounded. Arm its- * deadline before executable hashing, daemon startup, and IPC connection;- * arming only inside the request frontend leaves bootstrap outside the- * guard. Windows is the exception: its fixed 300 ms budget covers only- * the post-authentication hook operation because a cold daemon bootstrap- * has its own finite 1500 ms bound and cannot fit that budget. */+ /* Hook augmentation is contractually fail-open and time-bounded. It is+ * daemon-backed but CONNECT-ONLY: a hook never spawns a daemon (a cold+ * spawn cannot fit the fail-open budget and livelocks against the+ * last-client-exit teardown), it recycles whichever daemon an MCP+ * session or `daemon start` already brought up. Arm the deadline before+ * hashing and IPC. */if (role == CBM_DAEMON_PROCESS_HOOK_CLIENT) {#ifndef _WIN32cbm_hook_augment_arm_deadline();@@ -1671,7 +2046,13 @@ int main(int argc, char **argv) {cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_bootstrap_endpoint_new(NULL);if (!endpoint) {(void)fprintf(stderr, "codebase-memory-mcp: secure daemon endpoint could not be created\n");- return role == CBM_DAEMON_PROCESS_HOOK_CLIENT ? EXIT_SUCCESS : EXIT_FAILURE;+ return EXIT_FAILURE;+ }++ if (role == CBM_DAEMON_PROCESS_DAEMON_CTL) {+ int ctl_result = main_run_daemon_ctl(argc, argv, endpoint, &identity, executable_path);+ cbm_daemon_ipc_endpoint_free(endpoint);+ return ctl_result;}if (role == CBM_DAEMON_PROCESS_DAEMON) {@@ -1681,6 +2062,9 @@ int main(int argc, char **argv) {.identity = identity,.executable_path = executable_path,.stop_requested = &g_shutdown,+ /* The role classifier already enforced the byte-exact grammar:+ * argc==3 can only be the permanent spawn shape. */+ .permanent = argc == 3,};int result = cbm_daemon_host_run(&host_config);cbm_daemon_ipc_endpoint_free(endpoint);@@ -1694,7 +2078,7 @@ int main(int argc, char **argv) {client_cohort_manager? cbm_version_cohort_acquire(client_cohort_manager, &identity,main_deadline_after(role == CBM_DAEMON_PROCESS_HOOK_CLIENT- ? MAIN_HOOK_STARTUP_TIMEOUT_MS+ ? MAIN_HOOK_REQUEST_TIMEOUT_MS: MAIN_MCP_STARTUP_TIMEOUT_MS),&client_cohort_lease, &client_cohort_conflict): CBM_VERSION_COHORT_IO;@@ -1713,23 +2097,46 @@ int main(int argc, char **argv) {return role == CBM_DAEMON_PROCESS_HOOK_CLIENT ? EXIT_SUCCESS : EXIT_FAILURE;}+ if (role == CBM_DAEMON_PROCESS_HOOK_CLIENT) {+ /* Connect-only: recycle an active daemon or fail open fast. */+ cbm_daemon_runtime_connect_result_t hook_connect;+ cbm_daemon_runtime_client_t *hook_client = cbm_daemon_runtime_client_connect(+ endpoint, &identity, MAIN_HOOK_CONNECT_TIMEOUT_MS, &hook_connect);+ cbm_daemon_ipc_endpoint_free(endpoint);+ if (!hook_client) {+ main_hook_report_absent_daemon(hook_dialect);+ (void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);+ return EXIT_SUCCESS;+ }+#ifdef _WIN32+ /* Windows keeps the upstream fixed augmentation budget, armed only+ * after the authenticated connection. */+ cbm_hook_augment_arm_deadline();+#endif+ /* Fail-open: a hook must never block the caller's tool use, so the+ * exit code is EXIT_SUCCESS even when augmentation failed — the+ * frontend already emitted any visible notice. */+ (void)main_run_hook_frontend(hook_client, hook_event, hook_dialect);+ (void)cbm_daemon_runtime_client_close(hook_client, MAIN_HOOK_CLOSE_TIMEOUT_MS);+ (void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);+ return EXIT_SUCCESS;+ }+cbm_daemon_bootstrap_config_t bootstrap_config = {.role = role,.endpoint = endpoint,.identity = &identity,.executable_path = executable_path,- .connect_timeout_ms = role == CBM_DAEMON_PROCESS_HOOK_CLIENT ? MAIN_HOOK_CONNECT_TIMEOUT_MS- : MAIN_CONNECT_TIMEOUT_MS,- .startup_timeout_ms = role == CBM_DAEMON_PROCESS_HOOK_CLIENT ? MAIN_HOOK_STARTUP_TIMEOUT_MS- : MAIN_MCP_STARTUP_TIMEOUT_MS,+ .connect_timeout_ms = MAIN_CONNECT_TIMEOUT_MS,+ .startup_timeout_ms = MAIN_MCP_STARTUP_TIMEOUT_MS,};cbm_daemon_bootstrap_result_t bootstrap_result;cbm_daemon_bootstrap_status_t bootstrap_status =- cbm_daemon_bootstrap_execute(&bootstrap_config, &bootstrap_result);+ main_client_bootstrap_with_upgrade(&bootstrap_config, &bootstrap_result);cbm_daemon_ipc_endpoint_free(endpoint);if (bootstrap_status != CBM_DAEMON_BOOTSTRAP_CONNECTED || !bootstrap_result.client) {(void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);- return role == CBM_DAEMON_PROCESS_HOOK_CLIENT ? EXIT_SUCCESS : EXIT_FAILURE;+ return EXIT_FAILURE;}g_daemon_client = bootstrap_result.client;@@ -1772,36 +2179,20 @@ int main(int argc, char **argv) {#ifndef _WIN32if (!client_start_parent_watchdog(process_initial_ppid)) {(void)fprintf(stderr, "codebase-memory-mcp: parent-death watchdog could not start\n");- (void)cbm_daemon_runtime_client_close(- g_daemon_client, role == CBM_DAEMON_PROCESS_HOOK_CLIENT ? MAIN_HOOK_CLOSE_TIMEOUT_MS- : MAIN_CLOSE_TIMEOUT_MS);+ (void)cbm_daemon_runtime_client_close(g_daemon_client, MAIN_CLOSE_TIMEOUT_MS);g_daemon_client = NULL;(void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);- return role == CBM_DAEMON_PROCESS_HOOK_CLIENT ? EXIT_SUCCESS : EXIT_FAILURE;+ return EXIT_FAILURE;}#endif- int result = EXIT_FAILURE;- if (role == CBM_DAEMON_PROCESS_HOOK_CLIENT) {- /* POSIX carries its configurable deadline from process startup.- * Windows retains the upstream fixed 300 ms augmentation budget but- * starts it only after authenticated bootstrap, whose separate finite- * bound cannot fit inside that budget. */-#ifdef _WIN32- cbm_hook_augment_arm_deadline();-#endif- result = main_run_hook_frontend(g_daemon_client, hook_event, hook_dialect);- (void)cbm_daemon_runtime_client_close(g_daemon_client, MAIN_HOOK_CLOSE_TIMEOUT_MS);- g_daemon_client = NULL;- } else {- setup_signal_handlers();- result = cbm_daemon_frontend_mcp_run(g_daemon_client, client_cohort_manager, stdin, stdout);- g_daemon_client = NULL; /* frontend consumed the handle */- }+ setup_signal_handlers();+ int result = cbm_daemon_frontend_mcp_run(g_daemon_client, client_cohort_manager, stdin, stdout);+ g_daemon_client = NULL; /* frontend consumed the handle */bool client_cohort_cleanup =main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);atomic_store(&g_shutdown, 1);- if (!client_cohort_cleanup && role != CBM_DAEMON_PROCESS_HOOK_CLIENT) {+ if (!client_cohort_cleanup) {return EXIT_FAILURE;}return result < 0 ? EXIT_FAILURE : result;diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex 39a8b3708..fb5a750ec 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -1808,7 +1808,7 @@ static bool reserve_unique_corrupt_pending(const char *path, char *pending, sizecontinue;}#ifdef _WIN32- wchar_t *wide = cbm_utf8_to_wide(pending);+ wchar_t *wide = cbm_path_to_wide(pending);HANDLE file = wide ? CreateFileW(wide, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_NEW,FILE_ATTRIBUTE_NORMAL, NULL): INVALID_HANDLE_VALUE;@@ -1876,8 +1876,8 @@ static bool sync_parent_directory(const char *path) {* atomic no-clobber operations within the cache directory. */static bool publish_corrupt_backup(const char *pending, const char *backup) {#ifdef _WIN32- wchar_t *wide_pending = cbm_utf8_to_wide(pending);- wchar_t *wide_backup = cbm_utf8_to_wide(backup);+ wchar_t *wide_pending = cbm_path_to_wide(pending);+ wchar_t *wide_backup = cbm_path_to_wide(backup);bool published = wide_pending && wide_backup &&MoveFileExW(wide_pending, wide_backup, MOVEFILE_WRITE_THROUGH) != 0;free(wide_pending);@@ -9085,6 +9085,19 @@ static bool validate_search_path_arg(const char *s) {return true;}+/* These characters retain command-language meaning inside quoted cmd.exe+ * arguments: percent expands environment variables, exclamation can expand+ * delayed variables, and caret changes parsing. Never interpolate them from a+ * stored project root or request branch into the Windows detect_changes payload.+ * /V:OFF is defense in depth for exclamation; validation remains the boundary. */+static bool validate_windows_cmd_interpolation_arg(const char *s) {+#ifdef _WIN32+ return s && strpbrk(s, "%!^") == NULL;+#else+ return s != NULL;+#endif+}+static bool validate_search_args(const char *root_path, const char *file_pattern) {if (!validate_search_path_arg(root_path)) {return false;@@ -9421,6 +9434,34 @@ static bool mcp_command_output_path(char out[CBM_SZ_2K]) {return true;}+#ifdef _WIN32+/* Resolve the OS-owned command processor without consulting PATH or mutable+ * COMSPEC. cbm_subprocess receives this as lpApplicationName and validates the+ * same absolute cmd.exe path before using the dedicated payload serializer. */+static bool mcp_resolve_windows_cmd(char out[CBM_SZ_4K]) {+ if (!out) {+ return false;+ }+ out[0] = '\0';+ wchar_t system_directory[MAX_PATH + 1];+ UINT directory_length = GetSystemDirectoryW(system_directory, MAX_PATH + 1);+ static const wchar_t suffix[] = L"\\cmd.exe";+ if (directory_length == 0 || directory_length > MAX_PATH ||+ (size_t)directory_length + (sizeof(suffix) / sizeof(suffix[0])) >+ sizeof(system_directory) / sizeof(system_directory[0])) {+ return false;+ }+ memcpy(system_directory + directory_length, suffix, sizeof(suffix));+ char *candidate = cbm_wide_to_utf8(system_directory);+ if (!candidate) {+ return false;+ }+ bool resolved = cbm_canonical_path(candidate, out, CBM_SZ_4K) != 0;+ free(candidate);+ return resolved;+}+#endif+static int mcp_run_shell_command_cancellable(cbm_mcp_server_t *srv, const char *command,char output_path[CBM_SZ_2K],cbm_proc_result_t *result_out) {@@ -9433,18 +9474,23 @@ static int mcp_run_shell_command_cancellable(cbm_mcp_server_t *srv, const char *return -1;}#ifdef _WIN32- const char *shell = getenv("COMSPEC");- if (!shell || !shell[0]) {- shell = "cmd.exe";+ char shell[CBM_SZ_4K];+ if (!mcp_resolve_windows_cmd(shell)) {+ (void)cbm_unlink(output_path);+ output_path[0] = '\0';+ return -1;}- const char *argv[] = {shell, "/D", "/S", "/C", command, NULL};#elseconst char *shell = "/bin/sh";const char *argv[] = {"sh", "-c", command, NULL};#endifcbm_proc_opts_t options = {.bin = shell,+#ifdef _WIN32+ .windows_cmd_payload = command,+#else.argv = argv,+#endif.log_file = output_path,.quiet_timeout_ms = 0,.cancel_grace_ms = CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS,@@ -9634,7 +9680,8 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {* "<base>"...HEAD`; a value starting with '-' would be read by git as an* option rather than a ref (e.g. `--output=<path>` writes the diff to an* arbitrary file). A real git ref never begins with '-'. */- if (!cbm_validate_shell_arg(base_branch) || base_branch[0] == '-') {+ if (!cbm_validate_shell_arg(base_branch) || base_branch[0] == '-' ||+ !validate_windows_cmd_interpolation_arg(base_branch)) {free(project);free(base_branch);free(scope);@@ -9652,7 +9699,8 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {return res;}- if (!validate_search_path_arg(root_path)) {+ if (!validate_search_path_arg(root_path) ||+ !validate_windows_cmd_interpolation_arg(root_path)) {free(root_path);free(project);free(base_branch);diff --git a/src/pipeline/pass_pkgmap.c b/src/pipeline/pass_pkgmap.cindex 511a84564..075378b12 100644--- a/src/pipeline/pass_pkgmap.c+++ b/src/pipeline/pass_pkgmap.c@@ -787,7 +787,7 @@ static bool is_pkgmap_manifest_basename(const char *basename) {* safe_stat. */static int pkgmap_safe_stat(const char *abs_path, struct stat *st) {#ifdef _WIN32- wchar_t *wpath = cbm_utf8_to_wide(abs_path);+ wchar_t *wpath = cbm_path_to_wide(abs_path);if (!wpath) {return CBM_NOT_FOUND;}@@ -820,7 +820,7 @@ static int pkgmap_safe_stat(const char *abs_path, struct stat *st) {* guarantee; this check is a best-effort early skip on top of it. */#ifdef _WIN32static bool pkgmap_is_reparse_point(const char *abs_path) {- wchar_t *wpath = cbm_utf8_to_wide(abs_path);+ wchar_t *wpath = cbm_path_to_wide(abs_path);if (!wpath) {return false;}diff --git a/src/store/store.c b/src/store/store.cindex 2a704eb5c..1d49d33d1 100644--- a/src/store/store.c+++ b/src/store/store.c@@ -664,7 +664,16 @@ static cbm_store_t *store_open_internal(const char *path, bool in_memory, bool cflags |= SQLITE_OPEN_MEMORY;}- int rc = sqlite3_open_v2(path, &s->db, flags, NULL);+ char open_path[4096];+ const char *effective_path = path;+ if (path && !in_memory) {+ if (!cbm_path_for_file_api(path, open_path, sizeof(open_path))) {+ free(s);+ return NULL;+ }+ effective_path = open_path;+ }+ int rc = sqlite3_open_v2(effective_path, &s->db, flags, NULL);if (rc != SQLITE_OK) {sqlite3_close(s->db);free(s);@@ -807,7 +816,12 @@ cbm_store_t *cbm_store_open_path_query(const char *db_path) {** No SQLITE_OPEN_CREATE on either path — a missing DB must return NULL* (no ghost .db for unknown/unindexed projects). */- int rc = sqlite3_open_v2(db_path, &s->db, SQLITE_OPEN_READONLY, NULL);+ char open_path[4096];+ if (!cbm_path_for_file_api(db_path, open_path, sizeof(open_path))) {+ free(s);+ return NULL;+ }+ int rc = sqlite3_open_v2(open_path, &s->db, SQLITE_OPEN_READONLY, NULL);if (rc == SQLITE_OK) {/* Force first DB access so a read-only-FS WAL failure surfaces now. */if (sqlite3_exec(s->db, "SELECT 1 FROM sqlite_master LIMIT 1;", NULL, NULL, NULL) !=diff --git a/src/ui/config.c b/src/ui/config.cindex 206ff4918..bb8eb3284 100644--- a/src/ui/config.c+++ b/src/ui/config.c@@ -53,7 +53,7 @@ static char *config_read_file(const char *path, size_t *length_out, bool *openedreturn NULL;}#ifdef _WIN32- wchar_t *wide_path = cbm_utf8_to_wide(path);+ wchar_t *wide_path = cbm_path_to_wide(path);if (!wide_path) {return NULL;}@@ -188,7 +188,7 @@ static bool config_parent_directory(const char *path, char *directory, size_t distatic volatile LONG g_config_temp_sequence = 0;static bool config_write_atomic(const char *path, const char *json, size_t json_length) {- wchar_t *wide_path = cbm_utf8_to_wide(path);+ wchar_t *wide_path = cbm_path_to_wide(path);if (!wide_path) {return false;}diff --git a/src/ui/http_server.c b/src/ui/http_server.cindex 9da078436..8bbdaab47 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -39,6 +39,7 @@#include <sqlite3/sqlite3.h>#include <yyjson/yyjson.h>+#include <ctype.h>#include <errno.h>#include <math.h>#include <stdatomic.h>@@ -72,12 +73,26 @@static char g_cors[256]; /* CORS headers only */static char g_cors_json[512]; /* CORS + Content-Type: application/json */-/* Inspect the Origin header and only reflect it if it's a localhost URL.- * This prevents remote websites from making cross-origin requests to the- * local graph-ui server (the key defense against CORS-based data exfil). */-static void update_cors(const cbm_http_req_t *req) {- if (req->origin[0] != '\0' && (cbm_http_path_match(req->origin, "http://localhost:*") ||- cbm_http_path_match(req->origin, "http://127.0.0.1:*"))) {+static bool origin_is_same_server(const char *origin, int port) {+ char expected[128];+ int length = snprintf(expected, sizeof(expected), "http://127.0.0.1:%d", port);+ if (length > 0 && (size_t)length < sizeof(expected) && strcmp(origin, expected) == 0)+ return true;+ length = snprintf(expected, sizeof(expected), "http://localhost:%d", port);+ return length > 0 && (size_t)length < sizeof(expected) && strcmp(origin, expected) == 0;+}++static bool origin_matches_host(const char *origin, const char *host, int port) {+ const char *hostname = strncmp(host, "localhost", 9) == 0 ? "localhost" : "127.0.0.1";+ char expected[128];+ int length = snprintf(expected, sizeof(expected), "http://%s:%d", hostname, port);+ return length > 0 && (size_t)length < sizeof(expected) && strcmp(origin, expected) == 0;+}++/* Foreign origins are rejected before this runs. Reflect only the exact+ * same-server origin; a different localhost port is a different principal. */+static void update_cors(const cbm_http_req_t *req, int port) {+ if (req->origin[0] != '\0' && origin_is_same_server(req->origin, port)) {snprintf(g_cors, sizeof(g_cors),"Access-Control-Allow-Origin: %s\r\n""Access-Control-Allow-Methods: POST, GET, DELETE, OPTIONS\r\n"@@ -129,6 +144,13 @@ static void handle_ui_config(cbm_http_conn_t *c, const cbm_http_req_t *req) {#define MAX_INDEX_JOBS 4+enum {+ HTTP_RUN_IDLE = 0,+ HTTP_RUN_SCHEDULED = 1,+ HTTP_RUN_RUNNING = 2,+ HTTP_RUN_COMPLETED = 3,+};+typedef struct {cbm_http_server_t *server;char root_path[1024];@@ -137,6 +159,7 @@ typedef struct {char error_msg[256];cbm_thread_t thread;bool thread_started;+ atomic_int completed;} index_job_t;struct cbm_http_server {@@ -150,6 +173,7 @@ struct cbm_http_server {void *mutation_context;index_job_t index_jobs[MAX_INDEX_JOBS];atomic_int stop_flag;+ atomic_int run_state;int port;bool listener_ok;};@@ -591,6 +615,14 @@ static void append_roots_json(char *buf, size_t bufsz, int *pos) {if (!(drives & (1u << i))) {continue;}+ /* Advertise exactly what /api/browse will accept: a mounted letter+ * without a readable medium (empty optical drive, unformatted or+ * offline volume) fails the same cbm_is_dir gate browse applies, and+ * a root the picker cannot open must not be offered. */+ char root[4] = {(char)('A' + i), ':', '/', '\0'};+ if (!cbm_is_dir(root)) {+ continue;+ }if (count++ > 0) {buf[(*pos)++] = ',';}@@ -880,12 +912,21 @@ static bool resolve_self_executable(char *out, size_t outsz) {}#elsestatic bool resolve_self_executable(char *out, size_t outsz) {- char buf[1024];- DWORD n = GetModuleFileNameA(NULL, buf, (DWORD)sizeof(buf));- if (n > 0 && n < sizeof(buf)) {- return copy_path(out, outsz, buf);+ /* GetModuleFileNameA renders the module path through the ANSI code page,+ * which mangles non-ASCII install paths (café_日本語 -> caf?_???). Resolve+ * wide and convert to UTF-8 so the returned path survives verbatim. */+ wchar_t wbuf[1024];+ DWORD n = GetModuleFileNameW(NULL, wbuf, (DWORD)(sizeof(wbuf) / sizeof(wbuf[0])));+ if (n == 0 || n >= sizeof(wbuf) / sizeof(wbuf[0])) {+ return false;}- return false;+ char *utf8 = cbm_wide_to_utf8(wbuf);+ if (!utf8) {+ return false;+ }+ bool ok = copy_path(out, outsz, utf8);+ free(utf8);+ return ok;}#endif@@ -904,7 +945,12 @@ bool cbm_http_server_resolve_binary_path(const char *argv0, char *out, size_t ou}#elseif (argv0 && argv0[0]) {- DWORD attrs = GetFileAttributesA(argv0);+ /* GetFileAttributesA reads argv0 through the ANSI code page and fails on+ * non-ASCII install paths, forcing a fallback that can mangle the path;+ * check wide so a valid non-ASCII argv0 is used verbatim. */+ wchar_t *wargv0 = cbm_utf8_to_wide(argv0);+ DWORD attrs = wargv0 ? GetFileAttributesW(wargv0) : INVALID_FILE_ATTRIBUTES;+ free(wargv0);if (attrs != INVALID_FILE_ATTRIBUTES && !(attrs & FILE_ATTRIBUTE_DIRECTORY)) {return copy_path(out, outsz, argv0);}@@ -943,6 +989,7 @@ static void *index_thread_fn(void *arg) {atomic_store(&job->status, 2);}cbm_log_info("ui.index.done", "path", job->root_path, "rc", result == 0 ? "ok" : "err");+ atomic_store_explicit(&job->completed, 1, memory_order_release);return NULL;}@@ -986,7 +1033,10 @@ static void handle_index_start(cbm_http_server_t *server, cbm_http_conn_t *c,int slot = -1;for (int i = 0; i < MAX_INDEX_JOBS; i++) {int st = atomic_load(&server->index_jobs[i].status);- if (st == 0 || st == 2 || st == 3) {+ bool reusable =+ !server->index_jobs[i].thread_started ||+ atomic_load_explicit(&server->index_jobs[i].completed, memory_order_acquire);+ if ((st == 0 || st == 2 || st == 3) && reusable) {slot = i;break;}@@ -999,7 +1049,10 @@ static void handle_index_start(cbm_http_server_t *server, cbm_http_conn_t *c,index_job_t *job = &server->index_jobs[slot];if (job->thread_started) {- (void)cbm_thread_join(&job->thread);+ if (cbm_thread_join(&job->thread) != 0) {+ cbm_http_replyf(c, 503, g_cors_json, "{\"error\":\"index worker unavailable\"}");+ return;+ }job->thread_started = false;}job->server = server;@@ -1007,11 +1060,13 @@ static void handle_index_start(cbm_http_server_t *server, cbm_http_conn_t *c,snprintf(job->project_name, sizeof(job->project_name), "%s", project_name);job->error_msg[0] = '\0';atomic_store(&job->status, 1);+ atomic_store_explicit(&job->completed, 0, memory_order_release);yyjson_doc_free(doc);/* Spawn background thread */if (cbm_thread_create(&job->thread, 0, index_thread_fn, job) != 0) {atomic_store(&job->status, 3);+ atomic_store_explicit(&job->completed, 1, memory_order_release);snprintf(job->error_msg, sizeof(job->error_msg), "thread creation failed");cbm_http_replyf(c, 500, g_cors_json, "{\"error\":\"thread creation failed\"}");return;@@ -1507,6 +1562,39 @@ static void handle_layout(cbm_http_conn_t *c, const cbm_http_req_t *req) {/* ── Handle JSON-RPC request ──────────────────────────────────── */+static yyjson_val *json_unique_member(yyjson_val *object, const char *name) {+ if (!yyjson_is_obj(object))+ return NULL;+ yyjson_val *found = NULL;+ size_t index, maximum;+ yyjson_val *key, *value;+ yyjson_obj_foreach(object, index, maximum, key, value) {+ if (strcmp(yyjson_get_str(key), name) == 0) {+ if (found)+ return NULL;+ found = value;+ }+ }+ return found;+}++static bool rpc_is_allowed_for_ui(const char *body, size_t body_len) {+ yyjson_doc *document = yyjson_read(body, body_len, 0);+ if (!document)+ return false;+ yyjson_val *root = yyjson_doc_get_root(document);+ yyjson_val *method = json_unique_member(root, "method");+ yyjson_val *params = json_unique_member(root, "params");+ yyjson_val *name = json_unique_member(params, "name");+ const char *method_text = yyjson_is_str(method) ? yyjson_get_str(method) : NULL;+ const char *name_text = yyjson_is_str(name) ? yyjson_get_str(name) : NULL;+ bool allowed =+ method_text && strcmp(method_text, "tools/call") == 0 && name_text &&+ (strcmp(name_text, "list_projects") == 0 || strcmp(name_text, "get_code_snippet") == 0);+ yyjson_doc_free(document);+ return allowed;+}+static void handle_rpc(cbm_http_conn_t *c, const cbm_http_req_t *req, cbm_mcp_server_t *mcp) {if (req->body_len == 0 || req->body_len > MAX_BODY_SIZE || !req->body) {cbm_http_replyf(c, 400, g_cors_json,@@ -1515,6 +1603,13 @@ static void handle_rpc(cbm_http_conn_t *c, const cbm_http_req_t *req, cbm_mcp_sereturn;}+ if (!rpc_is_allowed_for_ui(req->body, req->body_len)) {+ cbm_http_replyf(c, 403, g_cors_json,+ "{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32601,"+ "\"message\":\"UI RPC method is not allowed\"},\"id\":null}");+ return;+ }+/* req->body is NUL-terminated by the transport */char *response = cbm_mcp_server_handle(mcp, req->body);@@ -1528,31 +1623,68 @@ static void handle_rpc(cbm_http_conn_t *c, const cbm_http_req_t *req, cbm_mcp_se/* ── Request dispatch ─────────────────────────────────────────── */-/* True when the Host header names the loopback interface the server binds to- * (with or without a port). Anything else means the request reached us under a+/* True when the Host header names the loopback interface and exact port the+ * server binds to. Anything else means the request reached us under a* name that is not loopback — a rebinding DNS host or a proxy pointed at the* local port — which is the DNS-rebinding / cross-site vector against a* localhost-only service. */-static bool host_is_loopback(const char *host) {- return cbm_http_path_match(host, "localhost") || cbm_http_path_match(host, "localhost:*") ||- cbm_http_path_match(host, "127.0.0.1") || cbm_http_path_match(host, "127.0.0.1:*") ||- cbm_http_path_match(host, "[::1]") || cbm_http_path_match(host, "[::1]:*");+static bool host_is_this_server(const char *host, int port) {+ char expected[128];+ int length = snprintf(expected, sizeof(expected), "127.0.0.1:%d", port);+ if (length > 0 && (size_t)length < sizeof(expected) && strcmp(host, expected) == 0)+ return true;+ length = snprintf(expected, sizeof(expected), "localhost:%d", port);+ return length > 0 && (size_t)length < sizeof(expected) && strcmp(host, expected) == 0;+}++static bool route_is_protected(const char *path) {+ return strcmp(path, "/api") == 0 || strncmp(path, "/api/", 5) == 0 || strcmp(path, "/rpc") == 0;+}++static bool content_type_is_json(const char *content_type) {+ static const char json_type[] = "application/json";+ size_t type_length = sizeof(json_type) - 1;+ if (strlen(content_type) < type_length)+ return false;+ for (size_t i = 0; i < type_length; i++) {+ if (tolower((unsigned char)content_type[i]) != json_type[i])+ return false;+ }+ const char *suffix = content_type + type_length;+ while (*suffix == ' ' || *suffix == '\t')+ suffix++;+ return *suffix == '\0' || *suffix == ';';+}++static bool request_passes_http_security(cbm_http_server_t *srv, cbm_http_conn_t *c,+ const cbm_http_req_t *req) {+ if (req->http_minor == 1 && req->host[0] == '\0') {+ cbm_http_replyf(c, 400, "", "%s", "{\"error\":\"Host header required\"}");+ return false;+ }+ if (req->host[0] != '\0' && !host_is_this_server(req->host, srv->port)) {+ cbm_http_replyf(c, 403, "", "%s", "{\"error\":\"forbidden host\"}");+ return false;+ }+ if (req->origin[0] != '\0' &&+ (req->host[0] == '\0' || !origin_is_same_server(req->origin, srv->port) ||+ !origin_matches_host(req->origin, req->host, srv->port))) {+ cbm_http_replyf(c, 403, "", "%s", "{\"error\":\"forbidden origin\"}");+ return false;+ }+ update_cors(req, srv->port);+ bool is_post = strcmp(req->method, "POST") == 0;+ if (route_is_protected(req->path) && is_post && !content_type_is_json(req->content_type)) {+ cbm_http_replyf(c, 415, g_cors_json, "%s", "{\"error\":\"application/json required\"}");+ return false;+ }+ return true;}static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,const cbm_http_req_t *req) {- /* Build per-request CORS headers (only reflects localhost origins) */- update_cors(req);-- /* DNS-rebinding / cross-site guard: the server binds to loopback only, so a- * request carrying any non-loopback Host was routed here under a foreign- * name (a rebinding DNS record, a proxy) and must be refused before it can- * reach a state-changing endpoint. A bare request with no Host header- * (HTTP/1.0 local tooling) is still allowed. */- if (req->host[0] != '\0' && !host_is_loopback(req->host)) {- cbm_http_replyf(c, 403, g_cors, "%s", "{\"error\":\"forbidden host\"}");+ if (!request_passes_http_security(srv, c, req))return;- }bool is_get = strcmp(req->method, "GET") == 0;bool is_post = strcmp(req->method, "POST") == 0;@@ -1680,7 +1812,8 @@ cbm_http_server_t *cbm_http_server_new(int port) {return NULL;srv->port = port;- atomic_store(&srv->stop_flag, 0);+ atomic_init(&srv->stop_flag, 0);+ atomic_init(&srv->run_state, HTTP_RUN_IDLE);/* Create a dedicated MCP server for HTTP (own SQLite connection) */srv->mcp = cbm_mcp_server_new(NULL);@@ -1716,29 +1849,62 @@ cbm_http_server_t *cbm_http_server_new(int port) {return srv;}-void cbm_http_server_free(cbm_http_server_t *srv) {+bool cbm_http_server_free(cbm_http_server_t *srv) {if (!srv)- return;+ return true;+ int run_state = atomic_load_explicit(&srv->run_state, memory_order_acquire);+ if (run_state == HTTP_RUN_SCHEDULED || run_state == HTTP_RUN_RUNNING)+ return false;for (int i = 0; i < MAX_INDEX_JOBS; i++) {if (srv->index_jobs[i].thread_started) {- (void)cbm_thread_join(&srv->index_jobs[i].thread);+ if (!atomic_load_explicit(&srv->index_jobs[i].completed, memory_order_acquire))+ return false;+ if (cbm_thread_join(&srv->index_jobs[i].thread) != 0)+ return false;srv->index_jobs[i].thread_started = false;}}- cbm_httpd_close(srv->listener);+ if (!cbm_httpd_close(srv->listener))+ return false;cbm_mcp_server_free(srv->mcp);free(srv);+ return true;}void cbm_http_server_stop(cbm_http_server_t *srv) {if (srv) {atomic_store(&srv->stop_flag, 1);+ cbm_httpd_interrupt(srv->listener);}}-void cbm_http_server_run(cbm_http_server_t *srv) {+bool cbm_http_server_schedule_run(cbm_http_server_t *srv) {if (!srv || !srv->listener_ok)+ return false;+ int expected = HTTP_RUN_IDLE;+ return atomic_compare_exchange_strong_explicit(&srv->run_state, &expected, HTTP_RUN_SCHEDULED,+ memory_order_acq_rel, memory_order_acquire);+}++bool cbm_http_server_cancel_scheduled_run(cbm_http_server_t *srv) {+ if (!srv)+ return false;+ int expected = HTTP_RUN_SCHEDULED;+ return atomic_compare_exchange_strong_explicit(&srv->run_state, &expected, HTTP_RUN_IDLE,+ memory_order_acq_rel, memory_order_acquire);+}++void cbm_http_server_run(cbm_http_server_t *srv) {+ if (!srv)+ return;+ int expected = HTTP_RUN_SCHEDULED;+ if (!atomic_compare_exchange_strong_explicit(&srv->run_state, &expected, HTTP_RUN_RUNNING,+ memory_order_acq_rel, memory_order_acquire))+ return;+ if (!srv->listener_ok) {+ atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release);return;+ }while (!atomic_load(&srv->stop_flag)) {cbm_http_conn_t *conn = cbm_httpd_accept(srv->listener, 200);@@ -1749,6 +1915,11 @@ void cbm_http_server_run(cbm_http_server_t *srv) {cbm_http_req_t req;int rc = cbm_httpd_read_request(conn, &req);if (rc == 0) {+ if (atomic_load(&srv->stop_flag)) {+ cbm_http_req_free(&req);+ cbm_httpd_conn_close(conn);+ break;+ }dispatch_request(srv, conn, &req);cbm_log_http_request("graph_ui", req.method, req.path, cbm_http_conn_status(conn),(int64_t)(cbm_now_ms() - request_start_ms), req.body_len,@@ -1764,6 +1935,11 @@ void cbm_http_server_run(cbm_http_server_t *srv) {}cbm_httpd_conn_close(conn);}+ atomic_store_explicit(&srv->run_state, HTTP_RUN_COMPLETED, memory_order_release);+}++cbm_httpd_activity_t cbm_http_server_activity_for_test(cbm_http_server_t *srv) {+ return srv ? cbm_httpd_activity_for_test(srv->listener) : CBM_HTTPD_ACTIVITY_IDLE;}bool cbm_http_server_is_running(const cbm_http_server_t *srv) {diff --git a/src/ui/http_server.h b/src/ui/http_server.hindex 7544b7881..7e536023e 100644--- a/src/ui/http_server.h+++ b/src/ui/http_server.h@@ -10,6 +10,8 @@#ifndef CBM_UI_HTTP_SERVER_H#define CBM_UI_HTTP_SERVER_H+#include "ui/httpd.h"+#include <stdbool.h>#include <stddef.h>@@ -28,16 +30,27 @@ typedef void (*cbm_http_project_mutation_end_fn)(void *context, const char *proj* Returns NULL on failure (e.g. port in use). */cbm_http_server_t *cbm_http_server_new(int port);-/* Free the HTTP server (call after thread has been joined). */-void cbm_http_server_free(cbm_http_server_t *srv);+/* Free a quiescent HTTP server. Returns false without freeing if the run loop+ * or an index callback can still access it; callers must fail-stop rather than+ * continue cleanup in that state. */+bool cbm_http_server_free(cbm_http_server_t *srv);/* Signal the HTTP server to stop (safe to call from any thread). */void cbm_http_server_stop(cbm_http_server_t *srv);-/* Run the HTTP server event loop (call from background thread).+/* Claim a future run before handing the server pointer to a new thread. This+ * closes the create-to-child-start lifetime gap. If thread creation fails,+ * cancel the still-scheduled run before freeing. */+bool cbm_http_server_schedule_run(cbm_http_server_t *srv);+bool cbm_http_server_cancel_scheduled_run(cbm_http_server_t *srv);++/* Run the scheduled HTTP server event loop from the background thread.* Blocks until cbm_http_server_stop() is called. */void cbm_http_server_run(cbm_http_server_t *srv);+/* Observation-only phase seam for deterministic concurrency tests. */+cbm_httpd_activity_t cbm_http_server_activity_for_test(cbm_http_server_t *srv);+/* Check if the server started successfully (listener bound). */bool cbm_http_server_is_running(const cbm_http_server_t *srv);diff --git a/src/ui/httpd.c b/src/ui/httpd.cindex 7e41b46e4..b5b3ebb14 100644--- a/src/ui/httpd.c+++ b/src/ui/httpd.c@@ -6,8 +6,10 @@* single-threaded, localhost-only, strict CRLF, Connection: close).*/#include "ui/httpd.h"+#include "foundation/compat_thread.h"#include <ctype.h>+#include <limits.h>#include <stdarg.h>#include <stdatomic.h>#include <stdint.h>@@ -24,6 +26,7 @@ typedef SOCKET cbm_sock_t;#else#include <arpa/inet.h>#include <errno.h>+#include <fcntl.h>#include <netinet/in.h>#include <netinet/tcp.h>#include <poll.h>@@ -43,15 +46,31 @@ typedef int cbm_sock_t;#define CBM_SEND_FLAGS 0#endif+/* A non-reading peer may occupy the sequential event loop only briefly. */+#define CBM_HTTP_SEND_DEADLINE_MS 1000+#define CBM_HTTP_SEND_SLICE_BYTES (64U * 1024U)+#ifdef _WIN32+/* Winsock select() is not reliably interrupted by shutdown() from another+ * thread, so bound how long stop waits before re-checking the owner flag. */+#define CBM_HTTP_WAIT_SLICE_MS 50+#endif+struct cbm_httpd {cbm_sock_t fd;int port;int recv_deadline_ms;+ cbm_mutex_t active_mutex;+ struct cbm_http_conn *active;+ bool interrupted;+ int send_buffer_for_test;};struct cbm_http_conn {cbm_sock_t fd;+ cbm_httpd_t *owner;int recv_deadline_ms;+ int send_deadline_ms;+ atomic_bool response_started;int response_status;size_t response_bytes;};@@ -68,23 +87,28 @@ static int64_t now_ms(void) {#endif}-/* Wait until the socket is readable. 1 = readable, 0 = timeout, -1 = error.+/* Wait until the socket is readable/writable. 1 = ready, 0 = timeout, -1 = error.* Windows uses select() deliberately (WSAPoll has a Won't-Fix bug where* certain socket errors are never reported, which can stall an event loop). */-static int wait_readable(cbm_sock_t fd, int timeout_ms) {+static int wait_ready(cbm_sock_t fd, bool writing, int timeout_ms) {#ifdef _WIN32- fd_set rfds;- FD_ZERO(&rfds);- FD_SET(fd, &rfds);+ fd_set ready;+ fd_set errors;+ FD_ZERO(&ready);+ FD_ZERO(&errors);+ FD_SET(fd, &ready);+ FD_SET(fd, &errors);struct timeval tv;tv.tv_sec = timeout_ms / 1000;tv.tv_usec = (timeout_ms % 1000) * 1000;- int rc = select(0, &rfds, NULL, NULL, &tv);- return rc < 0 ? -1 : (rc > 0 ? 1 : 0);+ int rc = select(0, writing ? NULL : &ready, writing ? &ready : NULL, &errors, &tv);+ if (rc <= 0)+ return rc < 0 ? -1 : 0;+ return FD_ISSET(fd, &errors) ? -1 : 1;#elsestruct pollfd pfd;pfd.fd = fd;- pfd.events = POLLIN;+ pfd.events = writing ? POLLOUT : POLLIN;pfd.revents = 0;int rc = poll(&pfd, 1, timeout_ms);if (rc < 0)@@ -93,15 +117,95 @@ static int wait_readable(cbm_sock_t fd, int timeout_ms) {#endif}-static int send_all(cbm_sock_t fd, const void *data, size_t len) {+static int wait_readable(cbm_sock_t fd, int timeout_ms) {+ return wait_ready(fd, false, timeout_ms);+}++static bool socket_would_block(void) {+#ifdef _WIN32+ int error = WSAGetLastError();+ return error == WSAEWOULDBLOCK || error == WSAEINTR;+#else+ return errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR;+#endif+}++static bool socket_set_nonblocking(cbm_sock_t fd) {+#ifdef _WIN32+ u_long enabled = 1;+ return ioctlsocket(fd, FIONBIO, &enabled) == 0;+#else+ int flags = fcntl(fd, F_GETFL, 0);+ return flags >= 0 && fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0;+#endif+}++static void socket_shutdown(cbm_sock_t fd) {+#ifdef _WIN32+ (void)shutdown(fd, SD_BOTH);+#else+ (void)shutdown(fd, SHUT_RDWR);+#endif+}++static bool connection_interrupted(cbm_http_conn_t *connection) {+ cbm_httpd_t *owner = connection->owner;+ if (!owner)+ return false;+ cbm_mutex_lock(&owner->active_mutex);+ bool interrupted = owner->interrupted;+ cbm_mutex_unlock(&owner->active_mutex);+ return interrupted;+}++/* Wait against the caller's absolute deadline. Windows uses short select()+ * slices because shutdown() from the stop thread does not reliably wake a+ * Winsock select(); POSIX keeps its one-shot poll wait and shutdown fast path.+ * 1 = ready, 0 = original deadline expired, -1 = interrupted/error. */+static int wait_connection_ready(cbm_http_conn_t *connection, bool writing, int64_t deadline) {+ for (;;) {+ if (connection_interrupted(connection))+ return -1;++ int64_t remaining = deadline - now_ms();+ if (remaining <= 0)+ return 0;+ int timeout_ms = remaining > INT_MAX ? INT_MAX : (int)remaining;+#ifdef _WIN32+ if (timeout_ms > CBM_HTTP_WAIT_SLICE_MS)+ timeout_ms = CBM_HTTP_WAIT_SLICE_MS;+#endif++ int ready = wait_ready(connection->fd, writing, timeout_ms);+ if (connection_interrupted(connection))+ return -1;+ if (ready != 0)+ return ready;+ /* A Windows slice or POSIX EINTR is not the caller's timeout. */+ }+}++static int send_all(cbm_http_conn_t *connection, const void *data, size_t len, int64_t deadline) {const char *p = data;size_t off = 0;while (off < len) {+ if (wait_connection_ready(connection, true, deadline) != 1)+ return -1;+ size_t available = len - off;+ /* Bounded slices: a single nonblocking send() on Windows is absorbed+ * wholesale into AFD kernel buffers regardless of SO_SNDBUF, so one+ * giant call can never observe backpressure (and pins its full size+ * in nonpaged pool). Slicing keeps absorption bounded by the send+ * buffer so a non-reading peer hits EWOULDBLOCK deterministically. */+ if (available > CBM_HTTP_SEND_SLICE_BYTES)+ available = CBM_HTTP_SEND_SLICE_BYTES;#ifdef _WIN32- int n = send(fd, p + off, (int)(len - off), CBM_SEND_FLAGS);+ int n = send(connection->fd, p + off, (int)available, CBM_SEND_FLAGS);#else- ssize_t n = send(fd, p + off, len - off, CBM_SEND_FLAGS);+ ssize_t n = send(connection->fd, p + off, available, CBM_SEND_FLAGS);#endif+ if (n < 0 && socket_would_block())+ continue;if (n <= 0)return -1;off += (size_t)n;@@ -142,7 +246,8 @@ cbm_httpd_t *cbm_httpd_listen(int port) {addr.sin_port = htons((unsigned short)port);addr.sin_addr.s_addr = htonl(0x7F000001); /* 127.0.0.1 */- if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, 16) != 0) {+ if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, 16) != 0 ||+ !socket_set_nonblocking(fd)) {cbm_sock_close(fd);return NULL;}@@ -163,6 +268,7 @@ cbm_httpd_t *cbm_httpd_listen(int port) {d->fd = fd;d->port = (int)ntohs(bound.sin_port);d->recv_deadline_ms = CBM_HTTP_RECV_DEADLINE_MS;+ cbm_mutex_init(&d->active_mutex);return d;}@@ -171,15 +277,60 @@ int cbm_httpd_port(const cbm_httpd_t *d) {}void cbm_httpd_set_recv_deadline_ms(cbm_httpd_t *d, int ms) {- if (d && ms > 0)+ if (d && ms > 0) {+ cbm_mutex_lock(&d->active_mutex);d->recv_deadline_ms = ms;+ cbm_mutex_unlock(&d->active_mutex);+ }}-void cbm_httpd_close(cbm_httpd_t *d) {+void cbm_httpd_interrupt(cbm_httpd_t *d) {if (!d)return;+ cbm_mutex_lock(&d->active_mutex);+ d->interrupted = true;+ if (d->active)+ socket_shutdown(d->active->fd);+ cbm_mutex_unlock(&d->active_mutex);+}++bool cbm_httpd_close(cbm_httpd_t *d) {+ if (!d)+ return true;+ cbm_mutex_lock(&d->active_mutex);+ d->interrupted = true;+ if (d->active) {+ socket_shutdown(d->active->fd);+ cbm_mutex_unlock(&d->active_mutex);+ return false;+ }+ cbm_mutex_unlock(&d->active_mutex);cbm_sock_close(d->fd);+ cbm_mutex_destroy(&d->active_mutex);free(d);+ return true;+}++void cbm_httpd_set_send_buffer_for_test(cbm_httpd_t *d, int bytes) {+ if (!d)+ return;+ cbm_mutex_lock(&d->active_mutex);+ d->send_buffer_for_test = bytes;+ cbm_mutex_unlock(&d->active_mutex);+}++cbm_httpd_activity_t cbm_httpd_activity_for_test(cbm_httpd_t *d) {+ if (!d)+ return CBM_HTTPD_ACTIVITY_IDLE;+ cbm_mutex_lock(&d->active_mutex);+ cbm_httpd_activity_t activity = CBM_HTTPD_ACTIVITY_IDLE;+ if (d->active) {+ activity = atomic_load_explicit(&d->active->response_started, memory_order_acquire)+ ? CBM_HTTPD_ACTIVITY_RESPONDING+ : CBM_HTTPD_ACTIVITY_READING_REQUEST;+ }+ cbm_mutex_unlock(&d->active_mutex);+ return activity;}/* ── Accept ───────────────────────────────────────────────────── */@@ -187,6 +338,12 @@ void cbm_httpd_close(cbm_httpd_t *d) {cbm_http_conn_t *cbm_httpd_accept(cbm_httpd_t *d, int timeout_ms) {if (!d)return NULL;+ cbm_mutex_lock(&d->active_mutex);+ bool interrupted = d->interrupted;+ int send_buffer = d->send_buffer_for_test;+ cbm_mutex_unlock(&d->active_mutex);+ if (interrupted)+ return NULL;if (wait_readable(d->fd, timeout_ms) != 1)return NULL;@@ -196,24 +353,56 @@ cbm_http_conn_t *cbm_httpd_accept(cbm_httpd_t *d, int timeout_ms) {int one = 1;setsockopt(cfd, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof(one));+ /* An explicit SO_SNDBUF also disables Windows dynamic send buffering,+ * which otherwise grows kernel-side queuing past any fixed payload and+ * removes the backpressure point the deadline/interrupt tests rely on. */+ if (send_buffer > 0)+ setsockopt(cfd, SOL_SOCKET, SO_SNDBUF, (const char *)&send_buffer, sizeof(send_buffer));#ifdef SO_NOSIGPIPEsetsockopt(cfd, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof(one));#endif+ if (!socket_set_nonblocking(cfd)) {+ cbm_sock_close(cfd);+ return NULL;+ }+cbm_http_conn_t *c = calloc(1, sizeof(*c));if (!c) {cbm_sock_close(cfd);return NULL;}c->fd = cfd;+ c->owner = d;+ c->send_deadline_ms = CBM_HTTP_SEND_DEADLINE_MS;+ atomic_init(&c->response_started, false);++ cbm_mutex_lock(&d->active_mutex);+ if (d->interrupted || d->active) {+ cbm_mutex_unlock(&d->active_mutex);+ cbm_sock_close(cfd);+ free(c);+ return NULL;+ }c->recv_deadline_ms = d->recv_deadline_ms;+ d->active = c;+ cbm_mutex_unlock(&d->active_mutex);return c;}void cbm_httpd_conn_close(cbm_http_conn_t *c) {if (!c)return;- cbm_sock_close(c->fd);+ cbm_httpd_t *owner = c->owner;+ if (owner) {+ cbm_mutex_lock(&owner->active_mutex);+ if (owner->active == c)+ owner->active = NULL;+ cbm_sock_close(c->fd);+ cbm_mutex_unlock(&owner->active_mutex);+ } else {+ cbm_sock_close(c->fd);+ }free(c);}@@ -235,19 +424,21 @@ static bool header_name_is(const char *line, size_t name_len, const char *name)return name[name_len] == '\0' ? true : false;}-/* Copy a trimmed header value into out. */-static void copy_header_value(const char *val, const char *val_end, char *out, size_t outsz) {+/* Copy a trimmed header value into out. Oversize security headers are rejected,+ * never silently converted into an apparently absent header. */+static bool copy_header_value(const char *val, const char *val_end, char *out, size_t outsz) {while (val < val_end && (*val == ' ' || *val == '\t'))val++;while (val_end > val && (val_end[-1] == ' ' || val_end[-1] == '\t'))val_end--;size_t n = (size_t)(val_end - val);if (n >= outsz) {- out[0] = '\0'; /* oversize values are ignored, never truncated */- return;+ out[0] = '\0';+ return false;}memcpy(out, val, n);out[n] = '\0';+ return true;}int cbm_http_parse_head(const char *data, size_t len, cbm_http_req_t *req, size_t *body_offset,@@ -302,6 +493,7 @@ int cbm_http_parse_head(const char *data, size_t len, cbm_http_req_t *req, size_/* Exactly HTTP/1.0 or HTTP/1.1 */if (vlen != 8 || memcmp(version, "HTTP/1.", 7) != 0 || (version[7] != '0' && version[7] != '1'))return 400;+ req->http_minor = (unsigned char)(version[7] - '0');size_t tlen = (size_t)(sp2 - target);if (tlen == 0 || target[0] != '/')@@ -329,6 +521,10 @@ int cbm_http_parse_head(const char *data, size_t len, cbm_http_req_t *req, size_/* ── Header fields ── */bool have_content_length = false;+ bool have_origin = false;+ bool have_host = false;+ bool have_content_type = false;+ bool have_accept_language = false;const char *p = line_end + 2;const char *head_stop = data + head_end - 2; /* start of final CRLF */while (p < head_stop) {@@ -339,19 +535,34 @@ int cbm_http_parse_head(const char *data, size_t len, cbm_http_req_t *req, size_if (!colon)return 400;size_t nlen = (size_t)(colon - p);+ if (nlen == 0)+ return 400;if (header_name_is(p, nlen, "origin")) {- copy_header_value(colon + 1, eol, req->origin, sizeof(req->origin));+ if (have_origin || !copy_header_value(colon + 1, eol, req->origin, sizeof(req->origin)))+ return have_origin ? 400 : 431;+ have_origin = true;} else if (header_name_is(p, nlen, "host")) {- copy_header_value(colon + 1, eol, req->host, sizeof(req->host));+ if (have_host || !copy_header_value(colon + 1, eol, req->host, sizeof(req->host)))+ return have_host ? 400 : 431;+ have_host = true;+ } else if (header_name_is(p, nlen, "content-type")) {+ if (have_content_type ||+ !copy_header_value(colon + 1, eol, req->content_type, sizeof(req->content_type)))+ return have_content_type ? 400 : 431;+ have_content_type = true;} else if (header_name_is(p, nlen, "accept-language")) {- copy_header_value(colon + 1, eol, req->accept_language, sizeof(req->accept_language));+ if (have_accept_language || !copy_header_value(colon + 1, eol, req->accept_language,+ sizeof(req->accept_language)))+ return have_accept_language ? 400 : 431;+ have_accept_language = true;} else if (header_name_is(p, nlen, "transfer-encoding")) {/* Chunked (or any transfer coding) is not supported. */return 411;} else if (header_name_is(p, nlen, "content-length")) {char val[32];- copy_header_value(colon + 1, eol, val, sizeof(val));+ if (!copy_header_value(colon + 1, eol, val, sizeof(val)))+ return 431;if (val[0] == '\0')return 400;uint64_t cl = 0;@@ -391,12 +602,7 @@ int cbm_httpd_read_request(cbm_http_conn_t *c, cbm_http_req_t *req) {/* Read until the head parses (or fails to). */for (;;) {- int64_t remaining = deadline - now_ms();- if (remaining <= 0) {- free(head);- return 408;- }- int w = wait_readable(c->fd, (int)remaining);+ int w = wait_connection_ready(c, false, deadline);if (w == 0) {free(head);return 408;@@ -410,6 +616,8 @@ int cbm_httpd_read_request(cbm_http_conn_t *c, cbm_http_req_t *req) {#elsessize_t n = recv(c->fd, head + have, CBM_HTTP_MAX_HEAD - have, 0);#endif+ if (n < 0 && socket_would_block())+ continue;if (n <= 0) {free(head); /* peer vanished mid-request — nothing to answer */return -1;@@ -442,13 +650,7 @@ int cbm_httpd_read_request(cbm_http_conn_t *c, cbm_http_req_t *req) {memcpy(body, head + body_off, got);while (got < clen) {- int64_t remaining = deadline - now_ms();- if (remaining <= 0) {- free(body);- free(head);- return 408;- }- int w = wait_readable(c->fd, (int)remaining);+ int w = wait_connection_ready(c, false, deadline);if (w != 1) {free(body);free(head);@@ -459,6 +661,8 @@ int cbm_httpd_read_request(cbm_http_conn_t *c, cbm_http_req_t *req) {#elsessize_t n = recv(c->fd, body + got, clen - got, 0);#endif+ if (n < 0 && socket_would_block())+ continue;if (n <= 0) {free(body);free(head);@@ -505,12 +709,16 @@ static const char *status_reason(int status) {return "Length Required";case 413:return "Content Too Large";+ case 415:+ return "Unsupported Media Type";case 429:return "Too Many Requests";case 431:return "Request Header Fields Too Large";case 500:return "Internal Server Error";+ case 503:+ return "Service Unavailable";default:return "";}@@ -520,6 +728,7 @@ void cbm_http_reply_buf(cbm_http_conn_t *c, int status, const char *extra_headersize_t len) {if (!c)return;+ atomic_store_explicit(&c->response_started, true, memory_order_release);c->response_status = status;c->response_bytes = len;char head[1024];@@ -532,10 +741,11 @@ void cbm_http_reply_buf(cbm_http_conn_t *c, int status, const char *extra_headerstatus, status_reason(status), extra_headers ? extra_headers : "", len);if (hn < 0 || hn >= (int)sizeof(head))return; /* oversized extra_headers — drop the response, conn closes */- if (send_all(c->fd, head, (size_t)hn) != 0)+ int64_t deadline = now_ms() + c->send_deadline_ms;+ if (send_all(c, head, (size_t)hn, deadline) != 0)return;if (len > 0)- (void)send_all(c->fd, data, len);+ (void)send_all(c, data, len, deadline);}void cbm_http_replyf(cbm_http_conn_t *c, int status, const char *extra_headers, const char *fmt,diff --git a/src/ui/httpd.h b/src/ui/httpd.hindex d20d9a0f8..7e1afdfcc 100644--- a/src/ui/httpd.h+++ b/src/ui/httpd.h@@ -7,8 +7,8 @@* Design constraints (deliberate — do not "improve" without reading this):* - SINGLE-THREADED, sequential request handling. The routing layer* (http_server.c) keeps per-request state in static buffers; a thread- * pool would break it. One stalled client can hold the loop for at most- * the receive deadline (default 5 s) — acceptable for a localhost tool.+ * pool would break it. Reads and writes have hard deadlines, and stop+ * interrupts the event-loop-owned active socket from another thread.* - Binds 127.0.0.1 only (IPv4 loopback). Never any other interface.* - Every response carries explicit Content-Length and "Connection: close";* keep-alive is intentionally NOT implemented (smaller parsing surface;@@ -37,19 +37,27 @@#define CBM_HTTP_MAX_BODY (1024 * 1024)/* Default per-connection receive deadline. */#define CBM_HTTP_RECV_DEADLINE_MS 5000-typedef struct cbm_httpd cbm_httpd_t; /* listener */typedef struct cbm_http_conn cbm_http_conn_t; /* accepted connection */+/* Observable transport phase used by deterministic lifecycle tests. */+typedef enum {+ CBM_HTTPD_ACTIVITY_IDLE = 0,+ CBM_HTTPD_ACTIVITY_READING_REQUEST = 1,+ CBM_HTTPD_ACTIVITY_RESPONDING = 2,+} cbm_httpd_activity_t;+/* A parsed request. `path` and `query` are raw (NOT percent-decoded).- * `origin` and `accept_language` are the header values consumed by the- * routing layer ("" when absent). `body` is heap-allocated, NUL-terminated. */+ * Selected headers are copied for the routing/security layer ("" when+ * absent). `body` is heap-allocated and NUL-terminated. */typedef struct {char method[16];char path[2048];char query[2048];+ unsigned char http_minor; /* 0 for HTTP/1.0, 1 for HTTP/1.1 */char origin[256];char host[256];+ char content_type[128];char accept_language[256];char *body;size_t body_len;@@ -67,7 +75,21 @@ int cbm_httpd_port(const cbm_httpd_t *d);/* Override the per-connection receive deadline (tests use short values). */void cbm_httpd_set_recv_deadline_ms(cbm_httpd_t *d, int ms);-void cbm_httpd_close(cbm_httpd_t *d);+/* Interrupt the current accepted connection, if any. Safe from another+ * thread; the event-loop thread retains close/free ownership. */+void cbm_httpd_interrupt(cbm_httpd_t *d);++/* Interrupt and free a quiescent listener. Returns false without freeing while+ * an accepted connection still owns the listener; its event-loop owner must+ * close that connection before the caller retries. */+bool cbm_httpd_close(cbm_httpd_t *d);++/* Snapshot the active connection phase under the listener lifecycle lock.+ * This is an observation-only seam for deterministic concurrency tests. */+cbm_httpd_activity_t cbm_httpd_activity_for_test(cbm_httpd_t *d);+/* Caps SO_SNDBUF on subsequently accepted sockets so a non-reading peer+ * produces a deterministic backpressure point on every platform. */+void cbm_httpd_set_send_buffer_for_test(cbm_httpd_t *d, int bytes);/* ── Connection handling ──────────────────────────────────────── */@@ -114,8 +136,7 @@ int cbm_http_parse_head(const char *data, size_t len, cbm_http_req_t *req, size_size_t *content_length);/* Exact match, or prefix match when `pattern` ends with '*'.- * Used for both route patterns ("/api/layout*", "/assets" + star) and the- * CORS origin allow-list ("http://localhost:*", "http://127.0.0.1:*"). */+ * Used by route patterns such as "/api/layout*" and "/assets" + star. */bool cbm_http_path_match(const char *str, const char *pattern);/* Extract a query parameter value, percent-decoded (%XX and '+' → space).diff --git a/src/watcher/watcher.c b/src/watcher/watcher.cindex 6a4844137..38c1b0163 100644--- a/src/watcher/watcher.c+++ b/src/watcher/watcher.c@@ -30,8 +30,15 @@#include "foundation/compat_fs.h"#include "foundation/platform.h"#include "foundation/str_util.h"+#include "foundation/subprocess.h"+#ifdef _WIN32+#include "foundation/win_utf8.h"+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#endif#include <errno.h>+#include <limits.h>#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -48,22 +55,26 @@ typedef struct {* released. Unwatch/replacement tombstones a removed state so a later* snapshot entry cannot admit new indexing work. */atomic_bool registered;- char last_head[CBM_SZ_64]; /* git HEAD hash (committed baseline) */- bool is_git; /* false → skip polling */- bool baseline_done; /* true after first poll */- int missing_root_count; /* consecutive polls where root was missing (ENOENT/ENOTDIR) */- uint64_t first_missing_ms; /* cbm_now_ms() of the streak's first miss (0 = no streak) */- int file_count; /* approximate, for interval calc */- int interval_ms; /* adaptive poll interval */- int64_t next_poll_ns; /* next poll time (monotonic ns) */+ /* Published only while one supervised Git command is active. Access is+ * serialized by watcher->projects_lock; cancellation itself is atomic. */+ cbm_subprocess_t *active_git;+ /* Room for Git's 64-hex SHA-256 object ID plus newline/NUL while reading. */+ char last_head[CBM_SZ_128]; /* git HEAD hash (committed baseline) */+ bool is_git; /* false → skip polling */+ bool baseline_done; /* true after first poll */+ int missing_root_count; /* consecutive polls where root was missing (ENOENT/ENOTDIR) */+ uint64_t first_missing_ms; /* cbm_now_ms() of the streak's first miss (0 = no streak) */+ int file_count; /* approximate, for interval calc */+ int interval_ms; /* adaptive poll interval */+ int64_t next_poll_ns; /* next poll time (monotonic ns) *//* Dirty-state signature (#937): a persistently dirty worktree must* reindex once per DISTINCT dirty state, not on every poll. Baselines* are committed only after a SUCCESSFUL reindex (busy-skips and failed* runs retry); check_changes stages its observations in the pending_** fields. 0 = clean tree. */- uint64_t last_dirty_sig; /* committed dirty-state signature */- uint64_t pending_dirty_sig; /* observed at check time */- char pending_head[CBM_SZ_64]; /* HEAD observed at check time */+ uint64_t last_dirty_sig; /* committed dirty-state signature */+ uint64_t pending_dirty_sig; /* observed at check time */+ char pending_head[CBM_SZ_128]; /* HEAD observed at check time */} project_state_t;/* ── Watcher struct ─────────────────────────────────────────────── */@@ -110,6 +121,14 @@ struct cbm_watcher {/* Sleep chunk for responsive shutdown (ms) */#define SLEEP_CHUNK_MS 500+/* Git is external and repository-controlled configuration may activate slow+ * helpers (for example fsmonitor). Every invocation therefore has both a hard+ * wall-clock deadline and a finite capture budget. */+#define WATCHER_GIT_DEADLINE_MS 30000+#define WATCHER_GIT_OUTPUT_MAX (64U * 1024U * 1024U)+#define WATCHER_GIT_HEAD_MAX 4096U+#define WATCHER_GIT_POLL_US 10000U+/* ── Time helper ────────────────────────────────────────────────── */static int64_t now_ns(void) {@@ -130,49 +149,337 @@ int cbm_watcher_poll_interval_ms(int file_count) {/* ── Git helpers ────────────────────────────────────────────────── */-/* Portable command pieces: cbm_popen runs through cmd.exe on Windows, which does- * NOT strip single quotes (git would receive a literal-quoted path → "cannot find- * the path") and has no /dev/null. Use double quotes (stripped by both cmd.exe and- * POSIX sh) and the platform null device. */-#if defined(_WIN32)-#define WATCHER_NULDEV "NUL"+typedef struct {+ char path[CBM_SZ_4K];+ size_t size;+} watcher_git_output_t;++typedef enum {+ WATCHER_GIT_OK = 0,+ WATCHER_GIT_COMMAND_FAILED,+ WATCHER_GIT_CANCELLED,+ WATCHER_GIT_DEADLINE,+ WATCHER_GIT_OUTPUT_LIMIT,+ WATCHER_GIT_SUPERVISION_FAILED,+} watcher_git_status_t;++static void watcher_git_output_cleanup(watcher_git_output_t *output) {+ if (output && output->path[0]) {+ (void)cbm_unlink(output->path);+ output->path[0] = '\0';+ output->size = 0;+ }+}++static bool watcher_git_output_create(watcher_git_output_t *output) {+ if (!output) {+ return false;+ }+ memset(output, 0, sizeof(*output));+ int written =+ snprintf(output->path, sizeof(output->path), "%s/cbm-watcher-git-XXXXXX", cbm_tmpdir());+ if (written <= 0 || written >= (int)sizeof(output->path)) {+ output->path[0] = '\0';+ return false;+ }+ int descriptor = cbm_mkstemp(output->path);+ if (descriptor < 0) {+ output->path[0] = '\0';+ return false;+ }+#ifdef _WIN32+ bool closed = _close(descriptor) == 0;#else-#define WATCHER_NULDEV "/dev/null"+ bool closed = close(descriptor) == 0;#endif+ if (!closed) {+ watcher_git_output_cleanup(output);+ }+ return closed;+}-static bool is_git_repo(const char *root_path) {- char cmd[CBM_SZ_1K];- snprintf(cmd, sizeof(cmd), "git -C \"%s\" rev-parse --git-dir 2>%s", root_path, WATCHER_NULDEV);- FILE *fp = cbm_popen(cmd, "r");- if (!fp) {+#ifdef _WIN32+/* CreateProcessW does not search PATH when lpApplicationName is non-NULL.+ * Resolve Git ourselves, and deliberately accept only absolute PATH entries:+ * empty/relative entries would reintroduce Windows' current-directory search. */+static bool watcher_windows_path_absolute(const wchar_t *path) {+ if (!path || wcslen(path) < 3U) {return false;}- /* Drain output so pclose gets a clean exit status. */- char drain[CBM_SZ_128];- while (fgets(drain, (int)sizeof(drain), fp)) { /* discard */+ bool drive = ((path[0] >= L'A' && path[0] <= L'Z') || (path[0] >= L'a' && path[0] <= L'z')) &&+ path[1] == L':' && (path[2] == L'\\' || path[2] == L'/');+ bool unc = (path[0] == L'\\' || path[0] == L'/') && (path[1] == L'\\' || path[1] == L'/') &&+ path[2] != L'\0' && path[2] != L'\\' && path[2] != L'/';+ return drive || unc;+}++static bool watcher_windows_git_candidate(const wchar_t *entry, size_t entry_length,+ char output[CBM_SZ_4K]) {+ while (entry_length > 0U && (entry[0] == L' ' || entry[0] == L'\t')) {+ entry++;+ entry_length--;+ }+ while (entry_length > 0U &&+ (entry[entry_length - 1U] == L' ' || entry[entry_length - 1U] == L'\t')) {+ entry_length--;}- int rc = cbm_pclose(fp);- return rc == 0;+ if (entry_length >= 2U && entry[0] == L'"' && entry[entry_length - 1U] == L'"') {+ entry++;+ entry_length -= 2U;+ }+ while (entry_length > 0U && (entry[0] == L' ' || entry[0] == L'\t')) {+ entry++;+ entry_length--;+ }+ while (entry_length > 0U &&+ (entry[entry_length - 1U] == L' ' || entry[entry_length - 1U] == L'\t')) {+ entry_length--;+ }+ if (entry_length == 0U || entry_length >= CBM_SZ_4K) {+ return false;+ }+ wchar_t directory[CBM_SZ_4K];+ memcpy(directory, entry, entry_length * sizeof(*directory));+ directory[entry_length] = L'\0';+ if (!watcher_windows_path_absolute(directory) || wcschr(directory, L'"') != NULL) {+ return false;+ }++ bool separator = directory[entry_length - 1U] == L'\\' || directory[entry_length - 1U] == L'/';+ wchar_t candidate[CBM_SZ_4K];+ int written =+ swprintf(candidate, CBM_SZ_4K, separator ? L"%lsgit.exe" : L"%ls\\git.exe", directory);+ if (written <= 0 || written >= CBM_SZ_4K) {+ return false;+ }+ DWORD required = GetFullPathNameW(candidate, 0U, NULL, NULL);+ wchar_t *normalized =+ required > 0U ? malloc(((size_t)required + 1U) * sizeof(*normalized)) : NULL;+ DWORD normalized_length =+ normalized ? GetFullPathNameW(candidate, required + 1U, normalized, NULL) : 0U;+ if (!normalized || normalized_length == 0U || normalized_length > required ||+ !watcher_windows_path_absolute(normalized)) {+ free(normalized);+ return false;+ }+ HANDLE file = CreateFileW(normalized, GENERIC_READ | FILE_READ_ATTRIBUTES,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL);+ BY_HANDLE_FILE_INFORMATION information;+ bool regular = file != INVALID_HANDLE_VALUE && GetFileType(file) == FILE_TYPE_DISK &&+ GetFileInformationByHandle(file, &information) != 0 &&+ (information.dwFileAttributes &+ (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0;+ if (file != INVALID_HANDLE_VALUE) {+ (void)CloseHandle(file);+ }+ char *utf8 = regular ? cbm_wide_to_utf8(normalized) : NULL;+ size_t utf8_length = utf8 ? strlen(utf8) : 0U;+ bool valid = utf8 && utf8_length > 0U && utf8_length < CBM_SZ_4K;+ if (valid) {+ memcpy(output, utf8, utf8_length + 1U);+ }+ free(utf8);+ free(normalized);+ return valid;}-static int git_head(const char *root_path, char *out, size_t out_size) {- char cmd[CBM_SZ_1K];- snprintf(cmd, sizeof(cmd), "git -C \"%s\" rev-parse HEAD 2>%s", root_path, WATCHER_NULDEV);- FILE *fp = cbm_popen(cmd, "r");- if (!fp) {- return CBM_NOT_FOUND;+static bool watcher_resolve_git_executable(char output[CBM_SZ_4K]) {+ output[0] = '\0';+ DWORD required = GetEnvironmentVariableW(L"PATH", NULL, 0U);+ wchar_t *path = required > 0U ? malloc((size_t)required * sizeof(*path)) : NULL;+ DWORD length = path ? GetEnvironmentVariableW(L"PATH", path, required) : 0U;+ if (!path || length == 0U || length >= required) {+ free(path);+ return false;+ }+ const wchar_t *entry = path;+ for (const wchar_t *cursor = path;; cursor++) {+ if (*cursor != L';' && *cursor != L'\0') {+ continue;+ }+ if (watcher_windows_git_candidate(entry, (size_t)(cursor - entry), output)) {+ free(path);+ return true;+ }+ if (*cursor == L'\0') {+ break;+ }+ entry = cursor + 1;+ }+ free(path);+ return false;+}+#endif++/* Run one literal argv vector in a contained process tree. active_git is+ * published under projects_lock before supervision starts, so stop/unwatch can+ * request cancellation without racing destruction of the handle. */+static watcher_git_status_t watcher_git_run(cbm_watcher_t *w, project_state_t *state,+ const char *const *argv, size_t output_limit,+ watcher_git_output_t *output) {+ if (!w || !state || !argv || !argv[0]) {+ return WATCHER_GIT_SUPERVISION_FAILED;+ }+ if (output) {+ memset(output, 0, sizeof(*output));+ }+ if (output_limit > 0 && (!output || !watcher_git_output_create(output))) {+ return WATCHER_GIT_SUPERVISION_FAILED;+ }++#ifdef _WIN32+ char git_executable[CBM_SZ_4K];+ if (!watcher_resolve_git_executable(git_executable)) {+ watcher_git_output_cleanup(output);+ return WATCHER_GIT_SUPERVISION_FAILED;+ }+#endif++ cbm_proc_opts_t options = {+#ifdef _WIN32+ .bin = git_executable,+#else+ .bin = argv[0],+#endif+ .argv = argv,+ .log_file = output_limit > 0 ? output->path : NULL,+ /* A wall deadline below is authoritative. Binary `status -z` output+ * deliberately has no line-based quiet-timeout semantics. */+ .quiet_timeout_ms = 0,+ .cancel_grace_ms = CBM_SUBPROCESS_DEFAULT_CANCEL_GRACE_MS,+ .delete_log_on_exit = false,+ };+ cbm_subprocess_t *process = NULL;+ if (cbm_subprocess_spawn(&options, &process) != 0) {+ watcher_git_output_cleanup(output);+ return WATCHER_GIT_SUPERVISION_FAILED;}- if (fgets(out, (int)out_size, fp)) {- size_t len = strlen(out);- while (len > 0 && (out[len - SKIP_ONE] == '\n' || out[len - SKIP_ONE] == '\r')) {- out[--len] = '\0';+ bool cancelled = false;+ bool deadline_expired = false;+ bool output_exceeded = false;+ bool publication_conflict = false;+ cbm_mutex_lock(&w->projects_lock);+ if (state->active_git) {+ publication_conflict = true;+ cancelled = cbm_subprocess_request_cancel(process);+ } else {+ state->active_git = process;+ }+ if (!cancelled && (atomic_load_explicit(&w->stopped, memory_order_acquire) ||+ !atomic_load_explicit(&state->registered, memory_order_acquire))) {+ cancelled = cbm_subprocess_request_cancel(process);+ }+ cbm_mutex_unlock(&w->projects_lock);++ uint64_t started_at = cbm_now_ms();+ cbm_proc_result_t result = {0};+ for (;;) {+ uint64_t now = cbm_now_ms();+ if (!cancelled && (atomic_load_explicit(&w->stopped, memory_order_acquire) ||+ !atomic_load_explicit(&state->registered, memory_order_acquire))) {+ cancelled = cbm_subprocess_request_cancel(process);}- cbm_pclose(fp);- return 0;+ if (!cancelled && now - started_at >= WATCHER_GIT_DEADLINE_MS) {+ deadline_expired = true;+ cancelled = cbm_subprocess_request_cancel(process);+ }+ if (!cancelled && output_limit > 0) {+ int64_t observed_size = cbm_file_size(output->path);+ if (observed_size > 0 && (uint64_t)observed_size > output_limit) {+ output_exceeded = true;+ cancelled = cbm_subprocess_request_cancel(process);+ }+ }+ cbm_proc_poll_t polled = cbm_subprocess_poll(process, &result);+ if (polled == CBM_PROC_POLL_TERMINAL) {+ break;+ }+ if (polled == CBM_PROC_POLL_ERROR) {+ /* Valid owned handles have no ERROR transition. Fail closed, but+ * continue polling so the contained tree is never abandoned. */+ cancelled = cbm_subprocess_request_cancel(process) || cancelled;+ }+ cbm_usleep(WATCHER_GIT_POLL_US);}- cbm_pclose(fp);- return CBM_NOT_FOUND;++ cbm_mutex_lock(&w->projects_lock);+ if (state->active_git == process) {+ state->active_git = NULL;+ }+ cbm_mutex_unlock(&w->projects_lock);+ cbm_subprocess_destroy(process);++ watcher_git_status_t status = WATCHER_GIT_OK;+ if (publication_conflict || !result.tree_quiesced || result.supervision_failed) {+ status = WATCHER_GIT_SUPERVISION_FAILED;+ } else if (output_exceeded) {+ status = WATCHER_GIT_OUTPUT_LIMIT;+ } else if (deadline_expired) {+ status = WATCHER_GIT_DEADLINE;+ } else if (result.cancellation_requested || cancelled) {+ status = WATCHER_GIT_CANCELLED;+ } else if (result.outcome != CBM_PROC_CLEAN) {+ status = WATCHER_GIT_COMMAND_FAILED;+ }++ if (status == WATCHER_GIT_OK && output_limit > 0) {+ int64_t final_size = cbm_file_size(output->path);+ if (final_size < 0) {+ status = WATCHER_GIT_SUPERVISION_FAILED;+ } else if ((uint64_t)final_size > output_limit) {+ status = WATCHER_GIT_OUTPUT_LIMIT;+ } else {+ output->size = (size_t)final_size;+ }+ }+ if (status != WATCHER_GIT_OK) {+ watcher_git_output_cleanup(output);+ }+ if (status == WATCHER_GIT_DEADLINE || status == WATCHER_GIT_OUTPUT_LIMIT ||+ status == WATCHER_GIT_SUPERVISION_FAILED) {+ cbm_log_warn("watcher.git.failed", "project", state->project_name, "reason",+ status == WATCHER_GIT_DEADLINE+ ? "deadline"+ : (status == WATCHER_GIT_OUTPUT_LIMIT ? "output_limit" : "supervision"));+ }+ return status;+}++static watcher_git_status_t git_repo_status(cbm_watcher_t *w, project_state_t *state) {+ const char *argv[] = {"git", "-C", state->root_path, "rev-parse", "--git-dir", NULL};+ return watcher_git_run(w, state, argv, 0, NULL);+}++static watcher_git_status_t git_head(cbm_watcher_t *w, project_state_t *state, char *out,+ size_t out_size) {+ if (!out || out_size < 2) {+ return WATCHER_GIT_SUPERVISION_FAILED;+ }+ out[0] = '\0';+ const char *argv[] = {"git", "-C", state->root_path, "rev-parse", "HEAD", NULL};+ watcher_git_output_t output;+ watcher_git_status_t status = watcher_git_run(w, state, argv, WATCHER_GIT_HEAD_MAX, &output);+ if (status != WATCHER_GIT_OK) {+ return status;+ }+ FILE *file = cbm_fopen(output.path, "rb");+ bool read = file && fgets(out, (int)out_size, file) != NULL;+ int extra = file ? fgetc(file) : EOF;+ if (file) {+ read = fclose(file) == 0 && read;+ }+ watcher_git_output_cleanup(&output);+ if (!read || extra != EOF) {+ out[0] = '\0';+ return WATCHER_GIT_SUPERVISION_FAILED;+ }+ size_t len = strlen(out);+ while (len > 0 && (out[len - SKIP_ONE] == '\n' || out[len - SKIP_ONE] == '\r')) {+ out[--len] = '\0';+ }+ return len > 0 ? WATCHER_GIT_OK : WATCHER_GIT_COMMAND_FAILED;}/* ── Dirty-state signature (#937) ───────────────────────────────── */@@ -225,13 +532,25 @@ static uint64_t sig_fold_path_stat(uint64_t h, const char *root_path, const char* untracked directories individually (a nested addition under `?? dir/`* would otherwise be invisible); -z gives unquoted NUL-separated paths that* hash identically across polls and stat cleanly. */-static uint64_t git_dirty_signature(const char *root_path) {- char cmd[CBM_SZ_1K];- snprintf(cmd, sizeof(cmd), "git --no-optional-locks -C \"%s\" status --porcelain -uall -z 2>%s",- root_path, WATCHER_NULDEV);- FILE *fp = cbm_popen(cmd, "r");+static watcher_git_status_t git_dirty_signature(cbm_watcher_t *w, project_state_t *state,+ uint64_t *signature_out) {+ if (!signature_out) {+ return WATCHER_GIT_SUPERVISION_FAILED;+ }+ *signature_out = 0;+ const char *status_argv[] = {"git", "--no-optional-locks", "-C", state->root_path,+ "status", "--porcelain", "-uall", "-z",+ NULL};+ watcher_git_output_t output;+ watcher_git_status_t status =+ watcher_git_run(w, state, status_argv, WATCHER_GIT_OUTPUT_MAX, &output);+ if (status != WATCHER_GIT_OK) {+ return status;+ }+ FILE *fp = cbm_fopen(output.path, "rb");if (!fp) {- return 0;+ watcher_git_output_cleanup(&output);+ return WATCHER_GIT_SUPERVISION_FAILED;}uint64_t h = SIG_FNV_OFFSET;@@ -266,7 +585,7 @@ static uint64_t git_dirty_signature(const char *root_path) {if (entry[0] == 'R' || entry[0] == 'C') {origin_token = true;}- h = sig_fold_path_stat(h, root_path, entry + 3);+ h = sig_fold_path_stat(h, state->root_path, entry + 3);}}elen = 0;@@ -275,20 +594,37 @@ static uint64_t git_dirty_signature(const char *root_path) {break;}}- cbm_pclose(fp);+ bool parsed = !ferror(fp) && fclose(fp) == 0;+ watcher_git_output_cleanup(&output);+ if (!parsed) {+ return WATCHER_GIT_SUPERVISION_FAILED;+ }#if !defined(_WIN32)- /* Submodules (POSIX-only, mirroring git_is_dirty): fold each submodule's- * porcelain output with paths re-rooted at the superproject so they stat- * correctly. Line mode here (foreach output is line-oriented); rename- * lines fail the stat and degrade to text-only. */- snprintf(cmd, sizeof(cmd),- "git --no-optional-locks -C '%s' submodule foreach --quiet --recursive "- "'git status --porcelain -uall 2>/dev/null | "- "sed -e \"s@^\\(..\\) @\\1 $displaypath/@\"' 2>/dev/null",- root_path);- fp = cbm_popen(cmd, "r");- if (fp) {+ /* `submodule foreach` necessarily evaluates its final fixed argument in+ * Git's documented POSIX-shell environment. No repository/user text is+ * interpolated into that argument; the outer process is still argv-spawned+ * and its complete descendant tree remains supervised. */+ const char *submodule_argv[] = {+ "git",+ "--no-optional-locks",+ "-C",+ state->root_path,+ "submodule",+ "foreach",+ "--quiet",+ "--recursive",+ "git status --porcelain -uall 2>/dev/null | sed -e \"s@^\\(..\\) @\\1 $displaypath/@\"",+ NULL,+ };+ watcher_git_status_t submodule_status =+ watcher_git_run(w, state, submodule_argv, WATCHER_GIT_OUTPUT_MAX, &output);+ if (submodule_status == WATCHER_GIT_OK) {+ fp = cbm_fopen(output.path, "rb");+ if (!fp) {+ watcher_git_output_cleanup(&output);+ return WATCHER_GIT_SUPERVISION_FAILED;+ }char line[CBM_SZ_4K];while (fgets(line, sizeof(line), fp)) {size_t len = strlen(line);@@ -302,42 +638,60 @@ static uint64_t git_dirty_signature(const char *root_path) {h = sig_fold(h, line, len);h = sig_fold(h, "", 1);if (len > 3 && line[2] == ' ') {- h = sig_fold_path_stat(h, root_path, line + 3);+ h = sig_fold_path_stat(h, state->root_path, line + 3);}}- cbm_pclose(fp);+ parsed = !ferror(fp) && fclose(fp) == 0;+ watcher_git_output_cleanup(&output);+ if (!parsed) {+ return WATCHER_GIT_SUPERVISION_FAILED;+ }+ } else if (submodule_status != WATCHER_GIT_COMMAND_FAILED) {+ return submodule_status;}#endif- if (!any) {- return 0;- }- return h ? h : 1; /* reserve 0 for "clean" */+ *signature_out = any ? (h ? h : 1) : 0; /* reserve 0 for "clean" */+ return WATCHER_GIT_OK;}/* Count tracked files via git ls-files */-static int git_file_count(const char *root_path) {- char cmd[CBM_SZ_1K];- snprintf(cmd, sizeof(cmd), "git -C \"%s\" ls-files 2>%s", root_path, WATCHER_NULDEV);- FILE *fp = cbm_popen(cmd, "r");+static watcher_git_status_t git_file_count(cbm_watcher_t *w, project_state_t *state,+ int *count_out) {+ if (!count_out) {+ return WATCHER_GIT_SUPERVISION_FAILED;+ }+ *count_out = 0;+ const char *argv[] = {"git", "-C", state->root_path, "ls-files", "-z", NULL};+ watcher_git_output_t output;+ watcher_git_status_t status = watcher_git_run(w, state, argv, WATCHER_GIT_OUTPUT_MAX, &output);+ if (status != WATCHER_GIT_OK) {+ return status;+ }+ FILE *fp = cbm_fopen(output.path, "rb");if (!fp) {- return 0;+ watcher_git_output_cleanup(&output);+ return WATCHER_GIT_SUPERVISION_FAILED;}- /* Count newlines (one tracked file per line). `wc -l` is unavailable on- * Windows, so count in C, robust to paths longer than the read buffer. */+ /* NUL mode is unambiguous even for tracked filenames containing newlines. */int count = 0;char buf[CBM_SZ_1K];size_t n;while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {for (size_t i = 0; i < n; i++) {- if (buf[i] == '\n') {+ if (buf[i] == '\0' && count < INT_MAX) {count++;}}}- cbm_pclose(fp);- return count;+ if (ferror(fp) || fclose(fp) != 0) {+ watcher_git_output_cleanup(&output);+ return WATCHER_GIT_SUPERVISION_FAILED;+ }+ watcher_git_output_cleanup(&output);+ *count_out = count;+ return WATCHER_GIT_OK;}/* ── Project state lifecycle ────────────────────────────────────── */@@ -574,25 +928,24 @@ void cbm_watcher_set_project_mutation_guard(cbm_watcher_t *w,/* ── Watch list management ──────────────────────────────────────── */-void cbm_watcher_watch(cbm_watcher_t *w, const char *project_name, const char *root_path) {- if (!w || !project_name || !root_path) {- return;- }-- /* Reject paths with shell metacharacters — all git helpers use popen/system */- if (!cbm_validate_shell_arg(root_path)) {- cbm_log_warn("watcher.watch.reject", "project", project_name, "reason",- "path contains shell metacharacters");- return;+bool cbm_watcher_watch(cbm_watcher_t *w, const char *project_name, const char *root_path) {+ if (!w || !project_name || !project_name[0] || !root_path || !root_path[0] ||+ atomic_load_explicit(&w->stopped, memory_order_acquire)) {+ return false;}project_state_t *s = state_new(project_name, root_path);if (!s) {cbm_log_warn("watcher.watch.oom", "project", project_name, "path", root_path);- return;+ return false;}cbm_mutex_lock(&w->projects_lock);+ if (atomic_load_explicit(&w->stopped, memory_order_acquire)) {+ cbm_mutex_unlock(&w->projects_lock);+ state_free(s);+ return false;+ }project_state_t *old = cbm_ht_get(w->projects, project_name);if (old && strcmp(old->root_path, s->root_path) == 0) {/* Multiple daemon sessions may subscribe to the same canonical@@ -600,7 +953,7 @@ void cbm_watcher_watch(cbm_watcher_t *w, const char *project_name, const char *r* its git baseline, pending dirty signature, or immediate-touch state. */cbm_mutex_unlock(&w->projects_lock);state_free(s);- return;+ return true;}if (old) {/* A poll snapshot may still be using the old state, including while@@ -609,14 +962,39 @@ void cbm_watcher_watch(cbm_watcher_t *w, const char *project_name, const char *rif (!defer_state_free(w, old)) {cbm_mutex_unlock(&w->projects_lock);state_free(s);- return;+ return false;}- atomic_store_explicit(&old->registered, false, memory_order_release);cbm_ht_delete(w->projects, project_name);}cbm_ht_set(w->projects, s->project_name, s);+ bool registered = cbm_ht_get(w->projects, project_name) == s;+ if (!registered && old) {+ /* Restore the original table entry and remove the deferred-free slot.+ * The lock keeps this rollback invisible to poll/watch callers. */+ cbm_ht_set(w->projects, old->project_name, old);+ if (cbm_ht_get(w->projects, project_name) == old) {+ w->pending_free[--w->pending_free_count] = NULL;+ } else {+ atomic_store_explicit(&old->registered, false, memory_order_release);+ if (old->active_git) {+ (void)cbm_subprocess_request_cancel(old->active_git);+ }+ }+ }+ if (registered && old) {+ atomic_store_explicit(&old->registered, false, memory_order_release);+ if (old->active_git) {+ (void)cbm_subprocess_request_cancel(old->active_git);+ }+ }cbm_mutex_unlock(&w->projects_lock);+ if (!registered) {+ state_free(s);+ cbm_log_warn("watcher.watch.failed", "project", project_name, "reason", "registration");+ return false;+ }cbm_log_info("watcher.watch", "project", project_name, "path", root_path);+ return true;}void cbm_watcher_unwatch(cbm_watcher_t *w, const char *project_name) {@@ -630,6 +1008,9 @@ void cbm_watcher_unwatch(cbm_watcher_t *w, const char *project_name) {/* The entry leaves the table only once its state is safely on* the deferred-free list; on OOM the watch stays registered. */atomic_store_explicit(&s->registered, false, memory_order_release);+ if (s->active_git) {+ (void)cbm_subprocess_request_cancel(s->active_git);+ }cbm_ht_delete(w->projects, project_name);removed = true;}@@ -665,26 +1046,41 @@ int cbm_watcher_watch_count(cbm_watcher_t *w) {/* ── Single poll cycle ──────────────────────────────────────────── *//* Init baseline for a project: check if git, get HEAD, count files */-static void init_baseline(project_state_t *s) {+static bool init_baseline(cbm_watcher_t *w, project_state_t *s) {struct stat st;if (stat(s->root_path, &st) != 0) {cbm_log_warn("watcher.root_gone", "project", s->project_name, "path", s->root_path);s->baseline_done = true;s->is_git = false;- return;+ return true;}- s->is_git = is_git_repo(s->root_path);+ watcher_git_status_t repository_status = git_repo_status(w, s);+ if (repository_status != WATCHER_GIT_OK && repository_status != WATCHER_GIT_COMMAND_FAILED) {+ return false;+ }+ s->is_git = repository_status == WATCHER_GIT_OK;s->baseline_done = true;if (s->is_git) {- git_head(s->root_path, s->last_head, sizeof(s->last_head));+ watcher_git_status_t head_status = git_head(w, s, s->last_head, sizeof(s->last_head));+ if (head_status != WATCHER_GIT_OK && head_status != WATCHER_GIT_COMMAND_FAILED) {+ s->baseline_done = false;+ return false;+ }/* last_dirty_sig stays 0 ("clean known"): a tree that is ALREADY* dirty at baseline reindexes once on the first poll — the watcher* cannot know whether that state made it into the DB (e.g. server* restart with a stale artifact). At-least-once, then the signature* gates further polls (#937). */- s->file_count = git_file_count(s->root_path);+ int file_count = 0;+ watcher_git_status_t file_count_status = git_file_count(w, s, &file_count);+ if (file_count_status != WATCHER_GIT_OK &&+ file_count_status != WATCHER_GIT_COMMAND_FAILED) {+ s->baseline_done = false;+ return false;+ }+ s->file_count = file_count;s->interval_ms = cbm_watcher_poll_interval_ms(s->file_count);cbm_log_info("watcher.baseline", "project", s->project_name, "strategy", "git", "files",s->file_count > 0 ? "yes" : "0");@@ -693,6 +1089,7 @@ static void init_baseline(project_state_t *s) {}s->next_poll_ns = now_ns() + ((int64_t)s->interval_ms * US_PER_MS);+ return true;}/* Check if a project has changes. Returns true if reindex needed.@@ -700,17 +1097,22 @@ static void init_baseline(project_state_t *s) {* poll_project commits them only after a SUCCESSFUL reindex so that* busy-skips and failed runs retry instead of silently losing the change* (#937). Observations are staged in the pending_* fields. */-static bool check_changes(project_state_t *s) {- if (!s->is_git) {+static bool check_changes(cbm_watcher_t *w, project_state_t *s, bool *changed_out) {+ if (!changed_out) {return false;}+ *changed_out = false;+ if (!s->is_git) {+ return true;+ }bool changed = false;/* Check HEAD movement (commit, checkout, pull) */s->pending_head[0] = '\0';- char head[CBM_SZ_64] = {0};- if (git_head(s->root_path, head, sizeof(head)) == 0) {+ char head[CBM_SZ_128] = {0};+ watcher_git_status_t head_status = git_head(w, s, head, sizeof(head));+ if (head_status == WATCHER_GIT_OK) {if (s->last_head[0] == '\0') {/* First observed HEAD: adopt as baseline, not a change. */snprintf(s->last_head, sizeof(s->last_head), "%s", head);@@ -718,18 +1120,30 @@ static bool check_changes(project_state_t *s) {changed = true;}snprintf(s->pending_head, sizeof(s->pending_head), "%s", head);+ } else if (head_status != WATCHER_GIT_COMMAND_FAILED) {+ return false;}/* Working tree: reindex only when the DIRTY STATE ITSELF changed —* a persistently dirty tree polled while idle must not re-trigger* full reindex/write cycles (#937 write amplification). */- uint64_t sig = git_dirty_signature(s->root_path);+ uint64_t sig = 0;+ watcher_git_status_t signature_status = git_dirty_signature(w, s, &sig);+ if (signature_status == WATCHER_GIT_COMMAND_FAILED) {+ /* The repository may have been removed between baseline and poll.+ * Preserve committed observations and wait for a later clean probe. */+ return true;+ }+ if (signature_status != WATCHER_GIT_OK) {+ return false;+ }if (sig != s->last_dirty_sig) {changed = true;}s->pending_dirty_sig = sig;- return changed;+ *changed_out = changed;+ return true;}/* Context for poll_once foreach callback */@@ -852,7 +1266,7 @@ static void poll_project(const char *key, void *val, void *ud) {/* Initialize baseline on first poll */if (!s->baseline_done) {- init_baseline(s);+ (void)init_baseline(ctx->w, s);return;}@@ -867,7 +1281,10 @@ static void poll_project(const char *key, void *val, void *ud) {}/* Check for changes */- bool changed = check_changes(s);+ bool changed = false;+ if (!check_changes(ctx->w, s, &changed)) {+ return;+ }if (!changed) {s->next_poll_ns = ctx->now + ((int64_t)s->interval_ms * US_PER_MS);return;@@ -894,8 +1311,11 @@ static void poll_project(const char *key, void *val, void *ud) {}s->last_dirty_sig = s->pending_dirty_sig;/* Refresh file count for interval */- s->file_count = git_file_count(s->root_path);- s->interval_ms = cbm_watcher_poll_interval_ms(s->file_count);+ int file_count = 0;+ if (git_file_count(ctx->w, s, &file_count) == WATCHER_GIT_OK) {+ s->file_count = file_count;+ s->interval_ms = cbm_watcher_poll_interval_ms(s->file_count);+ }} else if (rc > 0) {/* Busy-skip: baseline stays uncommitted, next poll retries. */cbm_log_info("watcher.index.retry", "project", s->project_name);@@ -966,9 +1386,27 @@ int cbm_watcher_poll_once(cbm_watcher_t *w) {/* ── Blocking run loop ──────────────────────────────────────────── */+static void cancel_active_git_entry(const char *key, void *value, void *user_data) {+ (void)key;+ (void)user_data;+ project_state_t *state = value;+ if (state && state->active_git) {+ (void)cbm_subprocess_request_cancel(state->active_git);+ }+}+void cbm_watcher_stop(cbm_watcher_t *w) {if (w) {- atomic_store(&w->stopped, 1);+ atomic_store_explicit(&w->stopped, 1, memory_order_release);+ cbm_mutex_lock(&w->projects_lock);+ cbm_ht_foreach(w->projects, cancel_active_git_entry, NULL);+ for (int i = 0; i < w->pending_free_count; i++) {+ project_state_t *state = w->pending_free[i];+ if (state && state->active_git) {+ (void)cbm_subprocess_request_cancel(state->active_git);+ }+ }+ cbm_mutex_unlock(&w->projects_lock);}}diff --git a/src/watcher/watcher.h b/src/watcher/watcher.hindex 699013250..2a30cbb4f 100644--- a/src/watcher/watcher.h+++ b/src/watcher/watcher.h@@ -61,8 +61,10 @@ void cbm_watcher_set_project_mutation_guard(cbm_watcher_t *w,/* ── Watch list management ──────────────────────────────────────── */-/* Add a project to the watch list. root_path is copied. */-void cbm_watcher_watch(cbm_watcher_t *w, const char *project_name, const char *root_path);+/* Add a project to the watch list. root_path is copied. Returns true only when+ * the physical registration exists (including an identical existing watch).+ * A stopped watcher rejects new registrations. */+bool cbm_watcher_watch(cbm_watcher_t *w, const char *project_name, const char *root_path);/* Remove a project from the watch list. Any not-yet-admitted callback in the* current poll snapshot is invalidated before this function returns. */diff --git a/test-infrastructure/Dockerfile b/test-infrastructure/Dockerfileindex 52b272528..59e11a7da 100644--- a/test-infrastructure/Dockerfile+++ b/test-infrastructure/Dockerfile@@ -9,12 +9,16 @@FROM ubuntu:noble# Minimal: gcc + zlib only. sqlite3 is vendored (compiled from source with ASan).+# curl + zsh mirror the GitHub runner images: the self-update tests shell out+# to curl, and the shell-activation tests exercise zsh rc files.RUN apt-get update && apt-get install -y --no-install-recommends \gcc g++ make \zlib1g-dev \pkg-config \python3 \git \+ curl \+ zsh \ccache \ca-certificates \&& rm -rf /var/lib/apt/lists/*diff --git a/test-infrastructure/docker-compose.yml b/test-infrastructure/docker-compose.ymlindex 6d28d91ac..89080e616 100644--- a/test-infrastructure/docker-compose.yml+++ b/test-infrastructure/docker-compose.yml@@ -8,17 +8,16 @@services:# ── Linux test (ASan + UBSan + LeakSanitizer) ──────────────- # Default: unconstrained (speed first). CBM_LOCAL_CI_CPUS=4 enables- # CI-FIDELITY mode, mirroring the 4-core GitHub runners: deadline/starvation- # bugs (worker-readiness waits, watcher/subprocess deadlines) only reproduce- # under that constraint — run one capped pass before pushing anything that- # touches timing, scheduling, or subprocess code.+ # Always full-parallel: the suite is designed to be core-count-independent+ # for correctness — timing/scheduling/subprocess suites assert invariants+ # (ordering, bounded-return, RUNNING poll state), not wall-clock, so they+ # pass at any parallelism. Artificial CPU starvation belongs to smoke/soak+ # (CBM_LOCAL_CI_CPUS), not the regular suite.test:build:context: ..dockerfile: test-infrastructure/Dockerfileplatform: linux/arm64- cpus: ${CBM_LOCAL_CI_CPUS:-0}volumes:- ..:/src- cbm-ccache-arm64:/root/.ccache@@ -32,7 +31,6 @@ services:context: ..dockerfile: test-infrastructure/Dockerfileplatform: linux/amd64- cpus: ${CBM_LOCAL_CI_CPUS:-0}volumes:- ..:/src- cbm-ccache-amd64:/root/.ccache@@ -131,11 +129,16 @@ services:WINEDEBUG=-all scripts/smoke-test.sh ./build/win-cross/codebase-memory-mcp.exe# ── Windows soak (cross-compile + Wine) ───────────────────+ # Soak is the one place a CPU cap is meaningful: sustained runs under+ # deliberate resource starvation surface scheduling/backpressure behaviour the+ # full-parallel correctness suite does not target. Opt in with+ # CBM_LOCAL_CI_CPUS=<n>; default 0 = unlimited, so normal soak runs stay fast.soak-windows:build:context: ..dockerfile: test-infrastructure/Dockerfile.mingwplatform: linux/amd64+ cpus: ${CBM_LOCAL_CI_CPUS:-0}volumes:- ..:/srcentrypoint: ["/bin/bash", "-c"]diff --git a/test-infrastructure/run.sh b/test-infrastructure/run.shindex 43c33d267..017f4ecce 100755--- a/test-infrastructure/run.sh+++ b/test-infrastructure/run.sh@@ -10,11 +10,14 @@# vm/win.sh for mandatory real-Windows verification]# macOS: run natively (not in Docker)#-# Speed first: test containers run unconstrained by default. Before pushing-# anything that touches timing, scheduling, or subprocess code, run ONE pass-# with CBM_LOCAL_CI_CPUS=4 (CI-fidelity mode, mirrors the 4-core GitHub-# runners) — deadline/starvation failures only reproduce under that-# constraint. ccache persists in named volumes; entries are content-verified+# Full power, always: the test containers run unconstrained — the suite is+# built to be core-count-independent for correctness (timing/scheduling/+# subprocess suites assert invariants — ordering, bounded-return, RUNNING poll+# state — not wall-clock), so it passes at any parallelism and there is no+# reason to throttle it. The CBM_LOCAL_CI_CPUS knob survives only for the+# smoke/soak services, where deliberate resource starvation is the point; it is+# NOT a pre-push gate for the regular suite. ccache persists in named volumes;+# entries are content-verified# (stale hits impossible), so warm reruns skip unchanged compilation.# Run this from the WORKTREE you want tested: the containers mount the repo# this script resides in.diff --git a/test-infrastructure/vm/provision-windows.sh b/test-infrastructure/vm/provision-windows.shold mode 100644new mode 100755index 31c3a3e52..dc50986cc--- a/test-infrastructure/vm/provision-windows.sh+++ b/test-infrastructure/vm/provision-windows.sh@@ -86,6 +86,19 @@ if [ "${1:-}" != "--update" ]; thenmingw-w64-clang-aarch64-python mingw-w64-clang-aarch64-ccache \mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-compiler-rt \mingw-w64-clang-x86_64-zlib mingw-w64-clang-x86_64-ccache"++ step "3b/6 official Node.js + VC++ runtime (guards UI build)"+ # MSVC-built npm native modules (rollup) cannot resolve Node-API symbols+ # against MSYS2's mingw node, and they need the VC++ runtime. Pinned+ # official builds, hash/signature-verified.+ NODE_VERSION="v22.23.1"+ NODE_SHA256="b470fdfe3502c05151656e06d495e3f47544f2ee8b1d9c8705090f2dd5996bd0"+ if ! vm_cmd "if exist C:\\node\\node.exe echo NODE_PRESENT" | grep -q NODE_PRESENT; then+ vm_cmd "powershell -NoProfile -Command \"\$ProgressPreference='SilentlyContinue'; Invoke-WebRequest -Uri 'https://nodejs.org/dist/${NODE_VERSION}/node-${NODE_VERSION}-win-arm64.zip' -OutFile C:\\node.zip; \$actual=(Get-FileHash -LiteralPath C:\\node.zip -Algorithm SHA256).Hash.ToLowerInvariant(); if (\$actual -ne '${NODE_SHA256}') { Remove-Item C:\\node.zip; throw 'node SHA-256 mismatch' }; Expand-Archive -LiteralPath C:\\node.zip -DestinationPath C:\\; Move-Item C:\\node-${NODE_VERSION}-win-arm64 C:\\node; Remove-Item C:\\node.zip\""+ fi+ if ! vm_cmd "if exist C:\\Windows\\System32\\vcruntime140.dll echo VCR_PRESENT" | grep -q VCR_PRESENT; then+ vm_cmd "powershell -NoProfile -Command \"\$ProgressPreference='SilentlyContinue'; Invoke-WebRequest -Uri 'https://aka.ms/vs/17/release/vc_redist.arm64.exe' -OutFile C:\\vc_redist.arm64.exe; \$sig = Get-AuthenticodeSignature C:\\vc_redist.arm64.exe; if (\$sig.Status -ne 'Valid') { throw 'vc_redist unsigned' }; Start-Process C:\\vc_redist.arm64.exe -ArgumentList '/install','/quiet','/norestart' -Wait; Remove-Item C:\\vc_redist.arm64.exe\""+ fifistep "4/6 repo clone/update -> /c/cbm @ ${BRANCH}"diff --git a/test-infrastructure/vm/vm-smoke.sh b/test-infrastructure/vm/vm-smoke.shold mode 100644new mode 100755diff --git a/test-infrastructure/vm/win.sh b/test-infrastructure/vm/win.shindex 6de6596a8..f64cf85ed 100644--- a/test-infrastructure/vm/win.sh+++ b/test-infrastructure/vm/win.sh@@ -58,6 +58,7 @@ SCP=(scp "${SSH_OPTIONS[@]}")vm() { local env="$1"; shift"${SSH[@]}" "C:\\msys64\\msys2_shell.cmd -defterm -no-start -${env} -c \"set -e -o pipefail; $*\""; }+vm_cmd() { "${SSH[@]}" "$@"; } # plain cmd.exe (CI-shaped environment)cmd="${1:-status}"; shift || truecase "$cmd" in@@ -111,8 +112,21 @@ guards)# Match the Windows CI product build: a clean, embedded-UI payload plus the# permanent launcher. Passing those freshly built artifacts to the maintained# PowerShell driver prevents an earlier non-UI `win.sh build` from silently- # turning product guards into precondition skips.- vm clangarm64 "cd /c/cbm && scripts/build.sh --with-ui CC=clang CXX=clang++ SANITIZE= && powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/test-windows.ps1 -GuardsOnly -Binary build/c/codebase-memory-mcp.exe -Launcher build/c/codebase-memory-mcp-launcher.exe"+ # turning product guards into precondition skips. BUILD_DIR isolates the+ # clean product build from build/c, which build.sh would otherwise wipe —+ # taking the test-runner and every incremental object with it. The UI build+ # needs the official MSVC Node.js (/c/node, from provision-windows.sh):+ # MSVC-built npm native modules cannot resolve Node-API symbols against+ # MSYS2's mingw node.+ vm clangarm64 "export PATH=/c/node:\$PATH && cd /c/cbm && scripts/build.sh --with-ui CC=clang CXX=clang++ SANITIZE= BUILD_DIR=build/guards"+ # The guards themselves run through plain cmd/PowerShell, exactly like the+ # CI job: under the MSYS2 shell TMP is C:\msys64\tmp, whose ancestry+ # grants mutation rights to Authenticated Users — the daemon's+ # cache-private validation (correctly) refuses caches there, which is a+ # different environment shape than CI's profile-rooted TEMP. Python must+ # be PREPENDED: the Microsoft Store python.exe alias stub lives early in+ # the profile PATH and otherwise shadows any appended interpreter.+ vm_cmd "cd /d C:\\cbm && set PATH=C:\\msys64\\clangarm64\\bin;C:\\msys64\\usr\\bin;%PATH%&& powershell -NoProfile -ExecutionPolicy Bypass -File scripts\\test-windows.ps1 -GuardsOnly -Binary build\\guards\\codebase-memory-mcp.exe -Launcher build\\guards\\codebase-memory-mcp-launcher.exe -Make C:\\msys64\\usr\\bin\\make.exe";;smoke-install)# Real managed install E2E with FULL stderr visible — the exact class thediff --git a/tests/test_activation_transaction.c b/tests/test_activation_transaction.cindex 681c277e8..290a07135 100644--- a/tests/test_activation_transaction.c+++ b/tests/test_activation_transaction.c@@ -458,6 +458,51 @@ TEST(activation_transaction_stage_file_installs_new_target) {PASS();}+TEST(activation_transaction_stage_file_survives_long_target_path) {+ /* Managed installs and CI runners place the generation store far below a+ * deep profile path; the full store path routinely exceeds the legacy+ * 260-char limit. The activation transaction's own file operations must+ * carry those paths (extended-length form on Windows). */+ char base[ACTIVATION_TEST_PATH_CAP];+ ASSERT_TRUE(th_secure_runtime_parent_new(base, sizeof(base), "act-longpath"));+ static const char segment[] = "gen-abcdefghijklmnopqrstuvwxyz0123456789-abcdefghij";+ char deep[ACTIVATION_TEST_PATH_CAP];+ int written = snprintf(deep, sizeof(deep), "%s", base);+ ASSERT_TRUE(written > 0 && written < (int)sizeof(deep));+ /* Append segments until the store path comfortably exceeds the legacy+ * 260-char Windows limit, regardless of the (platform-dependent) base. */+ while (strlen(deep) <= 320U) {+ size_t used = strlen(deep);+ written = snprintf(deep + used, sizeof(deep) - used, "/%s", segment);+ ASSERT_TRUE(written > 0 && (size_t)written < sizeof(deep) - used);+ }+ ASSERT_TRUE(strlen(deep) > 300);+ ASSERT_TRUE(cbm_mkdir_p(deep, 0700));++ char source[ACTIVATION_TEST_PATH_CAP];+ char target[ACTIVATION_TEST_PATH_CAP];+ ASSERT_TRUE(activation_test_path(source, deep, "downloaded-cbm"));+ ASSERT_TRUE(activation_test_path(target, deep, "cbm"));+ ASSERT_TRUE(activation_test_write(source, "downloaded"));++ cbm_activation_transaction_t *transaction = NULL;+ ASSERT_EQ(cbm_activation_transaction_stage_file(target, source, &transaction),+ CBM_ACTIVATION_TRANSACTION_OK);+ activation_test_validation_t validation = {+ .expect_absent = false,+ .expected_contents = "downloaded",+ };+ ASSERT_EQ(cbm_activation_transaction_commit(transaction, activation_test_validate, &validation),+ CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_finalize(transaction), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_close(&transaction), CBM_ACTIVATION_TRANSACTION_OK);+ char contents[ACTIVATION_TEST_CONTENT_CAP];+ ASSERT_TRUE(activation_test_read(target, contents));+ ASSERT_STR_EQ(contents, "downloaded");+ ASSERT_EQ(th_rmtree(base), 0);+ PASS();+}+TEST(activation_transaction_removal_can_rollback_or_finalize) {char directory[ACTIVATION_TEST_PATH_CAP];char target[ACTIVATION_TEST_PATH_CAP];@@ -922,6 +967,7 @@ SUITE(activation_transaction) {RUN_TEST(activation_transaction_validation_failure_restores_previous_target);RUN_TEST(activation_transaction_explicit_rollback_restores_previous_target);RUN_TEST(activation_transaction_stage_file_installs_new_target);+ RUN_TEST(activation_transaction_stage_file_survives_long_target_path);RUN_TEST(activation_transaction_removal_can_rollback_or_finalize);RUN_TEST(activation_transaction_rejects_cross_account_writable_target_directory);RUN_TEST(activation_transaction_rejects_windows_callback_allow_directory_ace);diff --git a/tests/test_build_dir_safety.sh b/tests/test_build_dir_safety.shnew file mode 100644index 000000000..5294e6f61--- /dev/null+++ b/tests/test_build_dir_safety.sh@@ -0,0 +1,77 @@+#!/usr/bin/env bash+# Regression guard: build cleanup paths must stay within one direct child of+# the repository's build/ directory. A malformed BUILD_DIR must be rejected+# before any rm invocation can observe it.++set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"++# shellcheck source=../scripts/path-safety.sh+source "$ROOT/scripts/path-safety.sh"++for path in build/c build/linux-arm64 build/linux-amd64 build/win-cross; do+ cbm_require_safe_build_dir "$path"+done++for path in \+ "" \+ build \+ build/ \+ . \+ .. \+ ../outside \+ /tmp/outside \+ build/../outside \+ build/./c \+ build//c \+ build/nested/c \+ 'build\..\outside'; do+ if cbm_require_safe_build_dir "$path" >/dev/null 2>&1; then+ echo "FAIL: unsafe BUILD_DIR was accepted: '$path'" >&2+ exit 1+ fi+done++# Lexical containment is not enough: an attacker-controlled or accidental+# build/ symlink would make ROOT/build/c traverse outside the repository.+symlink_fixture="$(mktemp -d "${TMPDIR:-/tmp}/cbm-build-dir-symlink.XXXXXX")"+trap 'rm -rf -- "$symlink_fixture"' EXIT+mkdir -p "$symlink_fixture/repo" "$symlink_fixture/outside"+ln -s "$symlink_fixture/outside" "$symlink_fixture/repo/build"+if (+ cd "$symlink_fixture/repo"+ cbm_require_safe_build_dir build/c "$symlink_fixture/repo"+); then+ echo "FAIL: BUILD_DIR accepted a symlinked build/ ancestor" >&2+ exit 1+fi++mkdir -p "$symlink_fixture/safe-repo/build" "$symlink_fixture/final-target"+printf 'keep\n' >"$symlink_fixture/final-target/sentinel"+ln -s "$symlink_fixture/final-target" "$symlink_fixture/safe-repo/build/c"+if ! cbm_remove_build_dir "$symlink_fixture/safe-repo" build/c; then+ echo "FAIL: safe removal rejected a final-component symlink" >&2+ exit 1+fi+if [ -e "$symlink_fixture/safe-repo/build/c" ] ||+ [ ! -f "$symlink_fixture/final-target/sentinel" ]; then+ echo "FAIL: final-component symlink removal followed the link" >&2+ exit 1+fi+mkdir -p "$symlink_fixture/safe-repo/build/ordinary"+printf 'remove\n' >"$symlink_fixture/safe-repo/build/ordinary/artifact"+cbm_remove_build_dir "$symlink_fixture/safe-repo" build/ordinary+if [ -e "$symlink_fixture/safe-repo/build/ordinary" ]; then+ echo "FAIL: ordinary build child was not removed" >&2+ exit 1+fi++# Direct Makefile cleanup is a public developer entrypoint too; it must use+# the same guard instead of interpolating an untrusted value into a shell.+if make -s -f "$ROOT/Makefile.cbm" clean-c BUILD_DIR=build/nested/c >/dev/null 2>&1; then+ echo "FAIL: make clean-c accepted an unsafe BUILD_DIR" >&2+ exit 1+fi++echo "Build directory safety contract passed"diff --git a/tests/test_daemon_application.c b/tests/test_daemon_application.cindex 8ad5d933d..218ab13c3 100644--- a/tests/test_daemon_application.c+++ b/tests/test_daemon_application.c@@ -77,9 +77,8 @@ static bool app_project_lock_fixture_init(app_project_lock_fixture_t *fixture) {return false;}memset(fixture, 0, sizeof(*fixture));- (void)snprintf(fixture->runtime_parent, sizeof(fixture->runtime_parent),- "%s/cbm-app-project-lock-XXXXXX", cbm_tmpdir());- if (!cbm_mkdtemp(fixture->runtime_parent)) {+ if (!th_secure_runtime_parent_new(fixture->runtime_parent, sizeof(fixture->runtime_parent),+ "app-project-lock")) {return false;}fixture->endpoint = cbm_daemon_ipc_endpoint_new("fedcba9876543210", fixture->runtime_parent);@@ -111,6 +110,28 @@ static bool app_project_lock_release(cbm_project_lock_lease_t **lease) {return *lease == NULL;}+/* Windows may briefly report an overlapping byte-range lock as BUSY while the+ * just-completed worker's handle close becomes visible to another manager.+ * Accept only that bounded handoff; IO/UNSAFE failures remain immediate. */+static cbm_private_file_lock_status_t app_project_lock_try_acquire_until_released(+ cbm_project_lock_manager_t *manager, const char *project,+ cbm_project_lock_lease_t **lease_out) {+ if (!lease_out) {+ return CBM_PRIVATE_FILE_LOCK_UNSAFE;+ }+ *lease_out = NULL;+ uint64_t deadline = cbm_now_ms() + APP_TEST_TIMEOUT_MS;+ cbm_private_file_lock_status_t status = CBM_PRIVATE_FILE_LOCK_BUSY;+ do {+ status = cbm_project_lock_try_acquire(manager, project, lease_out);+ if (status != CBM_PRIVATE_FILE_LOCK_BUSY) {+ return status;+ }+ cbm_usleep(1000);+ } while (cbm_now_ms() < deadline);+ return status;+}+static cbm_daemon_runtime_application_session_t *app_test_open(const cbm_daemon_runtime_application_callbacks_t *callbacks, cbm_daemon_client_id_t client_id) {return callbacks->session_open(callbacks->context, client_id, 1234);@@ -606,10 +627,21 @@ static bool app_test_create_empty_file(const char *path) {static int app_test_git(const char *root, const char *operation, const char *argument_one,const char *argument_two) {- const char *argv[] = {"git", "-C", root, operation, argument_one, argument_two, NULL};+ const char *git = "git";+#ifdef _WIN32+ char git_executable[APP_TEST_PATH_CAP];+ const char *resolved = cbm_find_cli("git", cbm_get_home_dir());+ int resolved_length =+ resolved ? snprintf(git_executable, sizeof(git_executable), "%s", resolved) : -1;+ if (resolved_length <= 0 || (size_t)resolved_length >= sizeof(git_executable)) {+ return -1;+ }+ git = git_executable;+#endif+ const char *argv[] = {git, "-C", root, operation, argument_one, argument_two, NULL};cbm_proc_opts_t options = {0};cbm_proc_result_t result = {0};- options.bin = "git";+ options.bin = git;options.argv = argv;options.quiet_timeout_ms = 10000;return cbm_subprocess_run(&options, &result) == 0 && result.outcome == CBM_PROC_CLEAN ? 0 : -1;@@ -3937,7 +3969,8 @@ TEST(daemon_application_worker_lock_serializes_external_mutation) {cbm_project_lock_lease_t *terminal_other_probe = NULL;cbm_private_file_lock_status_t terminal_other_status =other_worker_acquired- ? cbm_project_lock_try_acquire(locks.probe_locks, other_project, &terminal_other_probe)+ ? app_project_lock_try_acquire_until_released(locks.probe_locks, other_project,+ &terminal_other_probe): CBM_PRIVATE_FILE_LOCK_IO;bool other_lock_released_at_terminal =terminal_other_status == CBM_PRIVATE_FILE_LOCK_OK && terminal_other_probe;@@ -3956,7 +3989,8 @@ TEST(daemon_application_worker_lock_serializes_external_mutation) {cbm_project_lock_lease_t *blocked_probe = NULL;cbm_private_file_lock_status_t terminal_blocked_status =blocked_worker_acquired- ? cbm_project_lock_try_acquire(locks.probe_locks, blocked_project, &blocked_probe)+ ? app_project_lock_try_acquire_until_released(locks.probe_locks, blocked_project,+ &blocked_probe): CBM_PRIVATE_FILE_LOCK_IO;bool blocked_lock_released_at_terminal =terminal_blocked_status == CBM_PRIVATE_FILE_LOCK_OK && blocked_probe;diff --git a/tests/test_daemon_bootstrap.c b/tests/test_daemon_bootstrap.cindex f95b1900b..d0e557a03 100644--- a/tests/test_daemon_bootstrap.c+++ b/tests/test_daemon_bootstrap.c@@ -218,7 +218,9 @@ static bool bootstrap_fake_handoff(void *opaque, cbm_daemon_bootstrap_lock_t locstatic bool bootstrap_fake_spawn(void *opaque, const cbm_daemon_bootstrap_launch_spec_t *spec) {bootstrap_fake_ops_t *fake = opaque;- bool exact = spec && spec->argc == CBM_DAEMON_BOOTSTRAP_LAUNCH_ARGC && spec->argv[0] &&+ /* Client bootstrap must only ever spawn the EPHEMERAL two-argument+ * shape; the permanent shape belongs exclusively to `daemon start`. */+ bool exact = spec && spec->argc == 2U && spec->argv[0] &&spec->argv[1] && !spec->argv[2] &&strcmp(spec->argv[1], CBM_DAEMON_INTERNAL_ARG) == 0 && spec->detached &&!spec->inherit_standard_handles && !spec->use_shell &&@@ -366,7 +368,7 @@ TEST(daemon_bootstrap_uses_one_stable_per_account_endpoint) {TEST(daemon_bootstrap_launches_only_exact_detached_hidden_role) {cbm_daemon_bootstrap_launch_spec_t spec;ASSERT_TRUE(cbm_daemon_bootstrap_launch_spec_init("/tmp/cbm exact", &spec));- ASSERT_EQ(spec.argc, CBM_DAEMON_BOOTSTRAP_LAUNCH_ARGC);+ ASSERT_EQ(spec.argc, 2U);ASSERT_STR_EQ(spec.executable_path, "/tmp/cbm exact");ASSERT_STR_EQ(spec.argv[0], "/tmp/cbm exact");ASSERT_STR_EQ(spec.argv[1], CBM_DAEMON_INTERNAL_ARG);@@ -377,6 +379,54 @@ TEST(daemon_bootstrap_launches_only_exact_detached_hidden_role) {PASS();}+TEST(daemon_bootstrap_permanent_daemon_argv_is_byte_exact) {+ char *permanent[] = {"codebase-memory-mcp", CBM_DAEMON_INTERNAL_ARG, CBM_DAEMON_PERMANENT_ARG,+ NULL};+ char *reordered[] = {"codebase-memory-mcp", CBM_DAEMON_PERMANENT_ARG, CBM_DAEMON_INTERNAL_ARG,+ NULL};+ char *repeated[] = {"codebase-memory-mcp", CBM_DAEMON_INTERNAL_ARG, CBM_DAEMON_INTERNAL_ARG,+ NULL};+ char *extended[] = {"codebase-memory-mcp", CBM_DAEMON_INTERNAL_ARG, CBM_DAEMON_PERMANENT_ARG,+ "extra", NULL};+ char *wrong_flag[] = {"codebase-memory-mcp", CBM_DAEMON_INTERNAL_ARG, "--permanent", NULL};+ ASSERT_EQ(classify(3, permanent), CBM_DAEMON_PROCESS_DAEMON);+ ASSERT_EQ(classify(3, reordered), CBM_DAEMON_PROCESS_INVALID);+ ASSERT_EQ(classify(3, repeated), CBM_DAEMON_PROCESS_INVALID);+ ASSERT_EQ(classify(4, extended), CBM_DAEMON_PROCESS_INVALID);+ ASSERT_EQ(classify(3, wrong_flag), CBM_DAEMON_PROCESS_INVALID);+ PASS();+}++TEST(daemon_bootstrap_daemon_ctl_token_routes_after_cli) {+ char *start[] = {"codebase-memory-mcp", "daemon", "start", NULL};+ char *stop[] = {"codebase-memory-mcp", "daemon", "stop", NULL};+ char *status[] = {"codebase-memory-mcp", "daemon", "status", NULL};+ char *help[] = {"codebase-memory-mcp", "daemon", "--help", NULL};+ /* `daemon` after `cli` is opaque tool input, never a control command. */+ char *opaque[] = {"codebase-memory-mcp", "cli", "search_code", "daemon", "start", NULL};+ ASSERT_EQ(classify(3, start), CBM_DAEMON_PROCESS_DAEMON_CTL);+ ASSERT_EQ(classify(3, stop), CBM_DAEMON_PROCESS_DAEMON_CTL);+ ASSERT_EQ(classify(3, status), CBM_DAEMON_PROCESS_DAEMON_CTL);+ ASSERT_EQ(classify(3, help), CBM_DAEMON_PROCESS_STATELESS);+ ASSERT_EQ(classify(5, opaque), CBM_DAEMON_PROCESS_LOCAL_CLI);+ ASSERT_FALSE(cbm_daemon_process_role_requires_client(CBM_DAEMON_PROCESS_DAEMON_CTL));+ PASS();+}++TEST(daemon_bootstrap_permanent_launch_spec_is_exact) {+ cbm_daemon_bootstrap_launch_spec_t spec;+ ASSERT_TRUE(cbm_daemon_bootstrap_launch_spec_init_permanent("/tmp/cbm exact", &spec));+ ASSERT_EQ(spec.argc, 3U);+ ASSERT_STR_EQ(spec.argv[0], "/tmp/cbm exact");+ ASSERT_STR_EQ(spec.argv[1], CBM_DAEMON_INTERNAL_ARG);+ ASSERT_STR_EQ(spec.argv[2], CBM_DAEMON_PERMANENT_ARG);+ ASSERT_NULL(spec.argv[3]);+ ASSERT_TRUE(spec.detached);+ ASSERT_FALSE(spec.inherit_standard_handles);+ ASSERT_FALSE(spec.use_shell);+ PASS();+}+TEST(daemon_bootstrap_stateless_roles_bypass_every_daemon_operation) {bootstrap_fake_ops_t fake = {0};cbm_daemon_bootstrap_ops_t ops = bootstrap_fake_callbacks(&fake);@@ -725,6 +775,9 @@ SUITE(daemon_bootstrap) {RUN_TEST(daemon_bootstrap_rejects_ambiguous_internal_daemon_argv);RUN_TEST(daemon_bootstrap_uses_one_stable_per_account_endpoint);RUN_TEST(daemon_bootstrap_launches_only_exact_detached_hidden_role);+ RUN_TEST(daemon_bootstrap_permanent_daemon_argv_is_byte_exact);+ RUN_TEST(daemon_bootstrap_daemon_ctl_token_routes_after_cli);+ RUN_TEST(daemon_bootstrap_permanent_launch_spec_is_exact);RUN_TEST(daemon_bootstrap_stateless_roles_bypass_every_daemon_operation);RUN_TEST(daemon_bootstrap_cohort_conflict_is_visible_before_probe_or_spawn);RUN_TEST(daemon_bootstrap_existing_exact_daemon_connects_without_spawn);diff --git a/tests/test_daemon_frontend.c b/tests/test_daemon_frontend.cindex b21d116b4..56040b71b 100644--- a/tests/test_daemon_frontend.c+++ b/tests/test_daemon_frontend.c@@ -36,9 +36,9 @@ typedef struct {static bool frontend_maintenance_fixture_start(frontend_maintenance_fixture_t *fixture,const char *tag) {memset(fixture, 0, sizeof(*fixture));- int written = snprintf(fixture->parent, sizeof(fixture->parent), "%s/cbm-frontend-%s-XXXXXX",- cbm_tmpdir(), tag);- if (written <= 0 || written >= (int)sizeof(fixture->parent) || !cbm_mkdtemp(fixture->parent)) {+ /* Endpoint parents need production-shaped ancestry (LocalAppData on+ * Windows); temp roots are refused by the runtime ancestry validation. */+ if (!th_secure_runtime_parent_new(fixture->parent, sizeof(fixture->parent), tag)) {return false;}fixture->endpoint = cbm_daemon_ipc_endpoint_new("0123456789abcdef", fixture->parent);diff --git a/tests/test_daemon_ipc.c b/tests/test_daemon_ipc.cindex 045d7202b..b9cd6b95f 100644--- a/tests/test_daemon_ipc.c+++ b/tests/test_daemon_ipc.c@@ -6,6 +6,7 @@* domain sockets on POSIX and current-user named pipes on Windows.*/#include "test_framework.h"+#include "test_helpers.h"#include "daemon/daemon.h"#include "daemon/ipc.h"@@ -63,8 +64,12 @@ static bool ipc_test_write_byte(const char *path, unsigned char byte);#endifstatic bool ipc_test_parent_new(char out[TEST_PATH_CAP], const char *tag) {- int n = snprintf(out, TEST_PATH_CAP, "%s/cbm-ipc-%s-XXXXXX", cbm_tmpdir(), tag);- return n > 0 && n < TEST_PATH_CAP && cbm_mkdtemp(out) != NULL;+ /* Endpoint parents must carry production-shaped ancestry: the runtime+ * ancestry validation (correctly) refuses temp roots whose ancestors+ * grant mutation rights to Authenticated Users, e.g. C:/msys64/tmp and+ * GitHub-runner work directories. th_secure_runtime_parent_new anchors+ * under LocalAppData on Windows, like the production default parent. */+ return th_secure_runtime_parent_new(out, TEST_PATH_CAP, tag);}static void ipc_test_copy_path(char out[TEST_PATH_CAP], const char *path) {@@ -655,6 +660,11 @@ TEST(daemon_ipc_windows_default_endpoint_ignores_temp_environment) {}if (endpoint_a) {int startup_status = cbm_daemon_ipc_startup_lock_try_acquire(endpoint_a, &startup);+ /* Publish the generation record: the address under test exists only+ * after a startup owner prepares the handoff. */+ if (startup_status == 1 && !cbm_daemon_ipc_startup_lock_prepare_handoff(startup)) {+ startup_status = -1;+ }cbm_daemon_ipc_startup_lock_release(&startup);startup = NULL;if (startup_status != 1) {@@ -1519,6 +1529,15 @@ TEST(daemon_ipc_endpoint_is_namespaced_by_instance_key) {int a_startup_status = a ? cbm_daemon_ipc_startup_lock_try_acquire(a, &a_startup) : -1;int other_startup_status =other ? cbm_daemon_ipc_startup_lock_try_acquire(other, &other_startup) : -1;+ /* Windows addresses are generation-bound and exist only once a startup+ * owner publishes the rendezvous record; drive the documented flow. */+ if (a_startup_status == 1 && !cbm_daemon_ipc_startup_lock_prepare_handoff(a_startup)) {+ a_startup_status = -1;+ }+ if (other_startup_status == 1 &&+ !cbm_daemon_ipc_startup_lock_prepare_handoff(other_startup)) {+ other_startup_status = -1;+ }cbm_daemon_ipc_startup_lock_release(&a_startup);cbm_daemon_ipc_startup_lock_release(&other_startup);a_startup = NULL;diff --git a/tests/test_daemon_runtime.c b/tests/test_daemon_runtime.cindex ff54b2b1c..c697853dc 100644--- a/tests/test_daemon_runtime.c+++ b/tests/test_daemon_runtime.c@@ -1240,17 +1240,14 @@ static bool runtime_test_fixture_start_failed(const char *tag, const char *stagereturn false;}+static bool runtime_test_fixture_permanent = false;+static bool runtime_test_fixture_start_configured(runtime_test_fixture_t *fixture, const char *tag, const cbm_daemon_build_identity_t *identity,uint32_t max_clients, uint64_t lease_timeout_ms,const cbm_daemon_runtime_application_callbacks_t *application) {memset(fixture, 0, sizeof(*fixture));- int parent_written = snprintf(fixture->parent, sizeof(fixture->parent),- "%s/cbm-runtime-%s-XXXXXX", cbm_tmpdir(), tag);- if (parent_written <= 0 || parent_written >= (int)sizeof(fixture->parent)) {- return runtime_test_fixture_start_failed(tag, "temporary-path", parent_written);- }- if (!cbm_mkdtemp(fixture->parent)) {+ if (!th_secure_runtime_parent_new(fixture->parent, sizeof(fixture->parent), tag)) {return runtime_test_fixture_start_failed(tag, "temporary-directory",runtime_test_last_os_error());}@@ -1293,6 +1290,9 @@ static bool runtime_test_fixture_start_configured(.lease_timeout_ms = lease_timeout_ms,.request_timeout_ms = RUNTIME_TEST_TIMEOUT_MS,.shutdown_timeout_ms = RUNTIME_TEST_TIMEOUT_MS,+ /* Default false: every teardown-latency fixture depends on prompt+ * last-client-exit. Only the permanent-lifecycle tests flip this. */+ .permanent = runtime_test_fixture_permanent,};if (application) {config.application = *application;@@ -1402,7 +1402,9 @@ static bool runtime_test_read_log(const char *path, char out[RUNTIME_TEST_LOG_CA/* A detached daemon loses its inherited stderr by design. Failures before the* runtime listener exists must therefore reach the owner-private operation log* or users and smoke tests see only a generic bootstrap timeout. An existing- * daemon claim deterministically fails before runtime startup. */+ * daemon claim deterministically fails before runtime startup on POSIX. The+ * Windows same-process participant guard rejects the nested host one stage+ * earlier, and that platform-correct refusal must be equally durable. */TEST(daemon_host_early_coordination_failure_is_durable) {const char *old_cache = getenv("CBM_CACHE_DIR");bool had_cache = old_cache != NULL;@@ -1412,14 +1414,11 @@ TEST(daemon_host_early_coordination_failure_is_durable) {char parent[RUNTIME_TEST_PATH_CAP] = {0};char cache[RUNTIME_TEST_PATH_CAP] = {0};char log_path[RUNTIME_TEST_PATH_CAP] = {0};- int parent_written =- snprintf(parent, sizeof(parent), "%s/cbm-host-early-log-XXXXXX", cbm_tmpdir());- bool parent_created = snapshot_ok && parent_written > 0 &&- parent_written < (int)sizeof(parent) && cbm_mkdtemp(parent) != NULL;+ bool parent_created =+ snapshot_ok && th_secure_runtime_parent_new(parent, sizeof(parent), "host-early-log");int cache_written = parent_created ? snprintf(cache, sizeof(cache), "%s/cache", parent) : -1;- int log_written = parent_created- ? snprintf(log_path, sizeof(log_path), "%s/logs/cbm-daemon.log", cache)- : -1;+ int log_written =+ parent_created ? snprintf(log_path, sizeof(log_path), "%s/logs/cbm-daemon.log", cache) : -1;bool environment_ready = cache_written > 0 && cache_written < (int)sizeof(cache) &&log_written > 0 && log_written < (int)sizeof(log_path) &&cbm_mkdir_p(cache, 0700) && cbm_setenv("CBM_CACHE_DIR", cache, 1) == 0;@@ -1434,10 +1433,9 @@ TEST(daemon_host_early_coordination_failure_is_durable) {runtime_test_identity("active-host", runtime_test_self_build());active_identity.cache_fingerprint = RUNTIME_BUILD_B;cbm_version_cohort_status_t active_status =- active_manager- ? cbm_version_cohort_acquire(active_manager, &active_identity, UINT64_MAX,- &active_lease, &active_conflict)- : CBM_VERSION_COHORT_IO;+ active_manager ? cbm_version_cohort_acquire(active_manager, &active_identity, UINT64_MAX,+ &active_lease, &active_conflict)+ : CBM_VERSION_COHORT_IO;cbm_version_cohort_status_t claim_status =active_status == CBM_VERSION_COHORT_OK? cbm_version_cohort_daemon_claim_acquire(active_manager, &active_claim)@@ -1452,9 +1450,14 @@ TEST(daemon_host_early_coordination_failure_is_durable) {int run_result = claim_status == CBM_VERSION_COHORT_OK ? cbm_daemon_host_run(&config) : 0;char log[RUNTIME_TEST_LOG_CAP] = {0};- bool durable = runtime_test_read_log(log_path, log) &&- strstr(log, "daemon.start_failed") != NULL &&- strstr(log, "claim") != NULL;+ bool log_read = runtime_test_read_log(log_path, log);+ bool durable_component = false;+#ifdef _WIN32+ durable_component = strstr(log, "participant") != NULL;+#else+ durable_component = strstr(log, "claim") != NULL;+#endif+ bool durable = log_read && strstr(log, "daemon.start_failed") != NULL && durable_component;bool endpoint_created = endpoint != NULL;while (active_claim &&cbm_version_cohort_daemon_claim_release(&active_claim) != CBM_PRIVATE_FILE_LOCK_OK) {@@ -1497,10 +1500,8 @@ TEST(daemon_host_refuses_unopenable_runtime_config_database) {char parent[RUNTIME_TEST_PATH_CAP] = {0};char cache[RUNTIME_TEST_PATH_CAP] = {0};char config_blocker[RUNTIME_TEST_PATH_CAP] = {0};- int parent_written =- snprintf(parent, sizeof(parent), "%s/cbm-host-config-XXXXXX", cbm_tmpdir());- bool parent_created = snapshot_ok && parent_written > 0 &&- parent_written < (int)sizeof(parent) && cbm_mkdtemp(parent) != NULL;+ bool parent_created =+ snapshot_ok && th_secure_runtime_parent_new(parent, sizeof(parent), "host-config");int cache_written = parent_created ? snprintf(cache, sizeof(cache), "%s/cache", parent) : -1;int blocker_written =parent_created ? snprintf(config_blocker, sizeof(config_blocker), "%s/_config.db", cache)@@ -1572,6 +1573,26 @@ TEST(daemon_host_http_retry_backoff_is_bounded) {PASS();}+/* A server can refuse destruction while an index callback still owns its host+ * context. Reconfiguration must retain that server and retry its retirement+ * even if the desired port reverts to the cached value before the next poll;+ * only successful retirement permits a replacement. */+TEST(daemon_host_http_reconcile_retains_busy_server_until_free_succeeds) {+ cbm_daemon_host_http_free_refusal_test_result_t result = {0};+ bool driven = cbm_daemon_host_http_reconcile_free_refusal_for_test(&result);++ ASSERT_TRUE(driven);+ ASSERT_TRUE(result.retained_after_refusal);+ ASSERT_EQ(result.server_create_attempts_after_refusal, 1);+ ASSERT_TRUE(result.replacement_active_after_retry);+ ASSERT_EQ(result.server_create_attempts, 2);+ ASSERT_EQ(result.thread_start_attempts, 2);+ ASSERT_EQ(result.server_stops, 1);+ ASSERT_EQ(result.server_free_attempts, 2);+ ASSERT_EQ(result.thread_joins, 1);+ PASS();+}+#ifndef _WIN32static int runtime_test_failed_host_child(const char *parent, const char *key) {char cache[RUNTIME_TEST_PATH_CAP];@@ -2369,6 +2390,13 @@ TEST(daemon_runtime_conflict_log_failure_uses_operation_log_fallback) {explicit_conflict = rejected == NULL &&conflict_result.status == CBM_DAEMON_RUNTIME_CONNECT_CONFLICT &&conflict_result.hello_status == CBM_DAEMON_HELLO_BUILD_CONFLICT;+ if (!explicit_conflict) {+ printf(" conflict fallback diagnostic: owner=%d rejected=%d owner_status=%d "+ "conflict_status=%d hello_status=%d message=%s\n",+ owner != NULL ? 1 : 0, rejected != NULL ? 1 : 0, (int)owner_result.status,+ (int)conflict_result.status, (int)conflict_result.hello_status,+ conflict_result.message);+ }(void)cbm_daemon_runtime_client_close(owner, RUNTIME_TEST_TIMEOUT_MS);owner = NULL;exited = cbm_daemon_runtime_service_wait_exited(fixture.service, RUNTIME_TEST_TIMEOUT_MS);@@ -2726,6 +2754,10 @@ TEST(daemon_runtime_application_response_roundtrip_is_byte_exact) {ASSERT_TRUE(exited);ASSERT_EQ(atomic_load(&context.opened), 1);ASSERT_EQ(atomic_load(&context.requests), 1);+ /* A close after a completed exchange has nothing to cancel: the client+ * only sends APPLICATION_CANCEL for an interrupted in-flight token, and+ * the server treats stale tokens as deliberate one-way no-ops. */+ ASSERT_EQ(atomic_load(&context.request_cancels), 0);ASSERT_EQ(atomic_load(&context.cancelled), 1);ASSERT_EQ(atomic_load(&context.closed), 1);PASS();@@ -3382,7 +3414,12 @@ TEST(daemon_runtime_disconnect_cancels_blocked_application_before_exit) {if (started) {exited = cbm_daemon_runtime_service_wait_exited(fixture.service, RUNTIME_TEST_TIMEOUT_MS);}- request_interrupted = call.status == CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR &&+ /* close_begin cancels the exchange and, on Windows, also sends the+ * active token's APPLICATION_CANCEL. Whether the local interrupt or the+ * server's CANCELLED response wins that race, the request ended promptly+ * without a payload — both outcomes are the contract. */+ request_interrupted = (call.status == CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR ||+ call.status == CBM_DAEMON_RUNTIME_APPLICATION_CANCELLED) &&call.response == NULL && call.response_length == 0;free(call.response);runtime_test_fixture_finish(&fixture);@@ -3435,8 +3472,15 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_othchar bin[RUNTIME_TEST_PATH_CAP] = {0};char fake_git[RUNTIME_TEST_PATH_CAP] = {0};char marker[RUNTIME_TEST_PATH_CAP] = {0};+#ifdef _WIN32+ /* cmd.exe searches a native PATH. Keep the copied git probe out of the+ * MSYS2 TEMP ancestry and canonicalize its directory before publication. */+ bool work_ready =+ snapshots_ok && th_secure_runtime_parent_new(work, sizeof(work), "non-index-work");+#else(void)snprintf(work, sizeof(work), "%s/cbm-runtime-non-index-XXXXXX", cbm_tmpdir());bool work_ready = snapshots_ok && cbm_mkdtemp(work) != NULL;+#endifint root_written = work_ready ? snprintf(root, sizeof(root), "%s/root", work) : -1;int cache_written = work_ready ? snprintf(cache, sizeof(cache), "%s/cache", work) : -1;int bin_written = work_ready ? snprintf(bin, sizeof(bin), "%s/bin", work) : -1;@@ -3455,6 +3499,21 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_othcbm_mkdir_p(cache, 0700) && cbm_mkdir_p(bin, 0700) &&runtime_test_copy_self_image(fake_git);+ char path_bin[RUNTIME_TEST_PATH_CAP] = {0};+#ifdef _WIN32+ bool path_bin_ready = paths_ready && cbm_canonical_path(bin, path_bin, sizeof(path_bin));+ if (path_bin_ready) {+ for (char *cursor = path_bin; *cursor; cursor++) {+ if (*cursor == '/') {+ *cursor = '\\';+ }+ }+ }+#else+ int path_bin_written = paths_ready ? snprintf(path_bin, sizeof(path_bin), "%s", bin) : -1;+ bool path_bin_ready = path_bin_written > 0 && path_bin_written < (int)sizeof(path_bin);+#endif+char *project = paths_ready ? cbm_project_name_from_path(root) : NULL;char db_path[RUNTIME_TEST_PATH_CAP] = {0};int db_written = project ? snprintf(db_path, sizeof(db_path), "%s/%s.db", cache, project) : -1;@@ -3463,13 +3522,13 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_othbool seeded = seed && cbm_store_upsert_project(seed, project, root) == CBM_STORE_OK;cbm_store_close(seed);- size_t path_length = strlen(bin) + 2U + (saved_path ? strlen(saved_path) : 0U);- char *test_path = seeded ? malloc(path_length) : NULL;+ size_t path_length = strlen(path_bin) + 2U + (saved_path ? strlen(saved_path) : 0U);+ char *test_path = seeded && path_bin_ready ? malloc(path_length) : NULL;if (test_path) {#ifdef _WIN32- (void)snprintf(test_path, path_length, "%s;%s", bin, saved_path ? saved_path : "");+ (void)snprintf(test_path, path_length, "%s;%s", path_bin, saved_path ? saved_path : "");#else- (void)snprintf(test_path, path_length, "%s:%s", bin, saved_path ? saved_path : "");+ (void)snprintf(test_path, path_length, "%s:%s", path_bin, saved_path ? saved_path : "");#endif}bool environment_ready = test_path && cbm_setenv("CBM_CACHE_DIR", cache, 1) == 0 &&@@ -3530,8 +3589,8 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_othrequest_thread_started &&runtime_test_wait_pid_marker(marker, CHILD_READY_BOUND_MS, &child_process_id);if (request_thread_started && !marker_published) {- printf(" blocking git marker missing: completed=%d status=%d response=%.*s\n",- atomic_load_explicit(&call.completed, memory_order_acquire) ? 1 : 0,+ printf(" blocking git marker missing: image=%s completed=%d status=%d response=%.*s\n",+ fake_git, atomic_load_explicit(&call.completed, memory_order_acquire) ? 1 : 0,(int)call.status, (int)call.response_length,call.response ? (const char *)call.response : "");}@@ -3539,9 +3598,16 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_othmarker_published && runtime_test_process_image_matches(child_process_id, fake_git);bool first_close_begun = child_identity_exact && cbm_daemon_runtime_client_close_begin(first);+ /* Admission must drop at close_begin on every platform: POSIX signals it+ * through shutdown()/EOF, Windows through the CLOSE_INTENT frame — a+ * named-pipe client has no transport-level half-close to lean on. */bool only_second_admitted =first_close_begun &&cbm_daemon_runtime_service_wait_for_clients(fixture.service, 1, RUNTIME_TEST_TIMEOUT_MS);+ size_t clients_after_admission_wait =+ started ? cbm_daemon_runtime_service_active_clients(fixture.service) : 0;+ size_t connections_after_admission_wait =+ started ? cbm_daemon_runtime_service_active_connections(fixture.service) : 0;bool child_gone_without_backstop =first_close_begun &&runtime_test_wait_process_image_gone(child_process_id, fake_git, CHILD_CANCEL_BOUND_MS);@@ -3603,8 +3669,20 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_othfree(saved_cache);bool files_removed = !work_ready || th_rmtree(work) == 0;+ if (!only_second_admitted || !child_gone_without_backstop || !request_completed ||+ !second_usable_after) {+ printf(" non-index cancellation diagnostic: close_begun=%d clients_after_wait=%zu "+ "connections_after_wait=%zu child_gone=%d backstop=%d request_completed=%d "+ "request_status=%d second_after=%d\n",+ first_close_begun ? 1 : 0, clients_after_admission_wait,+ connections_after_admission_wait, child_gone_without_backstop ? 1 : 0,+ cleanup_backstop_used ? 1 : 0, request_completed ? 1 : 0, (int)call.status,+ second_usable_after ? 1 : 0);+ }+ASSERT_TRUE(snapshots_ok);ASSERT_TRUE(paths_ready);+ ASSERT_TRUE(path_bin_ready);ASSERT_TRUE(seeded);ASSERT_TRUE(environment_ready);ASSERT_TRUE(started);@@ -3639,7 +3717,14 @@ TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_othTEST(daemon_runtime_noncooperative_callback_does_not_detach_or_unbound_stop) {static const uint8_t request[] = {'i', 'g', 'n', 'o', 'r', 'e'};- enum { STOP_BOUND_MS = 50, STOP_OBSERVED_MAX_MS = 500 };+ /* STOP_OBSERVED_MAX_MS is a coarse hang-detector, not a tight latency+ * bound: the invariant is that a deadline-bounded stop RETURNS (proven by+ * reaching the assertions below — a hang would deadlock the test) rather+ * than blocking indefinitely on the stuck callback. The window is well+ * above the STOP_BOUND_MS deadline yet far below a real hang, so heavy+ * scheduler starvation (the CBM_LOCAL_CI_CPUS=4 fidelity pass, CI runners)+ * cannot make it test-significant. */+ enum { STOP_BOUND_MS = 50, STOP_OBSERVED_MAX_MS = 5000 };cbm_daemon_build_identity_t identity =runtime_test_identity("2.4.0", runtime_test_self_build());runtime_application_context_t context;@@ -4252,11 +4337,187 @@ TEST(daemon_runtime_process_fingerprint_never_hashes_replacement_path) {}#endif++TEST(daemon_runtime_close_begin_releases_admission_with_inflight_request) {+ static const uint8_t request[] = {'b', 'l', 'o', 'c', 'k'};+ cbm_daemon_build_identity_t identity =+ runtime_test_identity("2.4.0", runtime_test_self_build());+ runtime_application_context_t context;+ runtime_application_context_init(&context, true);+ atomic_bool request_thread_completed;+ atomic_init(&request_thread_completed, false);+ runtime_test_fixture_t fixture;+ bool started = runtime_test_fixture_start_application(&fixture, "close-intent-admission",+ &identity, &context);+ cbm_daemon_runtime_client_t *client = NULL;+ cbm_daemon_runtime_connect_result_t result = {0};+ runtime_application_client_call_t call = {+ .request = request,+ .request_length = (uint32_t)sizeof(request),+ .completed = &request_thread_completed,+ .status = CBM_DAEMON_RUNTIME_APPLICATION_OK,+ };+ cbm_thread_t request_thread;+ int request_thread_create_rc = -1;+ bool request_thread_started = false;+ bool callback_started = false;+ bool close_begun = false;+ bool admission_released_at_begin = false;+ bool request_thread_joined = false;+ bool request_ended_without_payload = false;+ bool exited = false;++ if (started) {+ client = cbm_daemon_runtime_client_connect(fixture.endpoint, &identity,+ RUNTIME_TEST_TIMEOUT_MS, &result);+ }+ if (client) {+ call.client = client;+ request_thread_create_rc = cbm_thread_create(+ &request_thread, 128U * 1024U, runtime_application_client_request_thread, &call);+ request_thread_started = request_thread_create_rc == 0;+ callback_started =+ request_thread_started &&+ runtime_test_wait_atomic_bool(&context.first_request_started, RUNTIME_TEST_TIMEOUT_MS);+ }+ if (callback_started) {+ close_begun = cbm_daemon_runtime_client_close_begin(client);+ }+ /* The parity contract: after close_begin alone — before the handle+ * closes — the daemon has released this client's admission. POSIX learns+ * through shutdown()/EOF; Windows through the CLOSE_INTENT frame. */+ admission_released_at_begin =+ close_begun &&+ cbm_daemon_runtime_service_wait_for_clients(fixture.service, 0, RUNTIME_TEST_TIMEOUT_MS);+ if (request_thread_started) {+ request_thread_joined = cbm_thread_join(&request_thread) == 0;+ request_thread_started = false;+ }+ request_ended_without_payload =+ request_thread_joined &&+ (call.status == CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR ||+ call.status == CBM_DAEMON_RUNTIME_APPLICATION_CANCELLED) &&+ call.response == NULL && call.response_length == 0;+ if (client) {+ (void)(close_begun+ ? cbm_daemon_runtime_client_close_finish(client, RUNTIME_TEST_TIMEOUT_MS)+ : cbm_daemon_runtime_client_close(client, RUNTIME_TEST_TIMEOUT_MS));+ client = NULL;+ }+ if (started) {+ exited = cbm_daemon_runtime_service_wait_exited(fixture.service, RUNTIME_TEST_TIMEOUT_MS);+ }+ free(call.response);+ runtime_test_fixture_finish(&fixture);++ ASSERT_TRUE(started);+ ASSERT_EQ(request_thread_create_rc, 0);+ ASSERT_TRUE(callback_started);+ ASSERT_TRUE(close_begun);+ ASSERT_TRUE(admission_released_at_begin);+ ASSERT_TRUE(request_thread_joined);+ ASSERT_TRUE(request_ended_without_payload);+ ASSERT_TRUE(exited);+ ASSERT_EQ(atomic_load(&context.opened), 1);+ ASSERT_EQ(atomic_load(&context.requests), 1);+ ASSERT_EQ(atomic_load(&context.cancelled), 1);+ ASSERT_EQ(atomic_load(&context.closed), 1);+ PASS();+}++TEST(daemon_runtime_permanent_service_survives_last_disconnect_until_stop) {+ cbm_daemon_build_identity_t identity =+ runtime_test_identity("2.4.0", runtime_test_self_build());+ runtime_test_fixture_t fixture;+ runtime_test_fixture_permanent = true;+ bool started = runtime_test_fixture_start(&fixture, "permanent-lifecycle", &identity);+ runtime_test_fixture_permanent = false;+ cbm_daemon_runtime_client_t *client = NULL;+ cbm_daemon_runtime_connect_result_t connect_result = {0};+ bool survived = false;+ bool status_ok = false;+ bool stop_ok = false;+ bool exited = false;+ if (started) {+ client = cbm_daemon_runtime_client_connect(fixture.endpoint, &identity,+ RUNTIME_TEST_TIMEOUT_MS, &connect_result);+ }+ if (client) {+ (void)cbm_daemon_runtime_client_close(client, RUNTIME_TEST_TIMEOUT_MS);+ client = NULL;+ /* Give a wrongly-armed teardown time to fire before asserting. */+ survived =+ !cbm_daemon_runtime_service_wait_exited(fixture.service, 300U) &&+ cbm_daemon_runtime_service_state(fixture.service) == CBM_DAEMON_RUNTIME_SERVICE_RUNNING;+ cbm_daemon_runtime_status_t status = {0};+ status_ok = cbm_daemon_runtime_request_status(fixture.endpoint, &identity,+ RUNTIME_TEST_TIMEOUT_MS, &status) &&+ status.permanent && !status.stopping && status.committed_clients == 0;+ cbm_daemon_runtime_stop_result_t stop_result = {0};+ stop_ok = cbm_daemon_runtime_request_stop(fixture.endpoint, &identity,+ RUNTIME_TEST_TIMEOUT_MS, &stop_result) &&+ stop_result.accepted && !stop_result.busy;+ exited = cbm_daemon_runtime_service_wait_exited(fixture.service, RUNTIME_TEST_TIMEOUT_MS);+ }+ runtime_test_fixture_finish(&fixture);+ ASSERT_TRUE(started);+ ASSERT_TRUE(survived);+ ASSERT_TRUE(status_ok);+ ASSERT_TRUE(stop_ok);+ ASSERT_TRUE(exited);+ PASS();+}++TEST(daemon_runtime_stop_refuses_while_committed_clients_exist) {+ cbm_daemon_build_identity_t identity =+ runtime_test_identity("2.4.0", runtime_test_self_build());+ runtime_test_fixture_t fixture;+ runtime_test_fixture_permanent = true;+ bool started = runtime_test_fixture_start(&fixture, "stop-refuse-busy", &identity);+ runtime_test_fixture_permanent = false;+ cbm_daemon_runtime_client_t *client = NULL;+ cbm_daemon_runtime_connect_result_t connect_result = {0};+ bool refused = false;+ bool accepted_after_close = false;+ bool exited = false;+ if (started) {+ client = cbm_daemon_runtime_client_connect(fixture.endpoint, &identity,+ RUNTIME_TEST_TIMEOUT_MS, &connect_result);+ }+ if (client) {+ cbm_daemon_runtime_stop_result_t busy_result = {0};+ refused = cbm_daemon_runtime_request_stop(fixture.endpoint, &identity,+ RUNTIME_TEST_TIMEOUT_MS, &busy_result) &&+ busy_result.busy && !busy_result.accepted && busy_result.committed_clients == 1 &&+ busy_result.client_count == 1 &&+ busy_result.client_pids[0] == (uint32_t)connect_result.authenticated_process_id;+ (void)cbm_daemon_runtime_client_close(client, RUNTIME_TEST_TIMEOUT_MS);+ client = NULL;+ cbm_daemon_runtime_stop_result_t stop_result = {0};+ accepted_after_close =+ cbm_daemon_runtime_service_wait_for_clients(fixture.service, 0,+ RUNTIME_TEST_TIMEOUT_MS) &&+ cbm_daemon_runtime_request_stop(fixture.endpoint, &identity, RUNTIME_TEST_TIMEOUT_MS,+ &stop_result) &&+ stop_result.accepted && !stop_result.busy;+ exited = cbm_daemon_runtime_service_wait_exited(fixture.service, RUNTIME_TEST_TIMEOUT_MS);+ }+ runtime_test_fixture_finish(&fixture);+ ASSERT_TRUE(started);+ ASSERT_TRUE(refused);+ ASSERT_TRUE(accepted_after_close);+ ASSERT_TRUE(exited);+ PASS();+}+SUITE(daemon_runtime) {+ RUN_TEST(daemon_runtime_permanent_service_survives_last_disconnect_until_stop);+ RUN_TEST(daemon_runtime_stop_refuses_while_committed_clients_exist);RUN_TEST(daemon_host_early_coordination_failure_is_durable);RUN_TEST(daemon_host_refuses_unopenable_runtime_config_database);RUN_TEST(daemon_host_http_reconcile_rate_limits_and_retries_transient_failures);RUN_TEST(daemon_host_http_retry_backoff_is_bounded);+ RUN_TEST(daemon_host_http_reconcile_retains_busy_server_until_free_succeeds);#ifndef _WIN32RUN_TEST(daemon_host_failed_listener_reservation_starts_no_background_work);RUN_TEST(daemon_host_persistent_cleanup_release_failure_is_process_bounded);@@ -4296,6 +4557,7 @@ SUITE(daemon_runtime) {RUN_TEST(daemon_runtime_consumes_busy_application_token_before_response);RUN_TEST(daemon_runtime_close_begin_retains_storage_and_rejects_late_exchange);RUN_TEST(daemon_runtime_disconnect_cancels_blocked_application_before_exit);+ RUN_TEST(daemon_runtime_close_begin_releases_admission_with_inflight_request);RUN_TEST(daemon_runtime_disconnect_cancels_blocked_non_index_child_and_preserves_other_session);RUN_TEST(daemon_runtime_noncooperative_callback_does_not_detach_or_unbound_stop);RUN_TEST(daemon_runtime_application_busy_cap_and_malformed_are_isolated);diff --git a/tests/test_diagnostics.c b/tests/test_diagnostics.cnew file mode 100644index 000000000..e05677fd3--- /dev/null+++ b/tests/test_diagnostics.c@@ -0,0 +1,586 @@+/*+ * test_diagnostics.c — Security and lifecycle guards for the optional+ * periodic diagnostics writer.+ */+#include "test_framework.h"++#include "../src/foundation/compat.h"+#include "../src/foundation/compat_fs.h"+#include "../src/foundation/diagnostics.h"+#include "../src/foundation/log.h"+#include "../src/foundation/platform.h"++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#ifdef _WIN32+#include <windows.h>++#include <aclapi.h>+#include <process.h>+#define getpid _getpid+#else+#include <sys/stat.h>+#include <sys/types.h>+#include <unistd.h>+#endif++typedef struct {+ char directory[1024];+ char snapshot[1024];+ char trajectory[1024];+} diagnostics_paths_t;++static void diagnostics_wait_ms(unsigned int milliseconds) {+ struct timespec delay = {+ .tv_sec = (time_t)(milliseconds / 1000U),+ .tv_nsec = (long)((milliseconds % 1000U) * 1000000U),+ };+ (void)cbm_nanosleep(&delay, NULL);+}++#ifndef _WIN32+static bool diagnostics_file_equals(const char *path, const char *expected) {+ char contents[128] = "";+ FILE *file = cbm_fopen(path, "rb");+ if (!file) {+ return false;+ }+ size_t length = fread(contents, 1, sizeof(contents) - 1, file);+ bool closed = fclose(file) == 0;+ contents[length] = '\0';+ return closed && strcmp(contents, expected) == 0;+}+#endif++static bool diagnostics_capture_paths(diagnostics_paths_t *paths) {+ return cbm_diag_test_copy_paths(paths->directory, sizeof(paths->directory), paths->snapshot,+ sizeof(paths->snapshot), paths->trajectory,+ sizeof(paths->trajectory));+}++static bool diagnostics_wait_for_file(const char *path, unsigned int timeout_ms) {+ uint64_t deadline = cbm_now_ms() + timeout_ms;+ while (cbm_now_ms() < deadline) {+ if (cbm_file_exists(path)) {+ return true;+ }+ diagnostics_wait_ms(10);+ }+ return cbm_file_exists(path);+}++static char *diagnostics_read_file(const char *path) {+ FILE *file = cbm_fopen(path, "rb");+ if (!file || fseek(file, 0, SEEK_END) != 0) {+ if (file) {+ (void)fclose(file);+ }+ return NULL;+ }+ long length = ftell(file);+ if (length < 0 || fseek(file, 0, SEEK_SET) != 0) {+ (void)fclose(file);+ return NULL;+ }+ char *contents = malloc((size_t)length + 1);+ if (!contents) {+ (void)fclose(file);+ return NULL;+ }+ size_t read_length = fread(contents, 1, (size_t)length, file);+ bool closed = fclose(file) == 0;+ bool complete = read_length == (size_t)length && closed;+ contents[read_length] = '\0';+ if (!complete) {+ free(contents);+ return NULL;+ }+ return contents;+}++static void diagnostics_cleanup_outputs(const diagnostics_paths_t *paths) {+ char temporary[1100];+ char rotated[1100];+ if (snprintf(temporary, sizeof(temporary), "%s.tmp", paths->snapshot) > 0) {+ (void)cbm_unlink(temporary);+ }+ if (snprintf(rotated, sizeof(rotated), "%s.1", paths->trajectory) > 0) {+ (void)cbm_unlink(rotated);+ }+ (void)cbm_unlink(paths->snapshot);+ (void)cbm_unlink(paths->trajectory);+ (void)cbm_rmdir(paths->directory);+}++#ifndef _WIN32+TEST(diagnostics_rejects_predictable_tmp_symlinks) {+ char snapshot_link[256];+ char trajectory_link[256];+ char snapshot_target[256];+ char trajectory_target[256];+ const char *snapshot_seed = "snapshot sentinel\n";+ const char *trajectory_seed = "trajectory sentinel\n";+ int pid = (int)getpid();++ ASSERT_LT(+ snprintf(snapshot_link, sizeof(snapshot_link), "/tmp/cbm-diagnostics-%d.json.tmp", pid),+ (int)sizeof(snapshot_link));+ ASSERT_LT(+ snprintf(trajectory_link, sizeof(trajectory_link), "/tmp/cbm-diagnostics-%d.ndjson", pid),+ (int)sizeof(trajectory_link));+ ASSERT_LT(snprintf(snapshot_target, sizeof(snapshot_target),+ "/tmp/cbm-diagnostics-snapshot-sentinel-%d", pid),+ (int)sizeof(snapshot_target));+ ASSERT_LT(snprintf(trajectory_target, sizeof(trajectory_target),+ "/tmp/cbm-diagnostics-trajectory-sentinel-%d", pid),+ (int)sizeof(trajectory_target));++ (void)cbm_unlink(snapshot_link);+ (void)cbm_unlink(trajectory_link);+ (void)cbm_unlink(snapshot_target);+ (void)cbm_unlink(trajectory_target);++ FILE *snapshot = cbm_fopen(snapshot_target, "wb");+ ASSERT_NOT_NULL(snapshot);+ ASSERT_GTE(fputs(snapshot_seed, snapshot), 0);+ ASSERT_EQ(fclose(snapshot), 0);+ FILE *trajectory = cbm_fopen(trajectory_target, "wb");+ ASSERT_NOT_NULL(trajectory);+ ASSERT_GTE(fputs(trajectory_seed, trajectory), 0);+ ASSERT_EQ(fclose(trajectory), 0);+ ASSERT_EQ(symlink(snapshot_target, snapshot_link), 0);+ ASSERT_EQ(symlink(trajectory_target, trajectory_link), 0);++ ASSERT_EQ(cbm_setenv("CBM_DIAGNOSTICS", "1", 1), 0);+ ASSERT_TRUE(cbm_diag_start());+ diagnostics_paths_t outputs;+ bool captured = diagnostics_capture_paths(&outputs);+ bool emitted = captured && diagnostics_wait_for_file(outputs.snapshot, 1000);+ cbm_diag_stop();+ ASSERT_EQ(cbm_unsetenv("CBM_DIAGNOSTICS"), 0);++ bool snapshot_untouched = diagnostics_file_equals(snapshot_target, snapshot_seed);+ bool trajectory_untouched = diagnostics_file_equals(trajectory_target, trajectory_seed);+ (void)cbm_unlink(snapshot_link);+ (void)cbm_unlink(trajectory_link);+ (void)cbm_unlink(snapshot_target);+ (void)cbm_unlink(trajectory_target);+ if (captured) {+ diagnostics_cleanup_outputs(&outputs);+ }++ ASSERT_TRUE(captured);+ ASSERT_TRUE(emitted);+ ASSERT_TRUE(snapshot_untouched);+ ASSERT_TRUE(trajectory_untouched);+ PASS();+}+#endif++TEST(diagnostics_stop_interrupts_periodic_wait) {+ char legacy_snapshot[256];+ char legacy_trajectory[256];+ int pid = (int)getpid();+ ASSERT_LT(snprintf(legacy_snapshot, sizeof(legacy_snapshot), "%s/cbm-diagnostics-%d.json",+ cbm_tmpdir(), pid),+ (int)sizeof(legacy_snapshot));+ ASSERT_LT(snprintf(legacy_trajectory, sizeof(legacy_trajectory), "%s/cbm-diagnostics-%d.ndjson",+ cbm_tmpdir(), pid),+ (int)sizeof(legacy_trajectory));+ (void)cbm_unlink(legacy_snapshot);+ (void)cbm_unlink(legacy_trajectory);++ ASSERT_EQ(cbm_setenv("CBM_DIAGNOSTICS", "1", 1), 0);+ ASSERT_TRUE(cbm_diag_start());++ diagnostics_paths_t outputs;+ bool captured = diagnostics_capture_paths(&outputs);+ /* A visible snapshot proves the writer has reached its periodic wait. */+ bool emitted = captured && diagnostics_wait_for_file(outputs.snapshot, 1000);+ uint64_t started_ms = cbm_now_ms();+ cbm_diag_stop();+ uint64_t elapsed_ms = cbm_now_ms() - started_ms;+ ASSERT_EQ(cbm_unsetenv("CBM_DIAGNOSTICS"), 0);+ (void)cbm_unlink(legacy_snapshot);+ (void)cbm_unlink(legacy_trajectory);+ if (captured) {+ diagnostics_cleanup_outputs(&outputs);+ }++ ASSERT_TRUE(captured);+ ASSERT_TRUE(emitted);+ ASSERT_LT(elapsed_ms, UINT64_C(1000));+ PASS();+}++#ifndef _WIN32+TEST(diagnostics_outputs_are_owner_private_regular_files) {+ ASSERT_EQ(cbm_setenv("CBM_DIAGNOSTICS", "1", 1), 0);+ ASSERT_TRUE(cbm_diag_start());+ diagnostics_paths_t outputs;+ bool captured = diagnostics_capture_paths(&outputs);+ bool snapshot_emitted = captured && diagnostics_wait_for_file(outputs.snapshot, 1000);+ bool trajectory_emitted = captured && diagnostics_wait_for_file(outputs.trajectory, 1000);++ struct stat directory_state;+ struct stat snapshot_state;+ struct stat trajectory_state;+ bool secure = captured && snapshot_emitted && trajectory_emitted &&+ lstat(outputs.directory, &directory_state) == 0 &&+ S_ISDIR(directory_state.st_mode) && directory_state.st_uid == geteuid() &&+ (directory_state.st_mode & 07777) == 0700 &&+ lstat(outputs.snapshot, &snapshot_state) == 0 &&+ S_ISREG(snapshot_state.st_mode) && snapshot_state.st_uid == geteuid() &&+ snapshot_state.st_nlink == 1 && (snapshot_state.st_mode & 07777) == 0600 &&+ lstat(outputs.trajectory, &trajectory_state) == 0 &&+ S_ISREG(trajectory_state.st_mode) && trajectory_state.st_uid == geteuid() &&+ trajectory_state.st_nlink == 1 && (trajectory_state.st_mode & 07777) == 0600;++ cbm_diag_stop();+ ASSERT_EQ(cbm_unsetenv("CBM_DIAGNOSTICS"), 0);+ if (captured) {+ diagnostics_cleanup_outputs(&outputs);+ }+ ASSERT_TRUE(secure);+ PASS();+}+#endif++TEST(diagnostics_stalled_writer_cannot_retain_shutdown) {+ cbm_diag_test_hold_writer(true);+ ASSERT_EQ(cbm_setenv("CBM_DIAGNOSTICS", "1", 1), 0);+ if (!cbm_diag_start()) {+ cbm_diag_test_hold_writer(false);+ (void)cbm_unsetenv("CBM_DIAGNOSTICS");+ FAIL("failed to start held diagnostics writer");+ }+ diagnostics_paths_t outputs;+ bool captured = diagnostics_capture_paths(&outputs);+ uint64_t reach_deadline = cbm_now_ms() + 1000;+ while (!cbm_diag_test_writer_reached() && cbm_now_ms() < reach_deadline) {+ diagnostics_wait_ms(10);+ }+ bool reached = cbm_diag_test_writer_reached();+ if (!captured || !reached) {+ cbm_diag_test_hold_writer(false);+ cbm_diag_stop();+ (void)cbm_unsetenv("CBM_DIAGNOSTICS");+ if (captured) {+ diagnostics_cleanup_outputs(&outputs);+ }+ FAIL("diagnostics writer did not reach the held I/O boundary");+ }++ uint64_t started_ms = cbm_now_ms();+ cbm_diag_stop();+ uint64_t elapsed_ms = cbm_now_ms() - started_ms;+ bool abandoned = cbm_diag_test_abandoned();++ cbm_diag_test_hold_writer(false);+ bool reset = false;+ uint64_t reset_deadline = cbm_now_ms() + 1000;+ while (!reset && cbm_now_ms() < reset_deadline) {+ reset = cbm_diag_test_reset_abandoned();+ if (!reset) {+ diagnostics_wait_ms(10);+ }+ }+ (void)cbm_unsetenv("CBM_DIAGNOSTICS");+ diagnostics_cleanup_outputs(&outputs);++ ASSERT_LT(elapsed_ms, UINT64_C(1500));+ ASSERT_TRUE(abandoned);+ ASSERT_TRUE(reset);+ PASS();+}++TEST(diagnostics_soak_discovers_daemon_emitted_paths) {+ char *script = diagnostics_read_file("scripts/soak-test.sh");+ ASSERT_NOT_NULL(script);+ bool parses_start_event = strstr(script, "\"event\":\"diagnostics.start\"") != NULL;+ bool isolates_daemon = strstr(script, "CBM_CACHE_DIR=\"$SOAK_CACHE_DIR_VALUE\"") != NULL;+ bool legacy_predictable_path = strstr(script, "/tmp/cbm-diagnostics-${SERVER_PID}") != NULL;+ free(script);++ ASSERT_TRUE(parses_start_event);+ ASSERT_TRUE(isolates_daemon);+ ASSERT_FALSE(legacy_predictable_path);+ PASS();+}+++/* ── Discovery record contract ───────────────────────────────────────── */++static char diagnostics_discovery_line[2048];+static int diagnostics_discovery_records;++static void diagnostics_discovery_sink(const char *line) {+ if (!line || !strstr(line, "\"event\":\"diagnostics.start\"")) {+ return;+ }+ diagnostics_discovery_records++;+ (void)snprintf(diagnostics_discovery_line, sizeof(diagnostics_discovery_line), "%s", line);+}++static bool diagnostics_discovery_value(const char *key, char *out, size_t out_size) {+ char marker[64];+ if (snprintf(marker, sizeof(marker), "\"%s\":\"", key) >= (int)sizeof(marker)) {+ return false;+ }+ const char *cursor = strstr(diagnostics_discovery_line, marker);+ if (!cursor) {+ return false;+ }+ cursor += strlen(marker);+ size_t used = 0;+ while (*cursor && *cursor != '"' && used + 1 < out_size) {+ if (*cursor == '\\' && cursor[1] != '\0') {+ cursor++;+ char decoded = *cursor;+ if (decoded == 'n') {+ decoded = '\n';+ } else if (decoded == 't') {+ decoded = '\t';+ } else if (decoded == 'r') {+ decoded = '\r';+ }+ out[used++] = decoded;+ cursor++;+ continue;+ }+ out[used++] = *cursor++;+ }+ out[used] = '\0';+ return *cursor == '"';+}++TEST(diagnostics_discovery_record_survives_suppressed_log_level) {+ diagnostics_discovery_records = 0;+ diagnostics_discovery_line[0] = '\0';+ cbm_log_set_level(CBM_LOG_NONE);+ cbm_log_set_sink_ex(diagnostics_discovery_sink, CBM_LOG_SINK_REPLACE);+ ASSERT_EQ(cbm_setenv("CBM_DIAGNOSTICS", "1", 1), 0);+ bool started = cbm_diag_start();+ diagnostics_paths_t outputs;+ bool captured = started && diagnostics_capture_paths(&outputs);+ cbm_diag_stop();+ (void)cbm_unsetenv("CBM_DIAGNOSTICS");+ cbm_log_set_sink(NULL);+ cbm_log_set_level(CBM_LOG_INFO);++ char recorded_snapshot[1024] = "";+ char recorded_trajectory[1024] = "";+ bool decoded =+ diagnostics_discovery_value("snapshot", recorded_snapshot, sizeof(recorded_snapshot)) &&+ diagnostics_discovery_value("trajectory", recorded_trajectory,+ sizeof(recorded_trajectory));+ if (captured) {+ diagnostics_cleanup_outputs(&outputs);+ }+ ASSERT_TRUE(started);+ ASSERT_TRUE(captured);+ /* Exactly one discovery record, delivered despite CBM_LOG_LEVEL=none, and+ * its decoded paths are byte-exact against the writer's own paths. */+ ASSERT_EQ(diagnostics_discovery_records, 1);+ ASSERT_TRUE(decoded);+ ASSERT_EQ(strcmp(recorded_snapshot, outputs.snapshot), 0);+ ASSERT_EQ(strcmp(recorded_trajectory, outputs.trajectory), 0);+ PASS();+}++#ifndef _WIN32+TEST(diagnostics_placement_honors_tmpdir_with_spaces) {+ char saved_tmpdir[1024] = "";+ const char *current_tmpdir = getenv("TMPDIR");+ bool had_tmpdir = current_tmpdir != NULL;+ if (had_tmpdir) {+ ASSERT_LT(snprintf(saved_tmpdir, sizeof(saved_tmpdir), "%s", current_tmpdir),+ (int)sizeof(saved_tmpdir));+ }+ char base[256];+ ASSERT_LT(snprintf(base, sizeof(base), "/tmp/cbm diag spaces %d", (int)getpid()),+ (int)sizeof(base));+ (void)cbm_rmdir(base);+ ASSERT_EQ(mkdir(base, 0700), 0);+ ASSERT_EQ(cbm_setenv("TMPDIR", base, 1), 0);+ diagnostics_discovery_records = 0;+ diagnostics_discovery_line[0] = '\0';+ cbm_log_set_sink_ex(diagnostics_discovery_sink, CBM_LOG_SINK_REPLACE);+ ASSERT_EQ(cbm_setenv("CBM_DIAGNOSTICS", "1", 1), 0);+ bool started = cbm_diag_start();+ diagnostics_paths_t outputs;+ bool captured = started && diagnostics_capture_paths(&outputs);+ bool emitted = captured && diagnostics_wait_for_file(outputs.snapshot, 1000);+ cbm_diag_stop();+ (void)cbm_unsetenv("CBM_DIAGNOSTICS");+ cbm_log_set_sink(NULL);+ if (had_tmpdir) {+ (void)cbm_setenv("TMPDIR", saved_tmpdir, 1);+ } else {+ (void)cbm_unsetenv("TMPDIR");+ }++ char recorded[1024] = "";+ bool decoded = diagnostics_discovery_value("snapshot", recorded, sizeof(recorded));+ bool under_base = captured && strncmp(outputs.directory, base, strlen(base)) == 0;+ if (captured) {+ diagnostics_cleanup_outputs(&outputs);+ }+ (void)cbm_rmdir(base);+ ASSERT_TRUE(started);+ ASSERT_TRUE(captured);+ ASSERT_TRUE(emitted);+ /* The documented contract: honor $TMPDIR (with /tmp fallback), and the+ * discovery record must round-trip a path containing spaces exactly. */+ ASSERT_TRUE(under_base);+ ASSERT_TRUE(decoded);+ ASSERT_EQ(strcmp(recorded, outputs.snapshot), 0);+ PASS();+}+#endif++#ifdef _WIN32+static wchar_t *diagnostics_windows_utf8_to_wide(const char *value) {+ int needed = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value, -1, NULL, 0);+ wchar_t *wide = needed > 0 ? calloc((size_t)needed, sizeof(*wide)) : NULL;+ if (!wide || MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value, -1, wide, needed) <= 0) {+ free(wide);+ return NULL;+ }+ return wide;+}++static bool diagnostics_windows_current_user_sid(void **information_out, PSID *sid_out) {+ *information_out = NULL;+ *sid_out = NULL;+ HANDLE token = NULL;+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {+ return false;+ }+ DWORD needed = 0;+ (void)GetTokenInformation(token, TokenUser, NULL, 0, &needed);+ void *information = needed > 0 ? calloc(1, needed) : NULL;+ bool ok =+ information && GetTokenInformation(token, TokenUser, information, needed, &needed) != 0;+ (void)CloseHandle(token);+ if (!ok) {+ free(information);+ return false;+ }+ PSID sid = ((TOKEN_USER *)information)->User.Sid;+ if (!sid || !IsValidSid(sid)) {+ free(information);+ return false;+ }+ *information_out = information;+ *sid_out = sid;+ return true;+}++/* Owner is the current user AND the protected DACL grants access to that+ * owner alone — the Windows equivalent of the POSIX 0700/0600 assertions. */+static bool diagnostics_windows_path_owner_private(const char *path, bool directory) {+ void *user_information = NULL;+ PSID user_sid = NULL;+ wchar_t *wide_path = diagnostics_windows_utf8_to_wide(path);+ DWORD flags = FILE_FLAG_OPEN_REPARSE_POINT | (directory ? FILE_FLAG_BACKUP_SEMANTICS : 0);+ HANDLE handle = wide_path+ ? CreateFileW(wide_path, READ_CONTROL,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING, flags, NULL)+ : INVALID_HANDLE_VALUE;+ PSID owner = NULL;+ PACL dacl = NULL;+ PSECURITY_DESCRIPTOR descriptor = NULL;+ SECURITY_DESCRIPTOR_CONTROL control = 0;+ DWORD revision = 0;+ bool ok = handle != INVALID_HANDLE_VALUE &&+ diagnostics_windows_current_user_sid(&user_information, &user_sid) &&+ GetSecurityInfo(handle, SE_FILE_OBJECT,+ OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, &owner, NULL,+ &dacl, NULL, &descriptor) == ERROR_SUCCESS &&+ owner && IsValidSid(owner) && EqualSid(owner, user_sid) &&+ GetSecurityDescriptorControl(descriptor, &control, &revision) != 0 &&+ (control & SE_DACL_PROTECTED) != 0 && dacl && dacl->AceCount == 1;+ if (ok) {+ void *ace = NULL;+ ok = GetAce(dacl, 0, &ace) != 0 &&+ ((ACE_HEADER *)ace)->AceType == ACCESS_ALLOWED_ACE_TYPE &&+ EqualSid((PSID)&((ACCESS_ALLOWED_ACE *)ace)->SidStart, user_sid);+ }+ if (descriptor) {+ (void)LocalFree(descriptor);+ }+ if (handle != INVALID_HANDLE_VALUE) {+ (void)CloseHandle(handle);+ }+ free(wide_path);+ free(user_information);+ return ok;+}++static bool diagnostics_windows_output_contract(const char *path) {+ /* Mirrors production's diag_win_handle_valid: files are secured by their+ * owner-private parent directory; the file itself must be a plain local+ * regular file — no reparse, no extra links. Owner/DACL are asserted on+ * the directory, where the security boundary actually lives (file owners+ * follow the machine's default-owner policy, e.g. Administrators on+ * GitHub-runner-class images). */+ wchar_t *wide_path = diagnostics_windows_utf8_to_wide(path);+ HANDLE handle = wide_path+ ? CreateFileW(wide_path, GENERIC_READ,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL)+ : INVALID_HANDLE_VALUE;+ BY_HANDLE_FILE_INFORMATION information;+ bool ok = handle != INVALID_HANDLE_VALUE && GetFileType(handle) == FILE_TYPE_DISK &&+ GetFileInformationByHandle(handle, &information) != 0 &&+ (information.dwFileAttributes &+ (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0 &&+ information.nNumberOfLinks == 1;+ if (handle != INVALID_HANDLE_VALUE) {+ (void)CloseHandle(handle);+ }+ free(wide_path);+ return ok;+}++TEST(diagnostics_outputs_are_owner_private_windows) {+ ASSERT_EQ(cbm_setenv("CBM_DIAGNOSTICS", "1", 1), 0);+ ASSERT_TRUE(cbm_diag_start());+ diagnostics_paths_t outputs;+ bool captured = diagnostics_capture_paths(&outputs);+ bool snapshot_emitted = captured && diagnostics_wait_for_file(outputs.snapshot, 1000);+ bool trajectory_emitted = captured && diagnostics_wait_for_file(outputs.trajectory, 1000);+ bool secure = captured && snapshot_emitted && trajectory_emitted &&+ diagnostics_windows_path_owner_private(outputs.directory, true) &&+ diagnostics_windows_output_contract(outputs.snapshot) &&+ diagnostics_windows_output_contract(outputs.trajectory);+ cbm_diag_stop();+ ASSERT_EQ(cbm_unsetenv("CBM_DIAGNOSTICS"), 0);+ if (captured) {+ diagnostics_cleanup_outputs(&outputs);+ }+ ASSERT_TRUE(secure);+ PASS();+}+#endif++SUITE(diagnostics) {+#ifndef _WIN32+ RUN_TEST(diagnostics_rejects_predictable_tmp_symlinks);+#endif+ RUN_TEST(diagnostics_stop_interrupts_periodic_wait);+#ifndef _WIN32+ RUN_TEST(diagnostics_outputs_are_owner_private_regular_files);+ RUN_TEST(diagnostics_placement_honors_tmpdir_with_spaces);+#endif+#ifdef _WIN32+ RUN_TEST(diagnostics_outputs_are_owner_private_windows);+#endif+ RUN_TEST(diagnostics_discovery_record_survives_suppressed_log_level);+ RUN_TEST(diagnostics_stalled_writer_cannot_retain_shutdown);+ RUN_TEST(diagnostics_soak_discovers_daemon_emitted_paths);+}diff --git a/tests/test_helpers.h b/tests/test_helpers.hindex 0fce50e47..24da1f8b0 100644--- a/tests/test_helpers.h+++ b/tests/test_helpers.h@@ -14,6 +14,7 @@#include "../src/foundation/compat.h"#include "../src/foundation/compat_fs.h"+#include "../src/foundation/platform.h"#include <stdio.h>#include <stdlib.h>@@ -147,6 +148,32 @@ static inline char *th_mktempdir(const char *prefix) {return buf;}+/* Runtime IPC validates the complete Windows directory ancestry, so an MSYS2+ * TEMP rooted under C:/msys64/tmp is intentionally unsuitable even when the+ * leaf made by cbm_mkdtemp() has a private DACL. Keep these security-sensitive+ * fixtures under LocalAppData on Windows; preserve the ordinary temporary-root+ * behavior on POSIX. */+static inline bool th_secure_runtime_parent_new(char *out, size_t out_cap, const char *tag) {+ if (!out || out_cap == 0 || !tag || !tag[0]) {+ return false;+ }+#ifdef _WIN32+ const char *base = cbm_app_local_dir();+#else+ const char *base = cbm_tmpdir();+#endif+ if (!base || !base[0]) {+ out[0] = '\0';+ return false;+ }+ int written = snprintf(out, out_cap, "%s/cbm-runtime-%s-XXXXXX", base, tag);+ if (written <= 0 || (size_t)written >= out_cap) {+ out[0] = '\0';+ return false;+ }+ return cbm_mkdtemp(out) != NULL;+}+/* ── File permissions (no-op on Windows) ──────────────────────── *//* Make a file executable. On Windows this is a no-op (all files arediff --git a/tests/test_httpd.c b/tests/test_httpd.cindex 8544273af..997499e22 100644--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@ -16,6 +16,7 @@#include "../src/foundation/log.h"#include "../src/foundation/platform.h"#include "../src/cli/cli.h"+#include "../src/daemon/host_internal.h"#include "../src/git/git_context.h" /* #798 follow-up: live-socket git-resolve repro */#include "../src/ui/http_server.h"#include "test_framework.h"@@ -39,6 +40,7 @@#include <windows.h> /* #798 follow-up: CreateThread/WaitForSingleObject watchdog */typedef SOCKET th_sock_t;#define th_sock_close closesocket+#define th_sock_shutdown(s) shutdown((s), SD_BOTH)#define TH_SOCK_BAD INVALID_SOCKET#else#include <arpa/inet.h>@@ -49,6 +51,7 @@ typedef SOCKET th_sock_t;#include <unistd.h>typedef int th_sock_t;#define th_sock_close close+#define th_sock_shutdown(s) shutdown((s), SHUT_RDWR)#define TH_SOCK_BAD (-1)#endif@@ -66,7 +69,7 @@ static void httpd_capture_log(const char *line) {/* ── Raw-socket test client ───────────────────────────────────── */-static th_sock_t th_connect(int port) {+static th_sock_t th_connect_with_recv_buffer(int port, int recv_buffer) {#ifdef _WIN32WSADATA wsa;WSAStartup(MAKEWORD(2, 2), &wsa); /* refcounted; cleanup not needed in tests */@@ -74,6 +77,11 @@ static th_sock_t th_connect(int port) {th_sock_t s = socket(AF_INET, SOCK_STREAM, 0);if (s == TH_SOCK_BAD)return TH_SOCK_BAD;+ if (recv_buffer > 0 && setsockopt(s, SOL_SOCKET, SO_RCVBUF, (const char *)&recv_buffer,+ sizeof(recv_buffer)) != 0) {+ th_sock_close(s);+ return TH_SOCK_BAD;+ }struct sockaddr_in addr;memset(&addr, 0, sizeof(addr));addr.sin_family = AF_INET;@@ -86,6 +94,10 @@ static th_sock_t th_connect(int port) {return s;}+static th_sock_t th_connect(int port) {+ return th_connect_with_recv_buffer(port, 0);+}+static int th_send_all(th_sock_t s, const char *data, size_t len) {size_t off = 0;while (off < len) {@@ -120,8 +132,8 @@ static int th_recv_until_close(th_sock_t s, char *buf, size_t bufsz) {return (int)off;}-/* One-shot HTTP exchange. Returns response length, 0 on connect failure. */-static int th_http(int port, const char *request, char *resp, size_t respsz) {+/* One-shot raw HTTP exchange. Returns response length, 0 on connect failure. */+static int th_http_raw(int port, const char *request, char *resp, size_t respsz) {th_sock_t s = th_connect(port);if (s == TH_SOCK_BAD)return 0;@@ -134,6 +146,50 @@ static int th_http(int port, const char *request, char *resp, size_t respsz) {return n;}+/* Existing route tests focus on endpoint behavior. Add the loopback Host and+ * JSON mutation header the browser supplies. Security tests use th_http_raw()+ * to exercise missing/hostile headers without this convenience layer. */+static char *th_request_with_ui_headers(int port, const char *request) {+ const char *head_end = strstr(request, "\r\n\r\n");+ if (!head_end)+ return strdup(request);++ const char *target = strchr(request, ' ');+ target = target ? target + 1 : NULL;+ bool protected_route =+ target && (strncmp(target, "/api/", 5) == 0 || strncmp(target, "/rpc ", 5) == 0 ||+ strncmp(target, "/rpc?", 5) == 0);+ bool mutation = strncmp(request, "POST ", 5) == 0;+ bool have_host = strstr(request, "\r\nHost:") != NULL;+ bool have_content_type = strstr(request, "\r\nContent-Type:") != NULL;++ size_t request_len = strlen(request);+ size_t capacity = request_len + 256;+ char *result = malloc(capacity);+ if (!result)+ return NULL;++ size_t head_len = (size_t)(head_end - request);+ memcpy(result, request, head_len);+ size_t pos = head_len;+ if (!have_host)+ pos += (size_t)snprintf(result + pos, capacity - pos, "\r\nHost: 127.0.0.1:%d", port);+ if (protected_route && mutation && !have_content_type) {+ pos += (size_t)snprintf(result + pos, capacity - pos, "\r\nContent-Type: application/json");+ }+ (void)snprintf(result + pos, capacity - pos, "\r\n\r\n%s", head_end + 4);+ return result;+}++static int th_http(int port, const char *request, char *resp, size_t respsz) {+ char *prepared = th_request_with_ui_headers(port, request);+ if (!prepared)+ return 0;+ int result = th_http_raw(port, prepared, resp, respsz);+ free(prepared);+ return result;+}+/* HTTP status code from a raw response ("HTTP/1.1 404 ..."), or -1. */static int th_status(const char *resp) {if (strncmp(resp, "HTTP/1.1 ", 9) != 0)@@ -155,12 +211,39 @@ TEST(httpd_parse_simple_get) {ASSERT_STR_EQ(req.method, "GET");ASSERT_STR_EQ(req.path, "/api/logs");ASSERT_STR_EQ(req.query, "lines=5");+ ASSERT_EQ(req.http_minor, 1);ASSERT_STR_EQ(req.origin, "http://localhost:5173");ASSERT_EQ((int)clen, 0);ASSERT_EQ((int)body_off, (int)strlen(raw));PASS();}+TEST(httpd_parse_security_headers_and_rejects_duplicates) {+ const char *raw = "POST /rpc HTTP/1.1\r\n"+ "Host: 127.0.0.1:9749\r\n"+ "Content-Type: application/json\r\n"+ "Origin: http://127.0.0.1:9749\r\n"+ "Content-Length: 0\r\n\r\n";+ cbm_http_req_t req;+ size_t body_off = 0, content_length = 0;+ ASSERT_EQ(cbm_http_parse_head(raw, strlen(raw), &req, &body_off, &content_length), 0);+ ASSERT_STR_EQ(req.host, "127.0.0.1:9749");+ ASSERT_STR_EQ(req.content_type, "application/json");++ static const char *duplicates[] = {+ "GET / HTTP/1.1\r\nHost: localhost\r\nHost: localhost\r\n\r\n",+ "GET / HTTP/1.1\r\nOrigin: http://localhost\r\nOrigin: http://localhost\r\n\r\n",+ ("POST / HTTP/1.1\r\nContent-Type: application/json\r\nContent-Type: "+ "application/json\r\n\r\n"),+ };+ for (size_t i = 0; i < sizeof(duplicates) / sizeof(duplicates[0]); i++) {+ ASSERT_EQ(cbm_http_parse_head(duplicates[i], strlen(duplicates[i]), &req, &body_off,+ &content_length),+ 400);+ }+ PASS();+}+TEST(httpd_parse_post_with_body_offset) {const char *raw = "POST /rpc HTTP/1.1\r\n""Content-Length: 7\r\n"@@ -384,7 +467,7 @@ TEST(httpd_listen_ephemeral_port) {/* accept with a short timeout and no client → NULL, promptly */cbm_http_conn_t *c = cbm_httpd_accept(d, 50);ASSERT_NULL(c);- cbm_httpd_close(d);+ ASSERT_TRUE(cbm_httpd_close(d));PASS();}@@ -393,7 +476,22 @@ TEST(httpd_listen_port_collision_returns_null) {ASSERT_NOT_NULL(d1);cbm_httpd_t *d2 = cbm_httpd_listen(cbm_httpd_port(d1));ASSERT_NULL(d2);- cbm_httpd_close(d1);+ ASSERT_TRUE(cbm_httpd_close(d1));+ PASS();+}++TEST(httpd_close_refuses_while_connection_owns_listener) {+ cbm_httpd_t *listener = cbm_httpd_listen(0);+ ASSERT_NOT_NULL(listener);+ th_sock_t client = th_connect(cbm_httpd_port(listener));+ ASSERT_TRUE(client != TH_SOCK_BAD);+ cbm_http_conn_t *connection = cbm_httpd_accept(listener, 1000);+ ASSERT_NOT_NULL(connection);++ ASSERT_FALSE(cbm_httpd_close(listener));+ cbm_httpd_conn_close(connection);+ th_sock_close(client);+ ASSERT_TRUE(cbm_httpd_close(listener));PASS();}@@ -409,12 +507,21 @@ static void *th_server_thread(void *arg) {return NULL;}+static int th_server_thread_start(cbm_thread_t *thread, cbm_http_server_t *server) {+ if (!cbm_http_server_schedule_run(server))+ return -1;+ int rc = cbm_thread_create(thread, 0, th_server_thread, server);+ if (rc != 0 && !cbm_http_server_cancel_scheduled_run(server))+ return -1;+ return rc;+}+static int th_server_start(th_server_t *ts) {ts->srv = cbm_http_server_new(0);if (!ts->srv)return -1;- if (cbm_thread_create(&ts->tid, 0, th_server_thread, ts->srv) != 0) {- cbm_http_server_free(ts->srv);+ if (th_server_thread_start(&ts->tid, ts->srv) != 0) {+ (void)cbm_http_server_free(ts->srv);return -1;}return 0;@@ -425,8 +532,8 @@ static int th_server_start_with_watcher(th_server_t *ts, cbm_watcher_t *watcher)if (!ts->srv)return -1;cbm_http_server_set_watcher(ts->srv, watcher);- if (cbm_thread_create(&ts->tid, 0, th_server_thread, ts->srv) != 0) {- cbm_http_server_free(ts->srv);+ if (th_server_thread_start(&ts->tid, ts->srv) != 0) {+ (void)cbm_http_server_free(ts->srv);return -1;}return 0;@@ -438,6 +545,11 @@ typedef struct {char project_name[256];} th_ui_index_executor_t;+typedef struct {+ atomic_int calls;+ atomic_int release;+} th_ui_blocking_index_executor_t;+static int th_ui_index_executor(void *opaque, const char *root_path, const char *project_name) {th_ui_index_executor_t *executor = opaque;snprintf(executor->root_path, sizeof(executor->root_path), "%s", root_path);@@ -447,6 +559,17 @@ static int th_ui_index_executor(void *opaque, const char *root_path, const charreturn 0;}+static int th_ui_blocking_index_executor(void *opaque, const char *root_path,+ const char *project_name) {+ (void)root_path;+ (void)project_name;+ th_ui_blocking_index_executor_t *executor = opaque;+ atomic_fetch_add(&executor->calls, 1);+ while (!atomic_load(&executor->release))+ cbm_usleep(1000);+ return 0;+}+static bool th_wait_atomic_int(atomic_int *value, int expected, uint32_t timeout_ms) {uint64_t deadline = cbm_now_ms() + timeout_ms;while (cbm_now_ms() < deadline) {@@ -458,6 +581,28 @@ static bool th_wait_atomic_int(atomic_int *value, int expected, uint32_t timeoutreturn atomic_load(value) == expected;}+static bool th_wait_http_server_activity(cbm_http_server_t *server, cbm_httpd_activity_t expected,+ uint32_t timeout_ms) {+ uint64_t deadline = cbm_now_ms() + timeout_ms;+ while (cbm_now_ms() < deadline) {+ if (cbm_http_server_activity_for_test(server) == expected)+ return true;+ cbm_usleep(1000);+ }+ return cbm_http_server_activity_for_test(server) == expected;+}++static bool th_wait_httpd_activity(cbm_httpd_t *listener, cbm_httpd_activity_t expected,+ uint32_t timeout_ms) {+ uint64_t deadline = cbm_now_ms() + timeout_ms;+ while (cbm_now_ms() < deadline) {+ if (cbm_httpd_activity_for_test(listener) == expected)+ return true;+ cbm_usleep(1000);+ }+ return cbm_httpd_activity_for_test(listener) == expected;+}+typedef struct {atomic_int begin_calls;atomic_int end_calls;@@ -495,8 +640,8 @@ static int th_server_start_with_mutation_guard(th_server_t *ts, cbm_watcher_t *wcbm_http_server_set_watcher(ts->srv, watcher);cbm_http_server_set_project_mutation_guard(ts->srv, th_ui_mutation_begin, th_ui_mutation_end,guard);- if (cbm_thread_create(&ts->tid, 0, th_server_thread, ts->srv) != 0) {- cbm_http_server_free(ts->srv);+ if (th_server_thread_start(&ts->tid, ts->srv) != 0) {+ (void)cbm_http_server_free(ts->srv);return -1;}return 0;@@ -504,8 +649,8 @@ static int th_server_start_with_mutation_guard(th_server_t *ts, cbm_watcher_t *wstatic void th_server_stop(th_server_t *ts) {cbm_http_server_stop(ts->srv);- cbm_thread_join(&ts->tid);- cbm_http_server_free(ts->srv);+ (void)cbm_thread_join(&ts->tid);+ (void)cbm_http_server_free(ts->srv);}typedef struct {@@ -686,7 +831,7 @@ TEST(ui_server_routes_indexing_through_joinable_daemon_executor) {ts.srv = cbm_http_server_new(0);ASSERT_NOT_NULL(ts.srv);cbm_http_server_set_index_executor(ts.srv, th_ui_index_executor, &executor);- ASSERT_EQ(cbm_thread_create(&ts.tid, 0, th_server_thread, ts.srv), 0);+ ASSERT_EQ(th_server_thread_start(&ts.tid, ts.srv), 0);char body[1024];snprintf(body, sizeof(body), "{\"root_path\":\"%s\",\"project_name\":\"ui-project\"}", root);@@ -710,6 +855,50 @@ TEST(ui_server_routes_indexing_through_joinable_daemon_executor) {PASS();}+TEST(ui_server_free_never_joins_active_index_worker) {+ char *root = th_mktempdir("cbm_httpd_active_index");+ ASSERT_NOT_NULL(root);+ 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);++ char body[1024];+ snprintf(body, sizeof(body), "{\"root_path\":\"%s\",\"project_name\":\"blocked\"}", root);+ char request[1400];+ 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[4096];+ ASSERT_GT(th_http(cbm_http_server_port(ts.srv), request, response, sizeof(response)), 0);+ ASSERT_EQ(th_status(response), 202);+ ASSERT_TRUE(th_wait_atomic_int(&executor.calls, 1, 2000));++ cbm_http_server_stop(ts.srv);+ ASSERT_EQ(cbm_thread_join(&ts.tid), 0);+ uint64_t started = cbm_now_ms();+ ASSERT_FALSE(cbm_http_server_free(ts.srv));+ ASSERT_LT(cbm_now_ms() - started, 1000);++ atomic_store(&executor.release, 1);+ 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);+ }+ ASSERT_TRUE(freed);+ th_cleanup(root);+ PASS();+}+TEST(ui_server_root_serves_stub_404) {/* Test binary links embedded_stub.c → no frontend → 404 with marker */th_server_t ts;@@ -723,43 +912,114 @@ TEST(ui_server_root_serves_stub_404) {PASS();}-TEST(ui_server_cors_localhost_reflected) {+TEST(ui_server_same_origin_request_is_allowed) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);+ char req[512];+ snprintf(req, sizeof(req),+ "OPTIONS /rpc HTTP/1.1\r\n"+ "Host: 127.0.0.1:%d\r\n"+ "Origin: http://127.0.0.1:%d\r\n\r\n",+ port, port);char resp[4096];- int n = th_http(cbm_http_server_port(ts.srv),- "OPTIONS /rpc HTTP/1.1\r\n"- "Origin: http://localhost:5173\r\n\r\n",- resp, sizeof(resp));+ int n = th_http_raw(port, req, resp, sizeof(resp));ASSERT_GT(n, 0);ASSERT_EQ(th_status(resp), 204);- ASSERT_NOT_NULL(strstr(resp, "Access-Control-Allow-Origin: http://localhost:5173"));+ char expected_origin[128];+ snprintf(expected_origin, sizeof(expected_origin),+ "Access-Control-Allow-Origin: http://127.0.0.1:%d", port);+ ASSERT_NOT_NULL(strstr(resp, expected_origin));th_server_stop(&ts);PASS();}-TEST(ui_server_cors_evil_origin_not_reflected) {+TEST(ui_server_rejects_foreign_and_null_origins) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);char resp[4096];- int n = th_http(cbm_http_server_port(ts.srv),- "OPTIONS /rpc HTTP/1.1\r\n"- "Origin: http://evil.example.com\r\n\r\n",- resp, sizeof(resp));+ char req[768];+ snprintf(req, sizeof(req),+ "OPTIONS /rpc HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"+ "Origin: http://evil.example.com\r\n\r\n",+ port);+ int n = th_http_raw(port, req, resp, sizeof(resp));ASSERT_GT(n, 0);- ASSERT_EQ(th_status(resp), 204);+ ASSERT_EQ(th_status(resp), 403);ASSERT_NULL(strstr(resp, "Access-Control-Allow-Origin"));++ snprintf(req, sizeof(req), "GET / HTTP/1.1\r\nHost: localhost:%d\r\nOrigin: null\r\n\r\n",+ port);+ n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);++ snprintf(req, sizeof(req),+ "GET / HTTP/1.1\r\nHost: localhost:%d\r\n"+ "Origin: http://127.0.0.1:%d\r\n\r\n",+ port, port);+ n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);++ static const char body[] = "{\"project\":\"victim\",\"content\":\"poison\"}";+ snprintf(req, sizeof(req),+ "POST /api/adr HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"+ "Origin: http://evil.example.com\r\nContent-Type: text/plain\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ port, strlen(body), body);+ n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);+ th_server_stop(&ts);+ PASS();+}++TEST(ui_server_mutations_require_json_content_type) {+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ int port = cbm_http_server_port(ts.srv);+ const char *body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"list_projects\",\"arguments\":{}}}";+ char req[1024];+ char resp[8192];++ snprintf(req, sizeof(req),+ "POST /rpc HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"+ "Content-Type: text/plain\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ port, strlen(body), body);+ int n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 415);++ snprintf(req, sizeof(req),+ "POST /rpc HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ port, strlen(body), body);+ n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 415);++ snprintf(req, sizeof(req),+ "POST /rpc HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n"+ "Content-Type: application/json; charset=utf-8\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ port, strlen(body), body);+ n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 200);+th_server_stop(&ts);PASS();}-TEST(ui_server_rpc_initialize) {+TEST(ui_server_rpc_allows_only_ui_read_tools) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);- const char *body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\","- "\"params\":{\"protocolVersion\":\"2024-11-05\","- "\"capabilities\":{},"- "\"clientInfo\":{\"name\":\"t\",\"version\":\"0\"}}}";+ const char *body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"list_projects\",\"arguments\":{}}}";char req[1024];snprintf(req, sizeof(req),"POST /rpc HTTP/1.1\r\n"@@ -771,6 +1031,45 @@ TEST(ui_server_rpc_initialize) {ASSERT_GT(n, 0);ASSERT_EQ(th_status(resp), 200);ASSERT_NOT_NULL(strstr(resp, "\"jsonrpc\""));++ static const char *blocked_tools[] = {"delete_project", "manage_adr", "ingest_traces",+ "index_repository"};+ for (size_t i = 0; i < sizeof(blocked_tools) / sizeof(blocked_tools[0]); i++) {+ char blocked_body[512];+ snprintf(blocked_body, sizeof(blocked_body),+ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"%s\",\"arguments\":{}}}",+ blocked_tools[i]);+ snprintf(req, sizeof(req),+ "POST /rpc HTTP/1.1\r\nContent-Type: application/json\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ strlen(blocked_body), blocked_body);+ n = th_http(cbm_http_server_port(ts.srv), req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);+ }++ const char *initialize = "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"initialize\","+ "\"params\":{}}";+ snprintf(req, sizeof(req),+ "POST /rpc HTTP/1.1\r\nContent-Type: application/json\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ strlen(initialize), initialize);+ n = th_http(cbm_http_server_port(ts.srv), req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);++ const char *ambiguous = "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"list_projects\",\"name\":\"delete_project\","+ "\"arguments\":{}}}";+ snprintf(req, sizeof(req),+ "POST /rpc HTTP/1.1\r\nContent-Type: application/json\r\n"+ "Content-Length: %zu\r\n\r\n%s",+ strlen(ambiguous), ambiguous);+ n = th_http(cbm_http_server_port(ts.srv), req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);+th_server_stop(&ts);PASS();}@@ -1225,6 +1524,199 @@ TEST(ui_server_stop_joins_cleanly) {PASS();}+TEST(ui_server_free_refuses_active_loop) {+ cbm_http_server_t *server = cbm_http_server_new(0);+ ASSERT_NOT_NULL(server);++ cbm_thread_t thread;+ ASSERT_EQ(th_server_thread_start(&thread, server), 0);+ char response[512];+ ASSERT_GT(+ th_http(cbm_http_server_port(server), "GET / HTTP/1.1\r\n\r\n", response, sizeof(response)),+ 0);+ ASSERT_FALSE(cbm_http_server_free(server));+ cbm_http_server_stop(server);+ ASSERT_EQ(cbm_thread_join(&thread), 0);+ ASSERT_TRUE(cbm_http_server_free(server));+ PASS();+}++TEST(ui_server_free_refuses_scheduled_run_before_child_starts) {+ cbm_http_server_t *server = cbm_http_server_new(0);+ ASSERT_NOT_NULL(server);++ ASSERT_TRUE(cbm_http_server_schedule_run(server));+ ASSERT_FALSE(cbm_http_server_free(server));+ ASSERT_TRUE(cbm_http_server_cancel_scheduled_run(server));+ ASSERT_TRUE(cbm_http_server_free(server));+ PASS();+}++TEST(daemon_host_http_thread_create_failure_cancels_scheduled_run) {+ ASSERT_TRUE(cbm_daemon_host_http_thread_create_failure_lifecycle_for_test());+ PASS();+}++typedef struct {+ th_sock_t socket;+ atomic_int *operation_finished;+ atomic_int stop_finished;+ atomic_int watchdog_fired;+} th_http_stop_watchdog_t;++static void *th_http_stop_watchdog(void *opaque) {+ th_http_stop_watchdog_t *watchdog = opaque;+ for (int elapsed_ms = 0; elapsed_ms < 1500; elapsed_ms += 10) {+ if (atomic_load(&watchdog->stop_finished) ||+ (watchdog->operation_finished && atomic_load(watchdog->operation_finished)))+ return NULL;+ cbm_usleep(10 * 1000);+ }+ atomic_store(&watchdog->watchdog_fired, 1);+ (void)th_sock_shutdown(watchdog->socket);+ return NULL;+}++typedef struct {+ cbm_httpd_t *listener;+ atomic_int accepted;+ atomic_int finished;+} th_httpd_large_reply_t;++static void *th_httpd_large_reply(void *opaque) {+ th_httpd_large_reply_t *reply = opaque;+ cbm_http_conn_t *connection = cbm_httpd_accept(reply->listener, 3000);+ if (!connection) {+ atomic_store(&reply->finished, 1);+ return NULL;+ }+ atomic_store(&reply->accepted, 1);+ size_t response_size = 8U * 1024U * 1024U;+ char *response = malloc(response_size);+ if (response) {+ memset(response, 'R', response_size);+ cbm_http_reply_buf(connection, 200, "Content-Type: application/octet-stream\r\n", response,+ response_size);+ free(response);+ }+ cbm_httpd_conn_close(connection);+ atomic_store(&reply->finished, 1);+ return NULL;+}++TEST(httpd_interrupt_unblocks_nonreading_large_response_within_one_second) {+ cbm_httpd_t *listener = cbm_httpd_listen(0);+ ASSERT_NOT_NULL(listener);+ cbm_httpd_set_send_buffer_for_test(listener, 64 * 1024);+ th_httpd_large_reply_t reply = {.listener = listener};+ atomic_init(&reply.accepted, 0);+ atomic_init(&reply.finished, 0);++ th_sock_t socket = th_connect_with_recv_buffer(cbm_httpd_port(listener), 1024);+ ASSERT_TRUE(socket != TH_SOCK_BAD);+ cbm_thread_t reply_thread;+ ASSERT_EQ(cbm_thread_create(&reply_thread, 0, th_httpd_large_reply, &reply), 0);++ ASSERT_TRUE(th_wait_httpd_activity(listener, CBM_HTTPD_ACTIVITY_RESPONDING, 1000));+ ASSERT_EQ(atomic_load(&reply.accepted), 1);+ ASSERT_EQ(atomic_load(&reply.finished), 0);++ th_http_stop_watchdog_t watchdog = {+ .socket = socket,+ .operation_finished = &reply.finished,+ };+ atomic_init(&watchdog.stop_finished, 0);+ atomic_init(&watchdog.watchdog_fired, 0);+ cbm_thread_t watchdog_thread;+ ASSERT_EQ(cbm_thread_create(&watchdog_thread, 0, th_http_stop_watchdog, &watchdog), 0);++ uint64_t started = cbm_now_ms();+ cbm_httpd_interrupt(listener);+ ASSERT_EQ(cbm_thread_join(&reply_thread), 0);+ uint64_t elapsed = cbm_now_ms() - started;+ atomic_store(&watchdog.stop_finished, 1);+ ASSERT_EQ(cbm_thread_join(&watchdog_thread), 0);+ (void)th_sock_shutdown(socket);+ th_sock_close(socket);+ ASSERT_TRUE(cbm_httpd_close(listener));++ ASSERT_LT(elapsed, 500);+ ASSERT_EQ(atomic_load(&watchdog.watchdog_fired), 0);+ PASS();+}++TEST(httpd_nonreading_large_response_hits_send_deadline_without_interrupt) {+ cbm_httpd_t *listener = cbm_httpd_listen(0);+ ASSERT_NOT_NULL(listener);+ cbm_httpd_set_send_buffer_for_test(listener, 64 * 1024);+ th_httpd_large_reply_t reply = {.listener = listener};+ atomic_init(&reply.accepted, 0);+ atomic_init(&reply.finished, 0);++ th_sock_t socket = th_connect_with_recv_buffer(cbm_httpd_port(listener), 1024);+ ASSERT_TRUE(socket != TH_SOCK_BAD);+ cbm_thread_t reply_thread;+ ASSERT_EQ(cbm_thread_create(&reply_thread, 0, th_httpd_large_reply, &reply), 0);+ ASSERT_TRUE(th_wait_httpd_activity(listener, CBM_HTTPD_ACTIVITY_RESPONDING, 1000));+ ASSERT_EQ(atomic_load(&reply.accepted), 1);+ ASSERT_EQ(atomic_load(&reply.finished), 0);+ uint64_t started = cbm_now_ms();++ th_http_stop_watchdog_t watchdog = {+ .socket = socket,+ .operation_finished = &reply.finished,+ };+ atomic_init(&watchdog.stop_finished, 0);+ atomic_init(&watchdog.watchdog_fired, 0);+ cbm_thread_t watchdog_thread;+ ASSERT_EQ(cbm_thread_create(&watchdog_thread, 0, th_http_stop_watchdog, &watchdog), 0);++ ASSERT_EQ(cbm_thread_join(&reply_thread), 0);+ uint64_t elapsed = cbm_now_ms() - started;+ atomic_store(&watchdog.stop_finished, 1);+ ASSERT_EQ(cbm_thread_join(&watchdog_thread), 0);+ th_sock_close(socket);+ ASSERT_TRUE(cbm_httpd_close(listener));++ ASSERT_GTE(elapsed, 500);+ ASSERT_EQ(atomic_load(&watchdog.watchdog_fired), 0);+ PASS();+}++TEST(ui_server_stop_interrupts_partial_request_within_one_second) {+ th_server_t ts;+ ASSERT_EQ(th_server_start(&ts), 0);+ cbm_http_server_set_recv_deadline_ms(ts.srv, 3000);+ int port = cbm_http_server_port(ts.srv);+ th_sock_t socket = th_connect(port);+ ASSERT_TRUE(socket != TH_SOCK_BAD);++ char partial[256];+ snprintf(partial, sizeof(partial), "GET /api/logs HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n", port);+ ASSERT_EQ(th_send_all(socket, partial, strlen(partial)), 0);+ ASSERT_TRUE(th_wait_http_server_activity(ts.srv, CBM_HTTPD_ACTIVITY_READING_REQUEST, 1000));++ th_http_stop_watchdog_t watchdog = {.socket = socket};+ atomic_init(&watchdog.stop_finished, 0);+ atomic_init(&watchdog.watchdog_fired, 0);+ cbm_thread_t watchdog_thread;+ ASSERT_EQ(cbm_thread_create(&watchdog_thread, 0, th_http_stop_watchdog, &watchdog), 0);++ uint64_t started = cbm_now_ms();+ cbm_http_server_stop(ts.srv);+ ASSERT_EQ(cbm_thread_join(&ts.tid), 0);+ uint64_t elapsed = cbm_now_ms() - started;+ atomic_store(&watchdog.stop_finished, 1);+ ASSERT_EQ(cbm_thread_join(&watchdog_thread), 0);+ (void)th_sock_shutdown(socket);+ th_sock_close(socket);+ ASSERT_TRUE(cbm_http_server_free(ts.srv));++ ASSERT_LT(elapsed, 1000);+ ASSERT_EQ(atomic_load(&watchdog.watchdog_fired), 0);+ PASS();+}+/* ── /api/repo-info git-remote URL helpers (distilled from PR #789) ── *//* The web base must always be https (deep-links can't be downgraded) and must@@ -1293,9 +1785,14 @@ TEST(repo_info_strips_credentials_from_remote) {* the test FAILs deterministically rather than hanging CI. 0 on connect/timeout. */static int th_http_deadline(int port, const char *request, char *resp, size_t respsz,int timeout_ms) {+ char *prepared = th_request_with_ui_headers(port, request);+ if (!prepared)+ return 0;th_sock_t s = th_connect(port);- if (s == TH_SOCK_BAD)+ if (s == TH_SOCK_BAD) {+ free(prepared);return 0;+ }#ifdef _WIN32DWORD tv = (DWORD)timeout_ms;setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(tv));@@ -1305,10 +1802,12 @@ static int th_http_deadline(int port, const char *request, char *resp, size_t retv.tv_usec = (timeout_ms % 1000) * 1000;setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));#endif- if (th_send_all(s, request, strlen(request)) != 0) {+ if (th_send_all(s, prepared, strlen(prepared)) != 0) {+ free(prepared);th_sock_close(s);return 0;}+ free(prepared);int n = th_recv_until_close(s, resp, respsz);th_sock_close(s);return n;@@ -1406,10 +1905,10 @@ TEST(git_context_resolve_no_hang_under_live_ui_sockets) {#endif}-/* The server binds to loopback only. A request carrying a non-loopback Host- * header reached it under a foreign name — the DNS-rebinding / cross-site- * vector against a localhost service — and must be refused before routing. A- * loopback Host (or none) proceeds normally. */+/* Host is part of the authority boundary: HTTP/1.1 requires exactly one, and+ * the optional port must be the actual bound port. This blocks DNS rebinding+ * and prevents a foreign localhost service from manufacturing same-origin+ * requests for this daemon. */TEST(ui_server_rejects_non_loopback_host) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);@@ -1420,13 +1919,49 @@ TEST(ui_server_rejects_non_loopback_host) {ASSERT_GT(n, 0);ASSERT_EQ(th_status(resp), 403);- /* A loopback Host is not rejected (routes on to the normal 404 stub). */- char req[128];+ n = th_http_raw(port, "GET / HTTP/1.1\r\n\r\n", resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 400);++ static const char *bare_loopback_authorities[] = {+ "127.0.0.1",+ "localhost",+ "[::1]",+ };+ char req[256];+ for (size_t i = 0; i < sizeof(bare_loopback_authorities) / sizeof(bare_loopback_authorities[0]);+ i++) {+ snprintf(req, sizeof(req), "GET / HTTP/1.1\r\nHost: %s\r\n\r\n",+ bare_loopback_authorities[i]);+ n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);+ }++ snprintf(req, sizeof(req), "GET / HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n", port + 1);+ n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);+snprintf(req, sizeof(req), "GET / HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n", port);- n = th_http(port, req, resp, sizeof(resp));+ n = th_http_raw(port, req, resp, sizeof(resp));ASSERT_GT(n, 0);+ ASSERT_NEQ(th_status(resp), 400);ASSERT_NEQ(th_status(resp), 403);+ static const char *bare_origins[] = {+ "http://127.0.0.1",+ "http://localhost",+ "http://[::1]",+ };+ for (size_t i = 0; i < sizeof(bare_origins) / sizeof(bare_origins[0]); i++) {+ snprintf(req, sizeof(req), "GET / HTTP/1.1\r\nHost: 127.0.0.1:%d\r\nOrigin: %s\r\n\r\n",+ port, bare_origins[i]);+ n = th_http_raw(port, req, resp, sizeof(resp));+ ASSERT_GT(n, 0);+ ASSERT_EQ(th_status(resp), 403);+ }+th_server_stop(&ts);PASS();}@@ -1461,10 +1996,11 @@ TEST(ui_server_browse_wide_dir_no_overflow) {_exit(2);}char req[512];- snprintf(req, sizeof(req), "GET /api/browse?path=%s HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n",- dir);+ int port = cbm_http_server_port(ts.srv);+ snprintf(req, sizeof(req), "GET /api/browse?path=%s HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n",+ dir, port);char *resp = malloc(262144);- int n = resp ? th_http(cbm_http_server_port(ts.srv), req, resp, 262144) : 0;+ int n = resp ? th_http(port, req, resp, 262144) : 0;int ok = (n > 0 && strstr(resp, "HTTP/1.1 200") != NULL);free(resp);th_server_stop(&ts);@@ -1494,6 +2030,7 @@ SUITE(httpd) {RUN_TEST(ui_server_browse_wide_dir_no_overflow);/* Parser / helpers */RUN_TEST(httpd_parse_simple_get);+ RUN_TEST(httpd_parse_security_headers_and_rejects_duplicates);RUN_TEST(httpd_parse_post_with_body_offset);RUN_TEST(httpd_parse_origin_case_insensitive);RUN_TEST(httpd_parse_rejects_bare_lf);@@ -1515,16 +2052,19 @@ SUITE(httpd) {/* Transport */RUN_TEST(httpd_listen_ephemeral_port);RUN_TEST(httpd_listen_port_collision_returns_null);+ RUN_TEST(httpd_close_refuses_while_connection_owns_listener);/* Full UI server */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_routes_indexing_through_joinable_daemon_executor);+ RUN_TEST(ui_server_free_never_joins_active_index_worker);RUN_TEST(ui_server_root_serves_stub_404);- RUN_TEST(ui_server_cors_localhost_reflected);- RUN_TEST(ui_server_cors_evil_origin_not_reflected);- RUN_TEST(ui_server_rpc_initialize);+ RUN_TEST(ui_server_same_origin_request_is_allowed);+ RUN_TEST(ui_server_rejects_foreign_and_null_origins);+ RUN_TEST(ui_server_mutations_require_json_content_type);+ RUN_TEST(ui_server_rpc_allows_only_ui_read_tools);RUN_TEST(ui_server_oversized_body_rejected);RUN_TEST(ui_server_encoded_slash_not_routed);RUN_TEST(ui_server_nul_in_target_rejected);@@ -1544,6 +2084,12 @@ SUITE(httpd) {RUN_TEST(ui_server_slow_request_hits_deadline);RUN_TEST(ui_server_access_log_redacts_query);RUN_TEST(ui_server_stop_joins_cleanly);+ RUN_TEST(ui_server_free_refuses_active_loop);+ RUN_TEST(ui_server_free_refuses_scheduled_run_before_child_starts);+ RUN_TEST(daemon_host_http_thread_create_failure_cancels_scheduled_run);+ RUN_TEST(httpd_interrupt_unblocks_nonreading_large_response_within_one_second);+ RUN_TEST(httpd_nonreading_large_response_hits_send_deadline_without_interrupt);+ RUN_TEST(ui_server_stop_interrupts_partial_request_within_one_second);/* #798 follow-up: full UI-mode hang repro under live sockets */RUN_TEST(ui_server_list_projects_responds_under_watchdog);RUN_TEST(git_context_resolve_no_hang_under_live_ui_sockets);diff --git a/tests/test_main.c b/tests/test_main.cindex c5f2cbd3e..d153f0b4c 100644--- a/tests/test_main.c+++ b/tests/test_main.c@@ -21,6 +21,7 @@ int tf_skip_count = 0;#include "mcp/index_supervisor.h" /* cbm_index_set_worker_role */#include "mcp/mcp.h" /* cbm_mcp_handle_tool — act as a real worker */#include <sqlite3.h>+#include <errno.h>#include <stdbool.h>#include <stdint.h>#include <stdio.h>@@ -46,8 +47,37 @@ int tf_skip_count = 0;* unwind after either production containment or the test's verified backstop. */#define TF_BLOCKING_GIT_MARKER_ENV "CBM_TEST_RUNTIME_BLOCKING_GIT_PID_FILE"+#ifdef _WIN32+static bool tf_invoked_as_windows_git_module(void) {+ /* CreateProcessW authenticates the executable with lpApplicationName, but+ * the child CRT derives argv[0] from the separately supplied command line.+ * Inspect the actual loaded module so the copied git.exe probe cannot fall+ * through into the ordinary test runner when argv[0] is merely "git". */+ wchar_t image[32768];+ DWORD image_length =+ GetModuleFileNameW(NULL, image, (DWORD)(sizeof(image) / sizeof(image[0])));+ if (image_length == 0 || image_length >= (DWORD)(sizeof(image) / sizeof(image[0]))) {+ return false;+ }+ const wchar_t *base = image;+ for (const wchar_t *cursor = image; *cursor; cursor++) {+ if (*cursor == L'/' || *cursor == L'\\') {+ base = cursor + 1;+ }+ }+ return CompareStringOrdinal(base, -1, L"git.exe", -1, TRUE) == CSTR_EQUAL;+}+#endif+static bool tf_invoked_as_blocking_git(const char *argv0) {- if (!argv0 || !argv0[0] || !getenv(TF_BLOCKING_GIT_MARKER_ENV)) {+ if (!getenv(TF_BLOCKING_GIT_MARKER_ENV)) {+ return false;+ }+#ifdef _WIN32+ (void)argv0;+ return tf_invoked_as_windows_git_module();+#else+ if (!argv0 || !argv0[0]) {return false;}const char *base = argv0;@@ -56,7 +86,9 @@ static bool tf_invoked_as_blocking_git(const char *argv0) {base = cursor + 1;}}- return strcmp(base, "git") == 0 || strcmp(base, "git.exe") == 0 || strcmp(base, "GIT.EXE") == 0;+ return strcmp(base, "git") == 0 || strcmp(base, "git.exe") == 0 ||+ strcmp(base, "GIT.EXE") == 0;+#endif}#ifdef _WIN32@@ -67,15 +99,38 @@ static BOOL WINAPI tf_blocking_git_control_handler(DWORD event) {static int tf_maybe_run_blocking_git_probe(int argc, char **argv) {(void)argc;+#ifdef _WIN32+ bool windows_git_module = tf_invoked_as_windows_git_module();+ if (windows_git_module && !getenv(TF_BLOCKING_GIT_MARKER_ENV)) {+ (void)puts("TF_BLOCKING_GIT_DIAGNOSTIC marker_environment_missing");+ (void)fflush(stdout);+ return 32;+ }+#endifif (!argv || !tf_invoked_as_blocking_git(argv[0])) {return -1;}const char *marker_path = getenv(TF_BLOCKING_GIT_MARKER_ENV);+ errno = 0;+#ifdef _WIN32+ SetLastError(ERROR_SUCCESS);+#endifFILE *marker = cbm_fopen(marker_path, "wbx");if (!marker) {/* The first invocation already owns the blocking role. detect_changes* runs two more git commands after it terminates; those must not block. */+#ifdef _WIN32+ int marker_errno = errno;+ DWORD marker_error = GetLastError();+ bool marker_exists = cbm_file_exists(marker_path);+ (void)printf("TF_BLOCKING_GIT_DIAGNOSTIC marker_open_failed errno=%d win_error=%lu "+ "exists=%d\n",+ marker_errno, (unsigned long)marker_error, marker_exists ? 1 : 0);+ (void)fflush(stdout);+ return marker_exists ? 0 : 30;+#elsereturn cbm_file_exists(marker_path) ? 0 : 30;+#endif}#ifdef _WIN32unsigned long long process_id = (unsigned long long)GetCurrentProcessId();@@ -511,6 +566,15 @@ static bool suite_requested(const char *name) {* guard compares against it. */static bool g_list_only = false;+/* CBM_SKIP_PERF=1 excludes throughput/scale/perf-metric suites from the run.+ * The fidelity pass (CBM_LOCAL_CI_CPUS=4) and CI PRs set it: those suites+ * measure performance, which is meaningless under artificial CPU starvation,+ * and they dominate wall-clock. Correctness coverage is unaffected — the perf+ * suites run at full power in the perf/release legs (CBM_SKIP_PERF unset). The+ * skip applies to BOTH --list-suites and the run through the same macro, so+ * the shard union guard stays consistent. */+static bool g_skip_perf = false;+#define RUN_SELECTED_SUITE(name) \do { \if (g_list_only) { \@@ -520,6 +584,18 @@ static bool g_list_only = false;} \} while (0)+#define RUN_SELECTED_SUITE_PERF(name) \+ do { \+ if (g_skip_perf) { \+ break; \+ } \+ if (g_list_only) { \+ printf("%s\n", #name); \+ } else if (suite_requested(#name)) { \+ RUN_SUITE(name); \+ } \+ } while (0)+/* Forward declarations of suite functions */extern void suite_arena(void);extern void suite_hash_table(void);@@ -528,6 +604,7 @@ extern void suite_str_intern(void);extern void suite_log(void);extern void suite_str_util(void);extern void suite_platform(void);+extern void suite_diagnostics(void);extern void suite_subprocess(void);extern void suite_private_file_lock(void);extern void suite_lock_registry(void);@@ -728,6 +805,8 @@ int main(int argc, char **argv) {return 2;}+ const char *skip_perf_env = getenv("CBM_SKIP_PERF");+ g_skip_perf = skip_perf_env != NULL && strcmp(skip_perf_env, "1") == 0;if (argc == 2 && strcmp(argv[1], "--list-suites") == 0) {g_list_only = true;g_suite_argc = 1; /* no suite-name args to match */@@ -754,6 +833,7 @@ int main(int argc, char **argv) {RUN_SELECTED_SUITE(log);RUN_SELECTED_SUITE(str_util);RUN_SELECTED_SUITE(platform);+ RUN_SELECTED_SUITE(diagnostics);RUN_SELECTED_SUITE(subprocess);RUN_SELECTED_SUITE(private_file_lock);RUN_SELECTED_SUITE(lock_registry);@@ -834,14 +914,14 @@ int main(int argc, char **argv) {RUN_SELECTED_SUITE(c_lsp);RUN_SELECTED_SUITE(php_lsp);RUN_SELECTED_SUITE(cs_lsp);- RUN_SELECTED_SUITE(cs_lsp_bench);+ RUN_SELECTED_SUITE_PERF(cs_lsp_bench);RUN_SELECTED_SUITE(perl_lsp);RUN_SELECTED_SUITE(py_lsp);RUN_SELECTED_SUITE(kotlin_lsp);RUN_SELECTED_SUITE(rust_lsp);- RUN_SELECTED_SUITE(py_lsp_bench);+ RUN_SELECTED_SUITE_PERF(py_lsp_bench);RUN_SELECTED_SUITE(py_lsp_stress);- RUN_SELECTED_SUITE(py_lsp_scale);+ RUN_SELECTED_SUITE_PERF(py_lsp_scale);RUN_SELECTED_SUITE(ts_lsp);RUN_SELECTED_SUITE(java_lsp);RUN_SELECTED_SUITE(java_lsp_coverage);@@ -926,7 +1006,7 @@ int main(int argc, char **argv) {RUN_SELECTED_SUITE(grammar_probe_f);RUN_SELECTED_SUITE(grammar_probe_g);- RUN_SELECTED_SUITE(incremental);+ RUN_SELECTED_SUITE_PERF(incremental);if (g_list_only) {fflush(stdout);diff --git a/tests/test_mcp.c b/tests/test_mcp.cindex 8a38378d3..f1809dccd 100644--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@ -8838,7 +8838,25 @@ TEST(mcp_path_within_root_rejects_escape) {fputs("int outside;\n", fp);fclose(fp);- const char *junction_argv[] = {"cmd.exe", "/d", "/c", "mklink", "/J", junction, outside, NULL};+ /* cbm_tmpdir() can expose the MSYS spelling C:/msys64/...; cmd's mklink+ * builtin treats the slash before "msys64" as another option delimiter.+ * Native backslashes are required only at this cmd.exe fixture boundary. */+ char junction_native[sizeof(junction)];+ char outside_native[sizeof(outside)];+ snprintf(junction_native, sizeof(junction_native), "%s", junction);+ snprintf(outside_native, sizeof(outside_native), "%s", outside);+ for (char *cursor = junction_native; *cursor; cursor++) {+ if (*cursor == '/') {+ *cursor = '\\';+ }+ }+ for (char *cursor = outside_native; *cursor; cursor++) {+ if (*cursor == '/') {+ *cursor = '\\';+ }+ }+ const char *junction_argv[] = {"cmd.exe", "/d", "/c", "mklink", "/J",+ junction_native, outside_native, NULL};bool linked = cbm_exec_no_shell(junction_argv) == 0;ASSERT_TRUE(linked);@@ -8918,6 +8936,61 @@ TEST(detect_changes_rejects_option_like_base_branch) {PASS();}+TEST(detect_changes_rejects_windows_cmd_metacharacters_in_base_branch) {+#ifdef _WIN32+ const char *const branches[] = {"topic%PATH%", "topic!name!", "topic^name"};+ cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);+ ASSERT_NOT_NULL(srv);+ for (size_t i = 0; i < sizeof(branches) / sizeof(branches[0]); i++) {+ char request[512];+ snprintf(request, sizeof(request),+ "{\"jsonrpc\":\"2.0\",\"id\":78,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"detect_changes\","+ "\"arguments\":{\"project\":\"p\",\"base_branch\":\"%s\"}}}",+ branches[i]);+ char *response = cbm_mcp_server_handle(srv, request);+ ASSERT_NOT_NULL(response);+ ASSERT_NOT_NULL(strstr(response, "base_branch contains invalid characters"));+ free(response);+ }+ cbm_mcp_server_free(srv);+ PASS();+#else+ SKIP_PLATFORM("cmd.exe interpolation validation runs on Windows");+#endif+}++TEST(detect_changes_rejects_windows_cmd_metacharacters_in_project_root) {+#ifdef _WIN32+ const char *const roots[] = {"C:\\cbm-root-%PATH%", "C:\\cbm-root-!name!",+ "C:\\cbm-root-^name"};+ const char *project = "windows-cmd-root-validation";+ 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);+ cbm_mcp_server_set_project(srv, project);+ mcp_command_hook_probe_t command_probe = {0};+ cbm_mcp_server_set_command_test_hook(srv, mcp_command_hook_probe, &command_probe);++ for (size_t i = 0; i < sizeof(roots) / sizeof(roots[0]); i++) {+ ASSERT_EQ(cbm_store_upsert_project(store, project, roots[i]), CBM_STORE_OK);+ char *response = cbm_mcp_handle_tool(+ srv, "detect_changes",+ "{\"project\":\"windows-cmd-root-validation\",\"base_branch\":\"main\"}");+ ASSERT_NOT_NULL(response);+ ASSERT_NOT_NULL(strstr(response, "project path contains invalid characters"));+ free(response);+ }+ ASSERT_EQ(command_probe.diff_calls, 0);+ ASSERT_EQ(command_probe.merge_base_calls, 0);+ cbm_mcp_server_free(srv);+ PASS();+#else+ SKIP_PLATFORM("cmd.exe interpolation validation runs on Windows");+#endif+}+/* Opt-in workspace boundary: when CBM_ALLOWED_ROOT is set, index_repository* must refuse a repo_path that resolves outside it. Unset (the default) imposes* no restriction. */@@ -9205,6 +9278,8 @@ TEST(index_repository_supervisor_uses_canonical_session_path) {SUITE(mcp) {RUN_TEST(mcp_path_within_root_rejects_escape);RUN_TEST(detect_changes_rejects_option_like_base_branch);+ RUN_TEST(detect_changes_rejects_windows_cmd_metacharacters_in_base_branch);+ RUN_TEST(detect_changes_rejects_windows_cmd_metacharacters_in_project_root);RUN_TEST(index_repository_honors_allowed_root);/* JSON-RPC parsing */RUN_TEST(jsonrpc_parse_request);diff --git a/tests/test_platform.c b/tests/test_platform.cindex 3e1fe2fbf..d705c672f 100644--- a/tests/test_platform.c+++ b/tests/test_platform.c@@ -3,6 +3,8 @@*/#include "test_framework.h"#include "../src/foundation/compat.h" /* cbm_setenv / cbm_unsetenv (Windows-portable) */+#include "../src/foundation/compat_fs.h"+#include "../src/foundation/constants.h"#include "../src/foundation/compat_thread.h"#include "../src/foundation/platform.h"#include "../src/foundation/platform_internal.h"@@ -23,6 +25,83 @@enum { PLATFORM_TIME_THREADS = 8 };+#include <stdio.h>+#include <string.h>++/* Worker staging files land under CBM_CACHE_DIR, which users may place at+ * non-ASCII paths. On Windows the templates must round-trip through the wide+ * APIs; the ANSI CRT (_mktemp/_open) mangles UTF-8 bytes and fails. */+/* Store DB paths embed full repo-path-derived project names; deep repo or+ * runner paths overflow the legacy 260-char limit. The compat file layer must+ * carry absolute paths of any length (extended-length \\?\ form on+ * Windows). */+TEST(platform_file_apis_survive_max_path_overflow) {+ char base[CBM_SZ_512];+ int written = snprintf(base, sizeof(base), "/tmp/cbm-longpath-XXXXXX");+ ASSERT_TRUE(written > 0 && written < (int)sizeof(base));+ ASSERT_NOT_NULL(cbm_mkdtemp(base));++ enum { LONG_SEGMENTS = 5 };+ static const char segment[] =+ "segment-abcdefghijklmnopqrstuvwxyz0123456789-abcdefghijklmnop";+ char deep[CBM_SZ_1K];+ written = snprintf(deep, sizeof(deep), "%s", base);+ ASSERT_TRUE(written > 0 && written < (int)sizeof(deep));+ for (int index = 0; index < LONG_SEGMENTS; index++) {+ written = snprintf(deep + strlen(deep), sizeof(deep) - strlen(deep), "/%s", segment);+ ASSERT_TRUE(written > 0);+ }+ ASSERT_TRUE(strlen(deep) > 300);+ ASSERT_TRUE(cbm_mkdir_p(deep, 0700));++ char file_path[CBM_SZ_1K];+ written = snprintf(file_path, sizeof(file_path), "%s/store.db", deep);+ ASSERT_TRUE(written > 0 && written < (int)sizeof(file_path));+ FILE *file = cbm_fopen(file_path, "wb");+ ASSERT_NOT_NULL(file);+ ASSERT_GTE(fputs("deep\n", file), 0);+ ASSERT_EQ(fclose(file), 0);+ ASSERT_TRUE(cbm_file_exists(file_path));+ ASSERT_TRUE(cbm_is_dir(deep));+ ASSERT_EQ(cbm_unlink(file_path), 0);+ char cursor[CBM_SZ_1K];+ (void)snprintf(cursor, sizeof(cursor), "%s", deep);+ for (int index = 0; index < LONG_SEGMENTS; index++) {+ ASSERT_EQ(cbm_rmdir(cursor), 0);+ char *slash = strrchr(cursor, '/');+ ASSERT_NOT_NULL(slash);+ *slash = '\0';+ }+ (void)cbm_rmdir(base);+ PASS();+}++TEST(platform_mkstemp_and_mkdtemp_survive_non_ascii_directory) {+ char base[CBM_SZ_256];+ int written = snprintf(base, sizeof(base), "/tmp/cbm-utf8-éè-XXXXXX");+ ASSERT_TRUE(written > 0 && written < (int)sizeof(base));+ ASSERT_NOT_NULL(cbm_mkdtemp(base));++ char file_template[CBM_SZ_512];+ written = snprintf(file_template, sizeof(file_template), "%s/.probe-XXXXXX", base);+ ASSERT_TRUE(written > 0 && written < (int)sizeof(file_template));+ int descriptor = cbm_mkstemp(file_template);+ bool created = descriptor >= 0;+ if (created) {+#ifdef _WIN32+ _close(descriptor);+#else+ close(descriptor);+#endif+ (void)cbm_unlink(file_template);+ }+ (void)cbm_rmdir(base);+ ASSERT_TRUE(created);+ /* The returned path must keep the caller's UTF-8 directory intact. */+ ASSERT_NOT_NULL(strstr(file_template, "éè"));+ PASS();+}+TEST(platform_counter_scaling_avoids_intermediate_overflow) {const uint64_t frequency = UINT64_C(10000000);const uint64_t counter = UINT64_C(20000000000);@@ -532,6 +611,8 @@ TEST(cgroup_no_mem_files) {#endif /* __linux__ */SUITE(platform) {+ RUN_TEST(platform_file_apis_survive_max_path_overflow);+ RUN_TEST(platform_mkstemp_and_mkdtemp_survive_non_ascii_directory);RUN_TEST(platform_counter_scaling_avoids_intermediate_overflow);RUN_TEST(platform_counter_scaling_preserves_monotonic_deadlines);RUN_TEST(platform_now_ns_concurrent_first_call);diff --git a/tests/test_soak_daemon_recovery_contract.sh b/tests/test_soak_daemon_recovery_contract.shnew file mode 100644index 000000000..8bbba5302--- /dev/null+++ b/tests/test_soak_daemon_recovery_contract.sh@@ -0,0 +1,53 @@+#!/usr/bin/env bash+# Static contract for the daemon crash/restart assertions in the soak harness.+# Source-contract patterns intentionally retain shell variables literally.+# shellcheck disable=SC2016++set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+soak="$ROOT/scripts/soak-test.sh"++for required in \+ 'json_rpc_response_ok()' \+ 'and "result" in message' \+ 'diagnostics_start_count()' \+ 'DAEMON_PID=$(diagnostics_json_value pid)' \+ 'Idle daemon CPU:' \+ 'SOAK_PROJECT_VALUE="$SOAK_PROJECT"' \+ 'SOAK_PROJECT_VALUE=$(cygpath -m "$SOAK_PROJECT")' \+ 'SOAK_PROJECT_JSON=$(python3 -c' \+ 'mcp_response_project()' \+ 'PROJ_NAME=$(mcp_response_project "$MCP_LAST_RESPONSE")' \+ 'def handle_${i}(request):' \+ 'trace_path "{\"project\":\"$PROJ_NAME\",\"function_name\":\"handle_1\",\"direction\":\"both\"}"' \+ 'wait_for_daemon_stop "$DAEMON_STOP_COUNT"' \+ 'wait_for_daemon_stop "$FINAL_DAEMON_STOP_COUNT"' \+ 'wait_for_diagnostics_snapshot "$DIAGNOSTICS_START_COUNT" "$DIAG_FILE_BEFORE_CRASH"' \+ 'mcp_call index_repository "{\"repo_path\":$SOAK_PROJECT_JSON}" || PASS=false'; do+ if ! grep -Fq "$required" "$soak"; then+ echo "FAIL: daemon soak recovery contract missing: $required" >&2+ exit 1+ fi+done++if grep -Fq '"repo_path":"$SOAK_PROJECT"' "$soak"; then+ echo "FAIL: soak must not send an unconverted host/MSYS project path to a Windows binary" >&2+ exit 1+fi++if grep -Fq 'ps -o %cpu= -p "$SERVER_PID"' "$soak"; then+ echo "FAIL: soak idle CPU must not measure only the thin frontend" >&2+ exit 1+fi++if [ "$(grep -c '^PASS=true$' "$soak")" -ne 1 ]; then+ echo "FAIL: soak result state must be initialized exactly once" >&2+ exit 1+fi+if ! grep -Fq 'tests/test_soak_daemon_recovery_contract.sh' "$ROOT/scripts/test.sh"; then+ echo "FAIL: daemon soak recovery contract is not wired into the test suite" >&2+ exit 1+fi++echo "Daemon soak recovery contract passed"diff --git a/tests/test_subprocess.c b/tests/test_subprocess.cindex c8cf009cc..39a4b1249 100644--- a/tests/test_subprocess.c+++ b/tests/test_subprocess.c@@ -374,11 +374,15 @@ TEST(subprocess_spawn_returns_while_child_is_running) {cbm_subprocess_destroy(process);}- /* Generous thresholds distinguish a nonblocking call from waiting for the- * four-second probe, without making normal scheduler jitter test-significant. */- ASSERT_LT(spawn_elapsed, 1500);- ASSERT_LT(poll_elapsed, 1000);+ /* first_poll == RUNNING is the authoritative proof of non-blocking: the+ * 4s child is still running when spawn+poll returned. The wall-clock bounds+ * are only a coarse backstop against a regression that blocks on the child;+ * they stay well under the 4s child so heavy scheduler starvation (the+ * CBM_LOCAL_CI_CPUS=4 fidelity pass, CI runners) can never make them+ * test-significant. */ASSERT_EQ(first_poll, CBM_PROC_POLL_RUNNING);+ ASSERT_LT(spawn_elapsed, 3500);+ ASSERT_LT(poll_elapsed, 3500);ASSERT_TRUE(cancel_accepted);ASSERT_TRUE(terminal);ASSERT_TRUE(result.cancellation_requested);@@ -936,6 +940,46 @@ TEST(win_cmdline_overflow_leaves_empty_string) {PASS();}+/* cmd.exe /C receives command-language text, not another CRT argv element.+ * Preserve its quoted Windows paths byte-for-byte: generic argv quoting would+ * turn the payload's quotes into backslash-quote sequences before cmd sees it. */+TEST(win_cmd_payload_is_verbatim_and_capacity_checked) {+ const char *cmd = "C:\\Windows\\System32\\cmd.exe";+ const char *payload =+ "git -C \"C:\\Users\\test\\source repo\" diff --name-only \"main\"...HEAD 2>NUL";+ const char *expected =+ "\"C:\\Windows\\System32\\cmd.exe\" /D /S /V:OFF /C "+ "git -C \"C:\\Users\\test\\source repo\" diff --name-only \"main\"...HEAD 2>NUL";+ char result[512];++ ASSERT(cbm_build_win_cmd_payload(result, strlen(expected) + 1, cmd, payload));+ ASSERT_STR_EQ(result, expected);+ ASSERT_NULL(strstr(result, "\\\"C:\\Users"));++ memset(result, 'x', sizeof(result));+ ASSERT_FALSE(cbm_build_win_cmd_payload(result, strlen(expected), cmd, payload));+ ASSERT_EQ(result[0], '\0');+ PASS();+}++/* Input validation must inspect no bytes beyond short strings and must never+ * permit PATH lookup or a different executable behind the raw-payload mode. */+TEST(win_cmd_payload_rejects_short_relative_and_non_cmd_paths) {+ const char *payload = "echo ok";+ char result[256];+ ASSERT_FALSE(cbm_build_win_cmd_payload(result, sizeof(result), "", payload));+ ASSERT_FALSE(cbm_build_win_cmd_payload(result, sizeof(result), "C", payload));+ ASSERT_FALSE(cbm_build_win_cmd_payload(result, sizeof(result), "C:", payload));+ ASSERT_FALSE(cbm_build_win_cmd_payload(result, sizeof(result), "cmd.exe", payload));+ ASSERT_FALSE(+ cbm_build_win_cmd_payload(result, sizeof(result), "C:\\tools\\other.exe", payload));+ ASSERT_FALSE(+ cbm_build_win_cmd_payload(result, sizeof(result), "C:\\tools\\cmd.exe\\child", payload));+ ASSERT(+ cbm_build_win_cmd_payload(result, sizeof(result), "c:/Windows/System32/CMD.EXE", payload));+ PASS();+}+SUITE(subprocess) {RUN_TEST(subprocess_classify_clean);RUN_TEST(subprocess_classify_exit_nonzero);@@ -964,4 +1008,6 @@ SUITE(subprocess) {RUN_TEST(win_cmdline_roundtrip_battery);RUN_TEST(win_cmdline_overflow_rejected);RUN_TEST(win_cmdline_overflow_leaves_empty_string);+ RUN_TEST(win_cmd_payload_is_verbatim_and_capacity_checked);+ RUN_TEST(win_cmd_payload_rejects_short_relative_and_non_cmd_paths);}diff --git a/tests/test_ui_dev_proxy_security.sh b/tests/test_ui_dev_proxy_security.shnew file mode 100644index 000000000..63af12ad0--- /dev/null+++ b/tests/test_ui_dev_proxy_security.sh@@ -0,0 +1,28 @@+#!/usr/bin/env bash+# Static contract for the Vite-only loopback proxy security boundary.++set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+config="$ROOT/graph-ui/vite.config.ts"++for required in \+ 'strictPort: true' \+ 'bypass(req, res)' \+ '!uiDevOrigins.has(origin)' \+ 'res.writeHead(403' \+ 'headers: { Origin: uiBackendOrigin }'; do+ if ! grep -Fq "$required" "$config"; then+ echo "FAIL: Vite proxy security contract missing: $required" >&2+ exit 1+ fi+done++for origin in 'http://127.0.0.1:5173' 'http://localhost:5173'; do+ if ! grep -Fq "$origin" "$config"; then+ echo "FAIL: Vite proxy local development origin missing: $origin" >&2+ exit 1+ fi+done++echo "UI development proxy security contract passed"diff --git a/tests/test_vm_worktree_manifest.sh b/tests/test_vm_worktree_manifest.shindex 9d9d3e503..0711b6222 100644--- a/tests/test_vm_worktree_manifest.sh+++ b/tests/test_vm_worktree_manifest.sh@@ -84,12 +84,16 @@ if ! grep -Fq "JOBS='\$(nproc)'" "$provisioner" ||exit 1figuards_block="$(sed -n '/^guards)/,/^ ;;/p' "$driver")"-if ! grep -Fq 'scripts/build.sh --with-ui CC=clang CXX=clang++ SANITIZE= && powershell.exe' \+# The guards leg builds the CI-shaped product payload (embedded UI + launcher)+# into an isolated BUILD_DIR, then hands those artifacts to the maintained+# PowerShell driver through a plain cmd shell (CI's environment shape, not+# the MSYS2 login shell whose TMP ancestry the daemon correctly refuses).+if ! grep -Fq 'scripts/build.sh --with-ui CC=clang CXX=clang++ SANITIZE= BUILD_DIR=build/guards' \<<<"$guards_block" ||- ! grep -Fq 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/test-windows.ps1' \+ ! grep -Fq 'powershell -NoProfile -ExecutionPolicy Bypass -File scripts\\test-windows.ps1' \<<<"$guards_block" ||- ! grep -Fq -- '-GuardsOnly -Binary build/c/codebase-memory-mcp.exe' <<<"$guards_block" ||- ! grep -Fq -- '-Launcher build/c/codebase-memory-mcp-launcher.exe' <<<"$guards_block"; then+ ! grep -Fq -- '-GuardsOnly -Binary build\\guards\\codebase-memory-mcp.exe' <<<"$guards_block" ||+ ! grep -Fq -- '-Launcher build\\guards\\codebase-memory-mcp-launcher.exe' <<<"$guards_block"; thenecho "FAIL: Windows VM guards must delegate to the maintained native-Windows driver" >&2exit 1fidiff --git a/tests/test_watcher.c b/tests/test_watcher.cindex f89b5a2a2..ba7cf190e 100644--- a/tests/test_watcher.c+++ b/tests/test_watcher.c@@ -5,6 +5,8 @@* poll_once behavior.*/#include "../src/foundation/compat.h"+#include "../src/foundation/compat_thread.h"+#include "../src/foundation/constants.h"#include "../src/foundation/platform.h"#include "test_framework.h"#include "test_helpers.h"@@ -12,11 +14,19 @@#include <watcher/watcher.h>#include <store/store.h>#include <errno.h>+#include <stdatomic.h>+#include <signal.h>#include <string.h>#include <stdlib.h>#include <stdio.h>#include <unistd.h>#include <sys/stat.h>+#ifdef _WIN32+#include "../src/foundation/win_utf8.h"+#endif+#ifdef __APPLE__+#include <libproc.h>+#endif/* Portable git: `git -C "<dir>" <args>` with identity + non-interactive* config injected via -c, so it needs no global config and no POSIX shell@@ -139,6 +149,20 @@ TEST(watcher_watch_replace) {PASS();}+TEST(watcher_stopped_rejects_new_registration) {+ cbm_store_t *store = cbm_store_open_memory();+ cbm_watcher_t *w = cbm_watcher_new(store, NULL, NULL);+ ASSERT_NOT_NULL(w);++ cbm_watcher_stop(w);+ ASSERT_FALSE(cbm_watcher_watch(w, "late-project", "/tmp/late-project"));+ ASSERT_EQ(cbm_watcher_watch_count(w), 0);++ cbm_watcher_free(w);+ cbm_store_close(store);+ PASS();+}+TEST(watcher_null_safety) {/* All functions should be NULL-safe */cbm_watcher_free(NULL);@@ -645,6 +669,498 @@ TEST(watcher_stop_flag) {PASS();}+/* test_main turns an exact private-path alias named git/git.exe into a+ * deterministic child that publishes its PID and ignores graceful shutdown.+ * This reproduces the production failure where popen() left watcher shutdown+ * blocked forever in pclose(). The test owns a verified forced-termination+ * backstop so the pre-fix RED cannot wedge the rest of the suite. */+#define WATCHER_TEST_BLOCKING_GIT_MARKER_ENV "CBM_TEST_RUNTIME_BLOCKING_GIT_PID_FILE"++#ifdef _WIN32+typedef struct {+ cbm_watcher_t *watcher;+ atomic_bool completed;+} watcher_windows_blocked_run_t;++typedef struct {+ char canonical_path[CBM_SZ_4K];+ BY_HANDLE_FILE_INFORMATION information;+} watcher_windows_image_identity_t;++static void *watcher_windows_blocked_run_thread(void *opaque) {+ watcher_windows_blocked_run_t *run = opaque;+ (void)cbm_watcher_run(run->watcher, 10);+ atomic_store_explicit(&run->completed, true, memory_order_release);+ return NULL;+}++static bool watcher_windows_copy_self(const char *destination) {+ wchar_t source[32768];+ DWORD source_length =+ GetModuleFileNameW(NULL, source, (DWORD)(sizeof(source) / sizeof(source[0])));+ wchar_t *destination_wide = cbm_utf8_to_wide(destination);+ bool copied = source_length > 0 &&+ source_length < (DWORD)(sizeof(source) / sizeof(source[0])) && destination_wide &&+ CopyFileW(source, destination_wide, TRUE) != 0;+ free(destination_wide);+ return copied;+}++static bool watcher_windows_capture_image_identity(const char *path,+ watcher_windows_image_identity_t *identity) {+ if (!path || !identity) {+ return false;+ }+ memset(identity, 0, sizeof(*identity));+ if (!cbm_canonical_path(path, identity->canonical_path, sizeof(identity->canonical_path))) {+ return false;+ }+ wchar_t *wide = cbm_utf8_to_wide(identity->canonical_path);+ HANDLE file = wide ? CreateFileW(wide, FILE_READ_ATTRIBUTES,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL)+ : INVALID_HANDLE_VALUE;+ bool captured = file != INVALID_HANDLE_VALUE && GetFileType(file) == FILE_TYPE_DISK &&+ GetFileInformationByHandle(file, &identity->information) != 0 &&+ (identity->information.dwFileAttributes &+ (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0;+ if (file != INVALID_HANDLE_VALUE) {+ (void)CloseHandle(file);+ }+ free(wide);+ if (!captured) {+ memset(identity, 0, sizeof(*identity));+ }+ return captured;+}++static bool watcher_windows_same_image_identity(const watcher_windows_image_identity_t *first,+ const watcher_windows_image_identity_t *second) {+ return first && second && _stricmp(first->canonical_path, second->canonical_path) == 0 &&+ first->information.dwVolumeSerialNumber == second->information.dwVolumeSerialNumber &&+ first->information.nFileIndexHigh == second->information.nFileIndexHigh &&+ first->information.nFileIndexLow == second->information.nFileIndexLow;+}++static bool watcher_windows_process_matches_image(+ HANDLE process, const watcher_windows_image_identity_t *expected) {+ if (!process || !expected) {+ return false;+ }+ DWORD exit_code = 0;+ wchar_t image[32768];+ DWORD image_length = (DWORD)(sizeof(image) / sizeof(image[0]));+ bool queried = GetExitCodeProcess(process, &exit_code) != 0 && exit_code == STILL_ACTIVE &&+ QueryFullProcessImageNameW(process, 0U, image, &image_length) != 0 &&+ image_length > 0 && image_length < (DWORD)(sizeof(image) / sizeof(image[0]));+ if (queried) {+ image[image_length] = L'\0';+ }+ char *image_utf8 = queried ? cbm_wide_to_utf8(image) : NULL;+ watcher_windows_image_identity_t actual;+ bool captured = image_utf8 && watcher_windows_capture_image_identity(image_utf8, &actual);+ free(image_utf8);+ return captured && watcher_windows_same_image_identity(&actual, expected);+}++static bool watcher_windows_wait_pid(const char *marker, uint64_t deadline_ms,+ uint64_t *process_id_out) {+ if (process_id_out) {+ *process_id_out = 0;+ }+ while (cbm_now_ms() < deadline_ms) {+ FILE *file = cbm_fopen(marker, "rb");+ unsigned long long parsed = 0;+ bool valid = file && fscanf(file, "%llu", &parsed) == 1 && parsed > 1 &&+ parsed <= MAXDWORD && parsed != (unsigned long long)GetCurrentProcessId();+ if (file) {+ (void)fclose(file);+ }+ if (valid) {+ if (process_id_out) {+ *process_id_out = (uint64_t)parsed;+ }+ return true;+ }+ cbm_usleep(1000);+ }+ return false;+}++static HANDLE watcher_windows_open_exact_process(uint64_t process_id,+ const watcher_windows_image_identity_t *expected) {+ if (process_id <= 1 || process_id > MAXDWORD || process_id == (uint64_t)GetCurrentProcessId()) {+ return NULL;+ }+ HANDLE process =+ OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE | SYNCHRONIZE, FALSE,+ (DWORD)process_id);+ if (!watcher_windows_process_matches_image(process, expected)) {+ if (process) {+ (void)CloseHandle(process);+ }+ return NULL;+ }+ return process;+}++static bool watcher_windows_wait_complete(atomic_bool *completed, uint64_t deadline_ms) {+ while (cbm_now_ms() < deadline_ms) {+ if (atomic_load_explicit(completed, memory_order_acquire)) {+ return true;+ }+ cbm_usleep(1000);+ }+ return atomic_load_explicit(completed, memory_order_acquire);+}++static bool watcher_windows_wait_process_gone(HANDLE process, uint64_t deadline_ms) {+ while (cbm_now_ms() < deadline_ms) {+ if (WaitForSingleObject(process, 0U) == WAIT_OBJECT_0) {+ return true;+ }+ cbm_usleep(1000);+ }+ return WaitForSingleObject(process, 0U) == WAIT_OBJECT_0;+}++static bool watcher_windows_terminate_verified(HANDLE process,+ const watcher_windows_image_identity_t *expected,+ uint64_t deadline_ms) {+ if (!process) {+ return false;+ }+ if (WaitForSingleObject(process, 0U) == WAIT_OBJECT_0) {+ return true;+ }+ /* Re-query the live process image immediately before the only test-side+ * kill. The retained handle fixes the process instance; canonical path and+ * file identity ensure a cleanup backstop can target only our private copy. */+ if (!watcher_windows_process_matches_image(process, expected) ||+ TerminateProcess(process, 99U) == 0) {+ return false;+ }+ return watcher_windows_wait_process_gone(process, deadline_ms);+}+#endif++#if defined(__APPLE__) || defined(__linux__)+typedef struct {+ cbm_watcher_t *watcher;+ atomic_bool completed;+} watcher_blocked_run_t;++static void *watcher_blocked_run_thread(void *opaque) {+ watcher_blocked_run_t *run = opaque;+ (void)cbm_watcher_run(run->watcher, 10);+ atomic_store_explicit(&run->completed, true, memory_order_release);+ return NULL;+}++static bool watcher_test_self_image(char out[CBM_SZ_4K]) {+#ifdef __APPLE__+ int length = proc_pidpath(getpid(), out, CBM_SZ_4K);+ if (length <= 0 || length >= CBM_SZ_4K) {+ return false;+ }+ out[length] = '\0';+ return true;+#else+ ssize_t length = readlink("/proc/self/exe", out, CBM_SZ_4K - 1);+ if (length <= 0 || length >= CBM_SZ_4K - 1) {+ return false;+ }+ out[length] = '\0';+ return true;+#endif+}++static bool watcher_test_wait_pid(const char *marker, uint64_t deadline_ms, pid_t *pid_out) {+ while (cbm_now_ms() < deadline_ms) {+ FILE *file = cbm_fopen(marker, "rb");+ long parsed = 0;+ bool valid = file && fscanf(file, "%ld", &parsed) == 1 && parsed > 1 && parsed != getpid();+ if (file) {+ (void)fclose(file);+ }+ if (valid) {+ *pid_out = (pid_t)parsed;+ return true;+ }+ cbm_usleep(1000);+ }+ return false;+}++static bool watcher_test_wait_complete(atomic_bool *completed, uint64_t deadline_ms) {+ while (cbm_now_ms() < deadline_ms) {+ if (atomic_load_explicit(completed, memory_order_acquire)) {+ return true;+ }+ cbm_usleep(1000);+ }+ return atomic_load_explicit(completed, memory_order_acquire);+}++static bool watcher_test_wait_process_gone(pid_t process, uint64_t deadline_ms) {+ while (cbm_now_ms() < deadline_ms) {+ errno = 0;+ if (kill(process, 0) != 0 && errno == ESRCH) {+ return true;+ }+ cbm_usleep(1000);+ }+ errno = 0;+ return kill(process, 0) != 0 && errno == ESRCH;+}+#endif++TEST(watcher_stop_and_unwatch_cancel_blocked_git_without_backstop) {+#ifdef _WIN32+ char work[CBM_SZ_1K] = "/tmp/cbm-watcher-blocked-git-XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(work));+ char root[CBM_SZ_1K];+ char bin[CBM_SZ_1K];+ char fake_git[CBM_SZ_1K];+ char marker[CBM_SZ_1K];+ char unwatch_marker[CBM_SZ_1K];+ ASSERT_TRUE(snprintf(root, sizeof(root), "%s/root", work) > 0);+ ASSERT_TRUE(snprintf(bin, sizeof(bin), "%s/bin", work) > 0);+ ASSERT_TRUE(snprintf(fake_git, sizeof(fake_git), "%s/git.exe", bin) > 0);+ ASSERT_TRUE(snprintf(marker, sizeof(marker), "%s/git.pid", work) > 0);+ ASSERT_TRUE(snprintf(unwatch_marker, sizeof(unwatch_marker), "%s/unwatch-git.pid", work) > 0);+ ASSERT_TRUE(cbm_mkdir_p(root, 0700));+ ASSERT_TRUE(cbm_mkdir_p(bin, 0700));+ ASSERT_TRUE(watcher_windows_copy_self(fake_git));+ watcher_windows_image_identity_t expected_git;+ ASSERT_TRUE(watcher_windows_capture_image_identity(fake_git, &expected_git));++ const char *old_path_raw = getenv("PATH");+ const char *old_marker_raw = getenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV);+ char *old_path = old_path_raw ? cbm_strdup(old_path_raw) : NULL;+ char *old_marker = old_marker_raw ? cbm_strdup(old_marker_raw) : NULL;+ size_t path_size = strlen(bin) + 2 + (old_path ? strlen(old_path) : 0);+ char *path = malloc(path_size);+ ASSERT_NOT_NULL(path);+ (void)snprintf(path, path_size, "%s;%s", bin, old_path ? old_path : "");+ ASSERT_EQ(cbm_setenv("PATH", path, 1), 0);+ ASSERT_EQ(cbm_setenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV, marker, 1), 0);++ cbm_store_t *store = cbm_store_open_memory();+ cbm_watcher_t *watcher = cbm_watcher_new(store, NULL, NULL);+ ASSERT_NOT_NULL(watcher);+ ASSERT_TRUE(cbm_watcher_watch(watcher, "blocked-git", root));+ watcher_windows_blocked_run_t run = {.watcher = watcher};+ atomic_init(&run.completed, false);+ cbm_thread_t thread;+ ASSERT_EQ(cbm_thread_create(&thread, 128U * 1024U, watcher_windows_blocked_run_thread, &run),+ 0);++ uint64_t child_id = 0;+ bool marker_ready = watcher_windows_wait_pid(marker, cbm_now_ms() + 5000, &child_id);+ HANDLE child_process =+ marker_ready ? watcher_windows_open_exact_process(child_id, &expected_git) : NULL;+ bool exact_stop_image = child_process != NULL;+ cbm_watcher_stop(watcher);+ uint64_t stop_deadline = cbm_now_ms() + 2500;+ bool stop_process_gone =+ exact_stop_image && watcher_windows_wait_process_gone(child_process, stop_deadline);+ bool stop_run_completed = watcher_windows_wait_complete(&run.completed, stop_deadline);+ bool stopped_without_backstop = stop_process_gone && stop_run_completed;+ bool stop_cleanup_terminated = true;+ if (exact_stop_image && !stop_process_gone) {+ stop_cleanup_terminated =+ watcher_windows_terminate_verified(child_process, &expected_git, cbm_now_ms() + 5000);+ }+ bool cleanup_process_gone =+ exact_stop_image && watcher_windows_wait_process_gone(child_process, cbm_now_ms() + 5000);+ bool cleanup_completed = watcher_windows_wait_complete(&run.completed, cbm_now_ms() + 5000);+ int join_rc = cleanup_completed ? cbm_thread_join(&thread) : -1;+ if (child_process) {+ (void)CloseHandle(child_process);+ }+ cbm_watcher_free(watcher);++ /* A project losing its final daemon-session owner must cancel that+ * project's in-flight Git tree even while the shared watcher stays live. */+ ASSERT_EQ(cbm_setenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV, unwatch_marker, 1), 0);+ cbm_watcher_t *unwatch_watcher = cbm_watcher_new(store, NULL, NULL);+ ASSERT_NOT_NULL(unwatch_watcher);+ ASSERT_TRUE(cbm_watcher_watch(unwatch_watcher, "blocked-unwatch", root));+ watcher_windows_blocked_run_t unwatch_run = {.watcher = unwatch_watcher};+ atomic_init(&unwatch_run.completed, false);+ cbm_thread_t unwatch_thread;+ ASSERT_EQ(cbm_thread_create(&unwatch_thread, 128U * 1024U, watcher_windows_blocked_run_thread,+ &unwatch_run),+ 0);+ uint64_t unwatch_child_id = 0;+ bool unwatch_marker_ready =+ watcher_windows_wait_pid(unwatch_marker, cbm_now_ms() + 5000, &unwatch_child_id);+ HANDLE unwatch_process =+ unwatch_marker_ready ? watcher_windows_open_exact_process(unwatch_child_id, &expected_git)+ : NULL;+ bool exact_unwatch_image = unwatch_process != NULL;+ cbm_watcher_unwatch(unwatch_watcher, "blocked-unwatch");+ bool unwatch_cancelled_without_backstop =+ exact_unwatch_image &&+ watcher_windows_wait_process_gone(unwatch_process, cbm_now_ms() + 2500);+ bool unwatch_cleanup_terminated = true;+ if (exact_unwatch_image && !unwatch_cancelled_without_backstop) {+ unwatch_cleanup_terminated =+ watcher_windows_terminate_verified(unwatch_process, &expected_git, cbm_now_ms() + 5000);+ }+ bool unwatch_cleanup_gone = exact_unwatch_image && watcher_windows_wait_process_gone(+ unwatch_process, cbm_now_ms() + 5000);+ cbm_watcher_stop(unwatch_watcher);+ bool unwatch_run_completed =+ watcher_windows_wait_complete(&unwatch_run.completed, cbm_now_ms() + 5000);+ int unwatch_join_rc = unwatch_run_completed ? cbm_thread_join(&unwatch_thread) : -1;+ if (unwatch_process) {+ (void)CloseHandle(unwatch_process);+ }+ cbm_watcher_free(unwatch_watcher);+ cbm_store_close(store);+ if (old_path) {+ (void)cbm_setenv("PATH", old_path, 1);+ } else {+ (void)cbm_unsetenv("PATH");+ }+ if (old_marker) {+ (void)cbm_setenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV, old_marker, 1);+ } else {+ (void)cbm_unsetenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV);+ }+ free(path);+ free(old_marker);+ free(old_path);+ (void)th_rmtree(work);++ ASSERT_TRUE(marker_ready);+ ASSERT_TRUE(exact_stop_image);+ ASSERT_TRUE(stop_cleanup_terminated);+ ASSERT_TRUE(cleanup_process_gone);+ ASSERT_TRUE(cleanup_completed);+ ASSERT_EQ(join_rc, 0);+ ASSERT_TRUE(stopped_without_backstop);+ ASSERT_TRUE(unwatch_marker_ready);+ ASSERT_TRUE(exact_unwatch_image);+ ASSERT_TRUE(unwatch_cleanup_terminated);+ ASSERT_TRUE(unwatch_cancelled_without_backstop);+ ASSERT_TRUE(unwatch_cleanup_gone);+ ASSERT_TRUE(unwatch_run_completed);+ ASSERT_EQ(unwatch_join_rc, 0);+ PASS();+#elif defined(__APPLE__) || defined(__linux__)+ char work[CBM_SZ_1K] = "/tmp/cbm-watcher-blocked-git-XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(work));+ char root[CBM_SZ_1K];+ char bin[CBM_SZ_1K];+ char fake_git[CBM_SZ_1K];+ char marker[CBM_SZ_1K];+ char unwatch_marker[CBM_SZ_1K];+ char self[CBM_SZ_4K];+ ASSERT_TRUE(snprintf(root, sizeof(root), "%s/root", work) > 0);+ ASSERT_TRUE(snprintf(bin, sizeof(bin), "%s/bin", work) > 0);+ ASSERT_TRUE(snprintf(fake_git, sizeof(fake_git), "%s/git", bin) > 0);+ ASSERT_TRUE(snprintf(marker, sizeof(marker), "%s/git.pid", work) > 0);+ ASSERT_TRUE(snprintf(unwatch_marker, sizeof(unwatch_marker), "%s/unwatch-git.pid", work) > 0);+ ASSERT_TRUE(cbm_mkdir_p(root, 0700));+ ASSERT_TRUE(cbm_mkdir_p(bin, 0700));+ ASSERT_TRUE(watcher_test_self_image(self));+ ASSERT_EQ(symlink(self, fake_git), 0);++ const char *old_path_raw = getenv("PATH");+ const char *old_marker_raw = getenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV);+ char *old_path = old_path_raw ? strdup(old_path_raw) : NULL;+ char *old_marker = old_marker_raw ? strdup(old_marker_raw) : NULL;+ size_t path_size = strlen(bin) + 2 + (old_path ? strlen(old_path) : 0);+ char *path = malloc(path_size);+ ASSERT_NOT_NULL(path);+ (void)snprintf(path, path_size, "%s:%s", bin, old_path ? old_path : "");+ ASSERT_EQ(cbm_setenv("PATH", path, 1), 0);+ ASSERT_EQ(cbm_setenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV, marker, 1), 0);++ cbm_store_t *store = cbm_store_open_memory();+ cbm_watcher_t *watcher = cbm_watcher_new(store, NULL, NULL);+ ASSERT_NOT_NULL(watcher);+ cbm_watcher_watch(watcher, "blocked-git", root);+ watcher_blocked_run_t run = {.watcher = watcher};+ atomic_init(&run.completed, false);+ cbm_thread_t thread;+ ASSERT_EQ(cbm_thread_create(&thread, 128U * 1024U, watcher_blocked_run_thread, &run), 0);++ pid_t child = 0;+ bool marker_ready = watcher_test_wait_pid(marker, cbm_now_ms() + 5000, &child);+ cbm_watcher_stop(watcher);+ bool stopped_without_backstop =+ marker_ready && watcher_test_wait_complete(&run.completed, cbm_now_ms() + 2500);+ if (marker_ready && !stopped_without_backstop) {+ (void)kill(child, SIGKILL);+ }+ bool cleanup_completed = watcher_test_wait_complete(&run.completed, cbm_now_ms() + 5000);+ int join_rc = cleanup_completed ? cbm_thread_join(&thread) : -1;++ cbm_watcher_free(watcher);++ /* A project losing its final daemon-session owner must cancel that+ * project's in-flight Git tree even while the shared watcher stays live. */+ ASSERT_EQ(cbm_setenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV, unwatch_marker, 1), 0);+ cbm_watcher_t *unwatch_watcher = cbm_watcher_new(store, NULL, NULL);+ ASSERT_NOT_NULL(unwatch_watcher);+ ASSERT_TRUE(cbm_watcher_watch(unwatch_watcher, "blocked-unwatch", root));+ watcher_blocked_run_t unwatch_run = {.watcher = unwatch_watcher};+ atomic_init(&unwatch_run.completed, false);+ cbm_thread_t unwatch_thread;+ ASSERT_EQ(+ cbm_thread_create(&unwatch_thread, 128U * 1024U, watcher_blocked_run_thread, &unwatch_run),+ 0);+ pid_t unwatch_child = 0;+ bool unwatch_marker_ready =+ watcher_test_wait_pid(unwatch_marker, cbm_now_ms() + 5000, &unwatch_child);+ cbm_watcher_unwatch(unwatch_watcher, "blocked-unwatch");+ bool unwatch_cancelled_without_backstop =+ unwatch_marker_ready && watcher_test_wait_process_gone(unwatch_child, cbm_now_ms() + 2500);+ if (unwatch_marker_ready && !unwatch_cancelled_without_backstop) {+ (void)kill(unwatch_child, SIGKILL);+ }+ bool unwatch_cleanup_gone =+ unwatch_marker_ready && watcher_test_wait_process_gone(unwatch_child, cbm_now_ms() + 5000);+ cbm_watcher_stop(unwatch_watcher);+ bool unwatch_run_completed =+ watcher_test_wait_complete(&unwatch_run.completed, cbm_now_ms() + 5000);+ int unwatch_join_rc = unwatch_run_completed ? cbm_thread_join(&unwatch_thread) : -1;+ cbm_watcher_free(unwatch_watcher);+ cbm_store_close(store);+ if (old_path) {+ (void)cbm_setenv("PATH", old_path, 1);+ } else {+ (void)cbm_unsetenv("PATH");+ }+ if (old_marker) {+ (void)cbm_setenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV, old_marker, 1);+ } else {+ (void)cbm_unsetenv(WATCHER_TEST_BLOCKING_GIT_MARKER_ENV);+ }+ free(path);+ free(old_marker);+ free(old_path);+ (void)th_rmtree(work);++ ASSERT_TRUE(marker_ready);+ ASSERT_TRUE(cleanup_completed);+ ASSERT_EQ(join_rc, 0);+ ASSERT_TRUE(stopped_without_backstop);+ ASSERT_TRUE(unwatch_marker_ready);+ ASSERT_TRUE(unwatch_cancelled_without_backstop);+ ASSERT_TRUE(unwatch_cleanup_gone);+ ASSERT_TRUE(unwatch_run_completed);+ ASSERT_EQ(unwatch_join_rc, 0);+ PASS();+#else+ SKIP_PLATFORM("copied test-runner git probe is supported on Windows/macOS/Linux");+#endif+}+/* ══════════════════════════════════════════════════════════════════* GIT CHANGE DETECTION (with temp repo)* ══════════════════════════════════════════════════════════════════ */@@ -702,6 +1218,45 @@ TEST(watcher_detects_git_commit) {PASS();}+/* SHA-256 repositories emit a 64-hex-character HEAD. The watcher must retain+ * the complete object ID (plus line terminator/NUL while reading it), otherwise+ * baseline initialization silently retries forever and auto-refresh never runs. */+TEST(watcher_detects_sha256_git_commit) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_watcher_sha256_XXXXXX");+ if (!cbm_mkdtemp(tmpdir)) {+ FAIL("cbm_mkdtemp failed");+ }+ if (wt_git(tmpdir, "init -q --object-format=sha256") != 0) {+ th_rmtree(tmpdir);+ SKIP_PLATFORM("installed Git does not support SHA-256 repositories");+ }+ char path[300];+ th_write_file(wt_path(path, sizeof(path), tmpdir, "file.txt"), "first\n");+ ASSERT_EQ(wt_git(tmpdir, "add file.txt"), 0);+ ASSERT_EQ(wt_git(tmpdir, "commit -q -m first"), 0);++ cbm_store_t *store = cbm_store_open_memory();+ cbm_watcher_t *watcher = cbm_watcher_new(store, index_callback, NULL);+ ASSERT_NOT_NULL(watcher);+ ASSERT_TRUE(cbm_watcher_watch(watcher, "sha256-repo", tmpdir));+ index_call_count = 0;+ ASSERT_EQ(cbm_watcher_poll_once(watcher), 0); /* establish baseline */++ th_append_file(path, "second\n");+ ASSERT_EQ(wt_git(tmpdir, "add file.txt"), 0);+ ASSERT_EQ(wt_git(tmpdir, "commit -q -m second"), 0);+ cbm_watcher_touch(watcher, "sha256-repo");+ (void)cbm_watcher_poll_once(watcher);++ int observed = index_call_count;+ cbm_watcher_free(watcher);+ cbm_store_close(store);+ th_rmtree(tmpdir);+ ASSERT_EQ(observed, 1);+ PASS();+}+TEST(watcher_detects_dirty_worktree) {/* Create a temporary git repo */char tmpdir[256];@@ -2458,6 +3013,7 @@ SUITE(watcher) {RUN_TEST(watcher_watch_unwatch);RUN_TEST(watcher_unwatch_nonexistent);RUN_TEST(watcher_watch_replace);+ RUN_TEST(watcher_stopped_rejects_new_registration);RUN_TEST(watcher_null_safety);/* Polling */@@ -2473,9 +3029,11 @@ SUITE(watcher) {RUN_TEST(watcher_root_restore_resets_prune_streak);RUN_TEST(watcher_poll_this_repo);RUN_TEST(watcher_stop_flag);+ RUN_TEST(watcher_stop_and_unwatch_cancel_blocked_git_without_backstop);/* Git change detection */RUN_TEST(watcher_detects_git_commit);+ RUN_TEST(watcher_detects_sha256_git_commit);RUN_TEST(watcher_detects_dirty_worktree);RUN_TEST(watcher_identical_watch_preserves_dirty_baseline);RUN_TEST(watcher_detects_new_file);diff --git a/tests/test_windows_bundle_contract.sh b/tests/test_windows_bundle_contract.shindex 32dfa46cb..e1cf53793 100644--- a/tests/test_windows_bundle_contract.sh+++ b/tests/test_windows_bundle_contract.sh@@ -15,6 +15,7 @@ from __future__ import annotationsimport pathlibimport re+import subprocessimport sys@@ -31,6 +32,121 @@ def require(condition: bool, message: str) -> None:failures.append(message)+# The real-Windows local-CI drivers are documented as direct host entrypoints.+# Keep their Git checkout modes executable, and ensure the daily smoke command+# uses the isolated CI-equivalent harness rather than mutating the VM user's+# actual managed installation.+vm_host_scripts = (+ "test-infrastructure/vm/provision-windows.sh",+ "test-infrastructure/vm/vm-smoke.sh",+ "test-infrastructure/vm/win.sh",+)+for relative in vm_host_scripts:+ indexed = subprocess.run(+ ["git", "-C", str(root), "ls-files", "--stage", "--", relative],+ check=False,+ capture_output=True,+ text=True,+ )+ indexed_mode = indexed.stdout.split(maxsplit=1)[0] if indexed.returncode == 0 and indexed.stdout else ""+ require(+ indexed_mode == "100755"+ if indexed_mode+ else (root / relative).stat().st_mode & 0o111 != 0,+ f"{relative} must be executable as documented",+ )++vm_driver = read("test-infrastructure/vm/win.sh")+vm_provision = read("test-infrastructure/vm/provision-windows.sh")+vm_common = read("test-infrastructure/vm/ssh-common.sh")+require(+ "JOBS='$(nproc)'" in vm_driver,+ "win.sh must defer nproc expansion to the remote MSYS shell without over-escaping it",+)+for relative, source in (+ ("test-infrastructure/vm/win.sh", vm_driver),+ ("test-infrastructure/vm/provision-windows.sh", vm_provision),+):+ require(+ "StrictHostKeyChecking=no" not in source+ and "UserKnownHostsFile=/dev/null" not in source,+ f"{relative} must not disable SSH server identity verification",+ )+ require(+ "CBM_VM_HOST_KEY_SHA256" in source,+ f"{relative} must require the pinned VM SSH host-key fingerprint",+ )++require(+ "msys2-x86_64-latest" not in vm_provision+ and "msys2-base-x86_64-20260611.sfx.exe" in vm_provision+ and "c105946e64e08f099ac0e4647461ce762b95333ad211777666476a9a41451d65"+ in vm_provision,+ "provision-windows.sh must pin the official MSYS2 image and SHA-256 digest",+)+require(+ "pacman -Syu --noconfirm --noprogressbar\" || true" not in vm_provision,+ "provision-windows.sh must fail rather than hide an incomplete MSYS2 upgrade",+)+require(+ "feat/shared-coordination-daemon" not in vm_driver+ and "feat/shared-coordination-daemon" not in vm_provision,+ "Windows VM drivers must not default permanently to the feature branch",+)++local_ci_driver = read("test-infrastructure/run.sh")+require(+ "mac-vm)" not in local_ci_driver and "CBM_WIN_VM_SSH" not in local_ci_driver,+ "run.sh must not retain duplicate mutable VM drivers outside vm/win.sh",+)++vm_bootstrap = read("test-infrastructure/vm/windows-bootstrap.ps1")+require(+ re.search(r"ssh-(?:ed25519|rsa)\s+[A-Za-z0-9+/]{40,}={0,3}", vm_bootstrap) is None,+ "windows-bootstrap.ps1 must never embed an administrator-authorized SSH key",+)+require(+ "SshPublicKeyPath" in vm_bootstrap,+ "windows-bootstrap.ps1 must require an explicit caller-supplied SSH public key file",+)+smoke_case = re.search(r"^smoke-install\)\n(?P<body>.*?)^\s*;;", vm_driver, re.MULTILINE | re.DOTALL)+require(smoke_case is not None, "win.sh must expose the smoke-install command")+require(+ smoke_case is not None+ and "bash test-infrastructure/vm/vm-smoke.sh" in smoke_case.group("body"),+ "win.sh smoke-install must run the isolated CI-equivalent vm-smoke harness",+)+sync_case = re.search(r"^sync\)\n(?P<body>.*?)^\s*;;", vm_driver, re.MULTILINE | re.DOTALL)+require(sync_case is not None, "win.sh must expose an exact local-worktree sync command")+require(+ sync_case is not None+ and "cbm_vm_write_untracked_manifest" in sync_case.group("body")+ and "git -C \"$ROOT\" diff --binary" in sync_case.group("body")+ and "git reset --hard" in sync_case.group("body")+ and "git clean -fdx" in sync_case.group("body")+ and 'exec "$0" build' in sync_case.group("body")+ and "ls-files" in vm_common+ and '"$link"/*' in vm_common+ and "-e build" not in sync_case.group("body"),+ "win.sh sync must apply the binary Git diff plus untracked files, invalidate stale build "+ "outputs, and rebuild automatically",+)+require(+ sync_case is not None+ and "COPYFILE_DISABLE=1" in sync_case.group("body")+ and "--no-xattrs" in sync_case.group("body")+ and "--no-mac-metadata" in sync_case.group("body"),+ "win.sh sync must suppress macOS metadata instead of creating Windows AppleDouble files",+)+require(+ sync_case is not None+ and 'remote_head="$(vm clangarm64 "cd /c/cbm && git rev-parse --verify HEAD")"'+ in sync_case.group("body")+ and 'test \\"\\$(git rev-parse --verify HEAD)\\"' not in sync_case.group("body"),+ "win.sh sync must compare the remote HEAD locally instead of nesting shell quotes through cmd.exe",+)++def yaml_run_blocks(text: str) -> list[str]:"""Return literal/folded YAML run blocks without requiring PyYAML."""lines = text.splitlines()@@ -422,6 +538,22 @@ require(unsafe_acl_test.count('(extended_launcher, "extended DOS")') >= 2,"native Windows coverage must reject unsafe ancestor ACLs through extended DOS paths",)+add_only_start = windows_launcher_test.find(+ "def assert_add_only_ancestor_acl_allowed("+)+add_only_grant = windows_launcher_test.find(+ 'grant = run(["icacls", ancestor, "/grant", "*S-1-1-0:(AD)"]',+ add_only_start,+)+add_only_before_ace = windows_launcher_test[add_only_start:add_only_grant]+require(+ add_only_start >= 0+ and add_only_grant > add_only_start+ and 'before_ace = run([launcher, "--version"], env)' in add_only_before_ace+ and "launcher context failed before the add-only ACE was installed"+ in add_only_before_ace,+ "native add-only coverage must prove launcher-context authentication before mutating the ACL",+)require(windows_launcher_test.count("assert_launcher_death_contains_payload(") >= 2and "server.proc.kill()" in windows_launcher_test@@ -448,6 +580,225 @@ require("the permanent launcher must contain payloads and supervise immediate-parent death",)+# Launcher-context authentication accepts the launcher's bounded privileged+# owner set without widening the exact-current-owner policy used by mutable+# state transactions.+launcher_state_source = read("src/cli/windows_launcher_state.c")+generic_opener_start = launcher_state_source.find(+ "static HANDLE windows_open_regular_no_reparse_links("+)+context_opener_start = launcher_state_source.find(+ "static HANDLE windows_open_launcher_context_file("+)+generic_opener = launcher_state_source[generic_opener_start:context_opener_start]+context_opener_end = launcher_state_source.find(+ "static HANDLE windows_open_directory_secure_access(", context_opener_start+)+context_opener = launcher_state_source[context_opener_start:context_opener_end]+context_consume_start = launcher_state_source.rfind(+ "bool cbm_windows_launcher_context_consume("+)+context_consume_end = launcher_state_source.find(+ "bool cbm_windows_launcher_context_complete(", context_consume_start+)+context_consume = launcher_state_source[context_consume_start:context_consume_end]+require(+ generic_opener_start >= 0+ and context_opener_start > generic_opener_start+ and "windows_owner_is_current(file)" in generic_opener+ and "windows_owner_secure(file, false)" not in generic_opener,+ "generic Windows transaction-file opens must continue requiring the exact current owner",+)+require(+ context_opener_end > context_opener_start+ and all(+ needle in context_opener+ for needle in (+ "windows_path_tree_plain(path)",+ "windows_file_identity_links(file, &information, expected_links)",+ "windows_owner_secure(file, false)",+ "windows_acl_secure(file)",+ "FILE_FLAG_OPEN_REPARSE_POINT",+ )+ ),+ "launcher-context file opens must use the launcher trusted-owner set without weakening path, "+ "link-count, reparse-point, or ACL checks",+)+require(+ context_consume_start >= 0+ and context_consume_end > context_consume_start+ and all(+ needle in context_consume+ for needle in (+ "GetNamedPipeServerProcessId(pipe, &actual_pid)",+ "actual_pid == claimed_pid",+ "windows_filetime_equal(&actual_creation, &claimed_creation)",+ "QueryFullProcessImageNameW(server, 0U, actual_path, &actual_path_length)",+ "windows_open_launcher_context_file(actual_path, expected_launcher_links)",+ "windows_open_launcher_context_file(claimed_path, expected_launcher_links)",+ "windows_file_identity_links(actual_file, &actual_info, expected_launcher_links)",+ "windows_file_identity_links(claimed_file, &claimed_info, expected_launcher_links)",+ "windows_same_identity(&actual_info, &claimed_info)",+ "Windows launcher context actual image failed secure open",+ "Windows launcher context claimed path failed secure open",+ "Windows launcher context actual/claimed file identity mismatch",+ )+ ),+ "launcher-context consumption must bind PID/creation/file identity and diagnose each file-auth "+ "stage",+)++# Managed generations are exact two-file directories. Publication creates the+# canonical name as the generation launcher's second hard link; update and+# uninstall use mapped-image-safe namespace transactions rather than attempting+# to delete the mapped executable directly.+require(+ all(+ needle in launcher_state_source+ for needle in (+ "windows_generation_layout_exact",+ "CreateHardLinkW(stage, backing_path, NULL)",+ "windows_posix_rename_handle(stage_file, target_path)",+ "cbm_windows_managed_launcher_backing",+ "canonical launcher has no unique exact generation backing",+ "windows_open_regular_no_reparse_links(launcher_path, GENERIC_READ, 1U)",+ )+ ),+ "Windows launcher publication must enforce an exact two-file generation and exact-two "+ "canonical/backing hard-link identity",+)+capability_probe_start = launcher_state_source.rfind(+ "static bool windows_launcher_capability_probe_once("+)+capability_probe = launcher_state_source[capability_probe_start:]+require(+ capability_probe_start >= 0+ and "bool cbm_windows_launcher_capability_probe(" in capability_probe,+ "the capability probe implementation must keep its cold-scan retry wrapper",+)+require(+ all(+ needle in capability_probe+ for needle in (+ "old_generation",+ "new_generation",+ "windows_generation_layout_exact(old_generation, 2U, NULL)",+ "cbm_windows_launcher_replace_atomic(canonical, new_backing",+ "cbm_windows_launcher_remove_posix(canonical",+ "windows_posix_rename_handle_no_replace(state, retired_directory)",+ "windows_posix_rename_handle_no_replace(state, state_directory)",+ "WaitForSingleObject(child_b.hProcess, 0U) == WAIT_TIMEOUT",+ )+ ),+ "the capability probe must exercise the real exact-generation hard-link transaction and "+ "mapped state-directory retire/restore before session drain",+)+uninstall_commit_start = launcher_state_source.rfind(+ "bool cbm_windows_launcher_uninstall_commit("+)+uninstall_commit_end = launcher_state_source.find(+ "static bool windows_generation_directory_path(", uninstall_commit_start+)+uninstall_commit = launcher_state_source[uninstall_commit_start:uninstall_commit_end]+require(+ all(+ needle in uninstall_commit+ for needle in (+ "cbm_windows_retired_state_path",+ "windows_posix_rename_handle_no_replace(state, retired_directory)",+ "cbm_windows_launcher_remove_posix",+ "original_canonical_survived",+ "windows_same_identity(&canonical_information, &original_backing_information)",+ "windows_posix_rename_handle_no_replace(state, state_directory)",+ )+ ),+ "uninstall must retire state before its final canonical unlink and restore only when the "+ "original exact launcher identity survived",+)++cleanup_start = launcher_source.find("static bool launcher_schedule_managed_cleanup(")+cleanup_end = launcher_source.find("static bool launcher_read_all(", cleanup_start)+cleanup_source = launcher_source[cleanup_start:cleanup_end]+require(+ cleanup_start >= 0+ and all(+ needle in cleanup_source+ for needle in (+ "cbm_windows_retired_state_path",+ "cbm_windows_managed_launcher_backing",+ "GetSystemDirectoryW",+ 'L"%ls\\\\cmd.exe"',+ 'L"%ls\\\\ping.exe"',+ "DETACHED_PROCESS",+ "CREATE_NEW_PROCESS_GROUP",+ "CreateProcessW(command_path, mutable_command, NULL, NULL, FALSE",+ "retired_basename",+ )+ )+ and "rd /s /q .cbm" not in cleanup_source+ and "exist .cbm" not in cleanup_source,+ "launcher cleanup must delete only the authenticated retired basename via validated absolute "+ "System32 utilities and must preserve a concurrent reinstall's new .cbm",+)++cli_uninstall_source = read("src/cli/cli.c")+managed_uninstall_match = re.search(+ r"static int cli_windows_managed_uninstall_activate\(.*?\n}\n",+ cli_uninstall_source,+ re.DOTALL,+)+managed_uninstall = managed_uninstall_match.group(0) if managed_uninstall_match else ""+require(+ "cbm_windows_launcher_uninstall_commit" in managed_uninstall+ and "activation->state.payload_sha256" in managed_uninstall+ and "cbm_windows_launcher_remove_posix" not in managed_uninstall,+ "managed uninstall must use the state-retirement/final-unlink commit API rather than unlinking "+ "the mapped launcher directly",+)++require(+ all(+ needle in windows_launcher_test+ for needle in (+ "interrupted launcher-first initial install",+ "os.link(interrupted_backing, interrupted_launcher)",+ "assert_failed_uninstall_restores_state",+ "assert_uninstall_immediate_reinstall_safe",+ "retired_state_siblings",+ "old detached cleanup deleted or replaced",+ "canonical.samefile(backing)",+ "canonical.stat().st_nlink == 2",+ )+ ),+ "native Windows coverage must exercise interrupted hard-link publication, unlink rollback, "+ "retired cleanup, and immediate reinstall isolation",+)++# On Windows subprocess supervision receives a non-NULL lpApplicationName, so+# a literal `git` would not use PATH. Resolve only git.exe beneath inherited+# absolute PATH entries and never permit the current-directory search implied+# by empty or relative entries. POSIX retains execvp via argv[0].+watcher_source = read("src/watcher/watcher.c")+require(+ all(+ needle in watcher_source+ for needle in (+ "watcher_resolve_git_executable",+ 'GetEnvironmentVariableW(L"PATH"',+ 'L"%ls\\\\git.exe"',+ "GetFullPathNameW",+ "watcher_windows_path_absolute",+ "FILE_FLAG_OPEN_REPARSE_POINT",+ ".bin = git_executable",+ ".bin = argv[0]",+ "empty/relative entries",+ )+ )+ and "popen(" not in watcher_source,+ "Windows watcher Git commands must resolve an explicit absolute git.exe without cwd search "+ "while POSIX retains literal argv supervision",+)+# The build system exposes a distinct launcher artifact; release jobs later copy# that small binary to the canonical public name.makefile = read("Makefile.cbm")@@ -486,7 +837,7 @@ ancestor_security_contracts = {"windows_acl_secure_for_mutation(component, mutation)","windows_private_mutation_rights()","if (index < directory_length)",- "if (created->count > 0U)",+ "windows_private_mutation_rights() & ~((DWORD)FILE_ADD_SUBDIRECTORY)","mutation &= ~((DWORD)FILE_ADD_SUBDIRECTORY)","FILE_ADD_FILE","FILE_DELETE_CHILD",@@ -606,6 +957,12 @@ require(# use an explicit file:// CBM_DOWNLOAD_URL only for its local fixture, while the# installer and raw-curl phases continue to exercise the loopback HTTP server.smoke_script = read("scripts/smoke-test.sh")+require(+ 'copy_smoke_binary "$FAKE_HOME/.local/bin/codebase-memory-mcp.exe"' not in smoke_script+ and 'copy_smoke_binary "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"'+ not in smoke_script,+ "Windows smoke must leave managed canonical targets absent for authenticated install",+)require("smoke_mktemp_file" in smoke_scriptand "smoke_mktemp_dir" in smoke_scriptdiff --git a/tests/test_windows_launcher_state.c b/tests/test_windows_launcher_state.cindex d6a09911e..b040c6427 100644--- a/tests/test_windows_launcher_state.c+++ b/tests/test_windows_launcher_state.c@@ -320,6 +320,49 @@ TEST(windows_generation_path_is_launcher_relative_for_custom_unicode_directory)PASS();}+TEST(windows_generation_launcher_path_shares_the_payload_generation) {+ const wchar_t launcher[] =+ L"D:\\CBM Custom\\M\u00e4rtin\\\u5de5\u5177\\codebase-memory-mcp.exe";+ const wchar_t expected[] = L"D:\\CBM Custom\\M\u00e4rtin\\\u5de5\u5177\\.cbm\\generations\\"+ L"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\\"+ L"codebase-memory-mcp.exe";+ wchar_t actual[512];+ ASSERT_TRUE(cbm_windows_generation_launcher_path(launcher, launcher_sha256, actual,+ sizeof(actual) / sizeof(actual[0])));+ ASSERT_EQ(wcscmp(actual, expected), 0);++ const wchar_t root_launcher[] = L"C:\\codebase-memory-mcp.exe";+ const wchar_t root_expected[] =+ L"C:\\.cbm\\generations\\"+ L"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\\"+ L"codebase-memory-mcp.exe";+ ASSERT_TRUE(cbm_windows_generation_launcher_path(root_launcher, launcher_sha256, actual,+ sizeof(actual) / sizeof(actual[0])));+ ASSERT_EQ(wcscmp(actual, root_expected), 0);+ PASS();+}++TEST(windows_retired_state_path_is_unique_safe_and_launcher_relative) {+ const wchar_t launcher[] =+ L"D:\\CBM Custom\\M\u00e4rtin\\\u5de5\u5177\\codebase-memory-mcp.exe";+ const wchar_t expected[] =+ L"D:\\CBM Custom\\M\u00e4rtin\\\u5de5\u5177\\.cbm-retired-v1-"+ L"0123456789abcdef-4242";+ wchar_t actual[512];+ ASSERT_TRUE(cbm_windows_retired_state_path(launcher, launcher_sha256, 4242U, actual,+ sizeof(actual) / sizeof(actual[0])));+ ASSERT_EQ(wcscmp(actual, expected), 0);+ ASSERT_FALSE(cbm_windows_retired_state_path(launcher, launcher_sha256, 0U, actual,+ sizeof(actual) / sizeof(actual[0])));+ ASSERT_EQ(actual[0], L'\0');+ ASSERT_FALSE(cbm_windows_retired_state_path(L"codebase-memory-mcp.exe", launcher_sha256, 4242U,+ actual, sizeof(actual) / sizeof(actual[0])));+ ASSERT_EQ(actual[0], L'\0');+ ASSERT_FALSE(cbm_windows_retired_state_path(launcher, launcher_sha256, 4242U, actual, 32U));+ ASSERT_EQ(actual[0], L'\0');+ PASS();+}+TEST(windows_generation_path_rejects_ambiguous_or_truncated_inputs) {wchar_t output[512];memset(output, 0xa5, sizeof(output));@@ -337,6 +380,16 @@ TEST(windows_generation_path_rejects_ambiguous_or_truncated_inputs) {ASSERT_FALSE(cbm_windows_generation_payload_path(L"C:\\codebase-memory-mcp.exe", uppercase,output, sizeof(output) / sizeof(output[0])));ASSERT_EQ(output[0], L'\0');++ ASSERT_FALSE(cbm_windows_generation_launcher_path(L"codebase-memory-mcp.exe", launcher_sha256,+ output, sizeof(output) / sizeof(output[0])));+ ASSERT_EQ(output[0], L'\0');+ ASSERT_FALSE(cbm_windows_generation_launcher_path(L"C:\\codebase-memory-mcp.exe",+ launcher_sha256, output, 12));+ ASSERT_EQ(output[0], L'\0');+ ASSERT_FALSE(cbm_windows_generation_launcher_path(L"C:\\codebase-memory-mcp.exe", uppercase,+ output, sizeof(output) / sizeof(output[0])));+ ASSERT_EQ(output[0], L'\0');PASS();}@@ -389,6 +442,8 @@ SUITE(windows_launcher_state) {RUN_TEST(windows_current_v1_encoder_rejects_noncanonical_state);RUN_TEST(windows_current_v1_decoder_rejects_every_noncanonical_field);RUN_TEST(windows_generation_path_is_launcher_relative_for_custom_unicode_directory);+ RUN_TEST(windows_generation_launcher_path_shares_the_payload_generation);+ RUN_TEST(windows_retired_state_path_is_unique_safe_and_launcher_relative);RUN_TEST(windows_generation_path_rejects_ambiguous_or_truncated_inputs);RUN_TEST(windows_launcher_action_classifier_matches_top_level_dispatch);RUN_TEST(windows_portable_payload_rejects_only_managed_mutations);diff --git a/tests/windows/test_daemon_lifecycle.py b/tests/windows/test_daemon_lifecycle.pynew file mode 100644index 000000000..55ad85e66--- /dev/null+++ b/tests/windows/test_daemon_lifecycle.py@@ -0,0 +1,118 @@+r"""GREEN guard — explicit daemon lifecycle (`daemon start|status|stop`).++Guards the PR #1139 daemon-control surface at the product level:++* ``daemon status`` with no daemon reports not-running and exits nonzero.+* ``daemon start`` launches a PERMANENT daemon: it reports a pid, and the+ daemon survives its clients (a one-shot ``cli`` command recycles it without+ printing the cold-start hint, and the daemon is still active afterwards).+* A cold one-shot ``cli`` command (no daemon) prints the startup-tax hint.+* ``daemon stop`` on an idle daemon stops it; a second ``stop`` is idempotent.++Every path carries a kill-by-pid backstop so a stuck daemon can never hang the+suite (the Windows leg's test-infra hang sensitivity is on record).++Exit code: 0 == lifecycle behaves (green), 1 == regression, 2 == setup error.++Usage:+ python test_daemon_lifecycle.py <path-to-codebase-memory-mcp[.exe]>+"""+import os+import re+import subprocess+import sys+import tempfile+++def run_cli(binary, cache, args, timeout=60):+ env = dict(os.environ)+ env["CBM_CACHE_DIR"] = cache+ return subprocess.run([binary] + args, capture_output=True, timeout=timeout, env=env)+++def output_text(result):+ return ((result.stdout or b"") + (result.stderr or b"")).decode("utf-8", "replace")+++def force_kill(pid):+ if not pid:+ return+ if os.name == "nt":+ subprocess.run(["taskkill", "/F", "/PID", str(pid)], capture_output=True, timeout=30)+ else:+ subprocess.run(["kill", "-9", str(pid)], capture_output=True, timeout=30)+++def main():+ if len(sys.argv) < 2:+ print("usage: python test_daemon_lifecycle.py <binary>")+ return 2+ binary = os.path.abspath(sys.argv[1])+ if not os.path.exists(binary):+ print("FAIL: binary not found: %s" % binary)+ return 2++ work = tempfile.mkdtemp(prefix="cbm_win_daemonctl_")+ cache = os.path.join(work, "cache")+ os.makedirs(cache, exist_ok=True)+ daemon_pid = 0+ try:+ status_absent = run_cli(binary, cache, ["daemon", "status"])+ if status_absent.returncode == 0 or "not running" not in output_text(status_absent):+ print("RED: `daemon status` with no daemon should report not-running "+ "and exit nonzero:\n%s" % output_text(status_absent)[:300])+ return 1+ print("PASS: status reports not-running before any daemon exists")++ cold = run_cli(binary, cache, ["cli", "list_projects", "{}"])+ cold_text = output_text(cold)+ if cold.returncode != 0 or "daemon start" not in cold_text:+ print("RED: a cold one-shot cli command should succeed and hint at "+ "`daemon start`:\n%s" % cold_text[:400])+ return 1+ print("PASS: cold cli one-shot succeeded and printed the startup-tax hint")++ start = run_cli(binary, cache, ["daemon", "start"])+ start_text = output_text(start)+ pid_match = re.search(r"pid (\d+)", start_text)+ daemon_pid = int(pid_match.group(1)) if pid_match else 0+ if start.returncode != 0 or "permanent" not in start_text or not daemon_pid:+ print("RED: `daemon start` should report a permanent daemon with a pid:\n%s"+ % start_text[:400])+ return 1+ print("PASS: daemon start reported permanent pid %d" % daemon_pid)++ warm = run_cli(binary, cache, ["cli", "list_projects", "{}"])+ warm_text = output_text(warm)+ if warm.returncode != 0 or "daemon start" in warm_text:+ print("RED: a warm cli one-shot should recycle the daemon without the "+ "cold-start hint:\n%s" % warm_text[:400])+ return 1+ status_active = run_cli(binary, cache, ["daemon", "status"])+ status_text = output_text(status_active)+ if status_active.returncode != 0 or "permanent" not in status_text:+ print("RED: the permanent daemon should survive its cli client:\n%s"+ % status_text[:400])+ return 1+ print("PASS: warm cli recycled the daemon; daemon survived its client")++ stop = run_cli(binary, cache, ["daemon", "stop"])+ if stop.returncode != 0:+ print("RED: `daemon stop` on an idle daemon failed:\n%s"+ % output_text(stop)[:300])+ return 1+ stop_again = run_cli(binary, cache, ["daemon", "stop"])+ if stop_again.returncode != 0:+ print("RED: a second `daemon stop` should be idempotent:\n%s"+ % output_text(stop_again)[:300])+ return 1+ print("PASS: stop retired the idle daemon; second stop was idempotent")++ print("\nGREEN: daemon lifecycle (status/start/recycle/stop) behaves.")+ return 0+ finally:+ force_kill(daemon_pid)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/windows/test_hook_augment.py b/tests/windows/test_hook_augment.pyindex be809f368..d8d150a05 100644--- a/tests/windows/test_hook_augment.py+++ b/tests/windows/test_hook_augment.py@@ -26,6 +26,7 @@ Usage:"""import jsonimport os+import reimport shutilimport subprocessimport sys@@ -82,6 +83,20 @@ def main():return 2print("control: search_graph finds %s in project %s" % (SYMBOL, name))+ # Hooks are connect-only under the mandatory daemon: they never spawn+ # one and fail open when none is active. Bring up a permanent daemon+ # first — the supported way to keep hooks armed outside MCP sessions —+ # and retire it afterwards (with a kill-by-pid backstop so a stuck stop+ # can never hang CI).+ start = run_cli(binary, cache, ["daemon", "start"], timeout=60)+ start_out = (start.stdout or b"").decode("utf-8", "replace")+ print("daemon start rc=%d %r" % (start.returncode, start_out[:120]))+ if start.returncode != 0:+ print("SETUP FAIL: permanent daemon did not start")+ return 2+ pid_match = re.search(r"pid (\d+)", start_out)+ daemon_pid = int(pid_match.group(1)) if pid_match else 0+# Invoke hook-augment exactly as the installed PreToolUse hook does.payload = json.dumps({"hook_event_name": "PreToolUse",@@ -89,7 +104,21 @@ def main():"cwd": repo_fwd,"tool_input": {"pattern": SYMBOL},}).encode("utf-8")- ha = run_cli(binary, cache, ["hook-augment"], stdin=payload, timeout=60)+ try:+ ha = run_cli(binary, cache, ["hook-augment"], stdin=payload, timeout=60)+ finally:+ stopped = False+ try:+ stop = run_cli(binary, cache, ["daemon", "stop"], timeout=30)+ stopped = stop.returncode == 0+ except subprocess.TimeoutExpired:+ pass+ if not stopped and daemon_pid:+ subprocess.run(["taskkill" if os.name == "nt" else "kill",+ "/F" if os.name == "nt" else "-9",+ "/PID" if os.name == "nt" else str(daemon_pid)] ++ ([str(daemon_pid)] if os.name == "nt" else []),+ capture_output=True, timeout=30)out = (ha.stdout or b"").decode("utf-8", "replace").strip()print("hook-augment rc=%d stdout=%r" % (ha.returncode, out[:200]))diff --git a/tests/windows/test_ui_drive_listing.py b/tests/windows/test_ui_drive_listing.pyindex 2252c63cc..afa10fba6 100644--- a/tests/windows/test_ui_drive_listing.py+++ b/tests/windows/test_ui_drive_listing.py@@ -42,7 +42,11 @@ def list_fixed_drives():listdrives = getattr(os, "listdrives", None)if listdrives:try:- return [d for d in listdrives()]+ # os.listdrives() returns every mounted letter, including empty+ # optical drives and offline volumes. The picker contract under+ # test is "advertised == browsable", so only ready roots count+ # (isdir fails on a letter without a readable medium).+ return [d for d in listdrives() if os.path.isdir(d)]except Exception:passfound = []diff --git a/tests/windows/test_windows_launcher.py b/tests/windows/test_windows_launcher.pyindex 6179b8c65..9183f5afb 100644--- a/tests/windows/test_windows_launcher.py+++ b/tests/windows/test_windows_launcher.py@@ -227,13 +227,106 @@ def find_and_validate_current(managed_dir):/ digest/ "codebase-memory-mcp.payload.exe")+ backing = payload.parent / "codebase-memory-mcp.exe"+ canonical = managed_dir / "codebase-memory-mcp.exe"require(payload.is_file(), "current-v1 generation payload is missing: %s" % payload)+ require(backing.is_file(), "current-v1 generation launcher backing is missing: %s" % backing)+ require(canonical.is_file(), "managed canonical launcher is missing: %s" % canonical)+ require(+ {path.name for path in payload.parent.iterdir()}+ == {"codebase-memory-mcp.payload.exe", "codebase-memory-mcp.exe"},+ "managed generation must contain exactly payload plus launcher backing",+ )require(payload.stat().st_size == payload_size, "current-v1 payload size does not match")observed = hashlib.sha256(payload.read_bytes()).hexdigest()require(observed == digest, "installed generation name/digest does not match payload bytes")+ require(canonical.samefile(backing), "canonical launcher is not its generation hardlink")+ require(+ canonical.stat().st_nlink == 2 and backing.stat().st_nlink == 2,+ "canonical launcher/backing must report exactly two links",+ )+ require(payload.stat().st_nlink == 1, "generation payload must remain an exact one-link file")return current, data, payload+def current_v1_record(payload, abi_min=1, abi_max=1):+ digest = sha256_file(payload)+ record = bytearray(CURRENT_RECORD_SIZE)+ record[: len(CURRENT_MAGIC)] = CURRENT_MAGIC+ struct.pack_into("<I", record, CURRENT_FORMAT_OFFSET, 1)+ struct.pack_into("<I", record, CURRENT_SIZE_OFFSET, CURRENT_RECORD_SIZE)+ struct.pack_into("<I", record, CURRENT_ABI_MIN_OFFSET, abi_min)+ struct.pack_into("<I", record, CURRENT_ABI_MAX_OFFSET, abi_max)+ struct.pack_into("<Q", record, CURRENT_PAYLOAD_SIZE_OFFSET, payload.stat().st_size)+ record[+ CURRENT_SHA256_OFFSET : CURRENT_SHA256_OFFSET + CURRENT_SHA256_SIZE+ ] = digest.encode("ascii")+ return bytes(record)+++def generation_paths(managed_dir, payload):+ digest = sha256_file(payload)+ generation = managed_dir / ".cbm" / "generations" / digest+ return (+ generation,+ generation / "codebase-memory-mcp.payload.exe",+ generation / "codebase-memory-mcp.exe",+ )+++def wait_for_path_absent(path, timeout=30):+ deadline = time.monotonic() + timeout+ while path.exists() and time.monotonic() < deadline:+ time.sleep(0.05)+ return not path.exists()+++# The retired-state directory embeds the first 16 hex chars (64 bits) of the+# payload digest — enough to identify the generation while keeping the retired+# path within the managed uninstall's directory-rename length limit.+RETIRED_TAG_HEX = 16+++def retired_state_siblings(managed_dir, digest=None):+ tag = digest[:RETIRED_TAG_HEX] if digest else "*"+ pattern = ".cbm-retired-v1-%s-*" % tag+ return sorted(path for path in managed_dir.glob(pattern) if path.is_dir())+++def run_uninstall_observing_retirement(launcher, managed_dir, env, timeout=180):+ _, current_bytes, _ = find_and_validate_current(managed_dir)+ digest = current_bytes[+ CURRENT_SHA256_OFFSET : CURRENT_SHA256_OFFSET + CURRENT_SHA256_SIZE+ ].decode("ascii")+ process = subprocess.Popen(+ [str(launcher), "uninstall", "--yes"],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ env=env,+ )+ if process.stdin:+ process.stdin.close()+ process.stdin = None+ observed = set()+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ observed.update(retired_state_siblings(managed_dir, digest))+ if process.poll() is not None:+ break+ time.sleep(0.001)+ if process.poll() is None:+ process.kill()+ process.wait(timeout=5)+ raise GuardFailure("managed uninstall exceeded %ss" % timeout)+ stdout, stderr = process.communicate(timeout=5)+ observed.update(retired_state_siblings(managed_dir, digest))+ result = subprocess.CompletedProcess(+ [str(launcher), "uninstall", "--yes"], process.returncode, stdout, stderr+ )+ return result, observed, digest++def parse_release_descriptor(data):require(len(data) == DESCRIPTOR_RECORD_SIZE, "release descriptor size is not 128")require(data[:8] == DESCRIPTOR_MAGIC, "release descriptor magic is invalid")@@ -303,6 +396,12 @@ def assert_portable_mutations_refuse(source_payload, env, cache, work):# deterministic and fast. A correct implementation refuses before# it consults this URL or asks the daemon to drain.command_env["CBM_DOWNLOAD_URL"] = "https://127.0.0.1:1"+ # Warm the freshly-copied cold binary first: first-touch antivirus+ # scanning of the just-written image inflates process load time, and+ # the refusal itself is a fast STATELESS local check (no daemon IPC,+ # no download) whose timing is what this guard actually measures. The+ # warm-up refuses identically and is discarded.+ run([command_payload, action] + options, command_env, timeout=10)started = time.monotonic()result = run([command_payload, action] + options, command_env, timeout=10)elapsed = time.monotonic() - started@@ -407,6 +506,15 @@ def assert_add_only_ancestor_acl_allowed(source_launcher, source_payload, env, wlauncher, portable_payload = copy_portable_pair(source_launcher, source_payload, ancestor / "bundle")+ # The VM's hosted-runner policy can make this fresh copy+ # BUILTIN\Administrators-owned. Prove the trusted launcher context works+ # before the add-only ACE changes the ancestor's security descriptor.+ before_ace = run([launcher, "--version"], env)+ require(+ before_ace.returncode == 0,+ "launcher context failed before the add-only ACE was installed: %s"+ % output_text(before_ace)[-600:],+ )grant = run(["icacls", ancestor, "/grant", "*S-1-1-0:(AD)"], env)require(grant.returncode == 0,@@ -446,7 +554,7 @@ def assert_add_only_ancestor_acl_allowed(source_launcher, source_payload, env, w)managed_launcher = managed_dir / "codebase-memory-mcp.exe"require(managed_launcher.is_file(), "add-only managed install produced no launcher")- uninstall = run([managed_launcher, "uninstall", "--yes"], env, timeout=60)+ uninstall = run([managed_launcher, "uninstall", "--yes"], env, timeout=180)require(uninstall.returncode == 0,"add-only managed install could not be uninstalled: %s"@@ -714,6 +822,11 @@ def assert_launcher_relay(launcher, payload, env, cache):def assert_current_fail_closed(launcher, current, original, env):+ # cbm writes current-v1 with FILE_ATTRIBUTE_HIDDEN; Python's write_bytes+ # (CREATE_ALWAYS) cannot overwrite a hidden file (WinError 5 -> Errno 13),+ # so clear the attribute before corrupting it. The launcher reads current-v1+ # regardless of the attribute, so this does not affect the behavior tested.+ ctypes.windll.kernel32.SetFileAttributesW(ctypes.c_wchar_p(str(current)), 0x80)incompatible = bytearray(original)struct.pack_into("<II", incompatible, CURRENT_ABI_MIN_OFFSET, 0xFFFFFFFF, 0xFFFFFFFF)current.write_bytes(incompatible)@@ -742,13 +855,21 @@ def assert_managed_update():release = work / "release"release.mkdir()+ updated_payload = release / "updated-payload.exe"+ updated_payload.write_bytes(+ source_payload.read_bytes() + b"\0CBM runnable update generation fixture\n"+ )+ require(+ run([updated_payload, "--version"], env).returncode == 0,+ "PE-overlay update payload fixture is not runnable",+ )machine = platform.machine().lower()arch = "arm64" if machine in ("arm64", "aarch64") else "amd64"asset_name = "codebase-memory-mcp-windows-%s.zip" % archasset = release / asset_namewith zipfile.ZipFile(asset, "w", compression=zipfile.ZIP_STORED) as archive:archive.write(source_launcher, "codebase-memory-mcp.exe")- archive.write(source_payload, "codebase-memory-mcp.payload.exe")+ archive.write(updated_payload, "codebase-memory-mcp.payload.exe")archive.writestr("LICENSE", "test license\n")archive.writestr("install.ps1", "# test installer\n")archive.writestr("THIRD_PARTY_NOTICES.md", "test notices\n")@@ -759,11 +880,19 @@ def assert_managed_update(update_env = dict(env)update_env["CBM_DOWNLOAD_URL"] = release.resolve().as_uri()+ _, _, old_payload = find_and_validate_current(managed_dir)+ old_generation = old_payload.parentorphan_bytes = source_payload.read_bytes() + b"\0CBM generation prune fixture\n"orphan_digest = hashlib.sha256(orphan_bytes).hexdigest()orphan_directory = managed_dir / ".cbm" / "generations" / orphan_digestorphan_directory.mkdir()(orphan_directory / "codebase-memory-mcp.payload.exe").write_bytes(orphan_bytes)+ shutil.copy2(source_launcher, orphan_directory / "codebase-memory-mcp.exe")+ # A genuine orphan generation is cbm-created and current-user-owned; this+ # hand-built one defaults to the Administrators group on runner images, so+ # the update's owner-strict generation pruning (correctly) refuses it. Stamp+ # it so the prune reaches the same not-referenced verdict it would in reality.+ stamp_fixture_owner_current(orphan_directory, env)result = run([launcher, "update", "--force", "--standard", "--yes"],update_env,@@ -783,7 +912,33 @@ def assert_managed_update(run([generation_payload, "--version"], env).returncode == 0,"managed update returned with a non-runnable generation payload",)- require(not orphan_directory.exists(), "successful update did not prune old generation")+ require(not orphan_directory.exists(), "successful update did not prune orphan generation")+ require(+ old_generation.exists(),+ "update deleted the old generation while its supervising launcher was still mapped",+ )+ require(+ {path.name for path in old_generation.iterdir()}+ == {"codebase-memory-mcp.payload.exe", "codebase-memory-mcp.exe"}+ and (old_generation / "codebase-memory-mcp.exe").stat().st_nlink == 1,+ "deferred mapped old generation was not retained as an exact safe pair",+ )++ # The first updater has now exited, so a same-release activation can+ # prune the no-longer-mapped old backing without publishing another+ # generation.+ second = run(+ [launcher, "update", "--force", "--standard", "--yes"],+ update_env,+ timeout=90,+ )+ require(+ second.returncode == 0,+ "second managed update failed to prune deferred generation: %s"+ % output_text(second)[-1200:],+ )+ _, _, generation_payload = find_and_validate_current(managed_dir)+ require(not old_generation.exists(), "later activation did not prune unmapped old generation")generation_directories = [pathfor path in (managed_dir / ".cbm" / "generations").iterdir()@@ -794,7 +949,9 @@ def assert_managed_update(and generation_directories[0].name == generation_payload.parent.name,"successful update did not leave exactly the current generation",)- print("PASS: managed update committed a runnable pair and pruned non-current generations")+ print(+ "PASS: managed update retained mapped old backing, then pruned it on the next activation"+ )def assert_managed_update_rejects_unrunnable_launcher_before_drain(@@ -1040,14 +1197,244 @@ def assert_capability_probe_fail_hard(print("PASS: unsupported launcher capability failed hard before session drain")+def install_managed(portable_payload, managed_dir, env, timeout=180):+ return run(+ [+ portable_payload,+ "install",+ "--yes",+ "--force",+ "--skip-config",+ "--dir",+ managed_dir,+ ],+ env,+ timeout=timeout,+ )+++def stamp_fixture_owner_current(managed_dir, env):+ """Give a hand-built managed fixture the current-user ownership a genuine+ cbm install would stamp (windows_stamp_current_owner_private). Runner images+ default newly created files to the Administrators group, but the launcher's+ exact-owner validators — the recovery-install path and the capability+ probe's secure open of the target directory — (correctly) require the+ current user, so an Administrators-owned fixture is an unfaithful simulation+ of a real interrupted/partial install and must be re-owned."""+ result = run(+ ["icacls", str(managed_dir), "/setowner", os.environ.get("USERNAME", ""),+ "/T", "/C", "/Q"],+ env,+ )+ require(+ result.returncode == 0,+ "could not stamp current-user ownership on the managed fixture: %s"+ % output_text(result)[-400:],+ )+++def assert_partial_generation_recovery(+ source_launcher, source_payload, portable_payload, env, work+):+ # A current-v1 record is the commit point. Once it references a generation,+ # either missing half is corruption and install must fail without rewriting+ # or deleting the valid half.+ referenced = work / "referenced partial generation"+ _, referenced_payload, referenced_backing = generation_paths(+ referenced, source_payload+ )+ referenced_payload.parent.mkdir(parents=True)+ shutil.copy2(source_payload, referenced_payload)+ current = referenced / ".cbm" / "current-v1"+ current_bytes = current_v1_record(source_payload)+ current.write_bytes(current_bytes)+ payload_bytes = referenced_payload.read_bytes()+ rejected = install_managed(portable_payload, referenced, env, timeout=30)+ require(rejected.returncode != 0, "install repaired a current-referenced partial generation")+ require(current.read_bytes() == current_bytes, "failed partial repair changed current-v1")+ require(+ referenced_payload.read_bytes() == payload_bytes and not referenced_backing.exists(),+ "failed current-referenced repair modified or deleted the valid half",+ )++ # A failed unreferenced repair owns only the leaf it successfully creates.+ # A conflicting non-file at the missing leaf forces failure and the valid+ # payload half must remain byte-identical.+ blocked = work / "blocked partial generation repair"+ _, blocked_payload, blocked_backing = generation_paths(blocked, source_payload)+ blocked_payload.parent.mkdir(parents=True)+ shutil.copy2(source_payload, blocked_payload)+ blocked_bytes = blocked_payload.read_bytes()+ blocked_backing.mkdir()+ failed = install_managed(portable_payload, blocked, env, timeout=30)+ require(failed.returncode != 0, "conflicting partial generation repair succeeded")+ require(+ blocked_payload.read_bytes() == blocked_bytes and blocked_backing.is_dir(),+ "failed repair removed a pre-existing valid generation half",+ )++ # A launcher-first crash can leave the authenticated complete generation+ # published at canonical before current-v1 is committed. The exact-two+ # hardlink is intentionally not runnable as a portable launcher; install+ # must recognize and finish this one candidate without replacing either+ # immutable half.+ interrupted = work / "interrupted launcher-first initial install"+ _, interrupted_payload, interrupted_backing = generation_paths(+ interrupted, source_payload+ )+ interrupted_backing.parent.mkdir(parents=True)+ shutil.copy2(source_payload, interrupted_payload)+ shutil.copy2(source_launcher, interrupted_backing)+ interrupted_launcher = interrupted / "codebase-memory-mcp.exe"+ os.link(interrupted_backing, interrupted_launcher)+ payload_bytes = interrupted_payload.read_bytes()+ backing_bytes = interrupted_backing.read_bytes()+ require(+ interrupted_launcher.stat().st_nlink == 2+ and not (interrupted / ".cbm" / "current-v1").exists(),+ "interrupted launcher-first fixture is not exact pre-current state",+ )+ stamp_fixture_owner_current(interrupted, env)+ recovered = install_managed(portable_payload, interrupted, env)+ require(+ recovered.returncode == 0,+ "interrupted initial install recovery failed: %s"+ % output_text(recovered)[-800:],+ )+ require(+ interrupted_payload.read_bytes() == payload_bytes+ and interrupted_backing.read_bytes() == backing_bytes,+ "interrupted install recovery replaced an authenticated generation half",+ )+ find_and_validate_current(interrupted)+ assert_managed_uninstall(interrupted_launcher, interrupted, env)++ # The inverse safe partial (correct launcher backing, missing payload) is+ # repaired in place, then canonical is published as its second hardlink.+ launcher_only = work / "launcher-only partial generation"+ _, launcher_only_payload, launcher_only_backing = generation_paths(+ launcher_only, source_payload+ )+ launcher_only_backing.parent.mkdir(parents=True)+ shutil.copy2(source_launcher, launcher_only_backing)+ backing_bytes = launcher_only_backing.read_bytes()+ stamp_fixture_owner_current(launcher_only, env)+ repaired = install_managed(portable_payload, launcher_only, env)+ require(+ repaired.returncode == 0,+ "launcher-only generation repair failed: %s" % output_text(repaired)[-800:],+ )+ require(+ launcher_only_backing.read_bytes() == backing_bytes+ and launcher_only_payload.is_file(),+ "launcher-only repair replaced its valid half instead of adding the missing payload",+ )+ find_and_validate_current(launcher_only)+ assert_managed_uninstall(+ launcher_only / "codebase-memory-mcp.exe", launcher_only, env+ )+ print(+ "PASS: generation repair is additive, launcher-first recovery completes, "+ "and current-v1 corruption fails closed"+ )++def assert_managed_uninstall(launcher, managed_dir, env):- result = run([launcher, "uninstall", "--yes"], env, timeout=60)+ result, observed, digest = run_uninstall_observing_retirement(+ launcher, managed_dir, env+ )require(result.returncode == 0, "managed uninstall failed: %s" % output_text(result)[-800:])require(not launcher.exists(), "managed uninstall returned before launcher removal")- state = managed_dir / ".cbm"- leftovers = [p for p in state.rglob("*") if p.is_file()] if state.exists() else []- require(not leftovers, "managed uninstall left generation/current files behind: %s" % leftovers)- print("PASS: managed uninstall synchronously removed launcher and generation state")+ require(+ observed,+ "uninstall never exposed the authenticated SHA/PID retired-state commit",+ )+ deadline = time.monotonic() + 30+ while retired_state_siblings(managed_dir, digest) and time.monotonic() < deadline:+ time.sleep(0.05)+ require(+ not retired_state_siblings(managed_dir, digest),+ "launcher-owned detached cleanup did not remove the retired state after launcher exit",+ )+ require(+ not (managed_dir / ".cbm").exists(),+ "uninstall unexpectedly recreated the active .cbm state",+ )+ print("PASS: uninstall committed canonical unlink and cleaned only its retired SHA/PID state")+++def assert_failed_uninstall_restores_state(launcher, managed_dir, env):+ current, current_before, _ = find_and_validate_current(managed_dir)+ retired_before = set(retired_state_siblings(managed_dir))+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateFileW.argtypes = [+ wintypes.LPCWSTR,+ wintypes.DWORD,+ wintypes.DWORD,+ ctypes.c_void_p,+ wintypes.DWORD,+ wintypes.DWORD,+ wintypes.HANDLE,+ ]+ kernel32.CreateFileW.restype = wintypes.HANDLE+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL+ held_launcher = kernel32.CreateFileW(+ str(launcher), 0x80000000, 0x00000001, None, 3, 0x80, None+ )+ require(held_launcher != INVALID_HANDLE_VALUE, "could not lock uninstall launcher fixture")+ try:+ result = run([launcher, "uninstall", "--yes"], env, timeout=60)+ finally:+ kernel32.CloseHandle(held_launcher)+ require(result.returncode != 0, "share-blocked uninstall unexpectedly succeeded")+ require(current.read_bytes() == current_before, "failed uninstall changed current-v1")+ find_and_validate_current(managed_dir)+ require(+ set(retired_state_siblings(managed_dir)) == retired_before,+ "failed canonical unlink did not restore its retired state directory",+ )+ require(+ run([launcher, "--version"], env).returncode == 0,+ "failed uninstall did not leave a runnable launcher/current pair",+ )+ print("PASS: failed final unlink restored active state only for the original launcher identity")+++def assert_uninstall_immediate_reinstall_safe(+ launcher, managed_dir, portable_payload, env+):+ result, observed, digest = run_uninstall_observing_retirement(+ launcher, managed_dir, env+ )+ require(result.returncode == 0, "pre-reinstall uninstall failed: %s" % output_text(result)[-800:])+ require(observed, "immediate-reinstall test never observed retired state")+ require(not launcher.exists(), "uninstall returned before canonical unlink")++ reinstall = install_managed(portable_payload, managed_dir, env)+ require(+ reinstall.returncode == 0,+ "immediate managed reinstall failed: %s" % output_text(reinstall)[-800:],+ )+ new_current, new_current_bytes, _ = find_and_validate_current(managed_dir)+ deadline = time.monotonic() + 30+ while retired_state_siblings(managed_dir, digest) and time.monotonic() < deadline:+ time.sleep(0.05)+ require(+ not retired_state_siblings(managed_dir, digest),+ "detached cleanup did not remove its old retired state",+ )+ current_after, current_after_bytes, _ = find_and_validate_current(managed_dir)+ require(+ current_after == new_current and current_after_bytes == new_current_bytes,+ "old detached cleanup deleted or replaced the immediate reinstall's new .cbm",+ )+ require(+ run([launcher, "--version"], env).returncode == 0,+ "old detached cleanup broke the immediately reinstalled launcher",+ )+ print("PASS: retired cleanup preserved an immediate concurrent-generation reinstall")+ assert_managed_uninstall(launcher, managed_dir, env)def launcher_parent_probe_role():@@ -1112,58 +1499,30 @@ def main():_, portable_payload = copy_portable_pair(source_launcher, source_payload, work / "portable-install")- managed_dir = work / "managed café_日本語 with spaces"- # Reproduce the only durable partial state in a fresh launcher-first- # publication: the canonical launcher rename completed, then the- # process died before current-v1 was published. A retry must repair an- # exact private candidate, while the native preflight still rejects an- # unrelated conflicting launcher.- managed_dir.mkdir(parents=True)- interrupted_launcher = managed_dir / "codebase-memory-mcp.exe"- shutil.copy2(abi_mismatch_launcher, interrupted_launcher)- conflict = run(- [- portable_payload,- "install",- "--yes",- "--force",- "--skip-config",- "--dir",- managed_dir,- ],- env,- timeout=30,- )- require(- conflict.returncode != 0,- "fresh install accepted an unrelated launcher-only conflict",+ assert_partial_generation_recovery(+ source_launcher, source_payload, portable_payload, env, work)+ managed_dir = work / "managed café_日本語 with spaces"+ # The other safe partial (correct payload, missing launcher backing) is+ # the main managed fixture. Install must add only the missing half and+ # publish canonical as its second link.+ _, payload_half, backing_half = generation_paths(managed_dir, source_payload)+ payload_half.parent.mkdir(parents=True)+ shutil.copy2(source_payload, payload_half)+ payload_half_bytes = payload_half.read_bytes()+ stamp_fixture_owner_current(managed_dir, env)+ install = install_managed(portable_payload, managed_dir, env)+ require(install.returncode == 0, "managed install failed: %s" % output_text(install)[-800:])require(- sha256_file(interrupted_launcher) == sha256_file(abi_mismatch_launcher),- "rejected launcher-only conflict was modified",- )- shutil.copy2(source_launcher, interrupted_launcher)- install = run(- [- portable_payload,- "install",- "--yes",- "--force",- "--skip-config",- "--dir",- managed_dir,- ],- env,- timeout=60,+ payload_half.read_bytes() == payload_half_bytes and backing_half.is_file(),+ "payload-only repair replaced its valid half instead of adding the launcher",)- require(install.returncode == 0, "managed install failed: %s" % output_text(install)[-800:])launcher = managed_dir / "codebase-memory-mcp.exe"require(launcher.is_file(), "managed custom path has no canonical launcher")current, current_bytes, generation_payload = find_and_validate_current(managed_dir)print(- "PASS: interrupted fresh install recovered into a strict current-v1 "- "generation layout"+ "PASS: payload-only generation recovered into strict hardlink/current-v1 layout")assert_launcher_relay(launcher, generation_payload, env, cache)@@ -1206,7 +1565,10 @@ def main():assert_capability_probe_fail_hard(source_launcher, source_payload, launcher, env, cache, work)- assert_managed_uninstall(launcher, managed_dir, env)+ assert_failed_uninstall_restores_state(launcher, managed_dir, env)+ assert_uninstall_immediate_reinstall_safe(+ launcher, managed_dir, portable_payload, env+ )print("\nGREEN: permanent Windows launcher contract honored.")return 0except (GuardFailure, McpError, OSError, subprocess.SubprocessError) as exc: