Skip to content

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

fix(windows): ship one binary — remove the launcher stub flagged as a dropper

Martin Vogela54ea95719de
diff --git a/.github/workflows/_smoke.yml b/.github/workflows/_smoke.yml
index 26bb56795..7c175f710 100644
--- a/.github/workflows/_smoke.yml
+++ b/.github/workflows/_smoke.yml
@@ -206,18 +206,18 @@ jobs:
mkdir -p "$ARTIFACT_DIR"
unzip -o "codebase-memory-mcp${SUFFIX}-windows-${ARCH}.zip" -d "$ARTIFACT_DIR"
test -s "$ARTIFACT_DIR/codebase-memory-mcp.exe"
- test -s "$ARTIFACT_DIR/codebase-memory-mcp.payload.exe"
- # Pre-flight both images from a profile-rooted directory: the shared
- # runner workspace is deliberately not a valid launcher bundle root.
+ # ONE binary per platform: a payload sibling would mean the
+ # AV-flagged launcher stub came back.
+ test ! -e "$ARTIFACT_DIR/codebase-memory-mcp.payload.exe"
+ # Pre-flight the image from a profile-rooted directory: the shared
+ # runner workspace is deliberately not a valid install root.
PROFILE_ROOT="$(cygpath -u "$USERPROFILE")"
LAUNCH_DIR="$(mktemp -d "$PROFILE_ROOT/cbm-release-version.XXXXXX")"
# Best-effort cleanup with one retry: Windows holds the just-exited
# image's file busy for ~100ms (section teardown / first-touch AV),
# and a temp dir on an ephemeral runner must never fail the job.
trap 'rm -rf "$LAUNCH_DIR" 2>/dev/null || { sleep 2; rm -rf "$LAUNCH_DIR" 2>/dev/null || true; }' EXIT
- cp "$ARTIFACT_DIR/codebase-memory-mcp.exe" \
- "$ARTIFACT_DIR/codebase-memory-mcp.payload.exe" "$LAUNCH_DIR/"
- "$LAUNCH_DIR/codebase-memory-mcp.payload.exe" --version
+ cp "$ARTIFACT_DIR/codebase-memory-mcp.exe" "$LAUNCH_DIR/"
"$LAUNCH_DIR/codebase-memory-mcp.exe" --version
# ONE harness for every venue: the same script win.sh smoke-install and
@@ -241,13 +241,11 @@ jobs:
run: |
ARTIFACT_DIR="$(cygpath -u "$RUNNER_TEMP")/cbm-artifact"
scripts/security-strings.sh "$ARTIFACT_DIR/codebase-memory-mcp.exe"
- scripts/security-strings.sh "$ARTIFACT_DIR/codebase-memory-mcp.payload.exe"
PROFILE_ROOT="$(cygpath -u "$USERPROFILE")"
SECURITY_DIR="$(mktemp -d "$PROFILE_ROOT/cbm-release-security.XXXXXX")"
# Best-effort cleanup with one retry (see the version preflight).
trap 'rm -rf "$SECURITY_DIR" 2>/dev/null || { sleep 2; rm -rf "$SECURITY_DIR" 2>/dev/null || true; }' EXIT
- cp "$ARTIFACT_DIR/codebase-memory-mcp.exe" \
- "$ARTIFACT_DIR/codebase-memory-mcp.payload.exe" "$SECURITY_DIR/"
+ cp "$ARTIFACT_DIR/codebase-memory-mcp.exe" "$SECURITY_DIR/"
TMPDIR="$SECURITY_DIR" \
scripts/security-install.sh "$SECURITY_DIR/codebase-memory-mcp.exe"
@@ -256,7 +254,7 @@ jobs:
run: |
& "C:\Program Files\Windows Defender\MpCmdRun.exe" -SignatureUpdate 2>$null
$artifactDir = Join-Path $env:RUNNER_TEMP "cbm-artifact"
- foreach ($binary in @("codebase-memory-mcp.exe", "codebase-memory-mcp.payload.exe")) {
+ foreach ($binary in @("codebase-memory-mcp.exe")) {
$result = & "C:\Program Files\Windows Defender\MpCmdRun.exe" -Scan -ScanType 3 -File (Join-Path $artifactDir $binary) -DisableRemediation
$code = $LASTEXITCODE
Write-Host $result
diff --git a/Makefile.cbm b/Makefile.cbm
index 66c438ba9..657f4aacc 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -311,12 +311,7 @@ GIT_SRCS = src/git/git_context.c
CLI_SRCS = src/cli/cli.c src/cli/progress_sink.c src/cli/hook_augment.c \
src/cli/agent_clients.c src/cli/agent_profiles.c \
src/cli/config_json_like.c src/cli/config_toml_edit.c src/cli/config_yaml_edit.c \
- src/cli/config_text_edit.c src/cli/activation_transaction.c \
- src/cli/windows_launcher_state.c
-
-# Tiny permanent Windows launcher. It deliberately links only the stable
-# launcher-state module and Windows SDK libraries, never the parser/indexer.
-WINDOWS_LAUNCHER_SRC = src/launcher/windows_launcher.c
+ src/cli/config_text_edit.c src/cli/activation_transaction.c
# UI module (graph visualization)
UI_SRCS = \
@@ -490,8 +485,7 @@ TEST_TRACES_SRCS = tests/test_traces.c
TEST_CLI_SRCS = tests/test_cli.c tests/test_agent_clients.c tests/test_agent_profiles.c \
tests/test_config_json_like.c \
tests/test_config_toml_edit.c tests/test_config_yaml_edit.c tests/test_config_text_edit.c \
- tests/test_activation_transaction.c \
- tests/test_windows_launcher_state.c
+ tests/test_activation_transaction.c
TEST_MEM_SRCS = tests/test_mem.c
@@ -601,7 +595,7 @@ PP_OBJ_TSAN = $(BUILD_DIR)/tsan_preprocessor.o
# ── Targets ──────────────────────────────────────────────────────
-.PHONY: test test-par test-repro test-foundation test-tsan test-daemon-smoke cbm cbm-launcher cbm-with-ui frontend embed clean-c lint lint-tidy lint-cppcheck lint-format security
+.PHONY: test test-par test-repro test-foundation test-tsan test-daemon-smoke cbm cbm-with-ui frontend embed clean-c lint lint-tidy lint-cppcheck lint-format security
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
@@ -841,26 +835,6 @@ OBJS_VENDORED_PROD = $(MIMALLOC_OBJ_PROD) $(SQLITE3_OBJ_PROD) $(TRE_OBJ_PROD) $(
MAIN_SRC = src/main.c
-WINDOWS_LAUNCHER_TARGET :=
-ifeq ($(IS_MINGW),yes)
-WINDOWS_LAUNCHER_TARGET := $(BUILD_DIR)/codebase-memory-mcp-launcher.exe
-endif
-
-# Keep the explicit .exe target even on non-Windows hosts: packaging contracts
-# and native-Windows invocations share this single artifact name. A non-Windows
-# direct invocation builds a diagnostic stub and is not part of `cbm`.
-$(BUILD_DIR)/codebase-memory-mcp-launcher.exe: $(WINDOWS_LAUNCHER_SRC) src/cli/windows_launcher_state.c src/cli/windows_launcher_state.h | $(BUILD_DIR)
- $(CC) $(CFLAGS_PROD) -o $@ \
- $(WINDOWS_LAUNCHER_SRC) src/cli/windows_launcher_state.c \
- $(if $(filter yes,$(IS_MINGW)),-municode -lbcrypt $(WIN32_LIBS),)
-
-# Native-Windows compatibility fixture: its launcher ABI intentionally does
-# not fit the production payload's default [1,1] range. It is never packaged.
-$(BUILD_DIR)/codebase-memory-mcp-launcher-abi2.exe: $(WINDOWS_LAUNCHER_SRC) src/cli/windows_launcher_state.c src/cli/windows_launcher_state.h | $(BUILD_DIR)
- $(CC) $(CFLAGS_PROD) -DCBM_WINDOWS_LAUNCHER_ABI_CURRENT=2 -o $@ \
- $(WINDOWS_LAUNCHER_SRC) src/cli/windows_launcher_state.c \
- $(if $(filter yes,$(IS_MINGW)),-municode -lbcrypt $(WIN32_LIBS),)
-
$(BUILD_DIR)/codebase-memory-mcp: $(MAIN_SRC) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_PROD) | $(BUILD_DIR)
$(CC) $(CFLAGS_PROD) -o $@ \
$(MAIN_SRC) $(PROD_SRCS) \
@@ -868,12 +842,9 @@ $(BUILD_DIR)/codebase-memory-mcp: $(MAIN_SRC) $(PROD_SRCS) $(EXTRACTION_SRCS) $(
$(OBJS_VENDORED_PROD) \
$(LDFLAGS)
-cbm: $(BUILD_DIR)/codebase-memory-mcp $(WINDOWS_LAUNCHER_TARGET)
+cbm: $(BUILD_DIR)/codebase-memory-mcp
@echo "Built: $(BUILD_DIR)/codebase-memory-mcp"
-cbm-launcher: $(BUILD_DIR)/codebase-memory-mcp-launcher.exe
- @echo "Built: $(BUILD_DIR)/codebase-memory-mcp-launcher.exe"
-
# ── Build with embedded UI (requires Node.js) ───────────────────
# Swap embedded_stub.c for the generated embedded_assets.c
@@ -889,7 +860,7 @@ frontend:
embed: frontend
scripts/embed-frontend.sh graph-ui/dist $(BUILD_DIR)/embedded
-cbm-with-ui: embed $(OBJS_VENDORED_PROD) $(WINDOWS_LAUNCHER_TARGET)
+cbm-with-ui: embed $(OBJS_VENDORED_PROD)
$(CC) $(CFLAGS_PROD) -o $(BUILD_DIR)/codebase-memory-mcp \
$(MAIN_SRC) $(PROD_SRCS_WITH_ASSETS) \
$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \
@@ -919,7 +890,7 @@ SYSROOT_FLAG = $(if $(SYSROOT),-isysroot $(SYSROOT),)
LINT_SRCS = $(FOUNDATION_SRCS) $(STORE_SRCS) $(CYPHER_SRCS) $(MCP_SRCS) $(DAEMON_SRCS) \
$(DISCOVER_SRCS) $(GRAPH_BUFFER_SRCS) $(PIPELINE_SRCS) $(SIMHASH_SRCS) $(SEMANTIC_SRCS) \
$(TRACES_SRCS) $(WATCHER_SRCS) $(CLI_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) \
- $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(MAIN_SRC) $(WINDOWS_LAUNCHER_SRC)
+ $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(MAIN_SRC)
LINT_HDRS = $(wildcard src/**/*.h src/*.h $(CBM_DIR)/*.h)
LINT_TEST_SRCS = $(ALL_TEST_SRCS)
diff --git a/install.ps1 b/install.ps1
index 0cae9a24a..60df83477 100644
--- a/install.ps1
+++ b/install.ps1
@@ -14,10 +14,8 @@ Add-Type -AssemblyName System.Net.Http
$Repo = "DeusData/codebase-memory-mcp"
$InstallDir = "$env:LOCALAPPDATA\Programs\codebase-memory-mcp"
$BinName = "codebase-memory-mcp.exe"
-$PayloadName = "codebase-memory-mcp.payload.exe"
$WindowsArchiveNames = @(
$BinName,
- $PayloadName,
"LICENSE",
"install.ps1",
"THIRD_PARTY_NOTICES.md"
@@ -237,32 +235,28 @@ try {
exit 1
}
-# Extract the complete, validated bundle. The portable launcher owns the
-# managed install transaction and contains its adjacent payload.
+# Extract the validated bundle. Windows ships ONE binary, exactly like Linux
+# and macOS; this script is what replaces it, because a running executable
+# cannot replace itself on Windows. Re-running this script IS the update.
Write-Host "Extracting..."
Expand-Archive -Path "$TmpDir\$Archive" -DestinationPath $TmpDir -Force
-$DownloadedLauncher = Join-Path $TmpDir $BinName
-$DownloadedPayload = Join-Path $TmpDir $PayloadName
-if (-not (Test-Path -LiteralPath $DownloadedLauncher -PathType Leaf) -or
- -not (Test-Path -LiteralPath $DownloadedPayload -PathType Leaf)) {
- Write-Host "error: launcher or payload not found after extraction" -ForegroundColor Red
+$DownloadedBinary = Join-Path $TmpDir $BinName
+if (-not (Test-Path -LiteralPath $DownloadedBinary -PathType Leaf)) {
+ Write-Host "error: $BinName not found after extraction" -ForegroundColor Red
Remove-Item -Recurse -Force $TmpDir
exit 1
}
-$launcherItem = Get-Item -LiteralPath $DownloadedLauncher
-$payloadItem = Get-Item -LiteralPath $DownloadedPayload
-if (($launcherItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -or
- ($payloadItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
+$binaryItem = Get-Item -LiteralPath $DownloadedBinary
+if ($binaryItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
Write-Host "error: refusing reparse-point executable in release archive" -ForegroundColor Red
Remove-Item -Recurse -Force $TmpDir
exit 1
}
-# Verify the complete launcher/payload path before it asks all coordinated CBM
-# processes to stop.
+# Prove the downloaded binary runs before touching an existing installation.
try {
- $candidateVersion = & $DownloadedLauncher --version 2>&1
+ $candidateVersion = & $DownloadedBinary --version 2>&1
if ($LASTEXITCODE -ne 0) { throw "candidate exited with $LASTEXITCODE" }
Write-Host "Verified candidate: $candidateVersion"
} catch {
@@ -272,13 +266,36 @@ try {
}
$Dest = Join-Path $InstallDir $BinName
+
+# Retire the running installation before replacing it. Windows keeps an image
+# lock on a running .exe: the file cannot be overwritten, but it CAN be renamed
+# out of the way, which is what makes an in-place update possible from here.
+if (Test-Path -LiteralPath $Dest -PathType Leaf) {
+ try { & $Dest daemon stop 2>&1 | Out-Null } catch { }
+ $retired = "$Dest.retired-$(Get-Date -Format yyyyMMddHHmmss)"
+ $renamed = $false
+ foreach ($attempt in 1..10) {
+ try { Move-Item -LiteralPath $Dest -Destination $retired -Force -ErrorAction Stop; $renamed = $true; break }
+ catch { Start-Sleep -Milliseconds 500 }
+ }
+ if (-not $renamed) {
+ Write-Host "error: could not retire the existing $BinName — close all running" -ForegroundColor Red
+ Write-Host " codebase-memory-mcp sessions and coding agents, then re-run." -ForegroundColor Red
+ Remove-Item -Recurse -Force $TmpDir -ErrorAction SilentlyContinue
+ exit 1
+ }
+ # A retired image stays locked until its last process exits; delete it when
+ # we can, and leave it for the next run when we cannot. Never fail here.
+ Remove-Item -LiteralPath $retired -Force -ErrorAction SilentlyContinue
+}
+Get-ChildItem -LiteralPath $InstallDir -Filter "$BinName.retired-*" -ErrorAction SilentlyContinue |
+ ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue }
+
$InstallArgs = @("install", "-y", "--force", "--dir=$InstallDir")
if ($SkipConfig) { $InstallArgs += "--skip-config" }
-# PowerShell's call operator waits for the launcher, which in turn contains the
-# install payload in its native job and relays the exact exit status.
-& $DownloadedLauncher @InstallArgs
+& $DownloadedBinary @InstallArgs
if ($LASTEXITCODE -ne 0) {
- Write-Host "error: coordinated activation failed (exit code $LASTEXITCODE)" -ForegroundColor Red
+ Write-Host "error: installation failed (exit code $LASTEXITCODE)" -ForegroundColor Red
Remove-Item -Recurse -Force $TmpDir -ErrorAction SilentlyContinue
exit 1
}
diff --git a/pkg/npm/bin.js b/pkg/npm/bin.js
index f00105e30..8b7d82e09 100644
--- a/pkg/npm/bin.js
+++ b/pkg/npm/bin.js
@@ -8,23 +8,19 @@ const fs = require('fs');
const { spawnSync } = require('child_process');
const isWindows = process.platform === 'win32';
-const windowsLauncherName = 'codebase-memory-mcp.exe';
-// npm is a portable one-shot wrapper. On Windows the public .exe in the
-// release archive is the permanent launcher, so privately validate the
-// release pair, cache both files, and enter the native process through that
-// launcher. The adjacent payload remains the immutable cache readiness signal.
-const binName = isWindows ? 'codebase-memory-mcp.payload.exe' : 'codebase-memory-mcp';
+// npm is a portable one-shot wrapper. Every platform ships exactly ONE binary,
+// so the cached file is the executed file — there is no launcher pair to keep
+// in sync and no adjacent payload to validate.
+const binName = isWindows ? 'codebase-memory-mcp.exe' : 'codebase-memory-mcp';
const binPath = path.join(__dirname, 'bin', binName);
-const launcherPath = path.join(__dirname, 'bin', windowsLauncherName);
-const executionPath = isWindows ? launcherPath : binPath;
+const executionPath = binPath;
const cacheReady = () => {
- if (!fs.existsSync(binPath) || (isWindows && !fs.existsSync(launcherPath))) {
+ if (!fs.existsSync(binPath)) {
return false;
}
if (!isWindows) return true;
- // The launcher resolving --version through its adjacent payload validates
- // both halves of the immutable Windows cache pair.
- const probe = spawnSync(launcherPath, ['--version'], {
+ // A cached Windows binary that cannot report its own version is not usable.
+ const probe = spawnSync(binPath, ['--version'], {
stdio: 'ignore',
timeout: 15_000,
windowsHide: true,
@@ -77,8 +73,8 @@ if (mutation) {
process.stderr.write(
`This npm Windows copy is portable. Use "${packageCommand}" for package ` +
'maintenance (add -g for a global install), or run ' +
- '"codebase-memory-mcp install --yes" once to create ' +
- 'a managed launcher with coordinated self-update/uninstall.\n',
+ '"codebase-memory-mcp install --yes" once for a managed install with its ' +
+ 'own install.ps1 for updates.\n',
);
}
diff --git a/pkg/npm/install.js b/pkg/npm/install.js
index 75af5c6f4..2c3ea9b6c 100644
--- a/pkg/npm/install.js
+++ b/pkg/npm/install.js
@@ -18,8 +18,7 @@ const MAX_REDIRECTS = 5;
const DOWNLOAD_HOP_TIMEOUT_MS = 120_000;
const CANDIDATE_TIMEOUT_MS = 15_000;
const MAX_CHECKSUM_MANIFEST_BYTES = 1024 * 1024;
-const WINDOWS_LAUNCHER_NAME = 'codebase-memory-mcp.exe';
-const WINDOWS_PAYLOAD_NAME = 'codebase-memory-mcp.payload.exe';
+const WINDOWS_BINARY_NAME = 'codebase-memory-mcp.exe';
const UNIX_ARCHIVE_NAMES = [
'codebase-memory-mcp',
'LICENSE',
@@ -27,8 +26,7 @@ const UNIX_ARCHIVE_NAMES = [
'THIRD_PARTY_NOTICES.md',
];
const WINDOWS_ARCHIVE_NAMES = [
- WINDOWS_LAUNCHER_NAME,
- WINDOWS_PAYLOAD_NAME,
+ WINDOWS_BINARY_NAME,
'LICENSE',
'install.ps1',
'THIRD_PARTY_NOTICES.md',
@@ -258,7 +256,7 @@ function processIsAlive(pid) {
}
}
-function readPairLockOwner(lockPath) {
+function readBinaryLockOwner(lockPath) {
try {
const owner = JSON.parse(
fs.readFileSync(path.join(lockPath, 'owner.json'), 'utf8'),
@@ -273,9 +271,9 @@ function readPairLockOwner(lockPath) {
}
}
-function tryReclaimPairLock(lockPath, contenderToken) {
+function tryReclaimBinaryLock(lockPath, contenderToken) {
let reclaim = false;
- const owner = readPairLockOwner(lockPath);
+ const owner = readBinaryLockOwner(lockPath);
if (owner) {
reclaim = !processIsAlive(owner.pid);
} else {
@@ -299,7 +297,7 @@ function tryReclaimPairLock(lockPath, contenderToken) {
return true;
}
-function acquireWindowsPairLock(destDir) {
+function acquireWindowsBinaryLock(destDir) {
const lockPath = path.join(destDir, WINDOWS_PAIR_LOCK_NAME);
const token = crypto.randomBytes(16).toString('hex');
const deadline = Date.now() + WINDOWS_PAIR_LOCK_WAIT_MS;
@@ -319,7 +317,7 @@ function acquireWindowsPairLock(destDir) {
return { lockPath, token };
} catch (err) {
if (err.code !== 'EEXIST') throw err;
- if (tryReclaimPairLock(lockPath, token)) continue;
+ if (tryReclaimBinaryLock(lockPath, token)) continue;
if (Date.now() >= deadline) {
throw new Error('timed out waiting for Windows package-cache publication lock');
}
@@ -328,8 +326,8 @@ function acquireWindowsPairLock(destDir) {
}
}
-function releaseWindowsPairLock(lock) {
- const owner = readPairLockOwner(lock.lockPath);
+function releaseWindowsBinaryLock(lock) {
+ const owner = readBinaryLockOwner(lock.lockPath);
if (!owner || owner.token !== lock.token || owner.pid !== process.pid) {
throw new Error('Windows package-cache publication lock ownership changed');
}
@@ -337,17 +335,14 @@ function releaseWindowsPairLock(lock) {
fs.rmdirSync(lock.lockPath);
}
-function windowsPairReady(destDir, verifier = verifyCandidate) {
- const launcher = path.join(destDir, WINDOWS_LAUNCHER_NAME);
- const payload = path.join(destDir, WINDOWS_PAYLOAD_NAME);
+function windowsBinaryReady(destDir, verifier = verifyCandidate) {
+ const binary = path.join(destDir, WINDOWS_BINARY_NAME);
try {
- const launcherStatus = fs.lstatSync(launcher);
- const payloadStatus = fs.lstatSync(payload);
- if (!launcherStatus.isFile() || launcherStatus.isSymbolicLink() ||
- !payloadStatus.isFile() || payloadStatus.isSymbolicLink()) {
+ const status = fs.lstatSync(binary);
+ if (!status.isFile() || status.isSymbolicLink()) {
return false;
}
- verifier(launcher);
+ verifier(binary);
return true;
} catch (_) {
return false;
@@ -364,8 +359,8 @@ function pathMatchesDigest(candidatePath, expectedDigest) {
}
}
-function removeOwnedPublishedPair(destDir, publishedDigests) {
- for (const name of [WINDOWS_PAYLOAD_NAME, WINDOWS_LAUNCHER_NAME]) {
+function removeOwnedPublishedBinary(destDir, publishedDigests) {
+ for (const name of [WINDOWS_BINARY_NAME]) {
const digest = publishedDigests.get(name);
const target = path.join(destDir, name);
if (digest && pathMatchesDigest(target, digest)) {
@@ -374,8 +369,8 @@ function removeOwnedPublishedPair(destDir, publishedDigests) {
}
}
-function restorePairBackups(destDir, backups) {
- for (const name of [WINDOWS_LAUNCHER_NAME, WINDOWS_PAYLOAD_NAME]) {
+function restoreBinaryBackups(destDir, backups) {
+ for (const name of [WINDOWS_BINARY_NAME]) {
const backup = backups.get(name);
const target = path.join(destDir, name);
if (!backup || fs.existsSync(target)) continue;
@@ -383,15 +378,15 @@ function restorePairBackups(destDir, backups) {
}
}
-function installWindowsPairAtomically(sourceDir, destDir, verifier = verifyCandidate) {
- // Authenticate the complete source pair before it can contend for the cache.
- verifier(path.join(sourceDir, WINDOWS_LAUNCHER_NAME));
- const lock = acquireWindowsPairLock(destDir);
+function installWindowsBinaryAtomically(sourceDir, destDir, verifier = verifyCandidate) {
+ // Authenticate the source binary before it can contend for the cache.
+ verifier(path.join(sourceDir, WINDOWS_BINARY_NAME));
+ const lock = acquireWindowsBinaryLock(destDir);
let operationError = null;
try {
// A contender may have completed while this process waited. Its executable
- // pair wins and is never moved or deleted.
- if (windowsPairReady(destDir, verifier)) return;
+ // wins and is never moved or deleted.
+ if (windowsBinaryReady(destDir, verifier)) return;
const transaction = crypto.randomBytes(16).toString('hex');
const stagedPaths = new Map();
@@ -399,7 +394,7 @@ function installWindowsPairAtomically(sourceDir, destDir, verifier = verifyCandi
const backups = new Map();
const publishedDigests = new Map();
try {
- for (const name of [WINDOWS_LAUNCHER_NAME, WINDOWS_PAYLOAD_NAME]) {
+ for (const name of [WINDOWS_BINARY_NAME]) {
const staged = path.join(destDir, `.cbm-pair-stage-${transaction}-${name}`);
fs.copyFileSync(path.join(sourceDir, name), staged, fs.constants.COPYFILE_EXCL);
fs.chmodSync(staged, 0o755);
@@ -407,7 +402,7 @@ function installWindowsPairAtomically(sourceDir, destDir, verifier = verifyCandi
stagedDigests.set(name, fileSha256(staged));
}
- for (const name of [WINDOWS_LAUNCHER_NAME, WINDOWS_PAYLOAD_NAME]) {
+ for (const name of [WINDOWS_BINARY_NAME]) {
const target = path.join(destDir, name);
const status = fs.lstatSync(target, { throwIfNoEntry: false });
if (!status) continue;
@@ -419,32 +414,31 @@ function installWindowsPairAtomically(sourceDir, destDir, verifier = verifyCandi
backups.set(name, backup);
}
- // Payload is the readiness signal and is deliberately published last.
- for (const name of [WINDOWS_LAUNCHER_NAME, WINDOWS_PAYLOAD_NAME]) {
+ for (const name of [WINDOWS_BINARY_NAME]) {
const target = path.join(destDir, name);
fs.renameSync(stagedPaths.get(name), target);
stagedPaths.delete(name);
publishedDigests.set(name, stagedDigests.get(name));
}
- if (!windowsPairReady(destDir, verifier)) {
- throw new Error('published Windows package-cache pair failed verification');
+ if (!windowsBinaryReady(destDir, verifier)) {
+ throw new Error('published Windows package-cache binary failed verification');
}
for (const backup of backups.values()) {
- try { fs.unlinkSync(backup); } catch (_) { /* valid pair is already committed */ }
+ try { fs.unlinkSync(backup); } catch (_) { /* valid binary is already committed */ }
}
return;
} catch (err) {
- // If a non-cooperating contender nevertheless published a valid pair,
+ // If a non-cooperating contender nevertheless published a valid binary,
// preserve that winner. Otherwise remove only our exact staged bytes and
// restore the prior files when their target names are still absent.
- if (windowsPairReady(destDir, verifier)) {
+ if (windowsBinaryReady(destDir, verifier)) {
for (const backup of backups.values()) {
try { fs.unlinkSync(backup); } catch (_) { /* winner remains authoritative */ }
}
return;
}
- removeOwnedPublishedPair(destDir, publishedDigests);
- restorePairBackups(destDir, backups);
+ removeOwnedPublishedBinary(destDir, publishedDigests);
+ restoreBinaryBackups(destDir, backups);
throw err;
} finally {
for (const staged of stagedPaths.values()) {
@@ -456,7 +450,7 @@ function installWindowsPairAtomically(sourceDir, destDir, verifier = verifyCandi
throw err;
} finally {
try {
- releaseWindowsPairLock(lock);
+ releaseWindowsBinaryLock(lock);
} catch (releaseError) {
if (!operationError) throw releaseError;
}
@@ -552,25 +546,24 @@ async function main() {
const platform = getPlatform();
const arch = getArch();
const ext = platform === 'windows' ? 'zip' : 'tar.gz';
- // Package-manager shims are portable one-shot instances on Windows. They
- // enter through the cached launcher and never create managed launcher state.
- // The payload path remains the immutable pair's readiness signal.
+ // Package-manager shims are portable one-shot instances: one cached binary
+ // per platform, entered directly.
const binName = platform === 'windows'
- ? WINDOWS_PAYLOAD_NAME
+ ? WINDOWS_BINARY_NAME
: 'codebase-memory-mcp';
const binPath = path.join(BIN_DIR, binName);
const cacheNames = platform === 'windows'
- ? [WINDOWS_LAUNCHER_NAME, WINDOWS_PAYLOAD_NAME]
+ ? [WINDOWS_BINARY_NAME]
: [binName];
const extractedNames = platform === 'windows'
- ? [WINDOWS_LAUNCHER_NAME, WINDOWS_PAYLOAD_NAME]
+ ? [WINDOWS_BINARY_NAME]
: [binName];
const archiveNames = platform === 'windows'
? WINDOWS_ARCHIVE_NAMES
: UNIX_ARCHIVE_NAMES;
const cachePaths = cacheNames.map((name) => path.join(BIN_DIR, name));
- if (platform === 'windows' && windowsPairReady(BIN_DIR)) return;
+ if (platform === 'windows' && windowsBinaryReady(BIN_DIR)) return;
if (platform !== 'windows' &&
cachePaths.every((candidate) => fs.existsSync(candidate))) {
try {
@@ -631,13 +624,13 @@ async function main() {
if (platform === 'windows') {
// The launcher resolves the adjacent portable payload in this directory.
- verifyCandidate(extractedPaths.get(WINDOWS_LAUNCHER_NAME));
+ verifyCandidate(extractedPaths.get(WINDOWS_BINARY_NAME));
} else {
verifyCandidate(extractedPaths.get(binName));
}
if (platform === 'windows') {
- installWindowsPairAtomically(tmpDir, BIN_DIR);
+ installWindowsBinaryAtomically(tmpDir, BIN_DIR);
} else {
const staged = path.join(
BIN_DIR,
@@ -683,10 +676,9 @@ if (require.main === module || module.parent == null) {
module.exports = {
UNIX_ARCHIVE_NAMES,
- WINDOWS_LAUNCHER_NAME,
- WINDOWS_PAYLOAD_NAME,
+ WINDOWS_BINARY_NAME,
extractExactTarArchive,
- installWindowsPairAtomically,
+ installWindowsBinaryAtomically,
validateExactTarMemberListing,
- windowsPairReady,
+ windowsBinaryReady,
};
diff --git a/pkg/npm/test/package-publication.test.js b/pkg/npm/test/package-publication.test.js
index 2b7190ce5..560aec700 100644
--- a/pkg/npm/test/package-publication.test.js
+++ b/pkg/npm/test/package-publication.test.js
@@ -8,10 +8,9 @@ const test = require('node:test');
const {
UNIX_ARCHIVE_NAMES,
- WINDOWS_LAUNCHER_NAME,
- WINDOWS_PAYLOAD_NAME,
+ WINDOWS_BINARY_NAME,
extractExactTarArchive,
- installWindowsPairAtomically,
+ installWindowsBinaryAtomically,
validateExactTarMemberListing,
} = require('../install.js');
@@ -53,25 +52,20 @@ test('Unix extraction requests only the validated root executable', () => {
);
});
-function writePair(directory, tag) {
+function writeBinary(directory, tag) {
fs.mkdirSync(directory, { recursive: true });
- fs.writeFileSync(path.join(directory, WINDOWS_LAUNCHER_NAME), `launcher:${tag}`);
- fs.writeFileSync(path.join(directory, WINDOWS_PAYLOAD_NAME), `payload:${tag}`);
+ fs.writeFileSync(path.join(directory, WINDOWS_BINARY_NAME), `binary:${tag}`);
}
-function fakePairVerifier(launcherPath) {
- const launcher = fs.readFileSync(launcherPath, 'utf8');
- const payload = fs.readFileSync(
- path.join(path.dirname(launcherPath), WINDOWS_PAYLOAD_NAME), 'utf8',
- );
- const match = /^launcher:(.+)$/.exec(launcher);
- if (!match || payload !== `payload:${match[1]}`) {
- throw new Error('launcher/payload test pair mismatch');
+function fakeBinaryVerifier(binaryPath) {
+ const binary = fs.readFileSync(binaryPath, 'utf8');
+ if (!/^binary:(.+)$/.test(binary)) {
+ throw new Error('cached Windows binary failed verification');
}
}
-function withPairDirectories(callback) {
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cbm-npm-pair-test-'));
+function withBinaryDirectories(callback) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cbm-npm-binary-test-'));
const source = path.join(root, 'source');
const destination = path.join(root, 'destination');
fs.mkdirSync(destination);
@@ -82,56 +76,42 @@ function withPairDirectories(callback) {
}
}
-function assertPair(directory, tag) {
- assert.equal(
- fs.readFileSync(path.join(directory, WINDOWS_LAUNCHER_NAME), 'utf8'),
- `launcher:${tag}`,
- );
+function assertBinary(directory, tag) {
assert.equal(
- fs.readFileSync(path.join(directory, WINDOWS_PAYLOAD_NAME), 'utf8'),
- `payload:${tag}`,
+ fs.readFileSync(path.join(directory, WINDOWS_BINARY_NAME), 'utf8'),
+ `binary:${tag}`,
);
}
-test('Windows publication repairs a corrupt launcher', () => {
- withPairDirectories(({ source, destination }) => {
- writePair(source, 'candidate');
- writePair(destination, 'old');
- fs.writeFileSync(path.join(destination, WINDOWS_LAUNCHER_NAME), 'corrupt');
+test('Windows publication repairs a corrupt cached binary', () => {
+ withBinaryDirectories(({ source, destination }) => {
+ writeBinary(source, 'candidate');
+ writeBinary(destination, 'old');
+ fs.writeFileSync(path.join(destination, WINDOWS_BINARY_NAME), 'corrupt');
- installWindowsPairAtomically(source, destination, fakePairVerifier);
+ installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);
- assertPair(destination, 'candidate');
+ assertBinary(destination, 'candidate');
});
});
-test('Windows publication repairs corrupt or missing payload state', () => {
- for (const payload of ['corrupt', null]) {
- withPairDirectories(({ source, destination }) => {
- writePair(source, 'candidate');
- fs.writeFileSync(
- path.join(destination, WINDOWS_LAUNCHER_NAME), 'launcher:partial',
- );
- if (payload !== null) {
- fs.writeFileSync(
- path.join(destination, WINDOWS_PAYLOAD_NAME), payload,
- );
- }
-
- installWindowsPairAtomically(source, destination, fakePairVerifier);
-
- assertPair(destination, 'candidate');
- });
- }
+test('Windows publication installs into an empty cache', () => {
+ withBinaryDirectories(({ source, destination }) => {
+ writeBinary(source, 'candidate');
+
+ installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);
+
+ assertBinary(destination, 'candidate');
+ });
});
test('Windows publication preserves a valid concurrent winner', () => {
- withPairDirectories(({ source, destination }) => {
- writePair(source, 'loser');
- writePair(destination, 'winner');
+ withBinaryDirectories(({ source, destination }) => {
+ writeBinary(source, 'loser');
+ writeBinary(destination, 'winner');
- installWindowsPairAtomically(source, destination, fakePairVerifier);
+ installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);
- assertPair(destination, 'winner');
+ assertBinary(destination, 'winner');
});
});
diff --git a/pkg/npm/test/windows-launcher.test.js b/pkg/npm/test/windows-launcher.test.js
index b67aa9adf..756b238cb 100644
--- a/pkg/npm/test/windows-launcher.test.js
+++ b/pkg/npm/test/windows-launcher.test.js
@@ -95,7 +95,7 @@ test('non-Windows npm shim keeps its native payload execution path', () => {
assert.equal(path.basename(observed.calls[0].executable), 'codebase-memory-mcp');
});
-test('PowerShell install mutation runs through the downloaded launcher', () => {
+test('PowerShell install mutation runs through the downloaded binary', () => {
const installer = fs.readFileSync(
path.join(__dirname, '..', '..', '..', 'install.ps1'),
'utf8',
@@ -103,14 +103,16 @@ test('PowerShell install mutation runs through the downloaded launcher', () => {
assert.match(
installer,
- /^\s*\$candidateVersion\s*=\s*&\s*\$DownloadedLauncher\s+--version\b/m,
+ /^\s*\$candidateVersion\s*=\s*&\s*\$DownloadedBinary\s+--version\b/m,
);
assert.match(
installer,
- /^\s*&\s*\$DownloadedLauncher\s+@InstallArgs\b/m,
- );
- assert.doesNotMatch(
- installer,
- /^\s*&\s*\$DownloadedPayload\s+@InstallArgs\b/m,
+ /^\s*&\s*\$DownloadedBinary\s+@InstallArgs\b/m,
);
+ // One binary ships per platform — no launcher/payload pair to resolve.
+ assert.doesNotMatch(installer, /payload/i);
+ // A running .exe cannot be overwritten, so an in-place update has to retire
+ // the existing binary by renaming it aside first. This script IS the Windows
+ // update path, so losing that step would silently break every update.
+ assert.match(installer, /Move-Item[\s\S]{0,80}\$Dest[\s\S]{0,40}\$retired/);
});
diff --git a/pkg/pypi/src/codebase_memory_mcp/_cli.py b/pkg/pypi/src/codebase_memory_mcp/_cli.py
index 6495a0829..473c2d026 100644
--- a/pkg/pypi/src/codebase_memory_mcp/_cli.py
+++ b/pkg/pypi/src/codebase_memory_mcp/_cli.py
@@ -15,11 +15,9 @@ import urllib.request
from pathlib import Path
REPO = "DeusData/codebase-memory-mcp"
-_WINDOWS_LAUNCHER_NAME = "codebase-memory-mcp.exe"
-_WINDOWS_PAYLOAD_NAME = "codebase-memory-mcp.payload.exe"
+_WINDOWS_BINARY_NAME = "codebase-memory-mcp.exe"
_WINDOWS_ARCHIVE_NAMES = (
- _WINDOWS_LAUNCHER_NAME,
- _WINDOWS_PAYLOAD_NAME,
+ _WINDOWS_BINARY_NAME,
"LICENSE",
"install.ps1",
"THIRD_PARTY_NOTICES.md",
@@ -332,37 +330,26 @@ def _cache_dir() -> Path:
def _bin_path(version: str) -> Path:
- # The payload remains the immutable Windows cache pair's readiness signal.
- # _execution_path selects the adjacent launcher for process execution.
+ # One binary per platform: the cached file is the executed file.
name = (
- _WINDOWS_PAYLOAD_NAME
+ _WINDOWS_BINARY_NAME
if sys.platform == "win32"
else "codebase-memory-mcp"
)
return _cache_dir() / version / name
-def _windows_pair_paths(version: str):
- version_dir = _cache_dir() / version
- return (
- version_dir / _WINDOWS_LAUNCHER_NAME,
- version_dir / _WINDOWS_PAYLOAD_NAME,
- )
-
-
-def _execution_path(payload: Path, target_platform: str) -> Path:
- """Select the permanent Windows launcher without changing other platforms."""
- if target_platform == "win32":
- return payload.with_name(_WINDOWS_LAUNCHER_NAME)
- return payload
+def _execution_path(binary: Path, target_platform: str) -> Path:
+ """The cached binary is executed directly on every platform."""
+ return binary
-def _windows_pair_ready(version: str) -> bool:
- launcher, payload = _windows_pair_paths(version)
- if not launcher.is_file() or not payload.is_file():
+def _windows_binary_ready(version: str) -> bool:
+ binary = _cache_dir() / version / _WINDOWS_BINARY_NAME
+ if not binary.is_file():
return False
try:
- _verify_candidate(launcher)
+ _verify_candidate(binary)
except RuntimeError:
return False
return True
@@ -404,21 +391,12 @@ def _download(version: str) -> Path:
_verify_checksum(tmp_archive, archive, version)
- if os_name == "windows":
- bin_name = _WINDOWS_PAYLOAD_NAME
- extraction_names = (
- _WINDOWS_LAUNCHER_NAME,
- _WINDOWS_PAYLOAD_NAME,
- )
- else:
- bin_name = "codebase-memory-mcp"
- extraction_names = (bin_name,)
- cache_names = extraction_names
- publish_names = (
- (_WINDOWS_LAUNCHER_NAME, _WINDOWS_PAYLOAD_NAME)
- if os_name == "windows"
- else cache_names
+ bin_name = (
+ _WINDOWS_BINARY_NAME if os_name == "windows" else "codebase-memory-mcp"
)
+ extraction_names = (bin_name,)
+ cache_names = extraction_names
+ publish_names = cache_names
if ext == "tar.gz":
import tarfile
with tarfile.open(tmp_archive) as tf:
@@ -447,11 +425,7 @@ def _download(version: str) -> Path:
)
extracted_paths[name] = extracted_path
try:
- if os_name == "windows":
- # The portable launcher must resolve this adjacent payload.
- _verify_candidate(extracted_paths[_WINDOWS_LAUNCHER_NAME])
- else:
- _verify_candidate(extracted_paths[bin_name])
+ _verify_candidate(extracted_paths[bin_name])
except RuntimeError as exc:
sys.exit(f"codebase-memory-mcp: {exc}")
@@ -488,7 +462,7 @@ def _download(version: str) -> Path:
if not _files_equal_sha256(staged_paths[name], target):
raise publish_error
if os_name == "windows":
- _verify_candidate(dest.parent / _WINDOWS_LAUNCHER_NAME)
+ _verify_candidate(dest.parent / _WINDOWS_BINARY_NAME)
else:
_verify_candidate(dest)
except RuntimeError as exc:
@@ -508,7 +482,7 @@ def main() -> None:
bin_path = _bin_path(version)
cache_ready = (
- _windows_pair_ready(version)
+ _windows_binary_ready(version)
if sys.platform == "win32"
else bin_path.is_file()
)
diff --git a/pkg/pypi/tests/test_cli.py b/pkg/pypi/tests/test_cli.py
index a5d8eaf03..4fe297689 100644
--- a/pkg/pypi/tests/test_cli.py
+++ b/pkg/pypi/tests/test_cli.py
@@ -9,19 +9,18 @@ sys.path.insert(0, str(PACKAGE_ROOT / "src"))
from codebase_memory_mcp import _cli # noqa: E402
-class WindowsLauncherSelectionTests(unittest.TestCase):
- def test_windows_uses_adjacent_launcher(self):
- payload = Path("cache") / "0.8.1" / _cli._WINDOWS_PAYLOAD_NAME
+class BinarySelectionTests(unittest.TestCase):
+ """One binary ships per platform: the cached file is the executed file."""
- self.assertEqual(
- _cli._execution_path(payload, "win32"),
- payload.with_name(_cli._WINDOWS_LAUNCHER_NAME),
- )
+ def test_windows_executes_the_cached_binary(self):
+ binary = Path("cache") / "0.8.1" / _cli._WINDOWS_BINARY_NAME
+
+ self.assertEqual(_cli._execution_path(binary, "win32"), binary)
- def test_non_windows_keeps_payload(self):
- payload = Path("cache") / "0.8.1" / "codebase-memory-mcp"
+ def test_non_windows_executes_the_cached_binary(self):
+ binary = Path("cache") / "0.8.1" / "codebase-memory-mcp"
- self.assertEqual(_cli._execution_path(payload, "linux"), payload)
+ self.assertEqual(_cli._execution_path(binary, "linux"), binary)
def test_portable_mutation_guidance_classification_is_preserved(self):
self.assertEqual(_cli._portable_mutation_action(["update"]), "update")
diff --git a/scripts/ci/smoke-artifact.sh b/scripts/ci/smoke-artifact.sh
index 6f9cf81de..539a70415 100755
--- a/scripts/ci/smoke-artifact.sh
+++ b/scripts/ci/smoke-artifact.sh
@@ -104,7 +104,9 @@ mkdir -p "$EXTRACT_DIR"
if [ "$GOOS" = "windows" ]; then
unzip -q -o "$WORK_DIR/$NAME.zip" -d "$EXTRACT_DIR"
test -s "$EXTRACT_DIR/codebase-memory-mcp.exe"
- test -s "$EXTRACT_DIR/codebase-memory-mcp.payload.exe"
+ # ONE binary per platform: a payload sibling means the AV-flagged launcher
+ # stub came back.
+ test ! -e "$EXTRACT_DIR/codebase-memory-mcp.payload.exe"
echo "=== smoke-artifact: smoking EXTRACTED $NAME.zip via vm-smoke.sh ==="
SMOKE_ARCH="$GOARCH" SMOKE_VARIANT="$VARIANT" \
CBM_SMOKE_ARTIFACT_DIR="$EXTRACT_DIR" \
diff --git a/scripts/package-release.sh b/scripts/package-release.sh
index eb349ad73..a70fc8764 100755
--- a/scripts/package-release.sh
+++ b/scripts/package-release.sh
@@ -30,16 +30,16 @@ local artifact-flow smoke lane.
matching binary must already have been built (--with-ui for ui).
--out-dir where to place the archive (default: repository root).
-Make passthrough (VAR=VAL, forwarded to the Windows launcher build):
+Make passthrough (VAR=VAL, forwarded to the build):
CC= CXX= compiler override, e.g. CC=clang CXX=clang++.
Environment:
BUILD_DIR build tree to archive from (default build/c).
-Archive contents (defined here, canonical):
+Archive contents (defined here, canonical) — ONE binary per platform:
unix: codebase-memory-mcp LICENSE install.sh THIRD_PARTY_NOTICES.md (.tar.gz)
- windows: codebase-memory-mcp.exe (launcher) codebase-memory-mcp.payload.exe
- LICENSE install.ps1 THIRD_PARTY_NOTICES.md (.zip)
+ windows: codebase-memory-mcp.exe LICENSE install.ps1
+ THIRD_PARTY_NOTICES.md (.zip)
EOF
}
@@ -92,25 +92,28 @@ OUT_DIR="$(mkdir -p "$OUT_DIR" && cd "$OUT_DIR" && pwd)"
NAME="codebase-memory-mcp${SUFFIX}-${GOOS}-${GOARCH}"
if [ "$GOOS" = "windows" ]; then
- # The launcher is part of the ARCHIVE layout (launcher fronts the payload),
- # so it is built here, exactly as the release venue does.
- make -f Makefile.cbm "$BUILD_DIR/codebase-memory-mcp-launcher.exe" \
- BUILD_DIR="$BUILD_DIR" ${MAKE_ARGS[@]+"${MAKE_ARGS[@]}"}
+ # Windows ships ONE binary, exactly like every other platform. There is no
+ # launcher stub: a small unsigned PE whose entire job is to verify and
+ # execute another binary is statically indistinguishable from a dropper,
+ # and Defender's ML scored it Trojan:Win32/Wacatac.B!ml on x64 regardless
+ # of what we changed (bcrypt-free, stripped, versioned, and even
+ # resource-free builds were all flagged, while the product binary itself
+ # scans clean on every platform). Self-update — the launcher's whole reason
+ # to exist — moves OUT of the running process into install.ps1: Windows'
+ # executable lock only blocks a process from replacing ITSELF.
PAYLOAD="$BUILD_DIR/codebase-memory-mcp"
[ -f "${PAYLOAD}.exe" ] && PAYLOAD="${PAYLOAD}.exe"
[ -f "$PAYLOAD" ] || { echo "package-release: build first; missing $PAYLOAD" >&2; exit 2; }
PACK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/cbm-package.XXXXXX")"
trap 'rm -rf "$PACK_DIR"' EXIT
- cp "$BUILD_DIR/codebase-memory-mcp-launcher.exe" "$PACK_DIR/codebase-memory-mcp.exe"
- cp "$PAYLOAD" "$PACK_DIR/codebase-memory-mcp.payload.exe"
+ cp "$PAYLOAD" "$PACK_DIR/codebase-memory-mcp.exe"
cp LICENSE install.ps1 "$PACK_DIR/"
scripts/gen-third-party-notices.sh "$PACK_DIR/THIRD_PARTY_NOTICES.md"
(
cd "$PACK_DIR"
rm -f "$OUT_DIR/$NAME.zip"
zip -q "$OUT_DIR/$NAME.zip" \
- codebase-memory-mcp.exe codebase-memory-mcp.payload.exe \
- LICENSE install.ps1 THIRD_PARTY_NOTICES.md
+ codebase-memory-mcp.exe LICENSE install.ps1 THIRD_PARTY_NOTICES.md
)
echo "=== package-release: $OUT_DIR/$NAME.zip ==="
else
diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.sh
index edd27a8fe..30aec35ed 100755
--- a/scripts/smoke-test.sh
+++ b/scripts/smoke-test.sh
@@ -57,24 +57,11 @@ smoke_mktemp_dir() {
fi
}
-# Windows release archives contain a small permanent launcher plus a portable
-# payload. Whenever a smoke fixture copies the launcher, keep the payload next
-# to it so the copied fixture remains a complete portable bundle.
-WINDOWS_PAYLOAD=""
-if [[ "$BINARY" == *.exe ]]; then
- WINDOWS_PAYLOAD="$(cd "$(dirname "$BINARY")" && pwd)/codebase-memory-mcp.payload.exe"
- if [ ! -f "$WINDOWS_PAYLOAD" ]; then
- echo "FAIL: Windows launcher has no adjacent codebase-memory-mcp.payload.exe"
- exit 1
- fi
-fi
-
+# Every platform ships ONE binary, Windows included: a fixture copy is complete
+# with nothing beside it.
copy_smoke_binary() {
local destination="$1"
cp "$BINARY" "$destination"
- if [ -n "$WINDOWS_PAYLOAD" ]; then
- cp "$WINDOWS_PAYLOAD" "$(dirname "$destination")/codebase-memory-mcp.payload.exe"
- fi
}
# Retire the shared account daemon (if one is running) and wait until it
@@ -1174,26 +1161,32 @@ HOME="$FAKE_HOME" \
"$BINARY" install -y > "$PHASE8_INSTALL_LOG" 2>&1 || PHASE8_INSTALL_RC=$?
cat "$PHASE8_INSTALL_LOG"
if [[ "$BINARY" == *.exe ]]; then
- # The managed install itself must SUCCEED on Windows — an install-time
- # staging/ACL refusal used to scroll past as tolerated noise while the
- # downstream config assertions kept passing against a previous generation
- # ("staging transaction open failed (status -3, os 0)" hid a real install
- # failure class on Administrators-default-owner profiles).
+ # The install itself must SUCCEED on Windows — an install-time staging/ACL
+ # refusal used to scroll past as tolerated noise while the downstream config
+ # assertions kept passing against a previous copy ("staging transaction open
+ # failed (status -3, os 0)" hid a real install failure class on
+ # Administrators-default-owner profiles).
if [ "$PHASE8_INSTALL_RC" -ne 0 ]; then
- echo "FAIL 8-0: managed install exited rc=$PHASE8_INSTALL_RC"
+ echo "FAIL 8-0: install exited rc=$PHASE8_INSTALL_RC"
exit 1
fi
PHASE8_CANONICAL="$FAKE_HOME/.local/bin/codebase-memory-mcp.exe"
if [ ! -f "$PHASE8_CANONICAL" ]; then
- echo "FAIL 8-0: canonical launcher missing after managed install"
+ echo "FAIL 8-0: installed binary missing after install"
exit 1
fi
- PHASE8_LINKS=$(stat -c %h "$PHASE8_CANONICAL" 2>/dev/null || echo 0)
- if [ "$PHASE8_LINKS" != "2" ]; then
- echo "FAIL 8-0: canonical launcher is not an exact two-link file (links=$PHASE8_LINKS)"
+ # ONE binary, one link: a second hard link here would mean the retired
+ # launcher/generation layout came back.
+ PHASE8_LINKS=$(stat -c %h "$PHASE8_CANONICAL" 2>/dev/null || echo 1)
+ if [ "$PHASE8_LINKS" != "1" ]; then
+ echo "FAIL 8-0: installed binary is not a single-link file (links=$PHASE8_LINKS)"
exit 1
fi
- echo "OK 8-0: managed install committed an exact two-link canonical launcher"
+ if [ -e "$FAKE_HOME/.local/bin/codebase-memory-mcp.payload.exe" ]; then
+ echo "FAIL 8-0: install produced a launcher/payload pair"
+ exit 1
+ fi
+ echo "OK 8-0: install committed exactly one Windows binary"
fi
# Helper for JSON validation (pipe file to python — avoids MSYS2 path translation issues)
@@ -2911,9 +2904,9 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; then
UPDATE_HOME=$(smoke_mktemp_dir)
mkdir -p "$UPDATE_HOME/.claude" "$UPDATE_HOME/.local/bin"
if [[ "$BINARY" == *.exe ]]; then
- # Keep the managed canonical absent until WINDOWS_PAYLOAD installs the
- # authenticated two-link launcher layout below.
- :
+ cp "$BINARY" "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"
+ mkdir -p "$UPDATE_HOME/retired-install"
+ cp "$BINARY" "$UPDATE_HOME/retired-install/codebase-memory-mcp.exe"
else
cp "$BINARY" "$UPDATE_HOME/.local/bin/codebase-memory-mcp"
chmod 755 "$UPDATE_HOME/.local/bin/codebase-memory-mcp"
@@ -2927,18 +2920,12 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; then
fi
fi
- # A portable Windows payload may install a managed launcher, but it must not
- # perform update/uninstall directly. Establish the managed layout first and
- # exercise those mutations through its canonical launcher.
- UPDATE_DRIVER="$BINARY"
+ # POSIX runs `update` from the retired image so the in-process replacement is
+ # exercised end to end. Windows has no in-process replacement: a running .exe
+ # cannot replace itself, so `update` hands off to install.ps1 (asserted in
+ # 14a below) and the installed copy drives the later uninstall phases.
if [[ "$BINARY" == *.exe ]]; then
- HOME="$UPDATE_HOME" "$WINDOWS_PAYLOAD" install -y --force --skip-config \
- "--dir=$UPDATE_HOME/.local/bin"
UPDATE_DRIVER="$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"
- if [ ! -f "$UPDATE_DRIVER" ]; then
- echo "FAIL 14a: managed Windows launcher missing after install"
- exit 1
- fi
else
RETIRED_DIR=$(cd "$UPDATE_HOME/retired-install" && pwd -P)
UPDATE_DRIVER="$RETIRED_DIR/codebase-memory-mcp"
@@ -2965,8 +2952,31 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; then
if curl --noproxy '*' -sf "$SMOKE_DOWNLOAD_URL/" 2>/dev/null | grep -q "ui-"; then
UPDATE_VARIANT="--ui"
fi
+ UPDATE_LOG=$(smoke_mktemp_file)
HOME="$UPDATE_HOME" CBM_DOWNLOAD_URL="$UPDATE_DOWNLOAD_URL" \
- "$UPDATE_DRIVER" update $UPDATE_VARIANT -y 2>&1
+ "$UPDATE_DRIVER" update $UPDATE_VARIANT -y > "$UPDATE_LOG" 2>&1
+ UPDATE_RC=$?
+ cat "$UPDATE_LOG"
+
+ if [[ "$BINARY" == *.exe ]]; then
+ # Windows contract: update NEVER replaces the running image in-process. It
+ # exits 0 and prints the install.ps1 command. Regressing to an in-process
+ # self-update means reintroducing the AV-flagged launcher stub.
+ if [ "$UPDATE_RC" -ne 0 ]; then
+ echo "FAIL 14a: Windows update exited rc=$UPDATE_RC (expected 0)"
+ exit 1
+ fi
+ if ! grep -q "install.ps1" "$UPDATE_LOG"; then
+ echo "FAIL 14a: Windows update did not print the install.ps1 command"
+ exit 1
+ fi
+ if ! cmp -s "$BINARY" "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"; then
+ echo "FAIL 14a: Windows update replaced the binary in-process"
+ exit 1
+ fi
+ echo "OK 14a: Windows update handed off to install.ps1 without touching the binary"
+ fi
+ rm -f "$UPDATE_LOG"
# 14b: Verify new binary exists and runs
if [[ "$BINARY" == *.exe ]]; then
@@ -2988,6 +2998,11 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; then
echo "OK 14b: updated binary runs"
# 14c: Verify agent config was refreshed to the exact installed binary.
+ # Windows has no in-process update, so there is no config refresh to assert:
+ # install.ps1 re-runs `install`, which is covered by Phase 8 and Phase 13.
+ if [[ "$BINARY" == *.exe ]]; then
+ echo "SKIP 14c: Windows update hands off to install.ps1 (config refresh covered by install)"
+ else
UPD_CMD=$(cat "$UPDATE_HOME/.claude.json" 2>/dev/null | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('mcpServers',{}).get('codebase-memory-mcp',{}).get('command',''))" 2>/dev/null || echo "")
EXPECTED_UPD_CMD="$UPD_BIN"
if command -v cygpath &>/dev/null; then
@@ -3000,6 +3015,7 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; then
exit 1
fi
echo "OK 14c: agent config refreshed (path=$UPD_CMD)"
+ fi
# ── 14d-f: Real uninstall with binary removal ──
# First verify binary + configs exist
@@ -3158,9 +3174,10 @@ echo "--- Phase 12d: extraction ---"
(cd "$DL_DIR" && if [ "$DL_EXT" = "zip" ]; then unzip -q "$DL_ARCHIVE"; else tar -xzf "$DL_ARCHIVE"; fi)
if [ "$DL_OS" = "windows" ]; then
DL_BIN="$DL_DIR/codebase-memory-mcp.exe"
- DL_PAYLOAD="$DL_DIR/codebase-memory-mcp.payload.exe"
- if [ ! -f "$DL_PAYLOAD" ]; then
- echo "FAIL 12d: Windows payload not found after extraction"
+ # ONE binary per platform: a second executable in the archive would mean the
+ # AV-flagged launcher/payload split came back.
+ if [ -e "$DL_DIR/codebase-memory-mcp.payload.exe" ]; then
+ echo "FAIL 12d: Windows archive still ships a launcher/payload pair"
exit 1
fi
else
@@ -3173,11 +3190,6 @@ fi
chmod +x "$DL_BIN"
echo "OK 12d: binary extracted"
-if [ "$DL_OS" = "windows" ] && ! "$DL_PAYLOAD" --version > /dev/null 2>&1; then
- echo "FAIL 12d: extracted Windows payload doesn't run"
- exit 1
-fi
-
# 12e: extracted binary runs
if ! "$DL_BIN" --version > /dev/null 2>&1; then
# On macOS arm64, may need signing
diff --git a/scripts/test-windows.ps1 b/scripts/test-windows.ps1
index ff67a9d7a..8c1a8358a 100644
--- a/scripts/test-windows.ps1
+++ b/scripts/test-windows.ps1
@@ -3,10 +3,10 @@
Run the native-Windows product-surface test suite for codebase-memory-mcp.
.DESCRIPTION
- Builds the payload and permanent launcher if they are not already present,
- stages them under their release names, then runs the deterministic Windows
- integration tests under tests/windows/ through the launcher (real stdio /
- CLI / HTTP UI, real SQLite DB).
+ Builds the product binary if it is not already present, stages it under its
+ release name, then runs the deterministic Windows integration tests under
+ tests/windows/ against it (real stdio / CLI / HTTP UI, real SQLite DB).
+ Windows ships ONE binary, exactly like Linux and macOS.
Two categories of test:
@@ -20,8 +20,9 @@
* test_cli_non_ascii_arg.py guards #423/#20 (wide-argv main())
* test_daemon_stability.py guards the daemon parameter
surface, crash recovery, busy-stop refusal, and churn
- * test_windows_launcher.py guards the permanent launcher,
- managed layout, portable refusal, and crash containment
+ * test_windows_update_handoff.py guards that `update`
+ hands off to install.ps1 instead of replacing its own
+ running image (the removed launcher stub's only job)
KNOWN REDS - genuine, still-open Windows bugs reproduced at the product
surface. They are EXPECTED to be RED (exit 1) and are opt-in
@@ -40,13 +41,8 @@
AddressSanitizer/UBSan (Linux containers, WSL), prefer scripts/test.sh.
.PARAMETER Binary
- Path to an existing portable payload executable. If omitted, the script
- builds it (target selected by -Target) into build/c/.
-
-.PARAMETER Launcher
- Path to the permanent launcher executable. If omitted, the script uses
- build/c/codebase-memory-mcp-launcher.exe, building target cbm-launcher when
- needed.
+ Path to an existing product executable. If omitted, the script builds it
+ (target selected by -Target) into build/c/.
.PARAMETER Target
Makefile.cbm target used when building: 'cbm-with-ui' (default; needed for the
@@ -68,7 +64,6 @@
[CmdletBinding()]
param(
[string]$Binary,
- [string]$Launcher,
[ValidateSet("cbm-with-ui", "cbm")]
[string]$Target = "cbm-with-ui",
[switch]$GuardsOnly,
@@ -103,36 +98,8 @@ function Resolve-Binary {
return $built
}
-function Resolve-Launcher {
- param([string]$Explicit)
- if ($Explicit) { return (Resolve-Path $Explicit).Path }
- $built = Join-Path $repoRoot "build\c\codebase-memory-mcp-launcher.exe"
- if (Test-Path $built) { return $built }
- Write-Host "Building permanent launcher via Makefile.cbm ..." -ForegroundColor Cyan
- & $Make "-j" "-f" "Makefile.cbm" "cbm-launcher" "SANITIZE=" "TMP=$tmp" "TEMP=$tmp" "TMPDIR=$tmp" | Out-Host
- $buildExit = $LASTEXITCODE
- if ($buildExit -ne 0) { throw "launcher build failed (exit $buildExit)" }
- if (-not (Test-Path $built)) { throw "launcher not produced at $built" }
- return $built
-}
-
-function Resolve-AbiMismatchLauncher {
- $built = Join-Path $repoRoot "build\c\codebase-memory-mcp-launcher-abi2.exe"
- if (Test-Path $built) { return $built }
- Write-Host "Building launcher ABI mismatch fixture via Makefile.cbm ..." -ForegroundColor Cyan
- & $Make "-j" "-f" "Makefile.cbm" "build/c/codebase-memory-mcp-launcher-abi2.exe" "SANITIZE=" "TMP=$tmp" "TEMP=$tmp" "TMPDIR=$tmp" | Out-Host
- $buildExit = $LASTEXITCODE
- if ($buildExit -ne 0) { throw "launcher ABI fixture build failed (exit $buildExit)" }
- if (-not (Test-Path $built)) { throw "launcher ABI fixture not produced at $built" }
- return $built
-}
-
$bin = Resolve-Binary -Explicit $Binary
-$launcherBin = Resolve-Launcher -Explicit $Launcher
-$abiMismatchLauncher = Resolve-AbiMismatchLauncher
-Write-Host "Payload: $bin" -ForegroundColor Green
-Write-Host "Launcher: $launcherBin" -ForegroundColor Green
-Write-Host "ABI mismatch fixture: $abiMismatchLauncher" -ForegroundColor Green
+Write-Host "Binary: $bin" -ForegroundColor Green
$previousTemp = $env:TEMP
$previousTmp = $env:TMP
@@ -145,8 +112,7 @@ try {
New-Item -ItemType Directory -Path $guardRoot | Out-Null
# GitHub-hosted runner profile children can inherit mutation-capable ACEs
- # even though the profile ancestry itself passes the launcher's bounded
- # trust policy. Replace that inheritance before creating any executable or
+ # even though the profile ancestry itself passes the bounded trust policy. Replace that inheritance before creating any executable or
# Python temporary descendant. Use SIDs rather than localized account names.
$currentSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
if (-not $currentSid) { throw "could not resolve the current user's SID" }
@@ -167,24 +133,22 @@ try {
$guardBundle = Join-Path $guardRoot ("cbm-windows-guards-" + [guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Path $guardBundle | Out-Null
$guardBin = Join-Path $guardBundle "codebase-memory-mcp.exe"
- $guardPayload = Join-Path $guardBundle "codebase-memory-mcp.payload.exe"
- Copy-Item -LiteralPath $launcherBin -Destination $guardBin
- Copy-Item -LiteralPath $bin -Destination $guardPayload
+ Copy-Item -LiteralPath $bin -Destination $guardBin
# Ownership is never inherited on Windows: descendants created under the
# hardened root by an admin-group token can default to the Administrators
- # SID, and the launcher's exe policy demands the exact current user as
- # owner. Stamp the current SID explicitly on everything staged here.
- foreach ($staged in @($guardBundle, $guardBin, $guardPayload)) {
+ # SID, while the exe policy demands the exact current user as owner. Stamp
+ # the current SID explicitly on everything staged here.
+ foreach ($staged in @($guardBundle, $guardBin)) {
$stagedAcl = Get-Acl -LiteralPath $staged
$stagedAcl.SetOwner($currentSid)
Set-Acl -LiteralPath $staged -AclObject $stagedAcl
}
Write-Host "Guard bundle: $guardBin" -ForegroundColor Green
- # The launcher deliberately rejects GitHub's shared D:\a ancestry and the
- # hosted runner's inherited LocalAppData\Temp ACL. Keep launcher fixtures
- # and Python-created descendants below the accepted profile ancestry.
+ # The guards deliberately reject GitHub's shared D:\a ancestry and the
+ # hosted runner's inherited LocalAppData\Temp ACL. Keep staged fixtures and
+ # Python-created descendants below the accepted profile ancestry.
$env:TEMP = $guardRoot
$env:TMP = $guardRoot
$env:TMPDIR = $guardRoot
@@ -202,7 +166,7 @@ $guards = @(
"tests\windows\test_hook_augment.py",
"tests\windows\test_ui_drive_listing.py",
"tests\windows\test_cli_non_ascii_arg.py",
- "tests\windows\test_windows_launcher.py"
+ "tests\windows\test_windows_update_handoff.py"
)
# Opt-in known-red repros - EXPECTED red (exit 1); never gate CI. Currently empty:
@@ -216,15 +180,11 @@ $fixedKeepers = @()
Write-Host "`n--- Green guards ---" -ForegroundColor Cyan
foreach ($t in $guards) {
Write-Host "`n=== $t ===" -ForegroundColor Cyan
- if ($t -eq "tests\windows\test_windows_launcher.py") {
- & $py $t $guardBin $guardPayload $abiMismatchLauncher
- } else {
- & $py $t $guardBin
- }
+ & $py $t $guardBin
$code = $LASTEXITCODE
if ($code -eq 0) {
Write-Host "GREEN ($t)" -ForegroundColor Green
- } elseif ($code -eq 1 -or $t -eq "tests\windows\test_windows_launcher.py") {
+ } elseif ($code -eq 1 -or $t -eq "tests\windows\test_windows_update_handoff.py") {
Write-Host "RED ($t) - REGRESSION: a fixed Windows bug is broken again" -ForegroundColor Red
$guardFailures += $t
} elseif ($code -eq 2) {
diff --git a/src/cli/cli.c b/src/cli/cli.c
index f792c4a32..d405d2310 100644
--- a/src/cli/cli.c
+++ b/src/cli/cli.c
@@ -12,7 +12,6 @@
#include "cli/config_text_edit.h"
#include "cli/config_toml_edit.h"
#include "cli/config_yaml_edit.h"
-#include "cli/windows_launcher_state.h"
#include "daemon/bootstrap.h"
#include "daemon/ipc.h"
#include "daemon/runtime.h"
@@ -195,171 +194,6 @@ static cbm_cli_activation_ops_t g_cli_activation_test_ops;
static bool g_cli_activation_test_ops_set = false;
static const char *g_cli_activation_runtime_parent_for_test = NULL;
-#ifdef _WIN32
-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) {
- return false;
- }
- wchar_t path[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- DWORD length = GetModuleFileNameW(NULL, path, (DWORD)(sizeof(path) / sizeof(path[0])));
- if (length == 0 || length >= (DWORD)(sizeof(path) / sizeof(path[0]))) {
- return false;
- }
- WIN32_FILE_ATTRIBUTE_DATA attributes;
- if (!GetFileAttributesExW(path, GetFileExInfoStandard, &attributes)) {
- return false;
- }
- *size_out = ((uint64_t)attributes.nFileSizeHigh << 32U) | (uint64_t)attributes.nFileSizeLow;
- return *size_out > 0;
-}
-
-int cbm_cli_windows_payload_descriptor_role(int argc, char *const argv[]) {
- static const char role[] = "__cbm_windows_payload_descriptor_v1";
- if (argc != 3 || !argv || !argv[1] || strcmp(argv[1], role) != 0) {
- return -1;
- }
- if (!argv[2] || !argv[2][0])
- return CLI_TRUE;
- uint64_t launcher_abi = 0U;
- for (const char *cursor = argv[2]; *cursor; cursor++) {
- if (*cursor < '0' || *cursor > '9' ||
- launcher_abi > (UINT32_MAX - (uint64_t)(*cursor - '0')) / 10U) {
- return CLI_TRUE;
- }
- launcher_abi = launcher_abi * 10U + (uint64_t)(*cursor - '0');
- }
- uint64_t payload_size = 0U;
- bool fingerprint_ready = launcher_abi > 0U && cbm_index_supervisor_capture_build_fingerprint();
- const char *fingerprint = fingerprint_ready ? cbm_index_supervisor_build_fingerprint() : NULL;
- cbm_windows_release_descriptor_v1_t descriptor = {
- .launcher_abi = (uint32_t)launcher_abi,
- .payload_launcher_abi_min = CBM_WINDOWS_PAYLOAD_LAUNCHER_ABI_MIN,
- .payload_launcher_abi_max = CBM_WINDOWS_PAYLOAD_LAUNCHER_ABI_MAX,
- };
- descriptor.payload_size = cli_windows_current_process_size(&payload_size) ? payload_size : 0U;
- if (fingerprint) {
- (void)snprintf(descriptor.payload_sha256, sizeof(descriptor.payload_sha256), "%s",
- fingerprint);
- }
- uint8_t record[CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE];
- /* stdout is a pipe for this private binary protocol, but the Windows CRT
- * still defaults it to text mode. A 0x0a byte in payload_size must remain
- * one byte rather than being expanded to CRLF. */
- bool binary_stdout = _setmode(_fileno(stdout), _O_BINARY) != -1;
- bool descriptor_written =
- binary_stdout && cbm_windows_release_descriptor_v1_encode(&descriptor, record) &&
- fwrite(record, 1U, sizeof(record), stdout) == sizeof(record) && fflush(stdout) == 0;
- return descriptor_written ? CLI_OK : CLI_TRUE;
-}
-
-int cbm_cli_windows_launcher_startup_authenticate(int argc, char *const argv[]) {
- cbm_windows_launcher_context_t context;
- char error[CLI_BUF_512] = {0};
- if (!cbm_windows_launcher_context_consume(&context, error, sizeof(error))) {
- (void)fprintf(stderr, "codebase-memory-mcp: untrusted Windows launcher context: %s\n",
- error[0] ? error : "authentication failed");
- return CLI_TRUE;
- }
-
- cbm_windows_launcher_action_t action =
- cbm_windows_launcher_classify_action(argc, (const char *const *)argv);
- if (context.present && context.action != action) {
- (void)cbm_windows_launcher_context_complete(&context, false, error, sizeof(error));
- (void)fprintf(stderr, "codebase-memory-mcp: Windows launcher action did not match the "
- "payload command\n");
- return CLI_TRUE;
- }
- if (!context.present) {
- if (!cbm_windows_launcher_context_complete(&context, true, error, sizeof(error))) {
- (void)fprintf(stderr,
- "codebase-memory-mcp: Windows launcher completion failed: "
- "%s\n",
- error[0] ? error : "authority acknowledgement failed");
- return CLI_TRUE;
- }
- memset(&g_windows_launcher_context, 0, sizeof(g_windows_launcher_context));
- return CLI_OK;
- }
-
- bool mutation = action == CBM_WINDOWS_LAUNCHER_ACTION_UPDATE ||
- action == CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL;
- if (!cbm_windows_launcher_action_allowed(action, context.managed) ||
- context.private_activation != mutation) {
- (void)cbm_windows_launcher_context_complete(&context, false, error, sizeof(error));
- (void)fprintf(stderr, "codebase-memory-mcp: Windows launcher refused an invalid "
- "managed activation context\n");
- return CLI_TRUE;
- }
-
- if (context.managed) {
- uint64_t process_size = 0;
- bool fingerprint_ok = cbm_index_supervisor_capture_build_fingerprint();
- const char *fingerprint = fingerprint_ok ? cbm_index_supervisor_build_fingerprint() : NULL;
- if (!fingerprint || context.payload_size == 0 ||
- !cli_windows_current_process_size(&process_size) ||
- process_size != context.payload_size ||
- strcmp(fingerprint, context.expected_payload_sha256) != 0 ||
- context.canonical_launcher_path[0] == L'\0') {
- (void)cbm_windows_launcher_context_complete(&context, false, error, sizeof(error));
- (void)fprintf(stderr, "codebase-memory-mcp: managed Windows payload identity did "
- "not match current-v1; startup refused\n");
- return CLI_TRUE;
- }
- }
-
- if (!cbm_windows_launcher_context_complete(&context, true, error, sizeof(error))) {
- (void)fprintf(stderr, "codebase-memory-mcp: Windows launcher completion failed: %s\n",
- 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;
-}
-
-static bool cli_windows_require_managed_mutation(cbm_windows_launcher_action_t action) {
- if (g_windows_launcher_context.present && g_windows_launcher_context.managed &&
- g_windows_launcher_context.private_activation &&
- g_windows_launcher_context.action == action) {
- return true;
- }
- const char *operation =
- action == CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL ? "uninstall" : "update";
- (void)fprintf(stderr,
- "error: portable Windows payloads cannot self-%s. Use your package "
- "manager to replace/remove this portable copy, or run "
- "\"codebase-memory-mcp.payload.exe install\" once to create a "
- "managed launcher installation.\n",
- operation);
- return false;
-}
-#else
-int cbm_cli_windows_payload_descriptor_role(int argc, char *const argv[]) {
- (void)argc;
- (void)argv;
- return -1;
-}
-
-int cbm_cli_windows_launcher_startup_authenticate(int argc, char *const argv[]) {
- (void)argc;
- (void)argv;
- return CLI_OK;
-}
-#endif
-
static void cli_activation_diagnostic(const cbm_cli_activation_ops_t *ops, const char *message) {
const char *diagnostic = message ? message : CLI_ACTIVATION_REFUSED_MESSAGE;
if (ops && ops->visible_diagnostic) {
@@ -763,10 +597,9 @@ static bool cli_activation_production_context_init(cli_activation_production_con
captured_build) > 0
: cbm_daemon_runtime_process_build_fingerprint(
cli_activation_process_id(), context->source_build);
- /* Managed update/uninstall payload copies are POSIX-unlinked immediately
- * after the authenticated startup handshake. Their process image can no
- * longer be reopened by pathname here, so reuse the exact fingerprint
- * captured and checked before that unlink. */
+ /* An update/uninstall may already have unlinked or replaced the running
+ * image by the time we get here, so its process image can no longer be
+ * reopened by pathname: reuse the exact fingerprint captured earlier. */
if (!context->endpoint || !context->cohort_manager || !build_ready) {
return false;
}
@@ -1205,7 +1038,6 @@ void cbm_cli_set_activation_cleanup_failure_for_test(bool enabled);
int cbm_cli_activation_abort_cleanup_probe_for_test(void);
#endif
-#if !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API)
static void cli_activation_transaction_abort_or_fail_stop(
cbm_activation_transaction_t **transaction_io, const char *component) {
int cleanup_status = cli_activation_transaction_abort(transaction_io);
@@ -1219,7 +1051,6 @@ static void cli_activation_transaction_abort_or_fail_stop(
component ? component : "activation_transaction_cleanup");
}
}
-#endif
#ifdef CBM_CLI_ENABLE_TEST_API
void cbm_cli_set_activation_cleanup_failure_for_test(bool enabled) {
@@ -1280,7 +1111,6 @@ static int cli_activation_transaction_finalize_close(
return cli_activation_transaction_abort(transaction_io);
}
-#if !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API)
static void cli_activation_transaction_finalize_committed_or_fail_stop(
cbm_activation_transaction_t **transaction_io, const char *component) {
if (!transaction_io || !*transaction_io) {
@@ -1313,7 +1143,6 @@ static int cli_activation_transaction_commit_removal(cbm_activation_transaction_
? CLI_OK
: CLI_ERR;
}
-#endif
static bool cli_activation_transaction_expected_build(cbm_activation_transaction_t *transaction,
cli_binary_validator_t *validator) {
@@ -6116,485 +5945,6 @@ 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 &&
- cli_windows_canonicalize_launcher_path(out);
-}
-
-static bool cli_windows_parent_path(const wchar_t *path, wchar_t *out, size_t capacity) {
- if (!path || !out || capacity == 0) {
- return false;
- }
- out[0] = L'\0';
- size_t length = wcslen(path);
- if (length == 0 || length >= capacity) {
- return false;
- }
- memcpy(out, path, (length + 1U) * sizeof(*out));
- wchar_t *slash = wcsrchr(out, L'\\');
- wchar_t *forward = wcsrchr(out, L'/');
- if (forward && (!slash || forward > slash)) {
- slash = forward;
- }
- if (!slash || slash == out) {
- out[0] = L'\0';
- return false;
- }
- *slash = L'\0';
- return true;
-}
-
-static bool cli_windows_join_path(const wchar_t *directory, const wchar_t *name, wchar_t *out,
- size_t capacity) {
- if (!directory || !directory[0] || !name || !name[0] || !out || capacity == 0) {
- return false;
- }
- int written = _snwprintf_s(out, capacity, _TRUNCATE, L"%ls\\%ls", directory, name);
- if (written <= 0 || (size_t)written >= capacity) {
- 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;
-}
-
-static bool cli_windows_regular_file_no_reparse(const wchar_t *path, uint64_t *size_out) {
- HANDLE file =
- CreateFileW(path, GENERIC_READ | READ_CONTROL, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
- OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
- BY_HANDLE_FILE_INFORMATION information;
- LARGE_INTEGER size;
- bool valid = 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 == 1 && GetFileSizeEx(file, &size) != 0 &&
- size.QuadPart > 0;
- if (valid && size_out) {
- *size_out = (uint64_t)size.QuadPart;
- }
- if (file != INVALID_HANDLE_VALUE) {
- (void)CloseHandle(file);
- }
- return valid;
-}
-
-/* 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) {
- 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) &&
- cli_windows_join_path(directory, L"codebase-memory-mcp.exe", launcher_out,
- CBM_WINDOWS_LAUNCHER_PATH_CAP) &&
- cli_windows_regular_file_no_reparse(launcher_out, NULL);
-}
-
-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;
- }
- /* 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;
-}
-
-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;
- }
- if (payload_size != state->payload_size) {
- (void)fprintf(stderr, "error: generation payload size mismatch\n");
- return false;
- }
- 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_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, &current, &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 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;
- }
- 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(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 *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);
- 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(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 *launcher,
- size_t launcher_size, const unsigned char *payload,
- size_t payload_size, bool *created_out) {
- if (created_out) {
- *created_out = false;
- }
- if (!state || !launcher || launcher_size == 0 || !payload || payload_size == 0 ||
- payload_size != state->payload_size) {
- return false;
- }
- 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;
- }
- 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_payload, generation_directory,
- CBM_WINDOWS_LAUNCHER_PATH_CAP)) {
- return false;
- }
- char *directory_utf8 = cbm_wide_to_utf8(generation_directory);
- 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;
- }
- 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;
- }
- if (created_out) {
- *created_out = fresh_generation;
- }
- return ready;
-}
#endif
/* ── Tar.gz extraction ────────────────────────────────────────── */
@@ -6867,260 +6217,6 @@ unsigned char *cbm_extract_binary_from_zip(const unsigned char *data, int data_l
return NULL;
}
-enum {
- ZIP_CENTRAL_HDR_SZ = 46,
- ZIP_END_HDR_SZ = 22,
- ZIP_OFF_FLAGS = 6,
- ZIP_OFF_CRC = 14,
- ZIP_CENTRAL_OFF_FLAGS = 8,
- ZIP_CENTRAL_OFF_METHOD = 10,
- ZIP_CENTRAL_OFF_CRC = 16,
- ZIP_CENTRAL_OFF_COMP = 20,
- ZIP_CENTRAL_OFF_UNCOMP = 24,
- ZIP_CENTRAL_OFF_NAMELEN = 28,
- ZIP_CENTRAL_OFF_EXTRALEN = 30,
- ZIP_CENTRAL_OFF_COMMENTLEN = 32,
- ZIP_CENTRAL_OFF_DISK = 34,
- ZIP_CENTRAL_OFF_LOCAL = 42,
- ZIP_END_OFF_DISK = 4,
- ZIP_END_OFF_CENTRAL_DISK = 6,
- ZIP_END_OFF_ENTRIES_DISK = 8,
- ZIP_END_OFF_ENTRIES_TOTAL = 10,
- ZIP_END_OFF_CENTRAL_SIZE = 12,
- ZIP_END_OFF_CENTRAL_OFFSET = 16,
- ZIP_END_OFF_COMMENTLEN = 20,
- ZIP_UTF8_FLAG = 0x0800,
-};
-
-static bool zip_signature_is(const unsigned char *data, size_t offset, size_t length,
- unsigned char third, unsigned char fourth) {
- return offset <= length && length - offset >= 4U && data[offset] == 0x50 &&
- data[offset + 1U] == 0x4b && data[offset + 2U] == third && data[offset + 3U] == fourth;
-}
-
-static bool zip_find_end_record(const unsigned char *data, size_t length, size_t *offset_out) {
- if (length < ZIP_END_HDR_SZ || !offset_out) {
- return false;
- }
- size_t floor =
- length > UINT16_MAX + ZIP_END_HDR_SZ ? length - (UINT16_MAX + ZIP_END_HDR_SZ) : 0;
- for (size_t offset = length - ZIP_END_HDR_SZ;; offset--) {
- if (zip_signature_is(data, offset, length, 0x05, 0x06)) {
- uint16_t comment = zip_read_u16le(data + offset + ZIP_END_OFF_COMMENTLEN);
- if (offset + ZIP_END_HDR_SZ + comment == length) {
- *offset_out = offset;
- return true;
- }
- }
- if (offset == floor) {
- break;
- }
- }
- return false;
-}
-
-static bool zip_ascii_equal_folded(const unsigned char *name, size_t name_length,
- const char *expected) {
- size_t expected_length = strlen(expected);
- if (name_length != expected_length) {
- return false;
- }
- for (size_t index = 0; index < name_length; index++) {
- unsigned char left = name[index];
- unsigned char right = (unsigned char)expected[index];
- if (left >= 'A' && left <= 'Z') {
- left = (unsigned char)(left - 'A' + 'a');
- }
- if (right >= 'A' && right <= 'Z') {
- right = (unsigned char)(right - 'A' + 'a');
- }
- if (left != right) {
- return false;
- }
- }
- return true;
-}
-
-static int zip_windows_bundle_name_kind(const unsigned char *name, size_t name_length) {
- static const char *const allowed[] = {
- NULL, "codebase-memory-mcp.exe", "codebase-memory-mcp.payload.exe", "LICENSE",
- "install.ps1", "THIRD_PARTY_NOTICES.md",
- };
- if (!name || name_length == 0 || name[name_length - 1U] == '.' ||
- name[name_length - 1U] == ' ') {
- return 0;
- }
- for (size_t index = 0; index < name_length; index++) {
- if (name[index] == '\0' || name[index] == '/' || name[index] == '\\' ||
- name[index] == ':') {
- return 0;
- }
- }
- for (size_t kind = 1U; kind < sizeof(allowed) / sizeof(allowed[0]); kind++) {
- const char *expected = allowed[kind];
- if (zip_ascii_equal_folded(name, name_length, expected)) {
- return name_length == strlen(expected) && memcmp(name, expected, name_length) == 0
- ? (int)kind
- : -1;
- }
- }
- return 0;
-}
-
-void cbm_windows_release_pair_free(cbm_windows_release_pair_t *pair) {
- if (pair) {
- free(pair->launcher);
- free(pair->payload);
- memset(pair, 0, sizeof(*pair));
- }
-}
-
-bool cbm_extract_windows_release_pair_from_zip(const unsigned char *data, int data_len,
- cbm_windows_release_pair_t *pair_out) {
- if (!data || data_len <= 0 || !pair_out) {
- return false;
- }
- memset(pair_out, 0, sizeof(*pair_out));
- size_t length = (size_t)data_len;
- size_t end_offset = 0;
- if (!zip_find_end_record(data, length, &end_offset)) {
- return false;
- }
- const unsigned char *end = data + end_offset;
- uint16_t entries_disk = zip_read_u16le(end + ZIP_END_OFF_ENTRIES_DISK);
- uint16_t entries_total = zip_read_u16le(end + ZIP_END_OFF_ENTRIES_TOTAL);
- uint32_t central_size = zip_read_u32le(end + ZIP_END_OFF_CENTRAL_SIZE);
- uint32_t central_offset = zip_read_u32le(end + ZIP_END_OFF_CENTRAL_OFFSET);
- if (zip_read_u16le(end + ZIP_END_OFF_DISK) != 0 ||
- zip_read_u16le(end + ZIP_END_OFF_CENTRAL_DISK) != 0 || entries_disk != 5 ||
- entries_total != 5 || central_offset > end_offset ||
- central_size != end_offset - central_offset) {
- return false;
- }
-
- size_t cursor = central_offset;
- bool seen[6] = {false, false, false, false, false, false};
- size_t local_starts[5] = {0, 0, 0, 0, 0};
- size_t local_ends[5] = {0, 0, 0, 0, 0};
- for (uint16_t entry = 0; entry < entries_total; entry++) {
- if (!zip_signature_is(data, cursor, length, 0x01, 0x02) ||
- length - cursor < ZIP_CENTRAL_HDR_SZ) {
- cbm_windows_release_pair_free(pair_out);
- return false;
- }
- const unsigned char *central = data + cursor;
- uint16_t flags = zip_read_u16le(central + ZIP_CENTRAL_OFF_FLAGS);
- uint16_t method = zip_read_u16le(central + ZIP_CENTRAL_OFF_METHOD);
- uint32_t crc = zip_read_u32le(central + ZIP_CENTRAL_OFF_CRC);
- uint32_t compressed = zip_read_u32le(central + ZIP_CENTRAL_OFF_COMP);
- uint32_t uncompressed = zip_read_u32le(central + ZIP_CENTRAL_OFF_UNCOMP);
- uint16_t name_length = zip_read_u16le(central + ZIP_CENTRAL_OFF_NAMELEN);
- uint16_t extra_length = zip_read_u16le(central + ZIP_CENTRAL_OFF_EXTRALEN);
- uint16_t comment_length = zip_read_u16le(central + ZIP_CENTRAL_OFF_COMMENTLEN);
- uint32_t local_offset = zip_read_u32le(central + ZIP_CENTRAL_OFF_LOCAL);
- size_t central_record_size = ZIP_CENTRAL_HDR_SZ + (size_t)name_length +
- (size_t)extra_length + (size_t)comment_length;
- if (name_length == 0 || central_record_size > end_offset - cursor ||
- zip_read_u16le(central + ZIP_CENTRAL_OFF_DISK) != 0 ||
- (flags & (uint16_t)~ZIP_UTF8_FLAG) != 0 ||
- (method != ZIP_STORED && method != ZIP_DEFLATE)) {
- cbm_windows_release_pair_free(pair_out);
- return false;
- }
- const unsigned char *name = central + ZIP_CENTRAL_HDR_SZ;
- int kind = zip_windows_bundle_name_kind(name, name_length);
- if (kind <= 0 || seen[kind]) {
- cbm_windows_release_pair_free(pair_out);
- return false;
- }
- seen[kind] = true;
-
- if (local_offset >= central_offset ||
- !zip_signature_is(data, local_offset, length, 0x03, 0x04) ||
- central_offset - local_offset < ZIP_HDR_SZ) {
- cbm_windows_release_pair_free(pair_out);
- return false;
- }
- const unsigned char *local = data + local_offset;
- uint16_t local_flags = zip_read_u16le(local + ZIP_OFF_FLAGS);
- uint16_t local_method = zip_read_u16le(local + ZIP_OFF_METHOD);
- uint32_t local_crc = zip_read_u32le(local + ZIP_OFF_CRC);
- uint32_t local_compressed = zip_read_u32le(local + ZIP_OFF_COMP);
- uint32_t local_uncompressed = zip_read_u32le(local + ZIP_OFF_UNCOMP);
- uint16_t local_name_length = zip_read_u16le(local + ZIP_OFF_NAMELEN);
- uint16_t local_extra_length = zip_read_u16le(local + ZIP_OFF_EXTRALEN);
- size_t data_offset = (size_t)local_offset + ZIP_HDR_SZ + (size_t)local_name_length +
- (size_t)local_extra_length;
- if (local_flags != flags || local_method != method || local_crc != crc ||
- local_compressed != compressed || local_uncompressed != uncompressed ||
- local_name_length != name_length || data_offset > central_offset ||
- compressed > central_offset - data_offset ||
- memcmp(local + ZIP_HDR_SZ, name, name_length) != 0) {
- cbm_windows_release_pair_free(pair_out);
- return false;
- }
- size_t local_end = data_offset + compressed;
- for (uint16_t prior = 0; prior < entry; prior++) {
- if (local_offset < local_ends[prior] && local_end > local_starts[prior]) {
- cbm_windows_release_pair_free(pair_out);
- return false;
- }
- }
- local_starts[entry] = local_offset;
- local_ends[entry] = local_end;
- int extracted_length = 0;
- unsigned char *extracted = zip_extract_entry(data + data_offset, method, compressed,
- uncompressed, &extracted_length);
- uLong observed_crc = extracted ? crc32(0L, extracted, (uInt)extracted_length) : 0;
- if (!extracted || extracted_length <= 0 || (uint32_t)extracted_length != uncompressed ||
- observed_crc != crc) {
- free(extracted);
- cbm_windows_release_pair_free(pair_out);
- return false;
- }
- if (kind == 1) {
- pair_out->launcher = extracted;
- pair_out->launcher_len = extracted_length;
- } else if (kind == 2) {
- pair_out->payload = extracted;
- pair_out->payload_len = extracted_length;
- } else {
- /* Legal/install metadata is part of the authenticated release
- * namespace but is never materialized by the updater. Parsing,
- * bounds checks, and CRC verification above still cover it. */
- free(extracted);
- }
- cursor += central_record_size;
- }
- for (size_t index = 1U; index < 5U; index++) {
- size_t start = local_starts[index];
- size_t end_value = local_ends[index];
- size_t position = index;
- while (position > 0U && local_starts[position - 1U] > start) {
- local_starts[position] = local_starts[position - 1U];
- local_ends[position] = local_ends[position - 1U];
- position--;
- }
- local_starts[position] = start;
- local_ends[position] = end_value;
- }
- bool namespace_complete = true;
- for (size_t kind = 1U; kind < 6U; kind++) {
- namespace_complete = namespace_complete && seen[kind];
- }
- bool local_records_contiguous = local_starts[0] == 0U;
- for (size_t index = 1U; index < 5U; index++) {
- local_records_contiguous =
- local_records_contiguous && local_ends[index - 1U] == local_starts[index];
- }
- if (cursor != end_offset || !namespace_complete || !local_records_contiguous ||
- local_ends[4] != central_offset) {
- cbm_windows_release_pair_free(pair_out);
- return false;
- }
- return true;
-}
-
/* ── Index management ─────────────────────────────────────────── */
static const char *get_cache_dir(const char *home_dir) {
@@ -8534,15 +7630,7 @@ static void print_detected_registry_agents(const char *home, bool *any) {
static void cbm_agent_installed_binary_path(const char *home, char *binary_path,
size_t binary_path_size) {
#ifdef _WIN32
- char *managed = g_windows_launcher_context.present && g_windows_launcher_context.managed
- ? cli_windows_plain_utf8(g_windows_launcher_context.canonical_launcher_path)
- : NULL;
- if (managed) {
- (void)snprintf(binary_path, binary_path_size, "%s", managed);
- free(managed);
- } else {
- snprintf(binary_path, binary_path_size, "%s/.local/bin/codebase-memory-mcp.exe", home);
- }
+ snprintf(binary_path, binary_path_size, "%s/.local/bin/codebase-memory-mcp.exe", home);
#else
snprintf(binary_path, binary_path_size, "%s/.local/bin/codebase-memory-mcp", home);
#endif
@@ -9676,7 +8764,6 @@ int cbm_install_agent_configs(const char *home, const char *binary_path, bool fo
return g_agent_install_errors == 0 ? CLI_OK : CLI_ERR;
}
-#if !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API)
static int cbm_install_agent_configs_with_previous(const char *home, const char *binary_path,
const char *previous_managed_binary_path,
bool force, bool dry_run) {
@@ -9686,7 +8773,6 @@ static int cbm_install_agent_configs_with_previous(const char *home, const char
g_previous_managed_mcp_command = saved;
return result;
}
-#endif
/* Count .db files in the cache directory. */
static int count_db_indexes(const char *home) {
@@ -9779,12 +8865,8 @@ int cbm_install_handle_existing_indexes(const char *home, bool reset, bool dry_r
/* ── Subcommand: install ──────────────────────────────────────── */
-/* The portable activation flow (self-path detection, simple-copy activate)
- * serves every POSIX build, and Windows TEST builds only: there the C suite
- * reaches it through the activation test seam to unit-cover the shared
- * activation/agent-config semantics, while release Windows binaries compile
- * exclusively the managed launcher transaction. */
-#if !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API)
+/* The activation flow (self-path detection, simple-copy activate) is the same
+ * on every platform: Windows ships ONE binary, exactly like Linux and macOS. */
/* Detect the running binary's path at runtime. The return value distinguishes
* OS-reported identity (safe ownership evidence) from the ~/.local/bin fallback
* used only as an install copy source. */
@@ -9823,7 +8905,6 @@ static bool cbm_detect_self_path(char *buf, size_t buf_sz, const char *home) {
}
return exact;
}
-#endif /* !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API) */
/* Build the agent.install.plan.v1 receipt (#388): a machine-readable list of
* the config / instruction / skill / agent / hook files `install` WOULD write, produced by
@@ -9945,7 +9026,6 @@ char *cbm_build_install_plan_json(const char *home, const char *binary_path) {
return cbm_build_install_plan_json_options(home, binary_path, false);
}
-#if !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API)
typedef struct {
const char *bin_target;
const char *bin_dir;
@@ -10071,816 +9151,6 @@ static int cli_install_activate(void *opaque) {
"install_transaction_finalize");
return CLI_OK;
}
-#endif /* !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API) */
-
-#ifdef _WIN32
-typedef struct {
- const char *home;
- const char *bin_dir;
- const char *bin_target;
- 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;
- bool dry_run;
-} cli_windows_install_activation_t;
-
-static bool cli_windows_current_path(const wchar_t *canonical_launcher,
- wchar_t out[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {
- wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t state_directory[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_directory,
- CBM_WINDOWS_LAUNCHER_PATH_CAP) &&
- cli_windows_join_path(state_directory, L"current-v1", 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) {
- if (!state_out || !exists_out) {
- return false;
- }
- memset(state_out, 0, sizeof(*state_out));
- *exists_out = false;
- wchar_t path[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!cli_windows_current_path(canonical_launcher, path)) {
- return false;
- }
- HANDLE file =
- CreateFileW(path, GENERIC_READ | READ_CONTROL, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
- OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
- if (file == INVALID_HANDLE_VALUE) {
- DWORD error = GetLastError();
- return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND;
- }
- BY_HANDLE_FILE_INFORMATION information;
- LARGE_INTEGER size;
- uint8_t record[CBM_WINDOWS_CURRENT_V1_SIZE];
- DWORD received = 0;
- bool valid = GetFileInformationByHandle(file, &information) != 0 &&
- (information.dwFileAttributes &
- (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0 &&
- information.nNumberOfLinks == 1 && GetFileSizeEx(file, &size) != 0 &&
- size.QuadPart == CBM_WINDOWS_CURRENT_V1_SIZE &&
- ReadFile(file, record, sizeof(record), &received, NULL) != 0 &&
- received == sizeof(record) &&
- cbm_windows_current_v1_decode(record, sizeof(record), state_out);
- (void)CloseHandle(file);
- *exists_out = true;
- 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]) {
- cbm_activation_transaction_t *transaction = NULL;
- cbm_activation_transaction_status_t status =
- cbm_activation_transaction_stage_file(target, source, &transaction);
- cli_binary_validator_t validator = {{0}};
- /* Each transaction step reports separately: a directory-validation
- * refusal, a build-identity mismatch, and a commit failure are three
- * different bugs, and the caller's single boolean previously collapsed
- * them into one blind "staging failed" with no OS error code. */
- bool ready = status == CBM_ACTIVATION_TRANSACTION_OK && transaction;
- if (!ready) {
- const char *refusal = cbm_activation_transaction_refusal_note();
- (void)fprintf(stderr, "error: staging transaction open failed (status %d, os %lu%s%s)\n",
- (int)status, (unsigned long)GetLastError(), refusal[0] ? ": " : "", refusal);
- }
- if (ready && !cli_activation_transaction_expected_build(transaction, &validator)) {
- (void)fprintf(stderr, "error: staged copy build-identity validation failed (os %lu)\n",
- (unsigned long)GetLastError());
- ready = false;
- }
- if (ready && cli_activation_transaction_commit_validated(transaction, &validator,
- CLI_OCTAL_PERM) != CLI_OK) {
- (void)fprintf(stderr, "error: staging transaction commit failed (os %lu)\n",
- (unsigned long)GetLastError());
- ready = false;
- }
- if (ready && cli_activation_transaction_finalize_close(&transaction) != CLI_OK) {
- (void)fprintf(stderr, "error: staging transaction finalize failed (os %lu)\n",
- (unsigned long)GetLastError());
- ready = false;
- }
- (void)cli_activation_transaction_abort(&transaction);
- if (ready && fingerprint_out) {
- (void)snprintf(fingerprint_out, CBM_DAEMON_BUILD_FINGERPRINT_SIZE, "%s",
- validator.fingerprint);
- }
- return ready;
-}
-
-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]) {
- if (!bytes || bytes_size == 0 || !target || !target[0]) {
- return false;
- }
- cbm_activation_transaction_t *transaction = NULL;
- cbm_activation_transaction_status_t status =
- cbm_activation_transaction_stage_bytes(target, bytes, bytes_size, &transaction);
- cli_binary_validator_t validator = {{0}};
- bool ready = status == 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);
- if (ready && fingerprint_out) {
- (void)snprintf(fingerprint_out, CBM_DAEMON_BUILD_FINGERPRINT_SIZE, "%s",
- validator.fingerprint);
- }
- return ready;
-}
-
-/* Per-user staging root for Windows install/update transactions. The
- * activation transaction and the release-descriptor probe validate the FULL
- * ancestor chain of everything they stage (trusted owner and no foreign
- * mutation grant on any path component). The process temp root routinely
- * fails that walk through no fault of ours: under msys2, TMP resolves
- * inside the msys install tree (C:\msys64\tmp), and on GitHub runners
- * inside the runner work directory, both of which carry broad inherited
- * grants such as Authenticated Users modify on an upper component. The
- * profile's AppData\Local chain is user-owned end to end, so staging there
- * satisfies the strict walk by construction instead of by environment
- * luck. */
-static const char *cli_windows_staging_root(char root_out[CLI_BUF_1K]) {
- char base[CLI_BUF_1K];
- if (!cbm_safe_getenv("LOCALAPPDATA", base, sizeof(base), NULL) || !base[0]) {
- char profile[CLI_BUF_1K];
- if (!cbm_safe_getenv("USERPROFILE", profile, sizeof(profile), NULL) || !profile[0]) {
- return cbm_tmpdir();
- }
- int base_length = snprintf(base, sizeof(base), "%s/AppData/Local", profile);
- if (base_length <= 0 || (size_t)base_length >= sizeof(base)) {
- return cbm_tmpdir();
- }
- }
- /* msys/CI harnesses export profile variables in POSIX drive form
- * ("/c/Users/..."); the CRT cannot resolve that, so rewrite it to the
- * native "C:/Users/..." form before building the root. */
- if (base[0] == '/' &&
- ((base[1] >= 'a' && base[1] <= 'z') || (base[1] >= 'A' && base[1] <= 'Z')) &&
- (base[2] == '/' || base[2] == '\0')) {
- char drive = base[1];
- char rest[CLI_BUF_1K];
- (void)snprintf(rest, sizeof(rest), "%s", base + 2);
- (void)snprintf(base, sizeof(base), "%c:%s", drive, rest[0] ? rest : "/");
- }
- int written = snprintf(root_out, CLI_BUF_1K, "%s/codebase-memory-mcp", base);
- if (written <= 0 || written >= CLI_BUF_1K) {
- return cbm_tmpdir();
- }
- /* Create the whole chain: harness environments point LOCALAPPDATA at a
- * fake profile whose AppData\Local ancestors do not exist on disk yet,
- * and a single-level mkdir silently leaves the root missing. */
- for (int index = 3; root_out[index] != '\0'; index++) {
- if (root_out[index] != '/' && root_out[index] != '\\') {
- continue;
- }
- char saved = root_out[index];
- root_out[index] = '\0';
- (void)_mkdir(root_out);
- root_out[index] = saved;
- }
- (void)_mkdir(root_out);
- DWORD attributes = GetFileAttributesA(root_out);
- if (attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
- return cbm_tmpdir();
- }
- return root_out;
-}
-
-static bool cli_windows_prepare_install_pair(const wchar_t *launcher_source,
- const wchar_t *payload_source,
- const char expected_payload_sha256[65],
- wchar_t launcher_out[CBM_WINDOWS_LAUNCHER_PATH_CAP],
- wchar_t payload_out[CBM_WINDOWS_LAUNCHER_PATH_CAP],
- char directory_out[CLI_BUF_1K]) {
- char *launcher_source_utf8 = cbm_wide_to_utf8(launcher_source);
- char *payload_source_utf8 = cbm_wide_to_utf8(payload_source);
- char staging_root[CLI_BUF_1K];
- int directory_length = snprintf(directory_out, CLI_BUF_1K, "%s/cbm-win-install-XXXXXX",
- cli_windows_staging_root(staging_root));
- bool ready = launcher_source_utf8 && payload_source_utf8 && directory_length > 0 &&
- directory_length < CLI_BUF_1K && cbm_mkdtemp(directory_out);
- if (!ready) {
- (void)fprintf(stderr, "error: could not create the private staging directory (%s)\n",
- directory_out);
- }
- char launcher_target[CLI_BUF_1K];
- char payload_target[CLI_BUF_1K];
- int launcher_length = ready ? snprintf(launcher_target, sizeof(launcher_target),
- "%s/codebase-memory-mcp.exe", directory_out)
- : CLI_ERR;
- int payload_length = ready ? snprintf(payload_target, sizeof(payload_target),
- "%s/codebase-memory-mcp.payload.exe", directory_out)
- : CLI_ERR;
- ready = ready && launcher_length > 0 && (size_t)launcher_length < sizeof(launcher_target) &&
- payload_length > 0 && (size_t)payload_length < sizeof(payload_target);
- char launcher_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];
- char payload_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];
- /* Each sub-step is checked separately so a staging failure is
- * distinguishable from a fingerprint mismatch or an unrunnable staged
- * launcher: the caller's single "did not remain runnable" message hides
- * which one failed, and cbm_exec_no_shell does not inherit the child's
- * stderr, so the launcher's own refusal reason never reaches the log. */
- if (ready && !cli_windows_stage_private_file(launcher_source_utf8, launcher_target,
- launcher_fingerprint)) {
- (void)fprintf(stderr, "error: private staging failed for the launcher (%s)\n",
- launcher_target);
- ready = false;
- }
- if (ready &&
- !cli_windows_stage_private_file(payload_source_utf8, payload_target, payload_fingerprint)) {
- (void)fprintf(stderr, "error: private staging failed for the payload (%s)\n",
- payload_target);
- ready = false;
- }
- if (ready && strcmp(payload_fingerprint, expected_payload_sha256) != 0) {
- (void)fprintf(
- stderr, "error: staged payload build fingerprint did not match the expected payload\n");
- ready = false;
- }
- if (ready) {
- const char *version_argv[] = {launcher_target, "--version", NULL};
- if (cbm_exec_no_shell(version_argv) != CLI_OK) {
- (void)fprintf(stderr,
- "error: the staged launcher did not run (--version probe failed)\n");
- ready = false;
- }
- }
- wchar_t *launcher_wide = ready ? cbm_utf8_to_wide(launcher_target) : NULL;
- wchar_t *payload_wide = ready ? cbm_utf8_to_wide(payload_target) : NULL;
- if (ready && launcher_wide && payload_wide) {
- (void)_snwprintf_s(launcher_out, CBM_WINDOWS_LAUNCHER_PATH_CAP, _TRUNCATE, L"%ls",
- launcher_wide);
- (void)_snwprintf_s(payload_out, CBM_WINDOWS_LAUNCHER_PATH_CAP, _TRUNCATE, L"%ls",
- payload_wide);
- } else {
- ready = false;
- }
- free(launcher_wide);
- free(payload_wide);
- free(launcher_source_utf8);
- free(payload_source_utf8);
- if (!ready) {
- if (launcher_length > 0 && (size_t)launcher_length < sizeof(launcher_target)) {
- (void)cbm_unlink(launcher_target);
- }
- if (payload_length > 0 && (size_t)payload_length < sizeof(payload_target)) {
- (void)cbm_unlink(payload_target);
- }
- if (directory_out[0]) {
- (void)cbm_rmdir(directory_out);
- }
- directory_out[0] = '\0';
- }
- return ready;
-}
-
-static void cli_windows_cleanup_install_pair(const wchar_t *launcher, const wchar_t *payload,
- const char *directory) {
- char *launcher_utf8 = cbm_wide_to_utf8(launcher);
- char *payload_utf8 = cbm_wide_to_utf8(payload);
- if (launcher_utf8) {
- (void)cbm_unlink(launcher_utf8);
- }
- if (payload_utf8) {
- (void)cbm_unlink(payload_utf8);
- }
- if (directory && directory[0]) {
- (void)cbm_rmdir(directory);
- }
- free(launcher_utf8);
- free(payload_utf8);
-}
-
-static bool cli_windows_prepare_update_pair(const cbm_windows_release_pair_t *pair,
- const char expected_payload_sha256[65],
- wchar_t launcher_out[CBM_WINDOWS_LAUNCHER_PATH_CAP],
- wchar_t payload_out[CBM_WINDOWS_LAUNCHER_PATH_CAP],
- char directory_out[CLI_BUF_1K]) {
- if (!pair || !pair->launcher || pair->launcher_len <= 0 || !pair->payload ||
- pair->payload_len <= 0 || !expected_payload_sha256) {
- return false;
- }
- char staging_root[CLI_BUF_1K];
- int directory_length = snprintf(directory_out, CLI_BUF_1K, "%s/cbm-win-update-XXXXXX",
- cli_windows_staging_root(staging_root));
- bool ready =
- directory_length > 0 && directory_length < CLI_BUF_1K && cbm_mkdtemp(directory_out);
- if (!ready) {
- (void)fprintf(stderr, "error: could not create the private staging directory (%s)\n",
- directory_out);
- }
- char launcher_target[CLI_BUF_1K];
- char payload_target[CLI_BUF_1K];
- int launcher_length = ready ? snprintf(launcher_target, sizeof(launcher_target),
- "%s/codebase-memory-mcp.exe", directory_out)
- : CLI_ERR;
- int payload_length = ready ? snprintf(payload_target, sizeof(payload_target),
- "%s/codebase-memory-mcp.payload.exe", directory_out)
- : CLI_ERR;
- ready = ready && launcher_length > 0 && (size_t)launcher_length < sizeof(launcher_target) &&
- payload_length > 0 && (size_t)payload_length < sizeof(payload_target);
- char payload_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE];
- ready = ready &&
- cli_windows_stage_private_bytes(pair->launcher, (size_t)pair->launcher_len,
- launcher_target, NULL) &&
- cli_windows_stage_private_bytes(pair->payload, (size_t)pair->payload_len,
- payload_target, payload_fingerprint) &&
- strcmp(payload_fingerprint, expected_payload_sha256) == 0;
- const char *version_argv[] = {launcher_target, "--version", NULL};
- ready = ready && cbm_exec_no_shell(version_argv) == CLI_OK;
- wchar_t *launcher_wide = ready ? cbm_utf8_to_wide(launcher_target) : NULL;
- wchar_t *payload_wide = ready ? cbm_utf8_to_wide(payload_target) : NULL;
- if (ready && launcher_wide && payload_wide) {
- int launcher_copied = _snwprintf_s(launcher_out, CBM_WINDOWS_LAUNCHER_PATH_CAP, _TRUNCATE,
- L"%ls", launcher_wide);
- int payload_copied = _snwprintf_s(payload_out, CBM_WINDOWS_LAUNCHER_PATH_CAP, _TRUNCATE,
- L"%ls", payload_wide);
- ready = launcher_copied > 0 && payload_copied > 0;
- } else {
- ready = false;
- }
- free(launcher_wide);
- free(payload_wide);
- if (!ready) {
- if (launcher_length > 0 && (size_t)launcher_length < sizeof(launcher_target)) {
- (void)cbm_unlink(launcher_target);
- }
- if (payload_length > 0 && (size_t)payload_length < sizeof(payload_target)) {
- (void)cbm_unlink(payload_target);
- }
- if (directory_out[0]) {
- (void)cbm_rmdir(directory_out);
- }
- directory_out[0] = '\0';
- }
- return ready;
-}
-
-static int cli_windows_managed_install_activate(void *opaque) {
- cli_windows_install_activation_t *activation = opaque;
- if (!activation || !activation->home || !activation->bin_dir || !activation->bin_target) {
- return CLI_TRUE;
- }
- int activation_status = CLI_OK;
- if (activation->dry_run) {
- printf("Would install managed launcher -> %s\n(dry-run — no files were modified)\n\n",
- activation->bin_target);
- } else {
- bool generation_created = false;
- 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->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,
- generation_launcher, error, sizeof(error));
- } else if (generation_ready) {
- 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 (!generation_ready || !launcher_committed || !current_committed) {
- 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};
- 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;
- }
- size_t generations_removed = 0U;
- char prune_error[CLI_BUF_256] = {0};
- if (!cbm_windows_generations_prune(activation->canonical_launcher, &generations_removed,
- prune_error, sizeof(prune_error))) {
- (void)fprintf(stderr,
- "error: managed Windows install committed, but old "
- "generation pruning was incomplete: %s\n",
- prune_error[0] ? prune_error : "unsafe generation entry");
- activation_status = CLI_ACTIVATION_PARTIAL;
- }
- printf("Installed managed launcher -> %s\n\n", activation->bin_target);
- }
-
- if (!activation->skip_config &&
- cbm_install_agent_configs(activation->home, activation->bin_target, activation->force,
- activation->dry_run) != CLI_OK) {
- (void)fprintf(stderr, "error: managed launcher was kept, but one or more agent "
- "configuration updates failed\n");
- return CLI_ACTIVATION_PARTIAL;
- }
- int path_status = cli_ensure_windows_user_path(
- activation->bin_dir, activation->dry_run || g_cli_activation_test_ops_set);
- if (path_status == CLI_ERR) {
- (void)fprintf(stderr, "error: managed launcher was kept, but current-user PATH "
- "configuration failed\n");
- return CLI_ACTIVATION_PARTIAL;
- }
- if (path_status == CLI_OK) {
- printf("\nAdded %s to the current-user PATH\n", activation->bin_dir);
- } else {
- printf("\nPATH already includes %s\n", activation->bin_dir);
- }
- if (!activation->dry_run && activation->delete_indexes) {
- int expected = count_db_indexes(activation->home);
- int removed = cbm_remove_indexes(activation->home);
- printf("Removed %d index(es).\n\n", removed);
- if (removed != expected) {
- (void)fprintf(stderr, "error: only %d of %d indexes could be removed\n", removed,
- expected);
- return CLI_ACTIVATION_PARTIAL;
- }
- }
- return activation_status;
-}
-
-static int cli_windows_managed_install(const char *home, const char *requested_bin_dir,
- bool dry_run, bool force, bool reset_indexes,
- bool skip_config) {
- char default_dir[CLI_BUF_1K];
- const char *directory_input = requested_bin_dir;
- if (!directory_input) {
- int written = snprintf(default_dir, sizeof(default_dir), "%s/.local/bin", home);
- if (written <= 0 || (size_t)written >= sizeof(default_dir)) {
- return CLI_TRUE;
- }
- directory_input = default_dir;
- }
-
- wchar_t *requested_wide = cli_windows_utf8_to_wide(directory_input);
- wchar_t full_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- DWORD full_length =
- requested_wide
- ? GetFullPathNameW(requested_wide, CBM_WINDOWS_LAUNCHER_PATH_CAP, full_directory, NULL)
- : 0;
- free(requested_wide);
- if (full_length == 0 || full_length >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- (void)fprintf(stderr, "error: install directory could not be resolved\n");
- return CLI_TRUE;
- }
-
- wchar_t canonical_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t payload_source[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t launcher_source[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!cli_windows_join_path(full_directory, L"codebase-memory-mcp.exe", canonical_launcher,
- CBM_WINDOWS_LAUNCHER_PATH_CAP) ||
- !cli_windows_module_path(payload_source) ||
- !cli_windows_regular_file_no_reparse(payload_source, NULL) ||
- !cli_windows_install_source_launcher(payload_source, launcher_source)) {
- (void)fprintf(stderr, "error: managed install requires a verified adjacent "
- "codebase-memory-mcp.exe launcher (or an authenticated existing "
- "managed launcher)\n");
- return CLI_TRUE;
- }
-
- char *bin_dir = cbm_wide_to_utf8(full_directory);
- 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};
- char launcher_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};
- uint64_t payload_size = 0;
- bool sources_valid = bin_dir && bin_target && payload_utf8 && launcher_utf8 &&
- cli_windows_regular_file_no_reparse(payload_source, &payload_size) &&
- cbm_daemon_build_fingerprint_file(payload_utf8, fingerprint) &&
- cbm_daemon_build_fingerprint_file(launcher_utf8, launcher_fingerprint);
- if (!sources_valid) {
- (void)fprintf(stderr, "error: launcher/payload source verification failed before "
- "managed install\n");
- free(bin_dir);
- free(bin_target);
- free(payload_utf8);
- free(launcher_utf8);
- return CLI_TRUE;
- }
-
- wchar_t prepared_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};
- wchar_t prepared_payload[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};
- char prepared_directory[CLI_BUF_1K] = {0};
- bool pair_prepared = false;
- cbm_windows_release_descriptor_v1_t descriptor = {
- .launcher_abi = CBM_WINDOWS_LAUNCHER_ABI_CURRENT,
- .payload_launcher_abi_min = CBM_WINDOWS_PAYLOAD_LAUNCHER_ABI_MIN,
- .payload_launcher_abi_max = CBM_WINDOWS_PAYLOAD_LAUNCHER_ABI_MAX,
- .payload_size = payload_size,
- };
- (void)snprintf(descriptor.payload_sha256, sizeof(descriptor.payload_sha256), "%s", fingerprint);
-
- cbm_windows_current_v1_t previous;
- memset(&previous, 0, sizeof(previous));
- bool current_exists = false;
- bool current_valid = cli_windows_read_current(canonical_launcher, &previous, &current_exists);
- 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_512] = {0};
- wchar_t target_backing[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};
- bool current_target_secure =
- 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 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_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 =
- 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",
- target_error[0] ? ": " : "", target_error[0] ? target_error : "");
- free(bin_dir);
- free(bin_target);
- free(payload_utf8);
- free(launcher_utf8);
- return CLI_TRUE;
- }
-
- if (!dry_run) {
- pair_prepared = cli_windows_prepare_install_pair(launcher_source, payload_source,
- fingerprint, prepared_launcher,
- prepared_payload, prepared_directory);
- if (!pair_prepared) {
- (void)fprintf(stderr, "error: launcher/payload source pair did not remain "
- "runnable after private staging\n");
- free(bin_dir);
- free(bin_target);
- free(payload_utf8);
- free(launcher_utf8);
- return CLI_TRUE;
- }
- char probe_error[CLI_BUF_512] = {0};
- if (!cbm_windows_release_descriptor_probe(prepared_launcher, &descriptor, probe_error,
- sizeof(probe_error)) ||
- descriptor.payload_size != payload_size ||
- strcmp(descriptor.payload_sha256, fingerprint) != 0) {
- (void)fprintf(stderr,
- "error: managed Windows install release descriptor is "
- "invalid or does not match the staged payload before "
- "stopping CBM sessions: %s\n",
- probe_error[0] ? probe_error : "payload identity mismatch");
- cli_windows_cleanup_install_pair(prepared_launcher, prepared_payload,
- prepared_directory);
- free(bin_dir);
- free(bin_target);
- free(payload_utf8);
- free(launcher_utf8);
- return CLI_TRUE;
- }
- cbm_windows_transition_plan_t candidate_plan =
- current_exists ? cbm_windows_transition_plan(&previous, &descriptor)
- : CBM_WINDOWS_TRANSITION_LAUNCHER_FIRST;
- if (candidate_plan == CBM_WINDOWS_TRANSITION_INCOMPATIBLE) {
- (void)fprintf(stderr, "error: managed Windows install requires an intermediate "
- "launcher ABI bridge; active CBM sessions were not stopped\n");
- cli_windows_cleanup_install_pair(prepared_launcher, prepared_payload,
- prepared_directory);
- free(bin_dir);
- free(bin_target);
- free(payload_utf8);
- free(launcher_utf8);
- return CLI_TRUE;
- }
- if (!cbm_windows_launcher_capability_probe(full_directory, prepared_launcher, probe_error,
- sizeof(probe_error))) {
- (void)fprintf(stderr,
- "error: managed launcher capability probe failed before "
- "stopping CBM sessions: %s\n",
- probe_error[0] ? probe_error
- : "local fixed NTFS atomic replacement is unavailable");
- cli_windows_cleanup_install_pair(prepared_launcher, prepared_payload,
- prepared_directory);
- free(bin_dir);
- free(bin_target);
- free(payload_utf8);
- free(launcher_utf8);
- return CLI_TRUE;
- }
- }
-
- bool delete_indexes = false;
- if (cbm_install_prepare_existing_indexes(home, reset_indexes, dry_run, &delete_indexes) == 0) {
- if (pair_prepared) {
- cli_windows_cleanup_install_pair(prepared_launcher, prepared_payload,
- prepared_directory);
- }
- free(bin_dir);
- free(bin_target);
- free(payload_utf8);
- free(launcher_utf8);
- return CLI_TRUE;
- }
- cbm_windows_current_v1_t state = {
- .launcher_abi_min = descriptor.payload_launcher_abi_min,
- .launcher_abi_max = descriptor.payload_launcher_abi_max,
- .payload_size = descriptor.payload_size,
- };
- (void)snprintf(state.payload_sha256, sizeof(state.payload_sha256), "%s", fingerprint);
- cli_windows_install_activation_t activation = {
- .home = home,
- .bin_dir = bin_dir,
- .bin_target = bin_target,
- .state = state,
- .previous_state = previous,
- .transition_plan = current_exists ? cbm_windows_transition_plan(&previous, &descriptor)
- : 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,
- sizeof(payload_source));
- int result = dry_run ? cli_windows_managed_install_activate(&activation)
- : cli_activation_guard(CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL, CBM_VERSION,
- state.payload_sha256,
- cli_windows_managed_install_activate, &activation);
- if (pair_prepared) {
- cli_windows_cleanup_install_pair(prepared_launcher, prepared_payload, prepared_directory);
- }
- free(bin_dir);
- free(bin_target);
- free(payload_utf8);
- free(launcher_utf8);
- return result == CLI_OK ? CLI_OK : CLI_TRUE;
-}
-#endif
int cbm_cmd_install(int argc, char **argv) {
parse_auto_answer(argc, argv);
@@ -10963,28 +9233,6 @@ int cbm_cmd_install(int argc, char **argv) {
printf("codebase-memory-mcp install %s\n\n", CBM_VERSION);
-#ifdef _WIN32
- /* Fail-closed dispatch polarity: the managed launcher transaction is the
- * ONLY Windows install path a release binary contains. Test builds
- * additionally compile the portable flow below, reachable solely through
- * the activation test seam and loudly announced, so the shared
- * activation/agent-config semantics stay unit-covered while a misroute
- * can never pass silently. The real managed transaction has its own
- * end-to-end gates (launcher guard, agent-config smoke, smoke-install). */
-#ifdef CBM_CLI_ENABLE_TEST_API
- if (g_cli_activation_test_ops_set) {
- (void)fprintf(stderr,
- "*** cbm test seam: portable install flow engaged; the managed Windows "
- "install transaction is bypassed (test builds only) ***\n");
- } else
-#endif
- {
- return cli_windows_managed_install(home, requested_bin_dir, dry_run, force, reset_indexes,
- skip_config);
- }
-#endif
-
-#if !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API)
char self_path[CLI_BUF_1K] = {0};
(void)cbm_detect_self_path(self_path, sizeof(self_path), home);
@@ -11208,7 +9456,6 @@ int cbm_cmd_install(int argc, char **argv) {
printf("\n(dry-run — no files were modified)\n");
}
return 0;
-#endif /* !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API) */
}
/* ── Subcommand: uninstall ────────────────────────────────────── */
@@ -12309,7 +10556,6 @@ static void uninstall_additional_agents(const cbm_detected_agents_t *agents, con
}
}
-#if !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API)
typedef struct {
const char *home;
const char *bin_path;
@@ -12376,176 +10622,6 @@ static int cli_uninstall_activate(void *opaque) {
}
return CLI_OK;
}
-#endif /* !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API) */
-
-#ifdef _WIN32
-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;
-} cli_windows_uninstall_activation_t;
-
-static int cli_windows_managed_uninstall_activate(void *opaque) {
- cli_windows_uninstall_activation_t *activation = 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);
- }
- uninstall_cli_agents(&activation->agents, activation->home, activation->dry_run);
- uninstall_editor_agents(&activation->agents, activation->home, activation->dry_run);
- uninstall_additional_agents(&activation->agents, activation->home, activation->dry_run);
- uninstall_agent_client_registry(activation->home, activation->dry_run);
- if (g_agent_uninstall_errors != 0) {
- (void)fprintf(stderr, "error: one or more agent cleanup operations failed; managed "
- "launcher and generation state were kept\n");
- return CLI_ACTIVATION_PARTIAL;
- }
- if (activation->dry_run) {
- printf("Would remove managed launcher and generation state -> %s\n",
- activation->canonical_launcher_utf8);
- return CLI_OK;
- }
-
- /* 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);
- printf("Removed %d index(es).\n", removed);
- if (removed != expected) {
- (void)fprintf(stderr, "error: only %d of %d indexes could be removed\n", removed,
- expected);
- 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;
-}
-
-static int cli_windows_managed_uninstall(const char *home, bool dry_run) {
- 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_UNINSTALL) {
- return CLI_TRUE;
- }
- 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, &current,
- &current_exists) ||
- !current_exists ||
- !cbm_windows_current_v1_supports_launcher_abi(&current, 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 ||
- !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];
- if (!cli_windows_parent_path(g_windows_launcher_context.canonical_launcher_path,
- target_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {
- return CLI_TRUE;
- }
- if (!dry_run) {
- char probe_error[CLI_BUF_512] = {0};
- if (!cbm_windows_launcher_capability_probe(
- target_directory, g_windows_launcher_context.canonical_launcher_path, probe_error,
- sizeof(probe_error))) {
- (void)fprintf(stderr,
- "error: managed launcher capability probe failed before "
- "stopping CBM sessions: %s\n",
- probe_error[0] ? probe_error
- : "local fixed NTFS atomic removal is unavailable");
- return CLI_TRUE;
- }
- }
-
- bool delete_indexes = false;
- int index_count = count_db_indexes(home);
- if (index_count > 0) {
- printf("\nFound %d index(es):\n", index_count);
- cbm_list_indexes(home);
- if (prompt_yn("Delete these indexes?")) {
- delete_indexes = !dry_run;
- if (dry_run) {
- printf("(dry-run — indexes would be deleted)\n");
- }
- } else {
- printf("Indexes kept.\n");
- }
- }
- char *canonical_utf8 =
- cli_windows_plain_utf8(g_windows_launcher_context.canonical_launcher_path);
- if (!canonical_utf8) {
- return CLI_TRUE;
- }
- g_agent_uninstall_errors = 0;
- 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,
- cli_windows_managed_uninstall_activate, &activation);
- free(canonical_utf8);
- return result;
-}
-#endif
int cbm_cmd_uninstall(int argc, char **argv) {
parse_auto_answer(argc, argv);
@@ -12565,23 +10641,6 @@ int cbm_cmd_uninstall(int argc, char **argv) {
}
}
-#ifdef _WIN32
- /* A direct/package-manager payload is a one-shot portable instance. Fail
- * before HOME/cache discovery, prompts, daemon IPC, or filesystem writes:
- * only the permanent launcher may authorize managed removal. Test builds
- * additionally compile the portable flow below, reachable solely through
- * the activation test seam (loud), so the shared removal semantics stay
- * unit-covered; release binaries contain only the managed path. */
-#ifdef CBM_CLI_ENABLE_TEST_API
- if (!g_cli_activation_test_ops_set)
-#endif
- {
- if (!cli_windows_require_managed_mutation(CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL)) {
- return CLI_TRUE;
- }
- }
-#endif
-
const char *home = cbm_get_home_dir();
if (!home) {
(void)fprintf(stderr, "error: HOME not set (use USERPROFILE on Windows)\n");
@@ -12590,25 +10649,6 @@ int cbm_cmd_uninstall(int argc, char **argv) {
printf("codebase-memory-mcp uninstall\n\n");
-#ifdef _WIN32
-#ifdef CBM_CLI_ENABLE_TEST_API
- if (g_cli_activation_test_ops_set) {
- (void)fprintf(stderr,
- "*** cbm test seam: portable uninstall flow engaged; the managed Windows "
- "uninstall transaction is bypassed (test builds only) ***\n");
- } else
-#endif
- {
- int windows_result = cli_windows_managed_uninstall(home, dry_run);
- if (windows_result == CLI_OK) {
- printf("\nUninstall complete. Please restart your coding-agent "
- "sessions to properly take this into account.\n");
- }
- return windows_result == CLI_OK ? CLI_OK : CLI_TRUE;
- }
-#endif
-
-#if !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API)
g_agent_uninstall_errors = 0;
cbm_detected_agents_t agents = cbm_detect_agents(home);
@@ -12680,7 +10720,6 @@ int cbm_cmd_uninstall(int argc, char **argv) {
printf("(dry-run — no files were modified)\n");
}
return g_agent_uninstall_errors == 0 ? 0 : CLI_TRUE;
-#endif /* !defined(_WIN32) || defined(CBM_CLI_ENABLE_TEST_API) */
}
/* ── Subcommand: update ───────────────────────────────────────── */
@@ -12696,297 +10735,6 @@ typedef struct {
bool delete_indexes;
} extract_install_args_t;
-#ifdef _WIN32
-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;
- cbm_windows_transition_plan_t transition_plan;
- bool delete_indexes;
-} cli_windows_update_activation_t;
-
-static int cli_windows_managed_update_activate(void *opaque) {
- cli_windows_update_activation_t *activation = opaque;
- if (!activation || !activation->home || !activation->canonical_launcher_utf8 ||
- !activation->pair.launcher || !activation->pair.payload) {
- return CLI_TRUE;
- }
- 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 || !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 generation_launcher[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};
- bool generation_created = false;
- 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,
- generation_launcher, error, sizeof(error));
- } else if (generation_ready) {
- 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 (!generation_ready || !launcher_committed || !current_committed) {
- 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(
- activation->canonical_launcher, activation->state.payload_sha256,
- generation_created, rollback_error, sizeof(rollback_error))) {
- (void)fprintf(stderr,
- "error: managed Windows update generation rollback failed: "
- "%s\n",
- rollback_error[0] ? rollback_error
- : "generation remains for safe recovery");
- }
- (void)fprintf(stderr,
- "error: managed Windows update commit failed: %s. The "
- "compatible launcher/current pair remains runnable; retry "
- "update after reviewing activation-events.ndjson.\n",
- error[0] ? error : "generation/launcher/current publish failed");
- return CLI_TRUE;
- }
-
- int activation_status = CLI_OK;
- size_t generations_removed = 0U;
- char prune_error[CLI_BUF_256] = {0};
- if (!cbm_windows_generations_prune(activation->canonical_launcher, &generations_removed,
- prune_error, sizeof(prune_error))) {
- (void)fprintf(stderr,
- "error: managed Windows update committed, but old generation "
- "pruning was incomplete: %s\n",
- prune_error[0] ? prune_error : "unsafe generation entry");
- activation_status = CLI_ACTIVATION_PARTIAL;
- }
- printf("Refreshing agent configurations...\n");
- if (cbm_install_agent_configs(activation->home, activation->canonical_launcher_utf8, true,
- false) != CLI_OK) {
- (void)fprintf(stderr, "error: update was published, but one or more agent "
- "configuration refreshes failed\n");
- return CLI_ACTIVATION_PARTIAL;
- }
- if (activation->delete_indexes) {
- int expected = count_db_indexes(activation->home);
- int removed = cbm_remove_indexes(activation->home);
- printf("Removed %d index(es).\n\n", removed);
- if (removed != expected) {
- (void)fprintf(stderr, "error: only %d of %d indexes could be removed\n", removed,
- expected);
- return CLI_ACTIVATION_PARTIAL;
- }
- }
- return activation_status;
-}
-
-static int cli_windows_extract_and_activate_update(const char *archive_path, const char *home,
- bool delete_indexes) {
- FILE *archive = cbm_fopen(archive_path, "rb");
- if (!archive || fseek(archive, 0, SEEK_END) != 0) {
- if (archive) {
- (void)fclose(archive);
- }
- (void)cbm_unlink(archive_path);
- return CLI_TRUE;
- }
- long length = ftell(archive);
- if (length <= 0 || length > INT_MAX || fseek(archive, 0, SEEK_SET) != 0) {
- (void)fclose(archive);
- (void)cbm_unlink(archive_path);
- return CLI_TRUE;
- }
- unsigned char *bytes = malloc((size_t)length);
- size_t received = bytes ? fread(bytes, 1, (size_t)length, archive) : 0;
- int closed = fclose(archive);
- (void)cbm_unlink(archive_path);
- cbm_windows_release_pair_t pair;
- bool extracted = bytes && received == (size_t)length && closed == 0 &&
- cbm_extract_windows_release_pair_from_zip(bytes, (int)length, &pair);
- free(bytes);
- if (!extracted || pair.launcher_len < 2 || pair.payload_len < 2 || pair.launcher[0] != 'M' ||
- pair.launcher[1] != 'Z' || pair.payload[0] != 'M' || pair.payload[1] != 'Z') {
- if (extracted) {
- cbm_windows_release_pair_free(&pair);
- }
- (void)fprintf(stderr, "error: Windows release must contain exactly one verified root "
- "launcher and payload executable\n");
- return CLI_TRUE;
- }
-
- char payload_sha[CBM_SHA256_HEX_LEN + 1];
- cbm_sha256_hex(pair.payload, (size_t)pair.payload_len, payload_sha);
-
- cbm_windows_current_v1_t current;
- memset(&current, 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, &current,
- &current_exists) &&
- current_exists &&
- cbm_windows_current_v1_supports_launcher_abi(&current, 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
- ? cli_windows_plain_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 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};
- wchar_t prepared_payload[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};
- wchar_t target_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP] = {0};
- char prepared_directory[CLI_BUF_1K] = {0};
- char candidate_error[CLI_BUF_512] = {0};
- bool pair_prepared = cli_windows_prepare_update_pair(&pair, payload_sha, prepared_launcher,
- prepared_payload, prepared_directory);
- cbm_windows_release_descriptor_v1_t descriptor;
- memset(&descriptor, 0, sizeof(descriptor));
- bool descriptor_ready =
- pair_prepared &&
- cbm_windows_release_descriptor_probe(prepared_launcher, &descriptor, candidate_error,
- sizeof(candidate_error)) &&
- descriptor.payload_size == (uint64_t)pair.payload_len &&
- strcmp(descriptor.payload_sha256, payload_sha) == 0;
- cbm_windows_transition_plan_t transition_plan =
- descriptor_ready ? cbm_windows_transition_plan(&current, &descriptor)
- : CBM_WINDOWS_TRANSITION_INCOMPATIBLE;
- bool candidate_supported =
- descriptor_ready && transition_plan != CBM_WINDOWS_TRANSITION_INCOMPATIBLE &&
- cli_windows_parent_path(g_windows_launcher_context.canonical_launcher_path,
- target_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP) &&
- cbm_windows_launcher_capability_probe(target_directory, prepared_launcher, candidate_error,
- sizeof(candidate_error));
- if (pair_prepared) {
- cli_windows_cleanup_install_pair(prepared_launcher, prepared_payload, prepared_directory);
- }
- if (!candidate_supported) {
- cbm_windows_release_pair_free(&pair);
- free(canonical_utf8);
- (void)fprintf(stderr,
- "error: downloaded Windows launcher candidate is not runnable, "
- "has an incompatible launcher/payload ABI descriptor, or lacks "
- "required mapped-image capability: %s. Active CBM sessions were "
- "not stopped.\n",
- candidate_error[0] ? candidate_error
- : transition_plan == CBM_WINDOWS_TRANSITION_INCOMPATIBLE
- ? "an intermediate launcher ABI bridge is required"
- : "private launcher/payload validation failed");
- return CLI_TRUE;
- }
- cbm_windows_current_v1_t next = {
- .launcher_abi_min = descriptor.payload_launcher_abi_min,
- .launcher_abi_max = descriptor.payload_launcher_abi_max,
- .payload_size = descriptor.payload_size,
- };
- (void)snprintf(next.payload_sha256, sizeof(next.payload_sha256), "%s",
- descriptor.payload_sha256);
- cli_windows_update_activation_t activation = {
- .home = home,
- .canonical_launcher_utf8 = canonical_utf8,
- .pair = pair,
- .state = next,
- .previous_state = current,
- .transition_plan = transition_plan,
- .delete_indexes = delete_indexes,
- };
- 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);
- cbm_windows_release_pair_free(&activation.pair);
- free(canonical_utf8);
- return result == CLI_OK ? CLI_OK : CLI_TRUE;
-}
-
-static 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 ||
- !cli_windows_read_current(g_windows_launcher_context.canonical_launcher_path, &current,
- &current_exists) ||
- !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(&current, CBM_WINDOWS_LAUNCHER_ABI_CURRENT) ||
- !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];
- 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(
- directory, g_windows_launcher_context.canonical_launcher_path, error, sizeof(error))) {
- (void)fprintf(stderr,
- "error: managed launcher capability probe failed before update: "
- "%s\n",
- error[0] ? error : "local fixed NTFS atomic replacement is unavailable");
- return false;
- }
- return true;
-}
-#endif
-
-#ifndef _WIN32
typedef struct {
const char *bin_dest;
const char *home;
@@ -13042,13 +10790,8 @@ static int cli_update_activate_binary(void *opaque) {
"update_transaction_finalize");
return CLI_OK;
}
-#endif
static int extract_and_install_binary(extract_install_args_t args) {
-#ifdef _WIN32
- return cli_windows_extract_and_activate_update(args.tmp_archive, args.home,
- args.delete_indexes);
-#else
const char *tmp_archive = args.tmp_archive;
const char *ext = args.ext;
const char *bin_dest = args.bin_dest;
@@ -13193,7 +10936,6 @@ static int extract_and_install_binary(extract_install_args_t args) {
(void)cli_activation_transaction_abort(&activation.binary_transaction);
}
return activation_rc == CLI_OK ? CLI_OK : CLI_TRUE;
-#endif
}
/* Build the download URL for the update command. */
@@ -13425,22 +11167,49 @@ int cbm_cmd_update(int argc, char **argv) {
}
#ifdef _WIN32
- /* Refuse portable self-update before HOME/cache discovery, the release
- * version check, network I/O, prompts, or cohort construction. In test
- * builds the activation test seam routes past both managed gates (loud)
- * so the shared update semantics stay unit-covered; release binaries
- * always enforce them. */
+ /* Windows updates run from install.ps1, not from this process.
+ *
+ * A running .exe cannot replace itself on Windows — the image lock refuses
+ * the replace — so an in-process updater needs a second, permanently
+ * resident binary to swap the first one out. That launcher stub (small,
+ * unsigned, doing nothing but verify-and-execute) is exactly the shape
+ * Defender's ML scores as a dropper, and on x64 no build variant escaped
+ * it. Handing the swap to a script that runs while we are NOT running
+ * removes the constraint and the stub together: one binary per platform,
+ * matching Linux and macOS.
+ *
+ * install.ps1 ships beside the binary and is idempotent, so re-running it
+ * IS the update. Print the exact command instead of feigning self-update. */
bool update_seam_portable = false;
#ifdef CBM_CLI_ENABLE_TEST_API
update_seam_portable = g_cli_activation_test_ops_set;
if (update_seam_portable) {
- (void)fprintf(stderr, "*** cbm test seam: portable update flow engaged; the managed "
- "Windows update gates are bypassed (test builds only) ***\n");
+ (void)fprintf(stderr, "*** cbm test seam: portable update flow engaged; the Windows "
+ "script-update handoff is bypassed (test builds only) ***\n");
}
#endif
- if (!update_seam_portable &&
- !cli_windows_require_managed_mutation(CBM_WINDOWS_LAUNCHER_ACTION_UPDATE)) {
- return CLI_TRUE;
+ if (!update_seam_portable) {
+ /* Native separators on purpose: this path is printed for the user to
+ * paste into PowerShell verbatim. */
+ char self_exe[CLI_BUF_1K] = {0};
+ DWORD self_len = GetModuleFileNameA(NULL, self_exe, (DWORD)sizeof(self_exe));
+ char *last_sep =
+ (self_len > 0 && (size_t)self_len < sizeof(self_exe)) ? strrchr(self_exe, '\\') : NULL;
+ if (last_sep) {
+ *last_sep = '\0';
+ }
+ printf("codebase-memory-mcp update (current: %s)\n\n", CBM_VERSION);
+ printf("On Windows the update runs from install.ps1: a running executable\n"
+ "cannot replace itself. Close any running sessions, then run\n\n");
+ if (last_sep) {
+ printf(" powershell -ExecutionPolicy Bypass -File \"%s\\install.ps1\"\n\n", self_exe);
+ } else {
+ printf(" powershell -ExecutionPolicy Bypass -File install.ps1\n\n");
+ }
+ printf("It downloads the latest release, verifies its checksum, and replaces\n"
+ "this binary in place. If PowerShell refuses to run the script because\n"
+ "it came from the internet, Unblock-File it first.\n");
+ return 0;
}
#endif
@@ -13450,12 +11219,6 @@ int cbm_cmd_update(int argc, char **argv) {
return CLI_TRUE;
}
-#ifdef _WIN32
- if (!update_seam_portable && !cli_windows_managed_update_preflight(!dry_run)) {
- return CLI_TRUE;
- }
-#endif
-
printf("codebase-memory-mcp update (current: %s)\n\n", CBM_VERSION);
/* Version check — skip download if already on latest (not in dry-run). */
@@ -13495,10 +11258,7 @@ int cbm_cmd_update(int argc, char **argv) {
if (dry_run) {
printf("\n(dry-run — skipping download, extraction, and binary replacement)\n");
#ifdef _WIN32
- char *dry_run_target =
- cli_windows_plain_utf8(g_windows_launcher_context.canonical_launcher_path);
- printf(" target: %s\n", dry_run_target ? dry_run_target : "(managed launcher)");
- free(dry_run_target);
+ printf(" target: %s/.local/bin/codebase-memory-mcp.exe\n", home);
#else
printf(" target: %s/.local/bin/codebase-memory-mcp\n", home);
#endif
@@ -13513,26 +11273,20 @@ int cbm_cmd_update(int argc, char **argv) {
char bin_dest_storage[CLI_BUF_1K];
const char *bin_dest = bin_dest_storage;
#ifdef _WIN32
- char *managed_target = cbm_wide_to_utf8(g_windows_launcher_context.canonical_launcher_path);
- if (!managed_target) {
- return CLI_TRUE;
- }
- bin_dest = managed_target;
+ snprintf(bin_dest_storage, sizeof(bin_dest_storage), "%s/.local/bin/codebase-memory-mcp.exe",
+ home);
#else
snprintf(bin_dest_storage, sizeof(bin_dest_storage), "%s/.local/bin/codebase-memory-mcp", home);
+#endif
char bin_dir[CLI_BUF_1K];
snprintf(bin_dir, sizeof(bin_dir), "%s/.local/bin", home);
if (!cbm_mkdir_p(bin_dir, CLI_OCTAL_PERM)) {
(void)fprintf(stderr, "error: cannot prepare update directory %s\n", bin_dir);
return CLI_TRUE;
}
-#endif
int rc = download_verify_install(url, ext, os, arch, want_ui, bin_dest, home, delete_indexes);
if (rc != 0) {
-#ifdef _WIN32
- free(managed_target);
-#endif
return CLI_TRUE;
}
@@ -13549,9 +11303,6 @@ int cbm_cmd_update(int argc, char **argv) {
printf("\nUpdate complete. Please restart your coding-agent sessions to "
"properly take this into account.\n");
(void)variant;
-#ifdef _WIN32
- free(managed_target);
-#endif
return 0;
}
diff --git a/src/cli/cli.h b/src/cli/cli.h
index 73069166e..32404bf1c 100644
--- a/src/cli/cli.h
+++ b/src/cli/cli.h
@@ -348,19 +348,6 @@ unsigned char *cbm_extract_binary_from_targz(const unsigned char *data, int data
* Returns NULL on error. Caller must free. */
unsigned char *cbm_extract_binary_from_zip(const unsigned char *data, int data_len, int *out_len);
-/* Strict two-file Windows release bundle extraction. The archive must contain
- * exactly one root launcher and one root payload; ambiguous aliases,
- * traversal, duplicates, and malformed central/local metadata fail closed. */
-typedef struct {
- unsigned char *launcher;
- int launcher_len;
- unsigned char *payload;
- int payload_len;
-} cbm_windows_release_pair_t;
-bool cbm_extract_windows_release_pair_from_zip(const unsigned char *data, int data_len,
- cbm_windows_release_pair_t *pair_out);
-void cbm_windows_release_pair_free(cbm_windows_release_pair_t *pair);
-
/* ── Index management ─────────────────────────────────────────── */
/* List .db files in the cache directory (~/.cache/codebase-memory-mcp/).
@@ -447,14 +434,6 @@ void cbm_cli_set_activation_ops_for_test(const cbm_cli_activation_ops_t *ops);
* command-line or environment override. */
void cbm_cli_set_activation_runtime_parent_for_test(const char *runtime_parent);
-/* Consume and authenticate any inherited permanent-launcher context before
- * process-role classification. An absent context is the normal portable
- * payload case; an advertised but invalid context fails closed. */
-int cbm_cli_windows_launcher_startup_authenticate(int argc, char *const argv[]);
-/* Internal release-pair probe. Returns -1 when argv does not select the role,
- * otherwise a process exit code. It runs before cache/daemon initialization. */
-int cbm_cli_windows_payload_descriptor_role(int argc, char *const argv[]);
-
/* ── Subcommands (wired from main.c) ─────────────────────────── */
/* install: copy binary, install skills, install editor MCP configs, ensure PATH.
diff --git a/src/cli/windows_launcher_state.c b/src/cli/windows_launcher_state.c
deleted file mode 100644
index 2219866b3..000000000
--- a/src/cli/windows_launcher_state.c
+++ /dev/null
@@ -1,3295 +0,0 @@
-#include "cli/windows_launcher_state.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-static const uint8_t current_v1_magic[8] = {
- 'C', 'B', 'M', 'C', 'U', 'R', '1', '\0',
-};
-
-static const uint8_t release_descriptor_v1_magic[8] = {
- 'C', 'B', 'M', 'W', 'R', 'D', '1', '\0',
-};
-
-static uint32_t read_u32_le(const uint8_t *input) {
- return (uint32_t)input[0] | ((uint32_t)input[1] << 8U) | ((uint32_t)input[2] << 16U) |
- ((uint32_t)input[3] << 24U);
-}
-
-static uint64_t read_u64_le(const uint8_t *input) {
- uint64_t value = 0;
- for (unsigned int index = 0; index < 8U; index++) {
- value |= (uint64_t)input[index] << (index * 8U);
- }
- return value;
-}
-
-static void write_u32_le(uint8_t *output, uint32_t value) {
- for (unsigned int index = 0; index < 4U; index++) {
- output[index] = (uint8_t)(value >> (index * 8U));
- }
-}
-
-static void write_u64_le(uint8_t *output, uint64_t value) {
- for (unsigned int index = 0; index < 8U; index++) {
- output[index] = (uint8_t)(value >> (index * 8U));
- }
-}
-
-static bool lowercase_sha256_valid(const char *digest) {
- if (!digest) {
- return false;
- }
- for (size_t index = 0; index < 64U; index++) {
- char value = digest[index];
- if (!((value >= '0' && value <= '9') || (value >= 'a' && value <= 'f'))) {
- return false;
- }
- }
- return digest[64] == '\0';
-}
-
-static bool current_v1_state_valid(const cbm_windows_current_v1_t *state) {
- return state && state->launcher_abi_min > 0U &&
- state->launcher_abi_min <= state->launcher_abi_max && state->payload_size > 0U &&
- lowercase_sha256_valid(state->payload_sha256);
-}
-
-static bool release_descriptor_v1_valid(const cbm_windows_release_descriptor_v1_t *descriptor) {
- return descriptor && descriptor->launcher_abi > 0U &&
- descriptor->payload_launcher_abi_min > 0U &&
- descriptor->payload_launcher_abi_min <= descriptor->payload_launcher_abi_max &&
- descriptor->launcher_abi >= descriptor->payload_launcher_abi_min &&
- descriptor->launcher_abi <= descriptor->payload_launcher_abi_max &&
- descriptor->payload_size > 0U && lowercase_sha256_valid(descriptor->payload_sha256);
-}
-
-bool cbm_windows_current_v1_encode(const cbm_windows_current_v1_t *state,
- uint8_t out[CBM_WINDOWS_CURRENT_V1_SIZE]) {
- if (!current_v1_state_valid(state) || !out) {
- return false;
- }
- memset(out, 0, CBM_WINDOWS_CURRENT_V1_SIZE);
- memcpy(out, current_v1_magic, sizeof(current_v1_magic));
- write_u32_le(out + 8U, 1U);
- write_u32_le(out + 12U, CBM_WINDOWS_CURRENT_V1_SIZE);
- write_u32_le(out + 16U, state->launcher_abi_min);
- write_u32_le(out + 20U, state->launcher_abi_max);
- write_u64_le(out + 24U, state->payload_size);
- memcpy(out + 32U, state->payload_sha256, 64U);
- return true;
-}
-
-bool cbm_windows_current_v1_decode(const uint8_t *record, size_t record_size,
- cbm_windows_current_v1_t *state_out) {
- if (state_out) {
- memset(state_out, 0, sizeof(*state_out));
- }
- if (!record || !state_out || record_size != CBM_WINDOWS_CURRENT_V1_SIZE ||
- memcmp(record, current_v1_magic, sizeof(current_v1_magic)) != 0 ||
- read_u32_le(record + 8U) != 1U ||
- read_u32_le(record + 12U) != CBM_WINDOWS_CURRENT_V1_SIZE) {
- return false;
- }
- for (size_t index = 96U; index < CBM_WINDOWS_CURRENT_V1_SIZE; index++) {
- if (record[index] != 0U) {
- return false;
- }
- }
- cbm_windows_current_v1_t decoded;
- memset(&decoded, 0, sizeof(decoded));
- decoded.launcher_abi_min = read_u32_le(record + 16U);
- decoded.launcher_abi_max = read_u32_le(record + 20U);
- decoded.payload_size = read_u64_le(record + 24U);
- memcpy(decoded.payload_sha256, record + 32U, 64U);
- decoded.payload_sha256[64] = '\0';
- if (!current_v1_state_valid(&decoded)) {
- return false;
- }
- *state_out = decoded;
- return true;
-}
-
-bool cbm_windows_current_v1_supports_launcher_abi(const cbm_windows_current_v1_t *state,
- uint32_t launcher_abi) {
- return current_v1_state_valid(state) && launcher_abi > 0U &&
- launcher_abi >= state->launcher_abi_min && launcher_abi <= state->launcher_abi_max;
-}
-
-bool cbm_windows_release_descriptor_v1_encode(const cbm_windows_release_descriptor_v1_t *descriptor,
- uint8_t out[CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE]) {
- if (!release_descriptor_v1_valid(descriptor) || !out) {
- return false;
- }
- memset(out, 0, CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE);
- memcpy(out, release_descriptor_v1_magic, sizeof(release_descriptor_v1_magic));
- write_u32_le(out + 8U, 1U);
- write_u32_le(out + 12U, CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE);
- write_u32_le(out + 16U, descriptor->launcher_abi);
- write_u32_le(out + 20U, descriptor->payload_launcher_abi_min);
- write_u32_le(out + 24U, descriptor->payload_launcher_abi_max);
- write_u32_le(out + 28U, 0U);
- write_u64_le(out + 32U, descriptor->payload_size);
- memcpy(out + 40U, descriptor->payload_sha256, 64U);
- return true;
-}
-
-bool cbm_windows_release_descriptor_v1_decode(const uint8_t *record, size_t record_size,
- cbm_windows_release_descriptor_v1_t *descriptor_out) {
- if (descriptor_out) {
- memset(descriptor_out, 0, sizeof(*descriptor_out));
- }
- if (!record || !descriptor_out || record_size != CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE ||
- memcmp(record, release_descriptor_v1_magic, sizeof(release_descriptor_v1_magic)) != 0 ||
- read_u32_le(record + 8U) != 1U ||
- read_u32_le(record + 12U) != CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE ||
- read_u32_le(record + 28U) != 0U) {
- return false;
- }
- for (size_t index = 104U; index < CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE; index++) {
- if (record[index] != 0U) {
- return false;
- }
- }
- cbm_windows_release_descriptor_v1_t decoded;
- memset(&decoded, 0, sizeof(decoded));
- decoded.launcher_abi = read_u32_le(record + 16U);
- decoded.payload_launcher_abi_min = read_u32_le(record + 20U);
- decoded.payload_launcher_abi_max = read_u32_le(record + 24U);
- decoded.payload_size = read_u64_le(record + 32U);
- memcpy(decoded.payload_sha256, record + 40U, 64U);
- decoded.payload_sha256[64] = '\0';
- if (!release_descriptor_v1_valid(&decoded)) {
- return false;
- }
- *descriptor_out = decoded;
- return true;
-}
-
-cbm_windows_transition_plan_t cbm_windows_transition_plan(
- const cbm_windows_current_v1_t *current, const cbm_windows_release_descriptor_v1_t *candidate) {
- if (!current_v1_state_valid(current) || !release_descriptor_v1_valid(candidate)) {
- return CBM_WINDOWS_TRANSITION_INCOMPATIBLE;
- }
- if (cbm_windows_current_v1_supports_launcher_abi(current, candidate->launcher_abi)) {
- return CBM_WINDOWS_TRANSITION_LAUNCHER_FIRST;
- }
- if (candidate->payload_launcher_abi_min <= current->launcher_abi_min &&
- candidate->payload_launcher_abi_max >= current->launcher_abi_max) {
- return CBM_WINDOWS_TRANSITION_CURRENT_FIRST;
- }
- return CBM_WINDOWS_TRANSITION_INCOMPATIBLE;
-}
-
-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) || !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'\\');
- 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; /* Preserve C:\ rather than producing C:.cbm. */
- }
- static const wchar_t middle[] = L".cbm\\generations\\";
- size_t middle_length = sizeof(middle) / sizeof(middle[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 + 1U + leaf_length + 1U;
- if (needed > path_capacity) {
- return false;
- }
- size_t offset = 0U;
- memcpy(path_out + offset, canonical_launcher_path, directory_length * sizeof(*path_out));
- offset += directory_length;
- if (!root) {
- path_out[offset++] = L'\\';
- } else {
- path_out[2] = L'\\';
- }
- memcpy(path_out + offset, middle, middle_length * sizeof(*path_out));
- offset += middle_length;
- 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;
-}
-
-static bool argument_is(const char *argument, const char *expected) {
- return argument && expected && strcmp(argument, expected) == 0;
-}
-
-cbm_windows_launcher_action_t cbm_windows_launcher_classify_action(int argc,
- const char *const argv[]) {
- if (argc <= 1 || !argv) {
- return CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY;
- }
- for (int index = 1; index < argc; index++) {
- const char *argument = argv[index];
- if (argument_is(argument, "cli") || argument_is(argument, "hook-augment") ||
- argument_is(argument, "config") || argument_is(argument, "install") ||
- argument_is(argument, "--help") || argument_is(argument, "-h") ||
- argument_is(argument, "--version")) {
- return CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY;
- }
- if (argument_is(argument, "update")) {
- return CBM_WINDOWS_LAUNCHER_ACTION_UPDATE;
- }
- if (argument_is(argument, "uninstall")) {
- return CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL;
- }
- }
- return CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY;
-}
-
-bool cbm_windows_launcher_action_allowed(cbm_windows_launcher_action_t action, bool managed) {
- switch (action) {
- case CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY:
- return true;
- case CBM_WINDOWS_LAUNCHER_ACTION_UPDATE:
- case CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL:
- return managed;
- default:
- return false;
- }
-}
-
-static void launcher_error(char *error, size_t error_size, const char *message) {
- if (error && error_size > 0U) {
- (void)snprintf(error, error_size, "%s", message ? message : "error");
- }
-}
-
-#ifndef _WIN32
-
-bool cbm_windows_launcher_context_consume(cbm_windows_launcher_context_t *context_out, char *error,
- size_t error_size) {
- if (context_out) {
- memset(context_out, 0, sizeof(*context_out));
- }
- if (!context_out) {
- launcher_error(error, error_size, "invalid launcher context output");
- return false;
- }
- if (error && error_size > 0U) {
- error[0] = '\0';
- }
- return true;
-}
-
-bool cbm_windows_launcher_context_complete(cbm_windows_launcher_context_t *context, bool accepted,
- char *error, size_t error_size) {
- (void)accepted;
- if (error && error_size > 0U)
- error[0] = '\0';
- if (!context || context->_authority_handle != 0U) {
- launcher_error(error, error_size, "invalid launcher context completion");
- return false;
- }
- return true;
-}
-
-bool cbm_windows_launcher_capability_probe(const wchar_t *target_directory,
- const wchar_t *launcher_candidate, char *error,
- size_t error_size) {
- (void)target_directory;
- (void)launcher_candidate;
- launcher_error(error, error_size, "Windows launcher support is unavailable");
- return false;
-}
-
-bool cbm_windows_launcher_file_secure(const wchar_t *launcher_path, char *error,
- size_t error_size) {
- (void)launcher_path;
- launcher_error(error, error_size, "Windows launcher support is unavailable");
- 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) {
- (void)launcher_candidate;
- if (descriptor_out) {
- memset(descriptor_out, 0, sizeof(*descriptor_out));
- }
- launcher_error(error, error_size, "Windows launcher support is unavailable");
- return false;
-}
-
-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) {
- (void)canonical_launcher_path;
- (void)state;
- launcher_error(error, error_size, "Windows launcher support is unavailable");
- return false;
-}
-
-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)backing_path;
- launcher_error(error, error_size, "Windows launcher support is unavailable");
- return false;
-}
-
-bool cbm_windows_launcher_remove_posix(const wchar_t *target_path, char *error, size_t error_size) {
- (void)target_path;
- launcher_error(error, error_size, "Windows launcher support is unavailable");
- 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,
- size_t error_size) {
- (void)canonical_launcher_path;
- (void)payload_sha256;
- (void)created_by_activation;
- launcher_error(error, error_size, "Windows launcher support is unavailable");
- return false;
-}
-
-bool cbm_windows_generations_prune(const wchar_t *canonical_launcher_path, size_t *removed_out,
- char *error, size_t error_size) {
- (void)canonical_launcher_path;
- if (removed_out) {
- *removed_out = 0U;
- }
- launcher_error(error, error_size, "Windows launcher support is unavailable");
- return false;
-}
-
-#else
-
-/* The Windows implementation follows below. Keep the byte codec above free
- * of platform conditionals so all hosts continuously test the release ABI. */
-
-#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0A00
-#endif
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <aclapi.h>
-#include <sddl.h>
-
-#ifndef PROC_THREAD_ATTRIBUTE_JOB_LIST
-#define PROC_THREAD_ATTRIBUTE_JOB_LIST ((DWORD_PTR)0x0002000dU)
-#endif
-
-#define CBM_LAUNCH_CONTEXT_ENV L"CBM_WINDOWS_LAUNCH_CONTEXT_HANDLE_V1"
-#define CBM_LAUNCH_CONTEXT_HEADER_SIZE 128U
-#define CBM_LAUNCH_CONTEXT_FLAG_MANAGED 0x00000001U
-#define CBM_LAUNCH_CONTEXT_FLAG_PRIVATE 0x00000002U
-
-static const uint8_t launch_context_magic[8] = {
- 'C', 'B', 'M', 'L', 'C', 'T', '1', '\0',
-};
-
-/* The launcher source writes this exact explicit byte layout. */
-static bool launch_context_header_decode(const uint8_t input[CBM_LAUNCH_CONTEXT_HEADER_SIZE],
- uint32_t *flags_out,
- cbm_windows_launcher_action_t *action_out,
- DWORD *server_pid_out, FILETIME *creation_out,
- uint64_t *payload_size_out, char digest_out[65],
- uint32_t *path_chars_out) {
- if (memcmp(input, launch_context_magic, sizeof(launch_context_magic)) != 0 ||
- read_u32_le(input + 8U) != 1U ||
- read_u32_le(input + 12U) != CBM_LAUNCH_CONTEXT_HEADER_SIZE) {
- return false;
- }
- uint32_t flags = read_u32_le(input + 16U);
- uint32_t action = read_u32_le(input + 20U);
- uint32_t server_pid = read_u32_le(input + 24U);
- uint32_t path_chars = read_u32_le(input + 28U);
- uint64_t creation = read_u64_le(input + 32U);
- uint64_t payload_size = read_u64_le(input + 40U);
- char digest[65];
- memcpy(digest, input + 48U, 64U);
- digest[64] = '\0';
- for (size_t index = 112U; index < CBM_LAUNCH_CONTEXT_HEADER_SIZE; index++) {
- if (input[index] != 0U) {
- return false;
- }
- }
- bool managed = (flags & CBM_LAUNCH_CONTEXT_FLAG_MANAGED) != 0U;
- bool digest_zero = true;
- for (size_t index = 0U; index < 64U; index++) {
- if (input[48U + index] != 0U) {
- digest_zero = false;
- }
- }
- if ((flags & ~(CBM_LAUNCH_CONTEXT_FLAG_MANAGED | CBM_LAUNCH_CONTEXT_FLAG_PRIVATE)) != 0U ||
- (!managed && (flags & CBM_LAUNCH_CONTEXT_FLAG_PRIVATE) != 0U) ||
- action > (uint32_t)CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL || server_pid == 0U ||
- path_chars < 4U || path_chars >= CBM_WINDOWS_LAUNCHER_PATH_CAP || creation == 0U ||
- (managed && (payload_size == 0U || !lowercase_sha256_valid(digest))) ||
- (!managed && (payload_size != 0U || !digest_zero))) {
- return false;
- }
- *flags_out = flags;
- *action_out = (cbm_windows_launcher_action_t)action;
- *server_pid_out = server_pid;
- creation_out->dwLowDateTime = (DWORD)creation;
- creation_out->dwHighDateTime = (DWORD)(creation >> 32U);
- *payload_size_out = payload_size;
- memcpy(digest_out, digest, sizeof(digest));
- *path_chars_out = path_chars;
- return true;
-}
-
-static bool windows_read_exact(HANDLE file, void *buffer, size_t size) {
- size_t offset = 0U;
- while (offset < size) {
- DWORD chunk = size - offset > (size_t)MAXDWORD ? MAXDWORD : (DWORD)(size - offset);
- DWORD amount = 0U;
- if (!ReadFile(file, (uint8_t *)buffer + offset, chunk, &amount, NULL) || amount == 0U) {
- return false;
- }
- offset += amount;
- }
- return true;
-}
-
-static bool windows_pipe_wait_available(HANDLE pipe, size_t needed, uint64_t deadline) {
- if (needed > (size_t)MAXDWORD)
- return false;
- while (GetTickCount64() < deadline) {
- DWORD available = 0U;
- if (!PeekNamedPipe(pipe, NULL, 0U, NULL, &available, NULL)) {
- return false;
- }
- if ((size_t)available >= needed)
- return true;
- Sleep(2U);
- }
- return false;
-}
-
-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;
-}
-
-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,
- const BY_HANDLE_FILE_INFORMATION *second) {
- return first->dwVolumeSerialNumber == second->dwVolumeSerialNumber &&
- first->nFileIndexHigh == second->nFileIndexHigh &&
- first->nFileIndexLow == second->nFileIndexLow;
-}
-
-static uint32_t windows_sid_read_u32_le(const uint8_t *bytes) {
- return (uint32_t)bytes[0] | ((uint32_t)bytes[1] << 8U) | ((uint32_t)bytes[2] << 16U) |
- ((uint32_t)bytes[3] << 24U);
-}
-
-static bool windows_sid_is_trusted_installer(PSID sid) {
- static const uint32_t subauthorities[] = {
- 80U, 956008885U, 3418522649U, 1831038044U, 1853292631U, 2271478464U,
- };
- if (!sid || !IsValidSid(sid)) {
- return false;
- }
- DWORD sid_length = GetLengthSid(sid);
- const uint8_t *bytes = (const uint8_t *)sid;
- if (sid_length != 32U || bytes[0] != 1U || bytes[1] != 6U || bytes[2] != 0U || bytes[3] != 0U ||
- bytes[4] != 0U || bytes[5] != 0U || bytes[6] != 0U || bytes[7] != 5U) {
- return false;
- }
- for (size_t index = 0U; index < sizeof(subauthorities) / sizeof(subauthorities[0]); index++) {
- if (windows_sid_read_u32_le(bytes + 8U + index * 4U) != subauthorities[index]) {
- return false;
- }
- }
- return true;
-}
-
-static bool windows_sid_is_trusted(PSID sid, PSID current_user) {
- return sid && current_user && IsValidSid(sid) &&
- (EqualSid(sid, current_user) || IsWellKnownSid(sid, WinLocalSystemSid) ||
- IsWellKnownSid(sid, WinBuiltinAdministratorsSid) ||
- windows_sid_is_trusted_installer(sid));
-}
-
-static bool windows_bounded_ace_sid_is_trusted(const ACE_HEADER *header, PSID current_user) {
- size_t sid_offset = offsetof(ACCESS_ALLOWED_ACE, SidStart);
- if (!header || (size_t)header->AceSize < sid_offset + 8U) {
- return false;
- }
- const ACCESS_ALLOWED_ACE *ace = (const ACCESS_ALLOWED_ACE *)header;
- const uint8_t *sid = (const uint8_t *)&ace->SidStart;
- size_t sid_capacity = (size_t)header->AceSize - sid_offset;
- if (sid[0] != 1U || sid[1] > 15U) {
- return false;
- }
- size_t sid_length = 8U + (size_t)sid[1] * 4U;
- return sid_length <= sid_capacity && IsValidSid((PSID)sid) &&
- GetLengthSid((PSID)sid) == (DWORD)sid_length &&
- (windows_sid_is_trusted((PSID)sid, current_user) ||
- (((header->AceFlags & INHERIT_ONLY_ACE) != 0U) &&
- 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) {
- HANDLE token = NULL;
- DWORD token_size = 0U;
- PTOKEN_USER user = NULL;
- PSID owner = NULL;
- PSECURITY_DESCRIPTOR descriptor = NULL;
- bool ok = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) != 0;
- if (ok) {
- (void)GetTokenInformation(token, TokenUser, NULL, 0U, &token_size);
- user = token_size ? (PTOKEN_USER)malloc(token_size) : NULL;
- ok = user && GetTokenInformation(token, TokenUser, user, token_size, &token_size) != 0;
- }
- if (ok) {
- ok = GetSecurityInfo(file, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &owner, NULL, NULL,
- NULL, &descriptor) == ERROR_SUCCESS &&
- owner && IsValidSid(owner) &&
- (require_current_user ? EqualSid(owner, user->User.Sid) != 0
- : windows_sid_is_trusted(owner, user->User.Sid));
- }
- if (descriptor) {
- (void)LocalFree(descriptor);
- }
- free(user);
- if (token) {
- (void)CloseHandle(token);
- }
- return ok;
-}
-
-static bool windows_owner_is_current(HANDLE file) {
- return windows_owner_secure(file, true);
-}
-
-static DWORD windows_private_mutation_rights(void) {
- return GENERIC_ALL | GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_ADD_FILE |
- FILE_ADD_SUBDIRECTORY | FILE_DELETE_CHILD | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES |
- DELETE | WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
-}
-
-static bool windows_acl_secure_for_mutation(HANDLE file, DWORD mutation) {
- HANDLE token = NULL;
- DWORD token_size = 0U;
- PTOKEN_USER user = NULL;
- PACL dacl = NULL;
- PSECURITY_DESCRIPTOR descriptor = NULL;
- bool secure = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) != 0;
- if (secure) {
- (void)GetTokenInformation(token, TokenUser, NULL, 0U, &token_size);
- user = token_size ? (PTOKEN_USER)malloc(token_size) : NULL;
- secure = user && GetTokenInformation(token, TokenUser, user, token_size, &token_size) != 0;
- }
- DWORD status = secure ? GetSecurityInfo(file, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
- NULL, &dacl, NULL, &descriptor)
- : ERROR_ACCESS_DENIED;
- ACL_SIZE_INFORMATION information;
- memset(&information, 0, sizeof(information));
- secure = secure && status == ERROR_SUCCESS && descriptor && dacl && IsValidAcl(dacl) != 0 &&
- GetAclInformation(dacl, &information, sizeof(information), AclSizeInformation) != 0;
- enum {
- CBM_ACE_ALLOW = 0x00,
- CBM_ACE_DENY = 0x01,
- CBM_ACE_DENY_OBJECT = 0x06,
- CBM_ACE_DENY_CALLBACK = 0x0a,
- CBM_ACE_DENY_CALLBACK_OBJECT = 0x0c,
- };
- for (DWORD index = 0U; secure && index < information.AceCount; index++) {
- void *opaque = NULL;
- if (!GetAce(dacl, index, &opaque) || !opaque) {
- secure = false;
- break;
- }
- ACE_HEADER *header = opaque;
- if (header->AceType == CBM_ACE_DENY || header->AceType == CBM_ACE_DENY_OBJECT ||
- header->AceType == CBM_ACE_DENY_CALLBACK ||
- header->AceType == CBM_ACE_DENY_CALLBACK_OBJECT) {
- continue;
- }
- if (header->AceType != CBM_ACE_ALLOW ||
- (size_t)header->AceSize <
- offsetof(ACCESS_ALLOWED_ACE, SidStart) + offsetof(SID, SubAuthority)) {
- secure = false;
- break;
- }
- ACCESS_ALLOWED_ACE *ace = opaque;
- if ((ace->Mask & mutation) == 0U) {
- continue;
- }
- if (!windows_bounded_ace_sid_is_trusted(header, user->User.Sid)) {
- secure = false;
- }
- }
- if (descriptor)
- (void)LocalFree(descriptor);
- free(user);
- if (token)
- (void)CloseHandle(token);
- return secure;
-}
-
-static bool windows_acl_secure(HANDLE file) {
- return windows_acl_secure_for_mutation(file, windows_private_mutation_rights());
-}
-
-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;
- }
- /* 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;
- }
- wmemcpy(path, L"\\\\?\\", 4);
- memcpy(path + 4, file_path, (length + 1U) * sizeof(*path));
- for (size_t index = 0U; index < length; index++) {
- if (path[4U + index] == L'/')
- path[4U + index] = L'\\';
- }
- 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 + 4);
- bool valid = true;
- for (size_t index = 3U; valid && index <= directory_length; index++) {
- if (index < directory_length && path[4U + index] != L'\\')
- continue;
- 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,
- FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
- BY_HANDLE_FILE_INFORMATION information;
- DWORD mutation = windows_private_mutation_rights();
- if (index < directory_length) {
- /* Default C:\\Users ACLs allow sibling-directory creation. That
- * cannot replace the existing next component. The executable's
- * immediate parent remains fully private. */
- mutation &= ~((DWORD)FILE_ADD_SUBDIRECTORY);
- }
- 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[4U + index] = saved;
- }
- free(path);
- return valid;
-}
-
-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_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);
- }
- return INVALID_HANDLE_VALUE;
- }
- return file;
-}
-
-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, 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;
- bool valid = directory != INVALID_HANDLE_VALUE && GetFileType(directory) == FILE_TYPE_DISK &&
- GetFileInformationByHandle(directory, &information) != 0 &&
- (information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&
- (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&
- windows_owner_is_current(directory) && windows_acl_secure(directory);
- if (!valid) {
- if (directory != INVALID_HANDLE_VALUE)
- (void)CloseHandle(directory);
- return INVALID_HANDLE_VALUE;
- }
- 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;
- FILETIME user_time;
- return GetProcessTimes(process, creation_out, &exit_time, &kernel_time, &user_time) != 0;
-}
-
-static bool windows_filetime_equal(const FILETIME *first, const FILETIME *second) {
- return first->dwLowDateTime == second->dwLowDateTime &&
- first->dwHighDateTime == second->dwHighDateTime;
-}
-
-bool cbm_windows_launcher_context_consume(cbm_windows_launcher_context_t *context_out, char *error,
- size_t error_size) {
- if (context_out) {
- memset(context_out, 0, sizeof(*context_out));
- }
- if (error && error_size > 0U) {
- error[0] = '\0';
- }
- if (!context_out) {
- launcher_error(error, error_size, "invalid launcher context output");
- return false;
- }
- wchar_t encoded[32];
- DWORD length = GetEnvironmentVariableW(CBM_LAUNCH_CONTEXT_ENV, encoded,
- (DWORD)(sizeof(encoded) / sizeof(encoded[0])));
- if (length == 0U && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
- return true;
- }
- /* Scrub before validation: malformed authority must never reach a child. */
- (void)SetEnvironmentVariableW(CBM_LAUNCH_CONTEXT_ENV, NULL);
- if (length == 0U || length >= sizeof(encoded) / sizeof(encoded[0])) {
- launcher_error(error, error_size, "invalid inherited launcher context handle");
- return false;
- }
- wchar_t *end = NULL;
- unsigned long long raw = wcstoull(encoded, &end, 16);
- if (!end || *end != L'\0' || raw == 0ULL || raw > (unsigned long long)(uintptr_t)UINTPTR_MAX) {
- launcher_error(error, error_size, "invalid inherited launcher context handle");
- return false;
- }
- HANDLE pipe = (HANDLE)(uintptr_t)raw;
- uint8_t header[CBM_LAUNCH_CONTEXT_HEADER_SIZE];
- uint32_t flags = 0U;
- cbm_windows_launcher_action_t action = CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY;
- DWORD claimed_pid = 0U;
- FILETIME claimed_creation;
- uint64_t payload_size = 0U;
- char digest[65];
- uint32_t path_chars = 0U;
- ULONG actual_pid = 0U;
- uint64_t context_now = GetTickCount64();
- uint64_t context_deadline = UINT64_MAX - context_now < 5000U ? UINT64_MAX : context_now + 5000U;
- bool valid =
- GetFileType(pipe) == FILE_TYPE_PIPE &&
- GetNamedPipeServerProcessId(pipe, &actual_pid) != 0 &&
- windows_pipe_wait_available(pipe, sizeof(header), context_deadline) &&
- windows_read_exact(pipe, header, sizeof(header)) &&
- launch_context_header_decode(header, &flags, &action, &claimed_pid, &claimed_creation,
- &payload_size, digest, &path_chars) &&
- actual_pid == claimed_pid;
- wchar_t claimed_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- memset(claimed_path, 0, sizeof(claimed_path));
- valid = valid &&
- windows_pipe_wait_available(pipe, (size_t)path_chars * sizeof(*claimed_path),
- context_deadline) &&
- windows_read_exact(pipe, claimed_path, (size_t)path_chars * sizeof(*claimed_path)) &&
- claimed_path[path_chars - 1U] == L'\0' &&
- wmemchr(claimed_path, L'\0', path_chars) == claimed_path + path_chars - 1U;
- DWORD trailing_count = 0U;
- valid = valid && PeekNamedPipe(pipe, NULL, 0U, NULL, &trailing_count, NULL) != 0 &&
- trailing_count == 0U;
-
- HANDLE server =
- valid ? OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, actual_pid) : NULL;
- FILETIME actual_creation;
- wchar_t actual_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- DWORD actual_path_length = CBM_WINDOWS_LAUNCHER_PATH_CAP;
- valid = valid && server && windows_process_creation(server, &actual_creation) &&
- windows_filetime_equal(&actual_creation, &claimed_creation) &&
- QueryFullProcessImageNameW(server, 0U, actual_path, &actual_path_length) != 0;
- if (server) {
- (void)CloseHandle(server);
- }
- 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;
- 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);
- }
- if (claimed_file != INVALID_HANDLE_VALUE) {
- (void)CloseHandle(claimed_file);
- }
- if (!valid) {
- (void)CloseHandle(pipe);
- launcher_error(error, error_size, context_error);
- memset(context_out, 0, sizeof(*context_out));
- return false;
- }
- context_out->present = true;
- context_out->managed = (flags & CBM_LAUNCH_CONTEXT_FLAG_MANAGED) != 0U;
- context_out->private_activation = (flags & CBM_LAUNCH_CONTEXT_FLAG_PRIVATE) != 0U;
- context_out->action = action;
- context_out->payload_size = payload_size;
- memcpy(context_out->expected_payload_sha256, digest, sizeof(digest));
- memcpy(context_out->canonical_launcher_path, claimed_path,
- (size_t)path_chars * sizeof(*claimed_path));
- context_out->_authority_handle = (uintptr_t)pipe;
- return true;
-}
-
-static bool windows_pipe_read_byte_until(HANDLE pipe, uint8_t *value_out, uint64_t deadline) {
- while (GetTickCount64() < deadline) {
- DWORD available = 0U;
- if (!PeekNamedPipe(pipe, NULL, 0U, NULL, &available, NULL)) {
- return false;
- }
- if (available > 0U) {
- DWORD received = 0U;
- return ReadFile(pipe, value_out, 1U, &received, NULL) != 0 && received == 1U;
- }
- Sleep(2U);
- }
- return false;
-}
-
-bool cbm_windows_launcher_context_complete(cbm_windows_launcher_context_t *context, bool accepted,
- char *error, size_t error_size) {
- if (error && error_size > 0U)
- error[0] = '\0';
- if (!context) {
- launcher_error(error, error_size, "invalid launcher context completion");
- return false;
- }
- if (!context->present) {
- return context->_authority_handle == 0U;
- }
- HANDLE pipe = (HANDLE)context->_authority_handle;
- context->_authority_handle = 0U;
- if (!pipe || pipe == INVALID_HANDLE_VALUE) {
- launcher_error(error, error_size, "launcher context authority was already consumed");
- return false;
- }
- uint8_t ready = accepted ? (uint8_t)'R' : (uint8_t)'X';
- DWORD written = 0U;
- bool ok = WriteFile(pipe, &ready, 1U, &written, NULL) != 0 && written == 1U;
- if (ok && accepted) {
- uint8_t result = 0U;
- uint64_t now = GetTickCount64();
- uint64_t deadline = UINT64_MAX - now < 30000U ? UINT64_MAX : now + 30000U;
- ok = windows_pipe_read_byte_until(pipe, &result, deadline) && result == (uint8_t)'G';
- }
- (void)CloseHandle(pipe);
- if (!ok) {
- launcher_error(error, error_size,
- "launcher rejected or timed out completing payload authentication");
- }
- return ok;
-}
-
-/* Remaining native transaction/probe helpers are below the launcher-facing
- * context code to keep their private Windows structures out of the ABI. */
-
-typedef struct {
- DWORD Flags;
-} cbm_file_disposition_info_ex_t;
-
-typedef struct {
- DWORD Flags;
- HANDLE RootDirectory;
- DWORD FileNameLength;
- WCHAR FileName[1];
-} cbm_file_rename_info_ex_t;
-
-#define CBM_FILE_DISPOSITION_INFO_EX_CLASS ((FILE_INFO_BY_HANDLE_CLASS)21)
-#define CBM_FILE_RENAME_INFO_EX_CLASS ((FILE_INFO_BY_HANDLE_CLASS)22)
-#define CBM_FILE_DISPOSITION_DELETE 0x00000001U
-#define CBM_FILE_DISPOSITION_POSIX 0x00000002U
-#define CBM_FILE_RENAME_REPLACE 0x00000001U
-#define CBM_FILE_RENAME_POSIX 0x00000002U
-
-static bool windows_posix_remove_handle(HANDLE file) {
- cbm_file_disposition_info_ex_t disposition = {
- .Flags = CBM_FILE_DISPOSITION_DELETE | CBM_FILE_DISPOSITION_POSIX,
- };
- return SetFileInformationByHandle(file, CBM_FILE_DISPOSITION_INFO_EX_CLASS, &disposition,
- sizeof(disposition)) != 0;
-}
-
-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);
- /* 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_POSIX | (replace_existing ? CBM_FILE_RENAME_REPLACE : 0U);
- rename->RootDirectory = NULL;
- rename->FileNameLength = (DWORD)bytes;
- 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;
- }
- size_t length = wcslen(path);
- if (length + 1U > capacity) {
- return false;
- }
- memcpy(parent, path, (length + 1U) * sizeof(*parent));
- wchar_t *separator = wcsrchr(parent, L'\\');
- wchar_t *slash = wcsrchr(parent, L'/');
- if (!separator || (slash && slash > separator)) {
- separator = slash;
- }
- if (!separator || separator <= parent + 2) {
- return false;
- }
- *separator = L'\0';
- return true;
-}
-
-static bool windows_copy_flush_private(const wchar_t *candidate, const wchar_t *stage) {
- /* 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)
- (void)CloseHandle(source);
- return false;
- }
- (void)CloseHandle(source);
- HANDLE file =
- 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;
- /* 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);
- }
- if (!ok) {
- (void)DeleteFileW(stage);
- }
- return ok;
-}
-
-static bool windows_unique_sibling(const wchar_t *target, const wchar_t *tag, wchar_t *path,
- size_t capacity) {
- static volatile LONG counter = 0;
- LONG sequence = InterlockedIncrement(&counter);
- int written = swprintf(path, capacity, L"%ls.cbm-%ls-%lu-%ld.tmp", target, tag,
- (unsigned long)GetCurrentProcessId(), (long)sequence);
- return written > 0 && (size_t)written < capacity;
-}
-
-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 || !backing_path || !target_path[0] || !backing_path[0]) {
- launcher_error(error, error_size, "invalid launcher replacement paths");
- return false;
- }
- 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_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);
- 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 backing or existing managed target has an unsafe link layout");
- return false;
- }
- (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"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 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 committed;
-}
-
-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 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 &&
- (remove_error == ERROR_FILE_NOT_FOUND || remove_error == ERROR_PATH_NOT_FOUND)) {
- return true;
- }
- launcher_error(error, error_size, "could not securely open launcher for removal");
- return false;
- }
- (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,
- "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) {
- if (state_out)
- memset(state_out, 0, sizeof(*state_out));
- wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t state_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t current[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!canonical_launcher_path || !state_out ||
- !windows_parent_path(canonical_launcher_path, directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {
- return -1;
- }
- int state_written =
- swprintf(state_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\.cbm", directory);
- int current_written =
- swprintf(current, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\current-v1", state_directory);
- 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) {
- return -1;
- }
- HANDLE file = windows_open_regular_no_reparse(current, GENERIC_READ);
- if (file == INVALID_HANDLE_VALUE) {
- DWORD attributes = GetFileAttributesW(current);
- DWORD open_error = attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;
- return attributes == INVALID_FILE_ATTRIBUTES &&
- (open_error == ERROR_FILE_NOT_FOUND || open_error == ERROR_PATH_NOT_FOUND)
- ? 0
- : -1;
- }
- LARGE_INTEGER size;
- uint8_t record[CBM_WINDOWS_CURRENT_V1_SIZE];
- uint8_t trailing = 0U;
- DWORD trailing_count = 0U;
- bool valid = GetFileSizeEx(file, &size) != 0 && size.QuadPart == CBM_WINDOWS_CURRENT_V1_SIZE &&
- windows_read_exact(file, record, sizeof(record)) &&
- ReadFile(file, &trailing, 1U, &trailing_count, NULL) != 0 &&
- trailing_count == 0U &&
- cbm_windows_current_v1_decode(record, sizeof(record), state_out);
- (void)CloseHandle(file);
- 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, &current) != 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]) {
- wchar_t payload[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- return cbm_windows_generation_payload_path(canonical_launcher_path, payload_sha256, payload,
- CBM_WINDOWS_LAUNCHER_PATH_CAP) &&
- windows_parent_path(payload, directory_out, CBM_WINDOWS_LAUNCHER_PATH_CAP);
-}
-
-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_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;
- }
- (void)CloseHandle(launcher);
- return true;
-}
-
-static bool windows_generation_name_valid(const wchar_t *name) {
- if (!name || wcslen(name) != 64U)
- return false;
- for (size_t index = 0U; index < 64U; index++) {
- wchar_t value = name[index];
- if (!((value >= L'0' && value <= L'9') || (value >= L'a' && value <= L'f'))) {
- return false;
- }
- }
- return true;
-}
-
-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) {
- return false;
- }
- (void)CloseHandle(directory);
-
- wchar_t pattern[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- int pattern_written =
- swprintf(pattern, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\*", generation_directory);
- if (pattern_written <= 0 || (size_t)pattern_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- return false;
- }
- WIN32_FIND_DATAW entry;
- HANDLE search = FindFirstFileW(pattern, &entry);
- 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 regular = (entry.dwFileAttributes &
- (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0;
- 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;
- }
- } while (FindNextFileW(search, &entry));
- DWORD find_error = GetLastError();
- (void)FindClose(search);
- 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);
- 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);
- 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,
- const char payload_sha256[65],
- bool created_by_activation, char *error,
- size_t error_size) {
- if (error && error_size > 0U)
- error[0] = '\0';
- if (!created_by_activation)
- return true;
- if (!canonical_launcher_path || !lowercase_sha256_valid(payload_sha256)) {
- launcher_error(error, error_size, "invalid generation rollback request");
- return false;
- }
- cbm_windows_current_v1_t current;
- int current_status = windows_current_v1_read(canonical_launcher_path, &current);
- if (current_status < 0) {
- launcher_error(error, error_size, "current-v1 is unsafe during generation rollback");
- return false;
- }
- if (current_status == 1 && strcmp(current.payload_sha256, payload_sha256) == 0) {
- return true;
- }
- wchar_t generation[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- 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;
- }
- return true;
-}
-
-bool cbm_windows_generations_prune(const wchar_t *canonical_launcher_path, size_t *removed_out,
- char *error, size_t error_size) {
- if (removed_out)
- *removed_out = 0U;
- if (error && error_size > 0U)
- error[0] = '\0';
- cbm_windows_current_v1_t current;
- if (!canonical_launcher_path ||
- windows_current_v1_read(canonical_launcher_path, &current) != 1) {
- launcher_error(error, error_size, "current-v1 is unsafe during generation pruning");
- return false;
- }
- wchar_t current_generation[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t generations_root[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!windows_generation_directory_path(canonical_launcher_path, current.payload_sha256,
- current_generation) ||
- !windows_parent_path(current_generation, generations_root, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {
- 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");
- 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);
- if (pattern_written <= 0 || (size_t)pattern_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- launcher_error(error, error_size, "generation enumeration path is too long");
- return false;
- }
- WIN32_FIND_DATAW entry;
- HANDLE search = FindFirstFileW(pattern, &entry);
- if (search == INVALID_HANDLE_VALUE) {
- launcher_error(error, error_size, "generation root could not be enumerated");
- return false;
- }
- wchar_t current_name[65];
- for (size_t index = 0U; index < 64U; index++) {
- 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 {
- if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0) {
- continue;
- }
- if (_wcsicmp(entry.cFileName, current_name) == 0) {
- bool canonical_current = wcscmp(entry.cFileName, current_name) == 0 &&
- (entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&
- (entry.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0;
- if (!canonical_current)
- 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) {
- ok = false;
- continue;
- }
- 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);
- 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;
- }
- removed++;
- } while (FindNextFileW(search, &entry));
- DWORD find_error = GetLastError();
- (void)FindClose(search);
- ok = ok && find_error == ERROR_NO_MORE_FILES;
- if (removed_out)
- *removed_out = removed;
- if (!ok) {
- launcher_error(error, error_size,
- "one or more non-current generations were unsafe or could not be pruned");
- }
- return ok;
-}
-
-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) {
- if (error && error_size > 0U)
- 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_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)) {
- if (canonical != INVALID_HANDLE_VALUE)
- (void)CloseHandle(canonical);
- launcher_error(error, error_size, "invalid current-v1 write request");
- return false;
- }
- (void)CloseHandle(canonical);
- wchar_t state_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t current[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- int state_written =
- swprintf(state_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\.cbm", directory);
- int current_written =
- swprintf(current, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\current-v1", state_directory);
- 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 ||
- (!windows_create_directory_private(state_directory) &&
- GetLastError() != ERROR_ALREADY_EXISTS)) {
- launcher_error(error, error_size, "could not create launcher state directory");
- return false;
- }
- HANDLE state_handle = windows_open_directory_secure(state_directory);
- DWORD current_attributes = GetFileAttributesW(current);
- DWORD current_error =
- current_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;
- HANDLE existing = current_attributes == INVALID_FILE_ATTRIBUTES
- ? INVALID_HANDLE_VALUE
- : windows_open_regular_no_reparse(current, GENERIC_READ);
- bool current_absent =
- current_attributes == INVALID_FILE_ATTRIBUTES &&
- (current_error == ERROR_FILE_NOT_FOUND || current_error == ERROR_PATH_NOT_FOUND);
- if (state_handle == INVALID_HANDLE_VALUE ||
- (!current_absent && existing == INVALID_HANDLE_VALUE)) {
- if (state_handle != INVALID_HANDLE_VALUE)
- (void)CloseHandle(state_handle);
- if (existing != INVALID_HANDLE_VALUE)
- (void)CloseHandle(existing);
- launcher_error(error, error_size, "launcher state directory or current-v1 is unsafe");
- return false;
- }
- (void)CloseHandle(state_handle);
- if (existing != INVALID_HANDLE_VALUE)
- (void)CloseHandle(existing);
- wchar_t stage[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!windows_unique_sibling(current, L"current", stage, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {
- launcher_error(error, error_size, "current-v1 stage path is too long");
- return false;
- }
- HANDLE file = CreateFileW(
- 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;
- /* 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) &&
- windows_acl_secure(file) && windows_posix_rename_handle(file, current);
- if (file != INVALID_HANDLE_VALUE)
- (void)CloseHandle(file);
- if (!ok) {
- (void)DeleteFileW(stage);
- launcher_error(error, error_size, "atomic current-v1 publication is unsupported or failed");
- }
- return ok;
-}
-
-#define CBM_RELEASE_DESCRIPTOR_ARG L"__cbm_windows_release_descriptor_v1"
-
-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) {
- if (descriptor_out) {
- memset(descriptor_out, 0, sizeof(*descriptor_out));
- }
- if (error && error_size > 0U)
- error[0] = '\0';
- HANDLE candidate = launcher_candidate
- ? windows_open_regular_no_reparse(launcher_candidate, GENERIC_READ)
- : INVALID_HANDLE_VALUE;
- if (!descriptor_out || candidate == INVALID_HANDLE_VALUE) {
- if (candidate != INVALID_HANDLE_VALUE)
- (void)CloseHandle(candidate);
- launcher_error(error, error_size, "launcher descriptor candidate is unsafe");
- return false;
- }
- (void)CloseHandle(candidate);
-
- SECURITY_ATTRIBUTES security = {
- .nLength = sizeof(security),
- .lpSecurityDescriptor = NULL,
- .bInheritHandle = TRUE,
- };
- HANDLE read_pipe = NULL;
- HANDLE write_pipe = NULL;
- HANDLE null_input = INVALID_HANDLE_VALUE;
- HANDLE null_error = INVALID_HANDLE_VALUE;
- HANDLE job = NULL;
- PROCESS_INFORMATION child;
- memset(&child, 0, sizeof(child));
- bool ready = CreatePipe(&read_pipe, &write_pipe, &security, 4096U) != 0 &&
- SetHandleInformation(read_pipe, HANDLE_FLAG_INHERIT, 0U) != 0;
- null_input = ready ? CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
- &security, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
- : INVALID_HANDLE_VALUE;
- null_error = ready ? CreateFileW(L"NUL", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
- &security, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
- : INVALID_HANDLE_VALUE;
- JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits;
- memset(&limits, 0, sizeof(limits));
- limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
- job = ready ? CreateJobObjectW(NULL, NULL) : NULL;
- ready =
- ready && null_input != INVALID_HANDLE_VALUE && null_error != INVALID_HANDLE_VALUE && job &&
- SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, sizeof(limits)) !=
- 0;
-
- HANDLE inherited[3] = {write_pipe, null_input, null_error};
- SIZE_T attribute_size = 0U;
- (void)InitializeProcThreadAttributeList(NULL, 2U, 0U, &attribute_size);
- LPPROC_THREAD_ATTRIBUTE_LIST attributes =
- ready && attribute_size ? malloc(attribute_size) : NULL;
- bool initialized =
- attributes && InitializeProcThreadAttributeList(attributes, 2U, 0U, &attribute_size) != 0;
- ready = ready && initialized &&
- UpdateProcThreadAttribute(attributes, 0U, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited,
- sizeof(inherited), NULL, NULL) != 0 &&
- UpdateProcThreadAttribute(attributes, 0U, PROC_THREAD_ATTRIBUTE_JOB_LIST, &job,
- sizeof(job), NULL, NULL) != 0;
-
- wchar_t command[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- int command_length = launcher_candidate
- ? swprintf(command, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"\"%ls\" %ls",
- launcher_candidate, CBM_RELEASE_DESCRIPTOR_ARG)
- : -1;
- STARTUPINFOEXW startup;
- memset(&startup, 0, sizeof(startup));
- startup.StartupInfo.cb = sizeof(startup);
- startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
- startup.StartupInfo.hStdInput = null_input;
- startup.StartupInfo.hStdOutput = write_pipe;
- startup.StartupInfo.hStdError = null_error;
- startup.lpAttributeList = attributes;
- bool spawned = ready && command_length > 0 &&
- (size_t)command_length < CBM_WINDOWS_LAUNCHER_PATH_CAP &&
- CreateProcessW(launcher_candidate, command, NULL, NULL, TRUE,
- CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, NULL, NULL,
- &startup.StartupInfo, &child) != 0;
- if (initialized)
- DeleteProcThreadAttributeList(attributes);
- free(attributes);
- if (write_pipe) {
- (void)CloseHandle(write_pipe);
- write_pipe = NULL;
- }
- if (null_input != INVALID_HANDLE_VALUE) {
- (void)CloseHandle(null_input);
- null_input = INVALID_HANDLE_VALUE;
- }
- if (null_error != INVALID_HANDLE_VALUE) {
- (void)CloseHandle(null_error);
- null_error = INVALID_HANDLE_VALUE;
- }
-
- uint8_t record[CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE + 1U];
- size_t received_total = 0U;
- bool pipe_closed = false;
- uint64_t now = GetTickCount64();
- uint64_t deadline = UINT64_MAX - now < 30000U ? UINT64_MAX : now + 30000U;
- while (spawned && GetTickCount64() < deadline && !pipe_closed) {
- DWORD available = 0U;
- if (!PeekNamedPipe(read_pipe, NULL, 0U, NULL, &available, NULL)) {
- pipe_closed = GetLastError() == ERROR_BROKEN_PIPE;
- break;
- }
- if (available > 0U) {
- DWORD capacity = (DWORD)(sizeof(record) - received_total);
- DWORD request = available < capacity ? available : capacity;
- DWORD amount = 0U;
- if (request == 0U ||
- !ReadFile(read_pipe, record + received_total, request, &amount, NULL) ||
- amount == 0U) {
- break;
- }
- received_total += amount;
- if (received_total == sizeof(record)) {
- break;
- }
- continue;
- }
- Sleep(2U);
- }
- DWORD wait = spawned ? WaitForSingleObject(child.hProcess, 0U) : WAIT_FAILED;
- if (spawned && wait != WAIT_OBJECT_0) {
- (void)TerminateJobObject(job, 1U);
- (void)WaitForSingleObject(child.hProcess, 5000U);
- }
- DWORD exit_code = 1U;
- bool valid =
- spawned && pipe_closed && received_total == CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE &&
- WaitForSingleObject(child.hProcess, 0U) == WAIT_OBJECT_0 &&
- GetExitCodeProcess(child.hProcess, &exit_code) != 0 && exit_code == 0U &&
- cbm_windows_release_descriptor_v1_decode(record, CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE,
- descriptor_out);
- if (child.hThread)
- (void)CloseHandle(child.hThread);
- if (child.hProcess)
- (void)CloseHandle(child.hProcess);
- if (read_pipe)
- (void)CloseHandle(read_pipe);
- if (job)
- (void)CloseHandle(job);
- if (!valid) {
- memset(descriptor_out, 0, sizeof(*descriptor_out));
- launcher_error(error, error_size,
- "launcher release descriptor was missing, malformed, or timed out");
- }
- return valid;
-}
-
-/* Probe subprocess protocol. The standalone launcher recognizes this private
- * mode, signals ready, and remains mapped until the release event is set. */
-#define CBM_LAUNCHER_PROBE_ARG L"__cbm_launcher_capability_probe_v1"
-
-static bool windows_probe_volume(const wchar_t *directory, char *error, size_t error_size) {
- wchar_t volume[MAX_PATH + 1U];
- wchar_t filesystem[MAX_PATH + 1U];
- if (!GetVolumePathNameW(directory, volume, MAX_PATH + 1U) ||
- GetDriveTypeW(volume) != DRIVE_FIXED ||
- !GetVolumeInformationW(volume, NULL, 0U, NULL, NULL, NULL, filesystem, MAX_PATH + 1U) ||
- _wcsicmp(filesystem, L"NTFS") != 0) {
- launcher_error(error, error_size, "managed launcher requires a local fixed NTFS volume");
- return false;
- }
- return true;
-}
-
-static bool windows_probe_spawn(const wchar_t *image, HANDLE ready, HANDLE release,
- PROCESS_INFORMATION *child) {
- wchar_t command[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- int written = swprintf(command, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"\"%ls\" %ls %llx %llx", image,
- CBM_LAUNCHER_PROBE_ARG, (unsigned long long)(uintptr_t)ready,
- (unsigned long long)(uintptr_t)release);
- if (written <= 0 || (size_t)written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- return false;
- }
- HANDLE inherited[2] = {ready, release};
- SIZE_T attribute_size = 0U;
- (void)InitializeProcThreadAttributeList(NULL, 1U, 0U, &attribute_size);
- LPPROC_THREAD_ATTRIBUTE_LIST attributes = attribute_size ? malloc(attribute_size) : NULL;
- bool initialized =
- attributes && InitializeProcThreadAttributeList(attributes, 1U, 0U, &attribute_size) != 0;
- bool ready_attributes =
- initialized && UpdateProcThreadAttribute(attributes, 0U, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
- inherited, sizeof(inherited), NULL, NULL) != 0;
- STARTUPINFOEXW startup;
- memset(&startup, 0, sizeof(startup));
- memset(child, 0, sizeof(*child));
- startup.StartupInfo.cb = sizeof(startup);
- startup.lpAttributeList = attributes;
- bool spawned =
- ready_attributes && CreateProcessW(image, command, NULL, NULL, TRUE,
- CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, NULL,
- NULL, &startup.StartupInfo, child) != 0;
- if (initialized)
- DeleteProcThreadAttributeList(attributes);
- free(attributes);
- return spawned;
-}
-
-static void windows_probe_child_stop(PROCESS_INFORMATION *child, HANDLE release) {
- if (release)
- (void)SetEvent(release);
- if (child->hProcess) {
- if (WaitForSingleObject(child->hProcess, 5000U) != WAIT_OBJECT_0) {
- (void)TerminateProcess(child->hProcess, 1U);
- (void)WaitForSingleObject(child->hProcess, 5000U);
- }
- (void)CloseHandle(child->hProcess);
- }
- if (child->hThread)
- (void)CloseHandle(child->hThread);
- memset(child, 0, sizeof(*child));
-}
-
-typedef struct {
- wchar_t **paths;
- size_t count;
- size_t capacity;
-} windows_created_directories_t;
-
-static void windows_created_directories_close(windows_created_directories_t *created,
- bool remove_directories) {
- if (!created)
- return;
- for (size_t index = 0U; index < created->count; index++) {
- if (remove_directories)
- (void)RemoveDirectoryW(created->paths[index]);
- free(created->paths[index]);
- }
- free(created->paths);
- memset(created, 0, sizeof(*created));
-}
-
-static bool windows_created_directories_push(windows_created_directories_t *created,
- const wchar_t *path) {
- if (created->count == created->capacity) {
- size_t next_capacity = created->capacity == 0U ? 8U : created->capacity * 2U;
- if (next_capacity < created->capacity || next_capacity > CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- return false;
- }
- wchar_t **next = realloc(created->paths, next_capacity * sizeof(*next));
- if (!next)
- return false;
- created->paths = next;
- created->capacity = next_capacity;
- }
- size_t length = wcslen(path);
- wchar_t *copy = malloc((length + 1U) * sizeof(*copy));
- if (!copy)
- return false;
- memcpy(copy, path, (length + 1U) * sizeof(*copy));
- created->paths[created->count++] = copy;
- return 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;
- /* 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 = root; index < length; index++) {
- if (cursor[index] == L'/')
- cursor[index] = L'\\';
- }
- while (length > root + 3U && cursor[length - 1U] == L'\\') {
- cursor[--length] = L'\0';
- }
- bool valid = true;
- for (;;) {
- DWORD attributes = GetFileAttributesW(cursor);
- if (attributes != INVALID_FILE_ATTRIBUTES) {
- HANDLE ancestor = CreateFileW(
- cursor, 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;
- /* 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 &&
- (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&
- windows_owner_secure(ancestor, false) &&
- windows_acl_secure_for_mutation(ancestor, mutation);
- if (ancestor != INVALID_HANDLE_VALUE)
- (void)CloseHandle(ancestor);
- break;
- }
- DWORD error = GetLastError();
- if ((error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND) ||
- !windows_created_directories_push(created, cursor)) {
- valid = false;
- break;
- }
- wchar_t *separator = wcsrchr(cursor + root, L'\\');
- if (!separator || separator <= cursor + root + 2) {
- valid = false;
- break;
- }
- *separator = L'\0';
- }
- for (size_t remaining = created->count; valid && remaining > 0U; remaining--) {
- const wchar_t *directory = created->paths[remaining - 1U];
- if (!windows_create_directory_private(directory)) {
- valid = false;
- break;
- }
- HANDLE handle = windows_open_directory_secure(directory);
- valid = handle != INVALID_HANDLE_VALUE;
- if (handle != INVALID_HANDLE_VALUE)
- (void)CloseHandle(handle);
- }
- free(cursor);
- if (!valid) {
- windows_created_directories_close(created, true);
- }
- return valid;
-}
-
-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 ||
- !launcher_candidate[0]) {
- launcher_error(error, error_size, "invalid launcher capability probe request");
- return false;
- }
- wchar_t forced[16];
- if (GetEnvironmentVariableW(L"CBM_TEST_WINDOWS_LAUNCHER_CAPABILITY_PROBE", forced,
- (DWORD)(sizeof(forced) / sizeof(forced[0]))) > 0U &&
- _wcsicmp(forced, L"fail") == 0) {
- launcher_error(error, error_size, "Windows launcher capability probe was forced to fail");
- return false;
- }
- windows_created_directories_t created;
- if (!windows_prepare_probe_directory(target_directory, &created)) {
- launcher_error(error, error_size, "could not safely prepare capability probe directory");
- return false;
- }
- wchar_t probe_tree_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- int tree_written = swprintf(probe_tree_path, CBM_WINDOWS_LAUNCHER_PATH_CAP,
- L"%ls\\.cbm-probe-path-check", target_directory);
- HANDLE target_handle = windows_open_directory_secure(target_directory);
- bool ok = tree_written > 0 && (size_t)tree_written < CBM_WINDOWS_LAUNCHER_PATH_CAP &&
- windows_path_tree_plain(probe_tree_path) && target_handle != INVALID_HANDLE_VALUE &&
- windows_probe_volume(target_directory, error, error_size);
- if (target_handle != INVALID_HANDLE_VALUE)
- (void)CloseHandle(target_handle);
- HANDLE mutex =
- 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;
- 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),
- .lpSecurityDescriptor = NULL,
- .bInheritHandle = TRUE,
- };
- HANDLE ready_a = ok ? CreateEventW(&security, TRUE, FALSE, NULL) : NULL;
- 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(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);
-
- windows_probe_child_stop(&child_a, release_a);
- if (ready_a)
- (void)CloseHandle(ready_a);
- if (release_a)
- (void)CloseHandle(release_a);
-
- /* 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));
- 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);
- 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 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.h
deleted file mode 100644
index 2948ff8b7..000000000
--- a/src/cli/windows_launcher_state.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * windows_launcher_state.h -- Stable state shared by the Windows launcher and
- * the CBM payload.
- *
- * The on-disk current-v1 record is deliberately fixed-size and contains no
- * native C layout. Keep its codec platform-independent: release compatibility
- * is a byte contract, not a compiler/architecture contract.
- */
-#ifndef CBM_WINDOWS_LAUNCHER_STATE_H
-#define CBM_WINDOWS_LAUNCHER_STATE_H
-
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <wchar.h>
-
-#define CBM_WINDOWS_CURRENT_V1_SIZE 128U
-#define CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE 128U
-#ifndef CBM_WINDOWS_LAUNCHER_ABI_CURRENT
-#define CBM_WINDOWS_LAUNCHER_ABI_CURRENT 1U
-#endif
-#ifndef CBM_WINDOWS_PAYLOAD_LAUNCHER_ABI_MIN
-#define CBM_WINDOWS_PAYLOAD_LAUNCHER_ABI_MIN 1U
-#endif
-#ifndef CBM_WINDOWS_PAYLOAD_LAUNCHER_ABI_MAX
-#define CBM_WINDOWS_PAYLOAD_LAUNCHER_ABI_MAX 1U
-#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;
- uint64_t payload_size;
- char payload_sha256[65];
-} cbm_windows_current_v1_t;
-
-typedef struct {
- uint32_t launcher_abi;
- uint32_t payload_launcher_abi_min;
- uint32_t payload_launcher_abi_max;
- uint64_t payload_size;
- char payload_sha256[65];
-} cbm_windows_release_descriptor_v1_t;
-
-typedef enum {
- CBM_WINDOWS_TRANSITION_INCOMPATIBLE = 0,
- CBM_WINDOWS_TRANSITION_LAUNCHER_FIRST = 1,
- CBM_WINDOWS_TRANSITION_CURRENT_FIRST = 2,
-} cbm_windows_transition_plan_t;
-
-typedef enum {
- CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY = 0,
- CBM_WINDOWS_LAUNCHER_ACTION_UPDATE = 1,
- CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL = 2,
-} cbm_windows_launcher_action_t;
-
-bool cbm_windows_current_v1_encode(const cbm_windows_current_v1_t *state,
- uint8_t out[CBM_WINDOWS_CURRENT_V1_SIZE]);
-bool cbm_windows_current_v1_decode(const uint8_t *record, size_t record_size,
- cbm_windows_current_v1_t *state_out);
-bool cbm_windows_current_v1_supports_launcher_abi(const cbm_windows_current_v1_t *state,
- uint32_t launcher_abi);
-
-bool cbm_windows_release_descriptor_v1_encode(const cbm_windows_release_descriptor_v1_t *descriptor,
- uint8_t out[CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE]);
-bool cbm_windows_release_descriptor_v1_decode(const uint8_t *record, size_t record_size,
- cbm_windows_release_descriptor_v1_t *descriptor_out);
-cbm_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 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. */
-cbm_windows_launcher_action_t cbm_windows_launcher_classify_action(int argc,
- const char *const argv[]);
-bool cbm_windows_launcher_action_allowed(cbm_windows_launcher_action_t action, bool managed);
-
-/* Trusted launch data delivered over a launcher-owned inherited named pipe.
- * An absent context is valid and returns true with present=false (direct
- * portable payload). An advertised but invalid context fails closed. */
-typedef struct {
- bool present;
- bool managed;
- bool private_activation;
- cbm_windows_launcher_action_t action;
- uint64_t payload_size;
- char expected_payload_sha256[65];
- wchar_t canonical_launcher_path[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- /* Opaque one-shot authority retained only until startup validation has
- * completed. Callers must use context_complete, never inspect it. */
- uintptr_t _authority_handle;
-} cbm_windows_launcher_context_t;
-
-bool cbm_windows_launcher_context_consume(cbm_windows_launcher_context_t *context_out, char *error,
- size_t error_size);
-bool cbm_windows_launcher_context_complete(cbm_windows_launcher_context_t *context, bool accepted,
- char *error, size_t error_size);
-
-/* Windows managed-install primitives. They fail closed on other platforms.
- * Diagnostics are optional and always NUL-terminated when capacity is nonzero.
- */
-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);
-/* 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,
- size_t error_size);
-bool cbm_windows_generations_prune(const wchar_t *canonical_launcher_path, size_t *removed_out,
- char *error, size_t error_size);
-
-#endif /* CBM_WINDOWS_LAUNCHER_STATE_H */
diff --git a/src/launcher/windows_launcher.c b/src/launcher/windows_launcher.c
deleted file mode 100644
index cadd4588e..000000000
--- a/src/launcher/windows_launcher.c
+++ /dev/null
@@ -1,1697 +0,0 @@
-/*
- * windows_launcher.c -- Permanent, self-relative Windows CBM launcher.
- *
- * This executable intentionally stays tiny. It owns no indexer or config
- * state: it validates one fixed current-v1 pointer and contains the selected
- * payload in a kill-on-close job while relaying stdio and the exact exit code.
- */
-#include "cli/windows_launcher_state.h"
-
-#ifndef _WIN32
-
-#include <stdio.h>
-
-int main(void) {
- (void)fprintf(stderr, "codebase-memory-mcp-launcher is available only on Windows\n");
- return 1;
-}
-
-#else
-
-#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0A00
-#endif
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#include <aclapi.h>
-#include <bcrypt.h>
-#include <sddl.h>
-#include <shellapi.h>
-#include <tlhelp32.h>
-
-#ifndef PIPE_REJECT_REMOTE_CLIENTS
-#define PIPE_REJECT_REMOTE_CLIENTS 0x00000008
-#endif
-
-#include <stdarg.h>
-#include <stdbool.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <wchar.h>
-
-#define LAUNCHER_CONTEXT_ENV L"CBM_WINDOWS_LAUNCH_CONTEXT_HANDLE_V1"
-#define LAUNCHER_CONTEXT_HEADER_SIZE 128U
-#define LAUNCHER_CONTEXT_MANAGED 0x00000001U
-#define LAUNCHER_CONTEXT_PRIVATE 0x00000002U
-#define LAUNCHER_PIPE_BUFFER (128U * 1024U)
-#define LAUNCHER_PROBE_ARG L"__cbm_launcher_capability_probe_v1"
-#define LAUNCHER_RELEASE_DESCRIPTOR_ARG L"__cbm_windows_release_descriptor_v1"
-#define PAYLOAD_RELEASE_DESCRIPTOR_ARG L"__cbm_windows_payload_descriptor_v1"
-
-static const uint8_t launcher_context_magic[8] = {
- 'C', 'B', 'M', 'L', 'C', 'T', '1', '\0',
-};
-
-typedef struct {
- DWORD Flags;
-} launcher_disposition_info_ex_t;
-
-#define LAUNCHER_FILE_DISPOSITION_INFO_EX ((FILE_INFO_BY_HANDLE_CLASS)21)
-#define LAUNCHER_FILE_DISPOSITION_DELETE 0x00000001U
-#define LAUNCHER_FILE_DISPOSITION_POSIX 0x00000002U
-#ifndef PROC_THREAD_ATTRIBUTE_JOB_LIST
-#define PROC_THREAD_ATTRIBUTE_JOB_LIST ((DWORD_PTR)0x0002000dU)
-#endif
-
-static void launcher_write_u32(uint8_t *output, uint32_t value) {
- for (unsigned int index = 0; index < 4U; index++) {
- output[index] = (uint8_t)(value >> (index * 8U));
- }
-}
-
-static void launcher_write_u64(uint8_t *output, uint64_t value) {
- for (unsigned int index = 0; index < 8U; index++) {
- output[index] = (uint8_t)(value >> (index * 8U));
- }
-}
-
-static uint64_t launcher_filetime_value(const FILETIME *time) {
- return (uint64_t)time->dwLowDateTime | ((uint64_t)time->dwHighDateTime << 32U);
-}
-
-/* Last refusal detail, set at the exact check that failed and printed once by
- * launcher_failure. A bare "policy is unsafe" is undiagnosable in the field;
- * naming the object and rule costs nothing and leaks nothing an owner of the
- * process could not query themselves. Last writer wins. */
-static wchar_t launcher_refusal_detail[320];
-
-static void launcher_refusal_set(const wchar_t *format, ...) {
- va_list arguments;
- va_start(arguments, format);
- (void)_vsnwprintf(launcher_refusal_detail,
- sizeof(launcher_refusal_detail) / sizeof(wchar_t) - 1U, format, arguments);
- va_end(arguments);
- launcher_refusal_detail[sizeof(launcher_refusal_detail) / sizeof(wchar_t) - 1U] = L'\0';
-}
-
-static void launcher_refusal_set_sid(const wchar_t *what, PSID sid, DWORD rights) {
- wchar_t *sid_text = NULL;
- bool converted = sid && ConvertSidToStringSidW(sid, &sid_text) != 0;
- if (rights) {
- launcher_refusal_set(L"%ls %ls (rights 0x%08lx)", what,
- converted ? sid_text : L"<unreadable SID>", (unsigned long)rights);
- } else {
- launcher_refusal_set(L"%ls %ls", what, converted ? sid_text : L"<unreadable SID>");
- }
- if (converted) {
- (void)LocalFree(sid_text);
- }
-}
-
-static int launcher_failure(const wchar_t *message) {
- if (message) {
- if (launcher_refusal_detail[0]) {
- (void)fwprintf(stderr, L"codebase-memory-mcp: %ls [%ls]\n", message,
- launcher_refusal_detail);
- } else {
- (void)fwprintf(stderr, L"codebase-memory-mcp: %ls\n", message);
- }
- (void)fflush(stderr);
- }
- return 1;
-}
-
-static bool launcher_same_identity(const BY_HANDLE_FILE_INFORMATION *first,
- const BY_HANDLE_FILE_INFORMATION *second) {
- return first->dwVolumeSerialNumber == second->dwVolumeSerialNumber &&
- first->nFileIndexHigh == second->nFileIndexHigh &&
- first->nFileIndexLow == second->nFileIndexLow;
-}
-
-static bool launcher_file_information(HANDLE file, BY_HANDLE_FILE_INFORMATION *information) {
- if (!file || file == INVALID_HANDLE_VALUE) {
- launcher_refusal_set(L"open failed (error %lu)", (unsigned long)GetLastError());
- return false;
- }
- if (GetFileType(file) != FILE_TYPE_DISK) {
- launcher_refusal_set(L"not a local disk file");
- return false;
- }
- if (GetFileInformationByHandle(file, information) == 0) {
- launcher_refusal_set(L"attribute query failed (error %lu)", (unsigned long)GetLastError());
- return false;
- }
- if ((information->dwFileAttributes &
- (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) != 0) {
- launcher_refusal_set(L"directory or reparse point (attributes 0x%08lx)",
- (unsigned long)information->dwFileAttributes);
- return false;
- }
- 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;
-}
-
-static bool launcher_current_user(void **token_user_out, PSID *sid_out) {
- *token_user_out = NULL;
- *sid_out = NULL;
- HANDLE token = NULL;
- DWORD needed = 0U;
- if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) {
- return false;
- }
- (void)GetTokenInformation(token, TokenUser, NULL, 0U, &needed);
- void *memory = needed ? malloc(needed) : NULL;
- bool ok = memory && GetTokenInformation(token, TokenUser, memory, needed, &needed) != 0;
- (void)CloseHandle(token);
- if (!ok) {
- free(memory);
- return false;
- }
- *token_user_out = memory;
- *sid_out = ((TOKEN_USER *)memory)->User.Sid;
- return true;
-}
-
-static uint32_t launcher_sid_read_u32_le(const uint8_t *bytes) {
- return (uint32_t)bytes[0] | ((uint32_t)bytes[1] << 8U) | ((uint32_t)bytes[2] << 16U) |
- ((uint32_t)bytes[3] << 24U);
-}
-
-static bool launcher_sid_is_trusted_installer(PSID sid) {
- static const uint32_t subauthorities[] = {
- 80U, 956008885U, 3418522649U, 1831038044U, 1853292631U, 2271478464U,
- };
- if (!sid || !IsValidSid(sid)) {
- return false;
- }
- DWORD sid_length = GetLengthSid(sid);
- const uint8_t *bytes = (const uint8_t *)sid;
- if (sid_length != 32U || bytes[0] != 1U || bytes[1] != 6U || bytes[2] != 0U || bytes[3] != 0U ||
- bytes[4] != 0U || bytes[5] != 0U || bytes[6] != 0U || bytes[7] != 5U) {
- return false;
- }
- for (size_t index = 0U; index < sizeof(subauthorities) / sizeof(subauthorities[0]); index++) {
- if (launcher_sid_read_u32_le(bytes + 8U + index * 4U) != subauthorities[index]) {
- return false;
- }
- }
- return true;
-}
-
-static bool launcher_sid_is_trusted(PSID sid, PSID current_user) {
- return sid && current_user && IsValidSid(sid) &&
- (EqualSid(sid, current_user) || IsWellKnownSid(sid, WinLocalSystemSid) ||
- IsWellKnownSid(sid, WinBuiltinAdministratorsSid) ||
- launcher_sid_is_trusted_installer(sid));
-}
-
-static bool launcher_bounded_ace_sid_is_trusted(const ACE_HEADER *header, PSID current_user) {
- size_t sid_offset = offsetof(ACCESS_ALLOWED_ACE, SidStart);
- if (!header || (size_t)header->AceSize < sid_offset + 8U) {
- return false;
- }
- const ACCESS_ALLOWED_ACE *ace = (const ACCESS_ALLOWED_ACE *)header;
- const uint8_t *sid = (const uint8_t *)&ace->SidStart;
- size_t sid_capacity = (size_t)header->AceSize - sid_offset;
- if (sid[0] != 1U || sid[1] > 15U) {
- return false;
- }
- size_t sid_length = 8U + (size_t)sid[1] * 4U;
- return sid_length <= sid_capacity && IsValidSid((PSID)sid) &&
- GetLengthSid((PSID)sid) == (DWORD)sid_length &&
- (launcher_sid_is_trusted((PSID)sid, current_user) ||
- (((header->AceFlags & INHERIT_ONLY_ACE) != 0U) &&
- IsWellKnownSid((PSID)sid, WinCreatorOwnerSid)) ||
- /* OWNER RIGHTS (S-1-3-4) applies to the validated current-user
- * owner; default profile ACLs carry it, and rejecting it locked
- * the launcher out of legitimate current-user directories. */
- IsWellKnownSid((PSID)sid, WinCreatorOwnerRightsSid));
-}
-
-static bool launcher_security_is_safe(HANDLE file, bool require_current_owner, DWORD mutation) {
- void *token_user = NULL;
- PSID user_sid = NULL;
- if (!launcher_current_user(&token_user, &user_sid)) {
- launcher_refusal_set(L"could not resolve the process token user");
- return false;
- }
- PSID owner = NULL;
- PACL dacl = NULL;
- PSECURITY_DESCRIPTOR descriptor = NULL;
- DWORD status = GetSecurityInfo(file, SE_FILE_OBJECT,
- OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, &owner,
- NULL, &dacl, NULL, &descriptor);
- ACL_SIZE_INFORMATION information;
- memset(&information, 0, sizeof(information));
- bool secure = status == ERROR_SUCCESS && owner && IsValidSid(owner);
- if (!secure) {
- launcher_refusal_set(L"security query failed (status %lu)", (unsigned long)status);
- } else if (require_current_owner ? EqualSid(owner, user_sid) == 0
- : !launcher_sid_is_trusted(owner, user_sid)) {
- launcher_refusal_set_sid(require_current_owner ? L"owner is not the current user:"
- : L"owner is not a trusted identity:",
- owner, 0U);
- secure = false;
- } else if (!dacl || !IsValidAcl(dacl) ||
- GetAclInformation(dacl, &information, sizeof(information), AclSizeInformation) ==
- 0) {
- launcher_refusal_set(L"missing or invalid DACL");
- secure = false;
- }
- for (DWORD index = 0; secure && index < information.AceCount; index++) {
- void *opaque = NULL;
- if (!GetAce(dacl, index, &opaque) || !opaque) {
- launcher_refusal_set(L"DACL entry %lu is unreadable", (unsigned long)index);
- secure = false;
- break;
- }
- ACE_HEADER *header = opaque;
- enum {
- LAUNCHER_ACE_ALLOW = 0x00,
- LAUNCHER_ACE_DENY = 0x01,
- LAUNCHER_ACE_DENY_OBJECT = 0x06,
- LAUNCHER_ACE_DENY_CALLBACK = 0x0a,
- LAUNCHER_ACE_DENY_CALLBACK_OBJECT = 0x0c,
- };
- if (header->AceType == LAUNCHER_ACE_DENY || header->AceType == LAUNCHER_ACE_DENY_OBJECT ||
- header->AceType == LAUNCHER_ACE_DENY_CALLBACK ||
- header->AceType == LAUNCHER_ACE_DENY_CALLBACK_OBJECT) {
- continue;
- }
- if (header->AceType != LAUNCHER_ACE_ALLOW ||
- header->AceSize <
- offsetof(ACCESS_ALLOWED_ACE, SidStart) + offsetof(SID, SubAuthority)) {
- launcher_refusal_set(L"DACL entry %lu has unsupported type 0x%02x",
- (unsigned long)index, (unsigned int)header->AceType);
- secure = false;
- break;
- }
- ACCESS_ALLOWED_ACE *ace = opaque;
- if ((ace->Mask & mutation) == 0U) {
- continue;
- }
- if (!launcher_bounded_ace_sid_is_trusted(header, user_sid)) {
- launcher_refusal_set_sid(L"mutation right granted to untrusted identity:",
- (PSID)&ace->SidStart, ace->Mask & mutation);
- secure = false;
- }
- }
- if (descriptor)
- (void)LocalFree(descriptor);
- free(token_user);
- return secure;
-}
-
-static DWORD launcher_private_mutation_rights(void) {
- return GENERIC_ALL | GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_ADD_FILE |
- FILE_ADD_SUBDIRECTORY | FILE_DELETE_CHILD | FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES |
- DELETE | WRITE_DAC | WRITE_OWNER | ACCESS_SYSTEM_SECURITY;
-}
-
-static bool launcher_security_is_trusted(HANDLE file) {
- /* The launcher validates its own binary, staged payloads, and their
- * directories. On an elevated or managed install (Program Files, an
- * admin-run installer, GitHub's Windows runners) the default owner of
- * newly created objects is BUILTIN\Administrators, not the exact token
- * user, so demanding the current user as owner rejects the launcher's
- * own legitimately privileged-owned files. Accept the trusted-owner set
- * (self, SYSTEM, Administrators, TrustedInstaller) that
- * launcher_sid_is_trusted already defines and that the daemon side
- * applies for the identical reason (see src/daemon/ipc.c owner policy):
- * a less-privileged attacker cannot stamp any of those owners without
- * already holding that privilege. DACL strictness is unchanged -- every
- * allow ACE must still grant only a trusted identity -- so tamper
- * resistance is preserved; only the owner field is widened to the
- * privileged identities that manage the install. */
- return launcher_security_is_safe(file, false, launcher_private_mutation_rights());
-}
-
-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;
- 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;
- }
- return 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,
- 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;
- bool valid = directory != INVALID_HANDLE_VALUE && GetFileType(directory) == FILE_TYPE_DISK &&
- GetFileInformationByHandle(directory, &information) != 0 &&
- (information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&
- (information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0 &&
- launcher_security_is_trusted(directory);
- if (!valid) {
- if (directory != INVALID_HANDLE_VALUE)
- (void)CloseHandle(directory);
- return INVALID_HANDLE_VALUE;
- }
- return directory;
-}
-
-static bool launcher_path_tree_plain(const wchar_t *file_path) {
- size_t length = wcslen(file_path);
- size_t root_length = 0U;
- if (length >= 4U && file_path[1] == L':' && (file_path[2] == L'\\' || file_path[2] == L'/')) {
- root_length = 3U;
- } else if (length >= 8U && file_path[0] == L'\\' && file_path[1] == L'\\' &&
- file_path[2] == L'?' && file_path[3] == L'\\' && file_path[5] == L':' &&
- (file_path[6] == L'\\' || file_path[6] == L'/')) {
- /* GetModuleFileNameW preserves the path format used to launch the
- * process. Keep an extended DOS path extended while walking it so
- * every ACL/reparse check names the exact object that was executed. */
- root_length = 7U;
- }
- if (root_length == 0U || length <= root_length || length >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- return false;
- }
- wchar_t *path = malloc((length + 1U) * sizeof(*path));
- if (!path)
- return false;
- memcpy(path, file_path, (length + 1U) * sizeof(*path));
- for (size_t index = 0; index < length; index++) {
- if (path[index] == L'/')
- path[index] = L'\\';
- }
- wchar_t *last = wcsrchr(path, L'\\');
- if (!last || last < path + root_length) {
- free(path);
- return false;
- }
- *last = L'\0';
- size_t directory_length = wcslen(path);
- bool valid = true;
- for (size_t index = root_length; valid && index <= directory_length; index++) {
- if (index < directory_length && path[index] != L'\\')
- continue;
- wchar_t saved = path[index];
- path[index] = L'\0';
- HANDLE component =
- CreateFileW(path, 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;
- DWORD mutation = launcher_private_mutation_rights();
- if (index < directory_length) {
- /* Default C:\\Users ACLs grant cross-account add-subdirectory on
- * this intermediate component. That cannot replace the existing
- * next component. No other write right is relaxed, and the final
- * executable directory remains fully private so a peer cannot
- * plant DLL or .exe.local redirection artifacts beside CBM. */
- mutation &= ~((DWORD)FILE_ADD_SUBDIRECTORY);
- }
- DWORD open_error = component == INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS;
- 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 &&
- launcher_security_is_safe(component, false, mutation);
- if (!valid) {
- /* Name the ancestry component that failed while it is still
- * NUL-terminated at this walk position. */
- if (open_error != ERROR_SUCCESS) {
- launcher_refusal_set(L"%ls: open failed (error %lu)", path,
- (unsigned long)open_error);
- } else {
- wchar_t inner[320];
- memcpy(inner, launcher_refusal_detail, sizeof(inner));
- inner[sizeof(inner) / sizeof(wchar_t) - 1U] = L'\0';
- launcher_refusal_set(L"%ls: %ls", path, inner);
- }
- }
- if (component != INVALID_HANDLE_VALUE)
- (void)CloseHandle(component);
- path[index] = saved;
- }
- free(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_self_path_canonicalize(output) && launcher_path_tree_plain(output);
-}
-
-static bool launcher_parent_path(const wchar_t *path, wchar_t *output, size_t capacity) {
- size_t length = wcslen(path);
- if (length + 1U > capacity)
- return false;
- memcpy(output, path, (length + 1U) * sizeof(*output));
- wchar_t *separator = wcsrchr(output, L'\\');
- wchar_t *slash = wcsrchr(output, L'/');
- if (!separator || (slash && slash > separator))
- separator = slash;
- if (!separator || separator <= output + 2)
- return false;
- *separator = L'\0';
- return 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) {
- DWORD amount = 0U;
- DWORD request = size - offset > (size_t)MAXDWORD ? MAXDWORD : (DWORD)(size - offset);
- if (!ReadFile(file, (uint8_t *)buffer + offset, request, &amount, NULL) || amount == 0U) {
- return false;
- }
- offset += amount;
- }
- return true;
-}
-
-/* 1 = managed valid state, 0 = current absent (portable bundle), -1 = corrupt. */
-static int launcher_load_current(const wchar_t *canonical_launcher,
- cbm_windows_current_v1_t *state_out) {
- wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t current[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!launcher_parent_path(canonical_launcher, directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {
- return -1;
- }
- int written =
- swprintf(current, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\.cbm\\current-v1", directory);
- if (written <= 0 || (size_t)written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- return -1;
- }
- wchar_t state_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- int state_written =
- swprintf(state_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\.cbm", directory);
- HANDLE install_handle = launcher_open_directory_private(directory);
- HANDLE state_handle = state_written > 0 && (size_t)state_written < CBM_WINDOWS_LAUNCHER_PATH_CAP
- ? launcher_open_directory_private(state_directory)
- : INVALID_HANDLE_VALUE;
- if (install_handle == INVALID_HANDLE_VALUE || state_handle == INVALID_HANDLE_VALUE) {
- if (install_handle != INVALID_HANDLE_VALUE)
- (void)CloseHandle(install_handle);
- if (state_handle != INVALID_HANDLE_VALUE)
- (void)CloseHandle(state_handle);
- DWORD state_attributes = GetFileAttributesW(state_directory);
- DWORD state_error =
- state_attributes == INVALID_FILE_ATTRIBUTES ? GetLastError() : ERROR_SUCCESS;
- return state_attributes == INVALID_FILE_ATTRIBUTES &&
- (state_error == ERROR_FILE_NOT_FOUND || state_error == ERROR_PATH_NOT_FOUND)
- ? 0
- : -1;
- }
- (void)CloseHandle(install_handle);
- (void)CloseHandle(state_handle);
- HANDLE file = launcher_open_regular(current, GENERIC_READ, true);
- if (file == INVALID_HANDLE_VALUE) {
- DWORD attributes = GetFileAttributesW(current);
- return attributes == INVALID_FILE_ATTRIBUTES && (GetLastError() == ERROR_FILE_NOT_FOUND ||
- GetLastError() == ERROR_PATH_NOT_FOUND)
- ? 0
- : -1;
- }
- LARGE_INTEGER size;
- uint8_t record[CBM_WINDOWS_CURRENT_V1_SIZE];
- uint8_t trailing = 0U;
- DWORD trailing_count = 0U;
- bool valid = GetFileSizeEx(file, &size) && size.QuadPart == CBM_WINDOWS_CURRENT_V1_SIZE &&
- launcher_read_all(file, record, sizeof(record)) &&
- ReadFile(file, &trailing, 1U, &trailing_count, NULL) != 0 &&
- trailing_count == 0U &&
- cbm_windows_current_v1_decode(record, sizeof(record), state_out);
- (void)CloseHandle(file);
- return valid ? 1 : -1;
-}
-
-static bool launcher_adjacent_payload(const wchar_t *canonical_launcher,
- wchar_t output[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {
- wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!launcher_parent_path(canonical_launcher, directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {
- return false;
- }
- int written = swprintf(output, CBM_WINDOWS_LAUNCHER_PATH_CAP,
- L"%ls\\codebase-memory-mcp.payload.exe", directory);
- return written > 0 && (size_t)written < CBM_WINDOWS_LAUNCHER_PATH_CAP;
-}
-
-/* WHY: wmain supplies wchar_t **. Adding nested pointee const would make these
- * read-only helpers' parameter types incompatible with that Windows ABI. */
-// cppcheck-suppress constParameter
-static cbm_windows_launcher_action_t launcher_wide_action(int argc, wchar_t *const argv[]) {
- if (argc <= 1 || !argv)
- return CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY;
- for (int index = 1; index < argc; index++) {
- const wchar_t *argument = argv[index];
- if (!argument)
- continue;
- if (wcscmp(argument, L"cli") == 0 || wcscmp(argument, L"hook-augment") == 0 ||
- wcscmp(argument, L"config") == 0 || wcscmp(argument, L"install") == 0 ||
- wcscmp(argument, L"--help") == 0 || wcscmp(argument, L"-h") == 0 ||
- wcscmp(argument, L"--version") == 0) {
- return CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY;
- }
- if (wcscmp(argument, L"update") == 0)
- return CBM_WINDOWS_LAUNCHER_ACTION_UPDATE;
- if (wcscmp(argument, L"uninstall") == 0)
- return CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL;
- }
- return CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY;
-}
-
-static size_t launcher_quoted_length(const wchar_t *argument) {
- bool quote = argument[0] == L'\0' || wcspbrk(argument, L" \t\n\v\"") != NULL;
- size_t length = quote ? 2U : 0U;
- size_t slashes = 0U;
- for (const wchar_t *cursor = argument;; cursor++) {
- if (*cursor == L'\\') {
- slashes++;
- continue;
- }
- if (*cursor == L'\"') {
- length += slashes * 2U + 2U;
- slashes = 0U;
- continue;
- }
- if (*cursor == L'\0') {
- length += quote ? slashes * 2U : slashes;
- break;
- }
- length += slashes + 1U;
- slashes = 0U;
- }
- return length;
-}
-
-static wchar_t *launcher_quote_into(wchar_t *output, const wchar_t *argument) {
- bool quote = argument[0] == L'\0' || wcspbrk(argument, L" \t\n\v\"") != NULL;
- if (quote)
- *output++ = L'\"';
- size_t slashes = 0U;
- for (const wchar_t *cursor = argument;; cursor++) {
- if (*cursor == L'\\') {
- slashes++;
- continue;
- }
- if (*cursor == L'\"') {
- size_t count = slashes * 2U + 1U;
- while (count-- > 0U)
- *output++ = L'\\';
- *output++ = L'\"';
- slashes = 0U;
- continue;
- }
- if (*cursor == L'\0') {
- size_t count = quote ? slashes * 2U : slashes;
- while (count-- > 0U)
- *output++ = L'\\';
- break;
- }
- while (slashes-- > 0U)
- *output++ = L'\\';
- slashes = 0U;
- *output++ = *cursor;
- }
- if (quote)
- *output++ = L'\"';
- return output;
-}
-
-static wchar_t *launcher_command_line(const wchar_t *image, int argc, wchar_t *const argv[]) {
- size_t capacity = launcher_quoted_length(image) + 1U;
- for (int index = 1; index < argc; index++) {
- size_t addition = launcher_quoted_length(argv[index]) + 1U;
- if (SIZE_MAX - capacity < addition)
- return NULL;
- capacity += addition;
- }
- wchar_t *command = calloc(capacity, sizeof(*command));
- if (!command)
- return NULL;
- wchar_t *cursor = launcher_quote_into(command, image);
- for (int index = 1; index < argc; index++) {
- *cursor++ = L' ';
- cursor = launcher_quote_into(cursor, argv[index]);
- }
- *cursor = L'\0';
- return command;
-}
-
-typedef struct {
- HANDLE server;
- HANDLE client;
-} launcher_context_pipe_t;
-
-static void launcher_context_pipe_close(launcher_context_pipe_t *pipe) {
- if (pipe->server && pipe->server != INVALID_HANDLE_VALUE)
- (void)CloseHandle(pipe->server);
- if (pipe->client && pipe->client != INVALID_HANDLE_VALUE)
- (void)CloseHandle(pipe->client);
- memset(pipe, 0, sizeof(*pipe));
-}
-
-static bool launcher_context_pipe_open(launcher_context_pipe_t *pipe) {
- memset(pipe, 0, sizeof(*pipe));
- uint8_t random[16];
- if (BCryptGenRandom(NULL, random, sizeof(random), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) {
- return false;
- }
- wchar_t name[160];
- int written =
- swprintf(name, sizeof(name) / sizeof(name[0]),
- L"\\\\.\\pipe\\cbm-launch-context-v1-%lu-"
- L"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
- (unsigned long)GetCurrentProcessId(), random[0], random[1], random[2], random[3],
- random[4], random[5], random[6], random[7], random[8], random[9], random[10],
- random[11], random[12], random[13], random[14], random[15]);
- if (written <= 0 || (size_t)written >= sizeof(name) / sizeof(name[0])) {
- return false;
- }
- pipe->server = CreateNamedPipeW(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
- PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT |
- PIPE_REJECT_REMOTE_CLIENTS,
- 1U, LAUNCHER_PIPE_BUFFER, 4096U, 0U, NULL);
- if (pipe->server == INVALID_HANDLE_VALUE) {
- launcher_context_pipe_close(pipe);
- return false;
- }
- SECURITY_ATTRIBUTES security = {
- .nLength = sizeof(security),
- .lpSecurityDescriptor = NULL,
- .bInheritHandle = TRUE,
- };
- pipe->client = CreateFileW(name, GENERIC_READ | GENERIC_WRITE, 0U, &security, OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL, NULL);
- if (pipe->client == INVALID_HANDLE_VALUE) {
- launcher_context_pipe_close(pipe);
- return false;
- }
- BOOL connected = ConnectNamedPipe(pipe->server, NULL);
- if (!connected && GetLastError() != ERROR_PIPE_CONNECTED) {
- launcher_context_pipe_close(pipe);
- return false;
- }
- return true;
-}
-
-static bool launcher_write_all(HANDLE file, const void *data, size_t size) {
- size_t offset = 0U;
- while (offset < size) {
- DWORD amount = 0U;
- DWORD request = size - offset > (size_t)MAXDWORD ? MAXDWORD : (DWORD)(size - offset);
- if (!WriteFile(file, (const uint8_t *)data + offset, request, &amount, NULL) ||
- amount == 0U) {
- return false;
- }
- offset += amount;
- }
- return true;
-}
-
-static bool launcher_wait_context_ready(HANDLE server, HANDLE child, HANDLE parent,
- bool *explicit_rejection_out) {
- *explicit_rejection_out = false;
- uint64_t now = GetTickCount64();
- uint64_t deadline = UINT64_MAX - now < 30000U ? UINT64_MAX : now + 30000U;
- while (GetTickCount64() < deadline) {
- DWORD available = 0U;
- if (!PeekNamedPipe(server, NULL, 0U, NULL, &available, NULL)) {
- return false;
- }
- if (available > 0U) {
- uint8_t ready = 0U;
- DWORD received = 0U;
- if (ReadFile(server, &ready, 1U, &received, NULL) == 0 || received != 1U) {
- return false;
- }
- *explicit_rejection_out = ready == (uint8_t)'X';
- return ready == (uint8_t)'R';
- }
- if (WaitForSingleObject(child, 0U) == WAIT_OBJECT_0) {
- return false;
- }
- if (WaitForSingleObject(parent, 0U) == WAIT_OBJECT_0) {
- return false;
- }
- Sleep(2U);
- }
- return false;
-}
-
-static bool launcher_context_send(HANDLE server, const wchar_t *canonical_launcher, bool managed,
- bool private_activation, cbm_windows_launcher_action_t action,
- const cbm_windows_current_v1_t *state) {
- size_t path_chars = wcslen(canonical_launcher) + 1U;
- if (path_chars >= CBM_WINDOWS_LAUNCHER_PATH_CAP || (managed && !state)) {
- return false;
- }
- FILETIME creation;
- FILETIME exit_time;
- FILETIME kernel_time;
- FILETIME user_time;
- if (!GetProcessTimes(GetCurrentProcess(), &creation, &exit_time, &kernel_time, &user_time)) {
- return false;
- }
- uint8_t header[LAUNCHER_CONTEXT_HEADER_SIZE];
- memset(header, 0, sizeof(header));
- memcpy(header, launcher_context_magic, sizeof(launcher_context_magic));
- launcher_write_u32(header + 8U, 1U);
- launcher_write_u32(header + 12U, LAUNCHER_CONTEXT_HEADER_SIZE);
- uint32_t flags = managed ? LAUNCHER_CONTEXT_MANAGED : 0U;
- if (private_activation)
- flags |= LAUNCHER_CONTEXT_PRIVATE;
- launcher_write_u32(header + 16U, flags);
- launcher_write_u32(header + 20U, (uint32_t)action);
- launcher_write_u32(header + 24U, GetCurrentProcessId());
- launcher_write_u32(header + 28U, (uint32_t)path_chars);
- launcher_write_u64(header + 32U, launcher_filetime_value(&creation));
- if (managed) {
- launcher_write_u64(header + 40U, state->payload_size);
- memcpy(header + 48U, state->payload_sha256, 64U);
- }
- return launcher_write_all(server, header, sizeof(header)) &&
- launcher_write_all(server, canonical_launcher, path_chars * sizeof(*canonical_launcher));
-}
-
-static HANDLE launcher_duplicate_standard(DWORD identifier, DWORD desired) {
- HANDLE source = GetStdHandle(identifier);
- HANDLE duplicate = NULL;
- if (source && source != INVALID_HANDLE_VALUE &&
- DuplicateHandle(GetCurrentProcess(), source, GetCurrentProcess(), &duplicate, 0U, TRUE,
- DUPLICATE_SAME_ACCESS)) {
- return duplicate;
- }
- SECURITY_ATTRIBUTES security = {
- .nLength = sizeof(security),
- .lpSecurityDescriptor = NULL,
- .bInheritHandle = TRUE,
- };
- return CreateFileW(L"NUL", desired, FILE_SHARE_READ | FILE_SHARE_WRITE, &security,
- OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
-}
-
-static bool launcher_posix_remove(HANDLE file) {
- launcher_disposition_info_ex_t disposition = {
- .Flags = LAUNCHER_FILE_DISPOSITION_DELETE | LAUNCHER_FILE_DISPOSITION_POSIX,
- };
- return SetFileInformationByHandle(file, LAUNCHER_FILE_DISPOSITION_INFO_EX, &disposition,
- 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,
- const cbm_windows_current_v1_t *state, HANDLE parent, int argc,
- wchar_t *const argv[]) {
- wchar_t *command = launcher_command_line(execution_path, argc, argv);
- launcher_context_pipe_t context_pipe = {0};
- HANDLE standard[3] = {
- launcher_duplicate_standard(STD_INPUT_HANDLE, GENERIC_READ),
- launcher_duplicate_standard(STD_OUTPUT_HANDLE, GENERIC_WRITE),
- launcher_duplicate_standard(STD_ERROR_HANDLE, GENERIC_WRITE),
- };
- bool handles_valid = standard[0] && standard[0] != INVALID_HANDLE_VALUE && standard[1] &&
- standard[1] != INVALID_HANDLE_VALUE && standard[2] &&
- standard[2] != INVALID_HANDLE_VALUE;
- bool pipe_valid = handles_valid && launcher_context_pipe_open(&context_pipe);
- HANDLE inherited[4] = {
- standard[0],
- standard[1],
- standard[2],
- pipe_valid ? context_pipe.client : NULL,
- };
- JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits;
- memset(&limits, 0, sizeof(limits));
- limits.BasicLimitInformation.LimitFlags =
- JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK;
- HANDLE job = CreateJobObjectW(NULL, NULL);
- bool job_ready = job && SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits,
- sizeof(limits)) != 0;
- SIZE_T attribute_size = 0U;
- (void)InitializeProcThreadAttributeList(NULL, 2U, 0U, &attribute_size);
- LPPROC_THREAD_ATTRIBUTE_LIST attributes = attribute_size ? malloc(attribute_size) : NULL;
- bool attribute_initialized =
- attributes && InitializeProcThreadAttributeList(attributes, 2U, 0U, &attribute_size) != 0;
- bool attribute_ready =
- attribute_initialized && job_ready &&
- UpdateProcThreadAttribute(attributes, 0U, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited,
- sizeof(inherited), NULL, NULL) != 0 &&
- UpdateProcThreadAttribute(attributes, 0U, PROC_THREAD_ATTRIBUTE_JOB_LIST, &job, sizeof(job),
- NULL, NULL) != 0;
-
- wchar_t context_handle[32];
- int context_written =
- pipe_valid ? swprintf(context_handle, sizeof(context_handle) / sizeof(context_handle[0]),
- L"%llx", (unsigned long long)(uintptr_t)context_pipe.client)
- : -1;
- bool environment_set =
- context_written > 0 &&
- (size_t)context_written < sizeof(context_handle) / sizeof(context_handle[0]) &&
- SetEnvironmentVariableW(LAUNCHER_CONTEXT_ENV, context_handle) != 0;
- STARTUPINFOEXW startup;
- PROCESS_INFORMATION child;
- memset(&startup, 0, sizeof(startup));
- memset(&child, 0, sizeof(child));
- startup.StartupInfo.cb = sizeof(startup);
- startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
- startup.StartupInfo.hStdInput = standard[0];
- startup.StartupInfo.hStdOutput = standard[1];
- startup.StartupInfo.hStdError = standard[2];
- startup.lpAttributeList = attributes;
- DWORD flags = EXTENDED_STARTUPINFO_PRESENT | CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT;
- bool parent_alive =
- parent && parent != INVALID_HANDLE_VALUE && WaitForSingleObject(parent, 0U) == WAIT_TIMEOUT;
- bool created = command && pipe_valid && attribute_ready && job_ready && parent_alive &&
- 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);
- free(attributes);
- free(command);
- for (size_t index = 0U; index < 3U; index++) {
- if (standard[index] && standard[index] != INVALID_HANDLE_VALUE)
- (void)CloseHandle(standard[index]);
- }
- if (context_pipe.client && context_pipe.client != INVALID_HANDLE_VALUE) {
- (void)CloseHandle(context_pipe.client);
- context_pipe.client = NULL;
- }
- bool context_sent =
- created && launcher_context_send(context_pipe.server, canonical_launcher, managed,
- private_activation, action, state);
- bool resumed = context_sent && ResumeThread(child.hThread) != (DWORD)-1;
- bool explicit_rejection = false;
- bool payload_ready = resumed && launcher_wait_context_ready(context_pipe.server, child.hProcess,
- parent, &explicit_rejection);
- HANDLE private_file = INVALID_HANDLE_VALUE;
- bool private_removed = true;
- if (payload_ready && private_activation) {
- /* DELETE only, never GENERIC_WRITE: the payload is RUNNING from this
- * staged image, and the image section always denies write sharing
- * (ERROR_SHARING_VIOLATION). First-touch antivirus scanners also hold
- * a just-staged executable without FILE_SHARE_DELETE, so this
- * DELETE-access open transiently collides as ERROR_SHARING_VIOLATION
- * on cold images (observed on hosted-runner images) — the same scan
- * window the staged rename above absorbs. Bounded backoff; every
- * retry re-runs the full secure-open validation. */
- for (DWORD wait_ms = 0U, waited_ms = 0U;; waited_ms += wait_ms) {
- private_file = launcher_open_regular(execution_path, GENERIC_READ | DELETE, true);
- if (private_file != INVALID_HANDLE_VALUE || GetLastError() != ERROR_SHARING_VIOLATION ||
- waited_ms >= 2000U) {
- break;
- }
- wait_ms = wait_ms == 0U ? 100U : (wait_ms < 1000U ? wait_ms * 2U : wait_ms);
- Sleep(wait_ms);
- }
- 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 &&
- launcher_write_all(context_pipe.server, &handshake_result, 1U) &&
- private_removed;
- bool graceful_failure = explicit_rejection || (payload_ready && !private_removed);
- if (context_pipe.server && context_pipe.server != INVALID_HANDLE_VALUE) {
- (void)CloseHandle(context_pipe.server);
- context_pipe.server = NULL;
- }
- if (!authenticated && created && !graceful_failure) {
- (void)TerminateProcess(child.hProcess, 1U);
- }
- if (private_file != INVALID_HANDLE_VALUE)
- (void)CloseHandle(private_file);
- HANDLE waits[2] = {child.hProcess, parent};
- DWORD wait = created
- ? WaitForMultipleObjects(2U, waits, FALSE, authenticated ? INFINITE : 5000U)
- : WAIT_FAILED;
- bool parent_died = wait == WAIT_OBJECT_0 + 1U;
- if ((wait != WAIT_OBJECT_0 || parent_died) && created) {
- (void)TerminateJobObject(job, 1U);
- (void)WaitForSingleObject(child.hProcess, 5000U);
- }
- DWORD exit_code = 1U;
- bool exit_valid = authenticated && wait == WAIT_OBJECT_0 &&
- GetExitCodeProcess(child.hProcess, &exit_code) != 0;
- if (child.hThread)
- (void)CloseHandle(child.hThread);
- if (child.hProcess)
- (void)CloseHandle(child.hProcess);
- 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;
-}
-
-static HANDLE launcher_parent_liveness_open(void) {
- DWORD self_pid = GetCurrentProcessId();
- HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0U);
- if (snapshot == INVALID_HANDLE_VALUE)
- return NULL;
- PROCESSENTRY32W entry;
- memset(&entry, 0, sizeof(entry));
- entry.dwSize = sizeof(entry);
- DWORD parent_pid = 0U;
- bool found = Process32FirstW(snapshot, &entry) != 0;
- while (found) {
- if (entry.th32ProcessID == self_pid) {
- parent_pid = entry.th32ParentProcessID;
- break;
- }
- found = Process32NextW(snapshot, &entry) != 0;
- }
- (void)CloseHandle(snapshot);
- if (parent_pid == 0U || parent_pid == self_pid)
- return NULL;
- HANDLE parent = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, parent_pid);
- if (!parent || WaitForSingleObject(parent, 0U) != WAIT_TIMEOUT) {
- if (parent)
- (void)CloseHandle(parent);
- return NULL;
- }
- FILETIME self_creation;
- FILETIME self_exit;
- FILETIME self_kernel;
- FILETIME self_user;
- FILETIME parent_creation;
- FILETIME parent_exit;
- FILETIME parent_kernel;
- FILETIME parent_user;
- bool chronological =
- GetProcessTimes(GetCurrentProcess(), &self_creation, &self_exit, &self_kernel,
- &self_user) != 0 &&
- GetProcessTimes(parent, &parent_creation, &parent_exit, &parent_kernel, &parent_user) !=
- 0 &&
- launcher_filetime_value(&parent_creation) <= launcher_filetime_value(&self_creation);
- if (!chronological) {
- (void)CloseHandle(parent);
- return NULL;
- }
- return parent;
-}
-
-static bool launcher_private_payload_path(const wchar_t *canonical_launcher, const wchar_t *payload,
- wchar_t output[CBM_WINDOWS_LAUNCHER_PATH_CAP]) {
- wchar_t directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t state_directory[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t runtime[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!launcher_parent_path(canonical_launcher, directory, CBM_WINDOWS_LAUNCHER_PATH_CAP)) {
- return false;
- }
- int state_written =
- swprintf(state_directory, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\.cbm", directory);
- int runtime_written =
- swprintf(runtime, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\runtime", state_directory);
- int output_written = swprintf(
- output, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"%ls\\activation-%lu-%llu.payload.exe", runtime,
- (unsigned long)GetCurrentProcessId(), (unsigned long long)GetTickCount64());
- if (state_written <= 0 || runtime_written <= 0 || output_written <= 0 ||
- (size_t)state_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||
- (size_t)runtime_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP ||
- (size_t)output_written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- return false;
- }
- HANDLE install_handle = launcher_open_directory_private(directory);
- HANDLE state_handle = launcher_open_directory_private(state_directory);
- bool runtime_created = CreateDirectoryW(runtime, NULL) != 0;
- DWORD runtime_error = runtime_created ? ERROR_SUCCESS : GetLastError();
- HANDLE runtime_handle = (runtime_created || runtime_error == ERROR_ALREADY_EXISTS)
- ? launcher_open_directory_private(runtime)
- : INVALID_HANDLE_VALUE;
- bool directories_valid =
- install_handle != INVALID_HANDLE_VALUE && state_handle != INVALID_HANDLE_VALUE &&
- runtime_handle != INVALID_HANDLE_VALUE && launcher_path_tree_plain(output);
- if (install_handle != INVALID_HANDLE_VALUE)
- (void)CloseHandle(install_handle);
- if (state_handle != INVALID_HANDLE_VALUE)
- (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);
- return false;
- }
- HANDLE source = launcher_open_regular(payload, GENERIC_READ, true);
- HANDLE copy = launcher_open_regular(output, GENERIC_READ | GENERIC_WRITE | DELETE, true);
- BY_HANDLE_FILE_INFORMATION source_info;
- BY_HANDLE_FILE_INFORMATION copy_info;
- LARGE_INTEGER source_size;
- LARGE_INTEGER copy_size;
- bool valid = launcher_file_information(source, &source_info) &&
- launcher_file_information(copy, &copy_info) &&
- GetFileSizeEx(source, &source_size) && GetFileSizeEx(copy, &copy_size) &&
- source_size.QuadPart == copy_size.QuadPart && FlushFileBuffers(copy) != 0;
- if (source != INVALID_HANDLE_VALUE)
- (void)CloseHandle(source);
- if (copy != INVALID_HANDLE_VALUE)
- (void)CloseHandle(copy);
- if (!valid)
- (void)DeleteFileW(output);
- return valid;
-}
-
-/* WHY: See launcher_wide_action; this role parser reads but never owns wmain's
- * mutable argv array. */
-// cppcheck-suppress constParameter
-static int launcher_probe_role(int argc, wchar_t *const argv[]) {
- if (argc != 4 || wcscmp(argv[1], LAUNCHER_PROBE_ARG) != 0)
- return -1;
- wchar_t *ready_end = NULL;
- wchar_t *release_end = NULL;
- unsigned long long ready_raw = wcstoull(argv[2], &ready_end, 16);
- unsigned long long release_raw = wcstoull(argv[3], &release_end, 16);
- if (!ready_end || *ready_end != L'\0' || !release_end || *release_end != L'\0' ||
- ready_raw == 0ULL || release_raw == 0ULL) {
- return 1;
- }
- HANDLE ready = (HANDLE)(uintptr_t)ready_raw;
- HANDLE release = (HANDLE)(uintptr_t)release_raw;
- if (!SetEvent(ready))
- return 1;
- return WaitForSingleObject(release, 30000U) == WAIT_OBJECT_0 ? 0 : 1;
-}
-
-/* WHY: See launcher_wide_action; retain the exact wmain-compatible argv type. */
-// cppcheck-suppress constParameter
-static int launcher_release_descriptor_role(int argc, wchar_t *const argv[]) {
- if (argc != 2 || wcscmp(argv[1], LAUNCHER_RELEASE_DESCRIPTOR_ARG) != 0) {
- return -1;
- }
- wchar_t canonical[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- wchar_t payload[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!launcher_self_path(canonical) || !launcher_adjacent_payload(canonical, payload)) {
- return 1;
- }
- HANDLE launcher_file = launcher_open_regular(canonical, GENERIC_READ, true);
- HANDLE payload_file = launcher_open_regular(payload, GENERIC_READ, true);
- BY_HANDLE_FILE_INFORMATION launcher_information;
- BY_HANDLE_FILE_INFORMATION payload_information;
- bool paths_ready = launcher_file_information(launcher_file, &launcher_information) &&
- launcher_file_information(payload_file, &payload_information) &&
- launcher_path_tree_plain(payload);
- if (launcher_file != INVALID_HANDLE_VALUE) {
- (void)CloseHandle(launcher_file);
- }
- if (payload_file != INVALID_HANDLE_VALUE) {
- (void)CloseHandle(payload_file);
- }
- if (!paths_ready)
- return 1;
-
- wchar_t command[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- int written =
- swprintf(command, CBM_WINDOWS_LAUNCHER_PATH_CAP, L"\"%ls\" %ls %u", payload,
- PAYLOAD_RELEASE_DESCRIPTOR_ARG, (unsigned int)CBM_WINDOWS_LAUNCHER_ABI_CURRENT);
- if (written <= 0 || (size_t)written >= CBM_WINDOWS_LAUNCHER_PATH_CAP) {
- return 1;
- }
- HANDLE standard[3] = {
- GetStdHandle(STD_INPUT_HANDLE),
- GetStdHandle(STD_OUTPUT_HANDLE),
- GetStdHandle(STD_ERROR_HANDLE),
- };
- bool handles_ready = true;
- for (size_t index = 0U; index < 3U; index++) {
- handles_ready = handles_ready && standard[index] && standard[index] != INVALID_HANDLE_VALUE;
- }
- SIZE_T attribute_size = 0U;
- (void)InitializeProcThreadAttributeList(NULL, 1U, 0U, &attribute_size);
- LPPROC_THREAD_ATTRIBUTE_LIST attributes =
- handles_ready && attribute_size ? malloc(attribute_size) : NULL;
- bool initialized =
- attributes && InitializeProcThreadAttributeList(attributes, 1U, 0U, &attribute_size) != 0;
- bool attributes_ready =
- initialized && UpdateProcThreadAttribute(attributes, 0U, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
- standard, sizeof(standard), NULL, NULL) != 0;
- STARTUPINFOEXW startup;
- PROCESS_INFORMATION child;
- memset(&startup, 0, sizeof(startup));
- memset(&child, 0, sizeof(child));
- startup.StartupInfo.cb = sizeof(startup);
- startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
- startup.StartupInfo.hStdInput = standard[0];
- startup.StartupInfo.hStdOutput = standard[1];
- startup.StartupInfo.hStdError = standard[2];
- startup.lpAttributeList = attributes;
- bool spawned =
- attributes_ready && CreateProcessW(payload, command, NULL, NULL, TRUE,
- CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, NULL,
- NULL, &startup.StartupInfo, &child) != 0;
- if (initialized)
- DeleteProcThreadAttributeList(attributes);
- free(attributes);
- DWORD wait = spawned ? WaitForSingleObject(child.hProcess, 30000U) : WAIT_FAILED;
- if (spawned && wait != WAIT_OBJECT_0) {
- (void)TerminateProcess(child.hProcess, 1U);
- (void)WaitForSingleObject(child.hProcess, 5000U);
- }
- DWORD exit_code = 1U;
- bool valid = spawned && wait == WAIT_OBJECT_0 &&
- GetExitCodeProcess(child.hProcess, &exit_code) != 0 && exit_code == 0U;
- if (child.hThread)
- (void)CloseHandle(child.hThread);
- if (child.hProcess)
- (void)CloseHandle(child.hProcess);
- return valid ? 0 : 1;
-}
-
-int wmain(void) {
- int argc = 0;
- LPWSTR *argv = CommandLineToArgvW(GetCommandLineW(), &argc);
- if (!argv || argc <= 0) {
- if (argv)
- (void)LocalFree(argv);
- return launcher_failure(L"could not parse the Windows command line");
- }
- int descriptor_result = launcher_release_descriptor_role(argc, argv);
- if (descriptor_result >= 0) {
- (void)LocalFree(argv);
- return descriptor_result;
- }
- int probe_result = launcher_probe_role(argc, argv);
- if (probe_result >= 0) {
- (void)LocalFree(argv);
- return probe_result;
- }
- wchar_t canonical[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- if (!launcher_self_path(canonical)) {
- (void)LocalFree(argv);
- return launcher_failure(L"could not securely resolve the launcher path");
- }
- 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");
- }
- 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);
- return launcher_failure(L"portable CBM cannot update or uninstall itself; run install "
- L"first or use your package manager");
- }
-
- wchar_t payload[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- bool path_valid =
- managed ? cbm_windows_generation_payload_path(canonical, state.payload_sha256, payload,
- CBM_WINDOWS_LAUNCHER_PATH_CAP)
- : launcher_adjacent_payload(canonical, payload);
- HANDLE payload_file =
- path_valid ? launcher_open_regular(payload, GENERIC_READ, true) : INVALID_HANDLE_VALUE;
- LARGE_INTEGER payload_size;
- BY_HANDLE_FILE_INFORMATION payload_before;
- bool payload_valid = launcher_file_information(payload_file, &payload_before) &&
- GetFileSizeEx(payload_file, &payload_size) && payload_size.QuadPart > 0 &&
- (!managed || (uint64_t)payload_size.QuadPart == state.payload_size) &&
- launcher_path_tree_plain(payload);
- if (!payload_valid) {
- if (payload_file != INVALID_HANDLE_VALUE)
- (void)CloseHandle(payload_file);
- (void)LocalFree(argv);
- return launcher_failure(L"selected payload is missing, unsafe, or has the wrong size");
- }
- HANDLE payload_recheck = launcher_open_regular(payload, GENERIC_READ, true);
- BY_HANDLE_FILE_INFORMATION payload_after;
- payload_valid = launcher_file_information(payload_recheck, &payload_after) &&
- launcher_same_identity(&payload_before, &payload_after);
- if (payload_recheck != INVALID_HANDLE_VALUE)
- (void)CloseHandle(payload_recheck);
- (void)CloseHandle(payload_file);
- if (!payload_valid) {
- (void)LocalFree(argv);
- return launcher_failure(L"selected payload changed during validation");
- }
-
- bool private_activation = managed && action != CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY;
- wchar_t private_payload[CBM_WINDOWS_LAUNCHER_PATH_CAP];
- const wchar_t *execution = payload;
- if (private_activation) {
- if (!launcher_private_payload_path(canonical, payload, private_payload)) {
- (void)LocalFree(argv);
- return launcher_failure(L"could not create a private activation payload");
- }
- execution = private_payload;
- }
- HANDLE parent = launcher_parent_liveness_open();
- if (!parent) {
- if (private_activation)
- (void)DeleteFileW(private_payload);
- (void)LocalFree(argv);
- return launcher_failure(L"could not establish immediate-parent liveness supervision");
- }
- int result = launcher_spawn_payload(execution, canonical, managed, private_activation, action,
- managed ? &state : NULL, parent, argc, argv);
- (void)CloseHandle(parent);
- if (private_activation)
- (void)DeleteFileW(private_payload);
- (void)LocalFree(argv);
- return result;
-}
-
-#endif /* _WIN32 */
diff --git a/src/main.c b/src/main.c
index 373800bde..b80862e11 100644
--- a/src/main.c
+++ b/src/main.c
@@ -1719,13 +1719,6 @@ int main(int argc, char **argv) {
}
}
#endif
- int windows_descriptor_role = cbm_cli_windows_payload_descriptor_role(argc, argv);
- if (windows_descriptor_role >= 0) {
- return windows_descriptor_role;
- }
- if (cbm_cli_windows_launcher_startup_authenticate(argc, argv) != 0) {
- return EXIT_FAILURE;
- }
cbm_daemon_process_role_t role = cbm_daemon_process_role(argc, argv);
if (role == CBM_DAEMON_PROCESS_INVALID) {
(void)fprintf(stderr, "codebase-memory-mcp: invalid internal process arguments\n");
diff --git a/test-infrastructure/docker-compose.yml b/test-infrastructure/docker-compose.yml
index b4d4e04a4..21a18b8f5 100644
--- a/test-infrastructure/docker-compose.yml
+++ b/test-infrastructure/docker-compose.yml
@@ -198,9 +198,8 @@ services:
command:
- |
scripts/build.sh CC=x86_64-w64-mingw32-clang CXX=x86_64-w64-mingw32-clang++ BUILD_DIR=build/win-cross &&
- mv build/win-cross/codebase-memory-mcp.exe build/win-cross/codebase-memory-mcp.payload.exe &&
- mv build/win-cross/codebase-memory-mcp-launcher.exe build/win-cross/codebase-memory-mcp.exe &&
- WINEDEBUG=-all wine64 ./build/win-cross/codebase-memory-mcp.payload.exe --version &&
+ test ! -e build/win-cross/codebase-memory-mcp.payload.exe &&
+ WINEDEBUG=-all wine64 ./build/win-cross/codebase-memory-mcp.exe --version &&
WINEDEBUG=-all wine64 cmd /c build/win-cross/codebase-memory-mcp.exe --version
# ── Linux portable (Alpine musl static) ────────────────────
diff --git a/test-infrastructure/run.sh b/test-infrastructure/run.sh
index ade190935..b0261a8dc 100755
--- a/test-infrastructure/run.sh
+++ b/test-infrastructure/run.sh
@@ -206,11 +206,11 @@ case "${1:-full}" in
$COMPOSE run --rm -e CBM_SKIP_PERF=1 test-portable
;;
windows)
- echo "=== Windows: cross-compile + launcher/payload version check (Wine) ==="
+ echo "=== Windows: cross-compile + binary version check (Wine) ==="
$COMPOSE run --rm smoke-windows
;;
smoke-windows)
- echo "=== Windows: launcher/payload version check (cross-compile + Wine) ==="
+ echo "=== Windows: binary version check (cross-compile + Wine) ==="
$COMPOSE run --rm smoke-windows
;;
amd64)
@@ -237,7 +237,7 @@ case "${1:-full}" in
$COMPOSE run --rm -e CBM_SKIP_PERF=1 test-amd64
$COMPOSE run --rm build-amd64
$COMPOSE run --rm smoke-amd64
- echo "=== Windows: cross-compile + launcher/payload version check (Wine) ==="
+ echo "=== Windows: cross-compile + binary version check (Wine) ==="
$COMPOSE run --rm smoke-windows
print_real_windows_gate
;;
diff --git a/test-infrastructure/vm/provision-windows.sh b/test-infrastructure/vm/provision-windows.sh
index 81cee00f5..7a4691594 100755
--- a/test-infrastructure/vm/provision-windows.sh
+++ b/test-infrastructure/vm/provision-windows.sh
@@ -110,7 +110,7 @@ else
vm "clangarm64" "git clone --branch ${BRANCH} --single-branch --depth 200 ${REPO_URL} /c/cbm && cd /c/cbm && git log --oneline -1"
fi
-step "5/6 build: native ARM64 binary + launcher + test-runner (no ASan on arm64)"
+step "5/6 build: native ARM64 binary + test-runner (no ASan on arm64)"
vm "clangarm64" "cd /c/cbm && make -j${JOBS} -f Makefile.cbm CC=clang CXX=clang++ SANITIZE= cbm build/c/test-runner > /tmp/provision-build.log 2>&1 && echo BUILD_OK || (echo BUILD_FAIL; tail -15 /tmp/provision-build.log; exit 1)"
step "6/6 smoke: binary + test-runner start"
diff --git a/test-infrastructure/vm/vm-smoke.sh b/test-infrastructure/vm/vm-smoke.sh
index 881469366..b2dd2176e 100755
--- a/test-infrastructure/vm/vm-smoke.sh
+++ b/test-infrastructure/vm/vm-smoke.sh
@@ -6,7 +6,7 @@
#
# Stages and serves a complete Windows release fixture from a profile-rooted
# directory. MSYS2 /tmp and the shared runner workspace are intentionally not
-# valid launcher bundle roots.
+# valid install roots.
#
# Run inside the VM's CLANGARM64 shell from the repo root:
# bash test-infrastructure/vm/vm-smoke.sh
@@ -19,7 +19,7 @@ Usage: [env] bash test-infrastructure/vm/vm-smoke.sh
The canonical WINDOWS smoke entry: identical in local CI (win.sh
smoke-install), PR CI (pr.yml) and the release venues (_smoke.yml). Stages a
-complete launcher+payload release fixture under a disposable profile root,
+complete single-binary release fixture under a disposable profile root,
serves it on a kernel-assigned port, prepares/verifies/cleans the user-PATH
registry via windows-user-path-guard.ps1, neutralizes every agent-config
destination override, then runs scripts/smoke-test.sh (all phases).
@@ -33,11 +33,11 @@ Environment:
binary cannot pass a ui run.
CBM_SMOKE_ARTIFACT_DIR
Release mode: an EXTRACTED windows release artifact
- (codebase-memory-mcp.exe + .payload.exe + LICENSE +
- install.ps1 + THIRD_PARTY_NOTICES.md). All five are required
- and served verbatim — an incomplete archive fails the smoke.
- Unset (default): stages the freshly built launcher/payload
- out of build/c and synthesizes the sidecars (local/PR mode).
+ (codebase-memory-mcp.exe + LICENSE + install.ps1 +
+ THIRD_PARTY_NOTICES.md). All four are required and served
+ verbatim — an incomplete archive fails the smoke.
+ Unset (default): stages the freshly built binary out of
+ build/c and synthesizes the sidecars (local/PR mode).
On failure the smoke root is preserved for post-mortem (path printed).
EOF
@@ -51,27 +51,22 @@ cd "$(dirname "$0")/../.."
ROOT="$PWD"
# Two staging sources, one smoke. Unset (the local + PR default): stage the
-# freshly built launcher/payload out of build/c and synthesize the release
-# sidecars. Set: stage an EXTRACTED release artifact verbatim, so the release
+# freshly built binary out of build/c and synthesize the release sidecars. Set: stage an EXTRACTED release artifact verbatim, so the release
# venue smokes the bytes it is about to publish rather than a local rebuild of
# them. Requiring the sidecars here also makes an incomplete archive a smoke
# failure instead of a discovery made after publishing.
ARTIFACT_DIR="${CBM_SMOKE_ARTIFACT_DIR:-}"
if [ -n "$ARTIFACT_DIR" ]; then
ARTIFACT_DIR="$(cd "$ARTIFACT_DIR" && pwd)"
- for required in codebase-memory-mcp.exe codebase-memory-mcp.payload.exe \
+ for required in codebase-memory-mcp.exe \
LICENSE install.ps1 THIRD_PARTY_NOTICES.md; do
[ -s "$ARTIFACT_DIR/$required" ] ||
{ echo "vm-smoke: release artifact is missing $required" >&2; exit 2; }
done
- LAUNCHER_SRC="$ARTIFACT_DIR/codebase-memory-mcp.exe"
- PAYLOAD_SRC="$ARTIFACT_DIR/codebase-memory-mcp.payload.exe"
+ BINARY_SRC="$ARTIFACT_DIR/codebase-memory-mcp.exe"
else
- LAUNCHER_SRC="build/c/codebase-memory-mcp-launcher.exe"
- PAYLOAD_SRC="build/c/codebase-memory-mcp.exe"
- for binary in "$LAUNCHER_SRC" "$PAYLOAD_SRC"; do
- [ -x "$binary" ] || { echo "build first; missing $binary" >&2; exit 2; }
- done
+ BINARY_SRC="build/c/codebase-memory-mcp.exe"
+ [ -x "$BINARY_SRC" ] || { echo "build first; missing $BINARY_SRC" >&2; exit 2; }
fi
SMOKE_ARCH="${SMOKE_ARCH:-arm64}"
@@ -149,10 +144,8 @@ MSYS2_ARG_CONV_EXCL='*' powershell.exe -NoProfile -ExecutionPolicy Bypass \
-RunId "$PATH_RUN_ID" \
-SnapshotPath "$(cygpath -w "$PATH_SNAPSHOT")" \
-SmokeRoot "$(cygpath -w "$SMOKE_DIR")"
-cp "$LAUNCHER_SRC" "$SMOKE_DIR/codebase-memory-mcp.exe"
-cp "$PAYLOAD_SRC" "$SMOKE_DIR/codebase-memory-mcp.payload.exe"
-cp "$SMOKE_DIR/codebase-memory-mcp.exe" \
- "$SMOKE_DIR/codebase-memory-mcp.payload.exe" "$FIXTURE_DIR/"
+cp "$BINARY_SRC" "$SMOKE_DIR/codebase-memory-mcp.exe"
+cp "$SMOKE_DIR/codebase-memory-mcp.exe" "$FIXTURE_DIR/"
# The install/update phases fetch these out of the served archive, so they must
# be the artifact's own copies whenever one was supplied — regenerating them
# here would smoke a sidecar the release never ships.
@@ -168,8 +161,7 @@ EXPECTED_ARTIFACT="codebase-memory-mcp${SUFFIX}-windows-${SMOKE_ARCH}.zip"
(
cd "$FIXTURE_DIR"
zip -q "$EXPECTED_ARTIFACT" \
- codebase-memory-mcp.exe codebase-memory-mcp.payload.exe \
- LICENSE install.ps1 THIRD_PARTY_NOTICES.md
+ codebase-memory-mcp.exe LICENSE install.ps1 THIRD_PARTY_NOTICES.md
if [ -n "$SUFFIX" ]; then
cp "$EXPECTED_ARTIFACT" "codebase-memory-mcp-windows-${SMOKE_ARCH}.zip"
fi
diff --git a/test-infrastructure/vm/win.sh b/test-infrastructure/vm/win.sh
index ed9179a49..c64264adc 100755
--- a/test-infrastructure/vm/win.sh
+++ b/test-infrastructure/vm/win.sh
@@ -196,7 +196,7 @@ sync)
;;
build)
# The canonical build entry, exactly as CI runs it: a CLEAN scripts/build.sh
- # (product binary + launcher). ccache engages through env.sh's masquerade
+ # (the single product binary). ccache engages through env.sh's masquerade
# (content-verified, so a warm cache only accelerates, never goes stale) —
# NOT via CC='ccache clang', which bypassed the verified-cache env layer.
# The test-runner is no longer built here: the test leg (scripts/test.sh)
@@ -213,8 +213,8 @@ test)
vm clangarm64 "cd /c/cbm && bash test-infrastructure/vm/vm-run-tests.sh $*"
;;
guards)
- # Match the Windows CI product build: a clean, embedded-UI payload plus the
- # permanent launcher. Passing those freshly built artifacts to the maintained
+ # Match the Windows CI product build: a clean, embedded-UI product binary.
+ # Passing that freshly built artifact to the maintained
# PowerShell driver prevents an earlier non-UI `win.sh build` from silently
# turning product guards into precondition skips. BUILD_DIR isolates the
# clean product build from build/c, which build.sh would otherwise wipe —
@@ -230,7 +230,7 @@ guards)
# 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"
+ 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 -Make C:\\msys64\\usr\\bin\\make.exe"
;;
smoke-install)
# EXACTLY the PR CI smoke job (pr.yml pr-smoke windows): a clean canonical
diff --git a/tests/test_cli.c b/tests/test_cli.c
index 647efe24a..3edb18c84 100644
--- a/tests/test_cli.c
+++ b/tests/test_cli.c
@@ -465,10 +465,10 @@ static cbm_cli_activation_ops_t cli_activation_fake_ops(cli_activation_fake_t *f
/* Every install/update/uninstall in this suite dispatches through here. On
* Windows a test that has not installed its own activation ops gets a default
- * fake for the duration of the command: without the seam, the portable-payload
- * gate (correctly) refuses managed mutations before the shared agent-config
- * logic these tests verify ever runs. POSIX behavior is untouched — tests
- * without ops keep exercising the real activation machinery. */
+ * fake for the duration of the command: without the seam, `update` (correctly)
+ * hands off to install.ps1 before the shared agent-config logic these tests
+ * verify ever runs. POSIX behavior is untouched — tests without ops keep
+ * exercising the real activation machinery. */
static cli_activation_fake_t g_cli_test_seam_fake;
static cbm_cli_activation_ops_t g_cli_test_seam_ops;
@@ -3688,249 +3688,6 @@ static unsigned char *create_test_zip_stored(const char *filename, const unsigne
return zip;
}
-static void test_zip_put_u16(unsigned char *output, uint16_t value) {
- output[0] = (unsigned char)value;
- output[1] = (unsigned char)(value >> 8);
-}
-
-static void test_zip_put_u32(unsigned char *output, uint32_t value) {
- output[0] = (unsigned char)value;
- output[1] = (unsigned char)(value >> 8);
- output[2] = (unsigned char)(value >> 16);
- output[3] = (unsigned char)(value >> 24);
-}
-
-typedef struct {
- const char *name;
- const unsigned char *content;
- size_t content_size;
-} test_zip_entry_t;
-
-static unsigned char *create_test_zip_entries(const test_zip_entry_t *entries, size_t entry_count,
- int *out_len) {
- enum { TEST_ZIP_ENTRY_MAX = 8 };
- if (!entries || !out_len || entry_count == 0 || entry_count > TEST_ZIP_ENTRY_MAX) {
- return NULL;
- }
- size_t local_size = 0;
- size_t central_size = 0;
- for (size_t index = 0; index < entry_count; index++) {
- size_t name_size = strlen(entries[index].name);
- local_size += 30U + name_size + entries[index].content_size;
- central_size += 46U + name_size;
- }
- size_t total = local_size + central_size + 22U;
- if (total > INT_MAX) {
- return NULL;
- }
- unsigned char *zip = calloc(1, total);
- if (!zip) {
- return NULL;
- }
- uint32_t local_offsets[TEST_ZIP_ENTRY_MAX];
- uint32_t crcs[TEST_ZIP_ENTRY_MAX];
- size_t cursor = 0;
- for (size_t index = 0; index < entry_count; index++) {
- size_t name_size = strlen(entries[index].name);
- local_offsets[index] = (uint32_t)cursor;
- crcs[index] =
- (uint32_t)crc32(0L, entries[index].content, (uInt)entries[index].content_size);
- zip[cursor] = 0x50;
- zip[cursor + 1U] = 0x4b;
- zip[cursor + 2U] = 0x03;
- zip[cursor + 3U] = 0x04;
- test_zip_put_u16(zip + cursor + 4U, 20U);
- test_zip_put_u32(zip + cursor + 14U, crcs[index]);
- test_zip_put_u32(zip + cursor + 18U, (uint32_t)entries[index].content_size);
- test_zip_put_u32(zip + cursor + 22U, (uint32_t)entries[index].content_size);
- test_zip_put_u16(zip + cursor + 26U, (uint16_t)name_size);
- memcpy(zip + cursor + 30U, entries[index].name, name_size);
- cursor += 30U + name_size;
- memcpy(zip + cursor, entries[index].content, entries[index].content_size);
- cursor += entries[index].content_size;
- }
-
- size_t central_offset = cursor;
- for (size_t index = 0; index < entry_count; index++) {
- size_t name_size = strlen(entries[index].name);
- zip[cursor] = 0x50;
- zip[cursor + 1U] = 0x4b;
- zip[cursor + 2U] = 0x01;
- zip[cursor + 3U] = 0x02;
- test_zip_put_u16(zip + cursor + 4U, 20U);
- test_zip_put_u16(zip + cursor + 6U, 20U);
- test_zip_put_u32(zip + cursor + 16U, crcs[index]);
- test_zip_put_u32(zip + cursor + 20U, (uint32_t)entries[index].content_size);
- test_zip_put_u32(zip + cursor + 24U, (uint32_t)entries[index].content_size);
- test_zip_put_u16(zip + cursor + 28U, (uint16_t)name_size);
- test_zip_put_u32(zip + cursor + 42U, local_offsets[index]);
- memcpy(zip + cursor + 46U, entries[index].name, name_size);
- cursor += 46U + name_size;
- }
- size_t central_length = cursor - central_offset;
- zip[cursor] = 0x50;
- zip[cursor + 1U] = 0x4b;
- zip[cursor + 2U] = 0x05;
- zip[cursor + 3U] = 0x06;
- test_zip_put_u16(zip + cursor + 8U, (uint16_t)entry_count);
- test_zip_put_u16(zip + cursor + 10U, (uint16_t)entry_count);
- test_zip_put_u32(zip + cursor + 12U, (uint32_t)central_length);
- test_zip_put_u32(zip + cursor + 16U, (uint32_t)central_offset);
- *out_len = (int)total;
- return zip;
-}
-
-static unsigned char *create_test_zip_pair(const test_zip_entry_t entries[2], int *out_len) {
- return create_test_zip_entries(entries, 2U, out_len);
-}
-
-static unsigned char *create_test_windows_release_zip(const char *launcher_name,
- const char *payload_name, int *out_len) {
- static const unsigned char launcher[] = "MZ-launcher";
- static const unsigned char payload[] = "MZ-payload";
- static const unsigned char license[] = "license";
- static const unsigned char installer[] = "installer";
- static const unsigned char notices[] = "notices";
- test_zip_entry_t entries[5] = {
- {
- .name = launcher_name,
- .content = launcher,
- .content_size = sizeof(launcher) - 1U,
- },
- {
- .name = payload_name,
- .content = payload,
- .content_size = sizeof(payload) - 1U,
- },
- {"LICENSE", license, sizeof(license) - 1U},
- {"install.ps1", installer, sizeof(installer) - 1U},
- {"THIRD_PARTY_NOTICES.md", notices, sizeof(notices) - 1U},
- };
- return create_test_zip_entries(entries, 5U, out_len);
-}
-
-TEST(cli_extract_windows_release_pair_rejects_incomplete_release_namespace) {
- static const unsigned char launcher[] = "MZ-launcher";
- static const unsigned char payload[] = "MZ-payload";
- const test_zip_entry_t entries[2] = {
- {"codebase-memory-mcp.exe", launcher, sizeof(launcher) - 1U},
- {"codebase-memory-mcp.payload.exe", payload, sizeof(payload) - 1U},
- };
- int zip_length = 0;
- unsigned char *zip = create_test_zip_pair(entries, &zip_length);
- ASSERT_NOT_NULL(zip);
- cbm_windows_release_pair_t pair;
- ASSERT_FALSE(cbm_extract_windows_release_pair_from_zip(zip, zip_length, &pair));
- cbm_windows_release_pair_free(&pair);
- free(zip);
- PASS();
-}
-
-/* Release archives retain their legal notices and the standalone installer.
- * The updater must accept that exact official namespace while extracting only
- * the launcher/payload pair. Synthetic two-file fixtures previously hid that
- * every published Windows update would be rejected. */
-TEST(cli_extract_windows_release_pair_accepts_official_release_namespace) {
- static const unsigned char launcher[] = "MZ-launcher";
- static const unsigned char payload[] = "MZ-payload";
- static const unsigned char license[] = "license";
- static const unsigned char installer[] = "installer";
- static const unsigned char notices[] = "notices";
- const test_zip_entry_t entries[] = {
- {"codebase-memory-mcp.exe", launcher, sizeof(launcher) - 1U},
- {"codebase-memory-mcp.payload.exe", payload, sizeof(payload) - 1U},
- {"LICENSE", license, sizeof(license) - 1U},
- {"install.ps1", installer, sizeof(installer) - 1U},
- {"THIRD_PARTY_NOTICES.md", notices, sizeof(notices) - 1U},
- };
- int zip_length = 0;
- unsigned char *zip =
- create_test_zip_entries(entries, sizeof(entries) / sizeof(entries[0]), &zip_length);
- ASSERT_NOT_NULL(zip);
- cbm_windows_release_pair_t pair;
- ASSERT_TRUE(cbm_extract_windows_release_pair_from_zip(zip, zip_length, &pair));
- ASSERT_EQ(pair.launcher_len, 11);
- ASSERT_EQ(pair.payload_len, 10);
- ASSERT_MEM_EQ(pair.launcher, "MZ-launcher", 11);
- ASSERT_MEM_EQ(pair.payload, "MZ-payload", 10);
- cbm_windows_release_pair_free(&pair);
- free(zip);
- PASS();
-}
-
-TEST(cli_extract_windows_release_pair_rejects_unknown_release_member) {
- static const unsigned char content[] = "x";
- const test_zip_entry_t entries[] = {
- {"codebase-memory-mcp.exe", content, sizeof(content) - 1U},
- {"codebase-memory-mcp.payload.exe", content, sizeof(content) - 1U},
- {"LICENSE", content, sizeof(content) - 1U},
- {"install.ps1", content, sizeof(content) - 1U},
- {"unexpected.dll", content, sizeof(content) - 1U},
- };
- int zip_length = 0;
- unsigned char *zip =
- create_test_zip_entries(entries, sizeof(entries) / sizeof(entries[0]), &zip_length);
- ASSERT_NOT_NULL(zip);
- cbm_windows_release_pair_t pair;
- ASSERT_FALSE(cbm_extract_windows_release_pair_from_zip(zip, zip_length, &pair));
- cbm_windows_release_pair_free(&pair);
- free(zip);
- PASS();
-}
-
-TEST(cli_extract_windows_release_pair_rejects_aliases_and_duplicates) {
- static const struct {
- const char *launcher;
- const char *payload;
- } attacks[] = {
- {
- "CODEBASE-MEMORY-MCP.EXE",
- "codebase-memory-mcp.payload.exe",
- },
- {
- "codebase-memory-mcp.exe",
- "codebase-memory-mcp.exe",
- },
- {
- ".\\codebase-memory-mcp.exe",
- "codebase-memory-mcp.payload.exe",
- },
- {
- "codebase-memory-mcp.exe.",
- "codebase-memory-mcp.payload.exe",
- },
- {
- "codebase-memory-mcp.exe",
- "codebase-memory-mcp.payload.exe ",
- },
- };
- for (size_t index = 0; index < sizeof(attacks) / sizeof(attacks[0]); index++) {
- int zip_length = 0;
- unsigned char *zip = create_test_windows_release_zip(attacks[index].launcher,
- attacks[index].payload, &zip_length);
- ASSERT_NOT_NULL(zip);
- cbm_windows_release_pair_t pair;
- ASSERT_FALSE(cbm_extract_windows_release_pair_from_zip(zip, zip_length, &pair));
- cbm_windows_release_pair_free(&pair);
- free(zip);
- }
- PASS();
-}
-
-TEST(cli_extract_windows_release_pair_rejects_local_central_mismatch) {
- int zip_length = 0;
- unsigned char *zip = create_test_windows_release_zip(
- "codebase-memory-mcp.exe", "codebase-memory-mcp.payload.exe", &zip_length);
- ASSERT_NOT_NULL(zip);
- /* Local name starts at offset 30; central metadata remains unchanged. */
- zip[30] = 'x';
- cbm_windows_release_pair_t pair;
- ASSERT_FALSE(cbm_extract_windows_release_pair_from_zip(zip, zip_length, &pair));
- cbm_windows_release_pair_free(&pair);
- free(zip);
- PASS();
-}
-
TEST(cli_extract_binary_from_zip) {
const char *content = "#!/bin/sh\necho test\n";
int zip_len = 0;
@@ -11950,12 +11707,14 @@ TEST(cli_sha256_file_matches_known_vector) {
}
#ifdef _WIN32
-/* The fail-closed release contract, asserted with the activation seam OFF:
- * these calls take the exact dispatch a release binary ships (the portable
- * body is unreachable), so the gates themselves keep direct unit coverage. */
-TEST(cli_windows_release_gates_refuse_portable_mutations) {
- char tmpdir[256];
- snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-portable-refusal-XXXXXX");
+/* The Windows update contract, asserted with the activation seam OFF so this
+ * takes the exact dispatch a release binary ships: `update` never replaces the
+ * running image in-process (Windows locks it), it prints the install.ps1
+ * command and exits 0. Regressing to an in-process self-update would mean
+ * reintroducing the launcher stub Defender flags as Trojan:Win32/Wacatac.B!ml. */
+TEST(cli_windows_update_hands_off_to_install_script) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-update-handoff-XXXXXX");
if (!cbm_mkdtemp(tmpdir)) {
FAIL("cbm_mkdtemp failed");
}
@@ -11972,61 +11731,17 @@ TEST(cli_windows_release_gates_refuse_portable_mutations) {
snprintf(bin_dir, sizeof(bin_dir), "%s/.local/bin", tmpdir);
test_mkdirp(bin_dir);
snprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp.exe", bin_dir);
- write_test_file(bin_target, "portable refusal must not touch this");
+ write_test_file(bin_target, "in-process update must not touch this");
- /* A one-shot portable payload (this test runner has no launcher context)
- * may never self-mutate a managed surface. */
- char *uninstall_argv[] = {"--yes"};
- int uninstall_rc = cbm_cmd_uninstall(1, uninstall_argv);
char *update_argv[] = {"--yes"};
int update_rc = cbm_cmd_update(1, update_argv);
const char *installed = read_test_file(bin_target);
- bool preserved = installed && strcmp(installed, "portable refusal must not touch this") == 0;
- cli_activation_restore_env(old_home, old_cache);
- test_rmdir_r(tmpdir);
-
- ASSERT_EQ(uninstall_rc, 1);
- ASSERT_EQ(update_rc, 1);
- ASSERT_TRUE(preserved);
- PASS();
-}
-
-TEST(cli_windows_release_gate_refuses_foreign_install_target) {
- char tmpdir[256];
- snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-foreign-target-XXXXXX");
- if (!cbm_mkdtemp(tmpdir)) {
- FAIL("cbm_mkdtemp failed");
- }
- char *old_home = NULL;
- char *old_cache = NULL;
- cli_activation_save_env(&old_home, &old_cache);
- cbm_setenv("HOME", tmpdir, 1);
- char cache_dir[512];
- snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);
- cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);
-
- char bin_dir[512];
- char bin_target[640];
- snprintf(bin_dir, sizeof(bin_dir), "%s/.local/bin", tmpdir);
- test_mkdirp(bin_dir);
- snprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp.exe", bin_dir);
- write_test_file(bin_target, "foreign binary must be preserved");
-
- /* An unmanaged file at the canonical launcher path is a conflict the
- * managed transaction refuses to adopt or replace — even under --force
- * with prompts auto-answered. */
- cbm_set_auto_answer_for_test(-1);
- char *argv[] = {"--force", "-y"};
- int rc = cbm_cmd_install(2, argv);
- cbm_set_auto_answer_for_test(0);
-
- const char *installed = read_test_file(bin_target);
- bool preserved = installed && strcmp(installed, "foreign binary must be preserved") == 0;
+ bool preserved = installed && strcmp(installed, "in-process update must not touch this") == 0;
cli_activation_restore_env(old_home, old_cache);
test_rmdir_r(tmpdir);
- ASSERT_EQ(rc, 1);
+ ASSERT_EQ(update_rc, 0);
ASSERT_TRUE(preserved);
PASS();
}
@@ -12070,8 +11785,7 @@ SUITE(cli) {
RUN_TEST(cli_uninstall_preserves_binary_and_index_when_cohort_does_not_drain);
RUN_TEST(cli_activation_guard_is_bypassed_for_dry_run_and_plan);
#ifdef _WIN32
- RUN_TEST(cli_windows_release_gates_refuse_portable_mutations);
- RUN_TEST(cli_windows_release_gate_refuses_foreign_install_target);
+ RUN_TEST(cli_windows_update_hands_off_to_install_script);
#endif
/* Version (2 tests — selfupdate_test.go) */
@@ -12159,11 +11873,6 @@ SUITE(cli) {
RUN_TEST(cli_extract_binary_from_targz_not_found);
RUN_TEST(cli_extract_binary_from_targz_invalid_data);
RUN_TEST(cli_extract_binary_from_zip);
- RUN_TEST(cli_extract_windows_release_pair_rejects_incomplete_release_namespace);
- RUN_TEST(cli_extract_windows_release_pair_accepts_official_release_namespace);
- RUN_TEST(cli_extract_windows_release_pair_rejects_unknown_release_member);
- RUN_TEST(cli_extract_windows_release_pair_rejects_aliases_and_duplicates);
- RUN_TEST(cli_extract_windows_release_pair_rejects_local_central_mismatch);
RUN_TEST(cli_extract_binary_from_zip_not_found);
RUN_TEST(cli_extract_binary_from_zip_path_traversal);
RUN_TEST(cli_extract_binary_from_zip_invalid);
diff --git a/tests/test_main.c b/tests/test_main.c
index d153f0b4c..6d6c3b3d1 100644
--- a/tests/test_main.c
+++ b/tests/test_main.c
@@ -682,7 +682,6 @@ extern void suite_config_toml_edit(void);
extern void suite_config_yaml_edit(void);
extern void suite_config_text_edit(void);
extern void suite_activation_transaction(void);
-extern void suite_windows_launcher_state(void);
extern void suite_system_info(void);
extern void suite_worker_pool(void);
extern void suite_parallel(void);
@@ -949,7 +948,6 @@ int main(int argc, char **argv) {
RUN_SELECTED_SUITE(config_yaml_edit);
RUN_SELECTED_SUITE(config_text_edit);
RUN_SELECTED_SUITE(activation_transaction);
- RUN_SELECTED_SUITE(windows_launcher_state);
/* System info + worker pool (parallelism) */
RUN_SELECTED_SUITE(system_info);
diff --git a/tests/test_smoke_fixture_contract.sh b/tests/test_smoke_fixture_contract.sh
index fdf707453..9b5ade76d 100755
--- a/tests/test_smoke_fixture_contract.sh
+++ b/tests/test_smoke_fixture_contract.sh
@@ -163,16 +163,20 @@ require(
"fixture checksums must name exact artifact basenames, never ./-prefixed paths",
)
-# Native Windows packages and serves the exact five-file release bundle, then
-# runs the full smoke from a protected profile-rooted directory/cache.
+# Native Windows packages and serves the exact four-file release bundle (ONE
+# binary, like every other platform), then runs the full smoke from a protected
+# profile-rooted directory/cache.
for name in (
"codebase-memory-mcp.exe",
- "codebase-memory-mcp.payload.exe",
"LICENSE",
"install.ps1",
"THIRD_PARTY_NOTICES.md",
):
require(name in vm_smoke, f"vm-smoke.sh archive must include {name}")
+require(
+ "codebase-memory-mcp.payload.exe" not in vm_smoke,
+ "vm-smoke.sh must not stage a Windows launcher/payload pair",
+)
require("checksums.txt" in vm_smoke, "vm-smoke.sh must generate checksums.txt")
require(
"SMOKE_DOWNLOAD_URL=" in vm_smoke
@@ -245,17 +249,21 @@ for service in ("smoke-windows:",):
)
section = match.group("body") if match else ""
require(
- "mv build/win-cross/codebase-memory-mcp.exe "
- "build/win-cross/codebase-memory-mcp.payload.exe" in section
- and "mv build/win-cross/codebase-memory-mcp-launcher.exe "
- "build/win-cross/codebase-memory-mcp.exe" in section,
- f"docker-compose {service[:-1]} must assemble the Windows launcher/payload pair",
+ "codebase-memory-mcp-launcher" not in section
+ and "codebase-memory-mcp.payload.exe" not in section.replace(
+ "test ! -e build/win-cross/codebase-memory-mcp.payload.exe", ""
+ ),
+ f"docker-compose {service[:-1]} must build ONE Windows binary, not a launcher/payload pair",
+ )
+ require(
+ "test ! -e build/win-cross/codebase-memory-mcp.payload.exe" in section,
+ f"docker-compose {service[:-1]} must assert no payload sibling is produced",
)
require(
- "wine64 ./build/win-cross/codebase-memory-mcp.payload.exe --version" in compose
+ "wine64 ./build/win-cross/codebase-memory-mcp.exe --version" in compose
and "wine64 cmd /c build/win-cross/codebase-memory-mcp.exe --version" in compose,
- "docker-compose Windows cross-smoke must execute the payload through Wine and the launcher "
- "through a Wine Windows parent",
+ "docker-compose Windows cross-smoke must execute the single binary through Wine and through a "
+ "Wine Windows parent",
)
require(
"soak-windows:" not in compose,
diff --git a/tests/test_venue_parity_contract.sh b/tests/test_venue_parity_contract.sh
index 84a75509c..11cac18da 100755
--- a/tests/test_venue_parity_contract.sh
+++ b/tests/test_venue_parity_contract.sh
@@ -98,9 +98,8 @@ ALLOWED_CMDS = {
# CI plumbing
"gh", "python3", "node", "codesign", "xcrun", "command", "awk",
}
-# Per-file additions: _build.yml packages artifacts (its make invocation builds
-# the launcher exe for the zip — packaging, not a test leg) and drives npm for
-# the embedded UI; release.yml pushes finished artifacts to registries after
+# Per-file additions: _build.yml packages artifacts (make/strip are packaging
+# steps, not test legs) and drives npm for the embedded UI; release.yml pushes finished artifacts to registries after
# every product-exercising gate already ran; the brew tap smoke installs the
# released formula.
ALLOWED_EXTRA = {
diff --git a/tests/test_vm_worktree_manifest.sh b/tests/test_vm_worktree_manifest.sh
index 5bda13e22..d858c2737 100644
--- a/tests/test_vm_worktree_manifest.sh
+++ b/tests/test_vm_worktree_manifest.sh
@@ -116,16 +116,15 @@ if ! grep -Fq "JOBS='\$(nproc)'" "$provisioner" ||
exit 1
fi
guards_block="$(sed -n '/^guards)/,/^ ;;/p' "$driver")"
-# The guards leg builds the CI-shaped product payload (embedded UI + launcher)
-# into an isolated BUILD_DIR, then hands those artifacts to the maintained
+# The guards leg builds the CI-shaped product binary (embedded UI) into an
+# isolated BUILD_DIR, then hands that artifact 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 -NoProfile -ExecutionPolicy Bypass -File scripts\\test-windows.ps1' \
<<<"$guards_block" ||
- ! grep -Fq -- '-GuardsOnly -Binary build\\guards\\codebase-memory-mcp.exe' <<<"$guards_block" ||
- ! grep -Fq -- '-Launcher build\\guards\\codebase-memory-mcp-launcher.exe' <<<"$guards_block"; then
+ ! grep -Fq -- '-GuardsOnly -Binary build\\guards\\codebase-memory-mcp.exe' <<<"$guards_block"; then
echo "FAIL: Windows VM guards must delegate to the maintained native-Windows driver" >&2
exit 1
fi
diff --git a/tests/test_windows_bundle_contract.sh b/tests/test_windows_bundle_contract.sh
index 7ebcf8c69..780c13027 100644
--- a/tests/test_windows_bundle_contract.sh
+++ b/tests/test_windows_bundle_contract.sh
@@ -1,10 +1,28 @@
#!/usr/bin/env bash
-# Static release-surface contract for the Windows permanent launcher.
+# INVERTED release-surface contract: Windows ships ONE binary.
#
-# This intentionally inspects the checked-in packaging sources. Native
-# launcher behavior is covered separately on Windows; this guard makes it hard
-# for a release/package edit to silently put the managed launcher where a
-# portable wrapper expects the payload (or omit one half of the release pair).
+# History this guards against. The Windows release used to be a PAIR — a small
+# permanent launcher (codebase-memory-mcp.exe) plus the real product binary
+# (codebase-memory-mcp.payload.exe). The launcher existed for exactly one
+# reason: a running .exe cannot replace its own image on Windows, so an
+# in-process self-update needs a second resident binary to do the swap.
+#
+# That stub is statically indistinguishable from a dropper — a small unsigned
+# PE whose whole job is verify-and-execute another binary — and Defender's ML
+# scored it Trojan:Win32/Wacatac.B!ml on x64 regardless of what we changed
+# (bcrypt-free, stripped, VERSIONINFO'd and even resource-free builds were all
+# flagged), while the product binary itself scans clean on every platform.
+#
+# The fix removed the stub and moved self-update OUT of the process into
+# install.ps1, which runs while CBM is NOT running. So this file asserts the
+# ABSENCE of the flagged design, plus the one step that replaces it:
+# install.ps1 must RETIRE the running binary (rename it out of the way) before
+# publishing the new one — losing that step silently breaks every Windows
+# update.
+#
+# The non-launcher release/security assertions from the previous contract
+# (VM-driver hardening, archive allowlists, HTTPS-only downloads, profile-rooted
+# smoke fixtures, PR-smoke delegation) are preserved below.
set -euo pipefail
@@ -32,121 +50,6 @@ 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()
@@ -170,221 +73,158 @@ def yaml_run_blocks(text: str) -> list[str]:
return blocks
-launcher = "codebase-memory-mcp.exe"
+binary = "codebase-memory-mcp.exe"
payload = "codebase-memory-mcp.payload.exe"
-windows_archive_names = (
- launcher,
+windows_archive_names = (binary, "LICENSE", "install.ps1", "THIRD_PARTY_NOTICES.md")
+
+# ── 1. The archive is exactly four files, defined in ONE place ───────────────
+# Every venue (release build, local artifact-flow smoke) produces archives
+# through scripts/package-release.sh, so the layout is asserted where it is
+# defined and cannot fork per venue.
+package_release = read("scripts/package-release.sh")
+zip_call = re.search(
+ r"zip -q \"\$OUT_DIR/\$NAME\.zip\" \\\n(?P<members>(?:.|\n)*?)\n", package_release
+)
+require(zip_call is not None, "package-release.sh must build the Windows zip in one zip call")
+zip_members = zip_call.group("members").split() if zip_call else []
+require(
+ zip_members == list(windows_archive_names),
+ "package-release.sh must archive EXACTLY "
+ f"{' '.join(windows_archive_names)} (found: {' '.join(zip_members) or 'nothing'})",
+)
+
+# ── 2. No shipped surface may name the payload or build a launcher ───────────
+# These are every file that decides what the Windows release contains or how a
+# Windows install is assembled. A single reappearance of the payload name (or
+# of a launcher build/copy) means the flagged two-binary design is back.
+launcher_markers = (
payload,
- "LICENSE",
+ "codebase-memory-mcp-launcher",
+ "windows_launcher_state",
+ "src/launcher/",
+)
+shipped_surfaces = (
+ "scripts/package-release.sh",
"install.ps1",
- "THIRD_PARTY_NOTICES.md",
+ "pkg/npm/install.js",
+ "pkg/npm/bin.js",
+ "pkg/pypi/src/codebase_memory_mcp/_cli.py",
+ ".github/workflows/_build.yml",
)
+for relative in shipped_surfaces:
+ source = read(relative)
+ for marker in launcher_markers:
+ require(
+ marker not in source,
+ f"{relative} must not reference '{marker}': Windows ships ONE binary and the "
+ "launcher stub is what Defender flagged as Trojan:Win32/Wacatac.B!ml",
+ )
-# Every Windows archive (standard/UI, x64/ARM64) is a five-file bundle containing
-# the executable pair plus the three release/legal files. Check the producing run
-# block itself so an attestation or comment cannot accidentally satisfy it.
-build_workflow = read(".github/workflows/_build.yml")
-build_blocks = yaml_run_blocks(build_workflow)
-archives = (
- "codebase-memory-mcp-windows-amd64.zip",
- "codebase-memory-mcp-ui-windows-amd64.zip",
- "codebase-memory-mcp-windows-arm64.zip",
- "codebase-memory-mcp-ui-windows-arm64.zip",
-)
-# The five-file layout lives in the ONE canonical packaging entry; every venue
-# (release build and the local artifact-flow smoke lane) produces archives
-# through it, so the bundle layout is asserted where it is defined and cannot
-# fork per venue.
-package_release = read("scripts/package-release.sh")
+# The stub sources themselves must stay deleted, and the build must not carry a
+# rule that could resurrect them.
+for relative in (
+ "src/launcher/windows_launcher.c",
+ "src/launcher/windows_launcher.rc",
+ "src/cli/windows_launcher_state.c",
+ "src/cli/windows_launcher_state.h",
+ "tests/test_windows_launcher_state.c",
+):
+ require(
+ not (root / relative).exists(),
+ f"{relative} must stay deleted — the Windows launcher stub is gone for good",
+ )
+makefile = read("Makefile.cbm")
require(
- all(name in package_release for name in windows_archive_names),
- "package-release.sh must archive the exact official five-file Windows bundle",
+ "codebase-memory-mcp-launcher" not in makefile and "WINDOWS_LAUNCHER" not in makefile,
+ "Makefile.cbm must not expose a Windows launcher target or variable",
)
+
+# Each archive variant is still produced through the ONE canonical packaging
+# entry, so the four-file layout above governs all of them.
+build_workflow = read(".github/workflows/_build.yml")
for archive, call, ui in (
- ("codebase-memory-mcp-windows-amd64.zip",
- "scripts/package-release.sh windows amd64", False),
+ ("codebase-memory-mcp-windows-amd64.zip", "scripts/package-release.sh windows amd64", False),
("codebase-memory-mcp-ui-windows-amd64.zip",
"scripts/package-release.sh windows amd64 --variant ui", True),
- ("codebase-memory-mcp-windows-arm64.zip",
- "scripts/package-release.sh windows arm64", False),
+ ("codebase-memory-mcp-windows-arm64.zip", "scripts/package-release.sh windows arm64", False),
("codebase-memory-mcp-ui-windows-arm64.zip",
"scripts/package-release.sh windows arm64 --variant ui", True),
):
- # The packaging steps are single-line runs (invisible to yaml_run_blocks,
- # which collects block scalars only), so associate archive -> call on the
- # workflow text; the lookahead keeps a ui call from satisfying a std check.
+ # The lookahead keeps a ui call from satisfying a standard check.
pattern = re.escape(call) + ("" if ui else r"(?!\s+--variant)")
require(
re.search(pattern, build_workflow) is not None,
f"_build.yml must produce {archive} via the canonical packaging entry ('{call}')",
)
-# install.ps1 must preserve the complete adjacent pair and enter the native
-# process through the downloaded launcher. The launcher owns containment and
-# resolves the payload; invoking the payload directly bypasses that boundary.
+# ── 3. install.ps1 retires the running binary before publishing ──────────────
+# This is THE step that replaces the launcher. Windows keeps an image lock on a
+# running .exe: it cannot be overwritten, but it CAN be renamed out of the way.
+# install.ps1 runs while CBM is not running, renames the installed binary to
+# "<dest>.retired-<timestamp>", then installs over the freed name. Without the
+# retire step every Windows update fails on a locked destination.
installer = read("install.ps1")
require(
- "$DownloadedLauncher = Join-Path $TmpDir $BinName" in installer
- and "$DownloadedPayload = Join-Path $TmpDir $PayloadName" in installer
- and "Test-Path -LiteralPath $DownloadedLauncher -PathType Leaf" in installer
- and "Test-Path -LiteralPath $DownloadedPayload -PathType Leaf" in installer,
- "install.ps1 must retain an adjacent downloaded launcher/payload pair",
+ "$Dest = Join-Path $InstallDir $BinName" in installer,
+ "install.ps1 must resolve the canonical install destination as $Dest",
+)
+retire_match = re.search(
+ r"if \(Test-Path -LiteralPath \$Dest -PathType Leaf\) \{(?P<body>(?:.|\n)*?)\n\}\n",
+ installer,
+)
+retire = retire_match.group("body") if retire_match else ""
+require(
+ retire_match is not None
+ and re.search(r"\$retired\s*=\s*\"\$Dest\.retired-", retire) is not None
+ and "Move-Item -LiteralPath $Dest -Destination $retired" in retire,
+ "install.ps1 must RETIRE the running binary (Move-Item $Dest -> $retired) before "
+ "publishing the new one — a running .exe cannot be overwritten in place",
)
require(
- "& $DownloadedLauncher --version" in installer
- and "& $DownloadedLauncher @InstallArgs" in installer
- and "& $DownloadedPayload @InstallArgs" not in installer,
- "install.ps1 must verify and install through the downloaded launcher",
+ retire_match is not None and "$renamed" in retire and "exit 1" in retire,
+ "install.ps1 must fail loudly when the running binary cannot be retired",
+)
+publish_index = installer.find("& $DownloadedBinary @InstallArgs")
+require(
+ publish_index > (retire_match.start() if retire_match else -1) >= 0,
+ "install.ps1 must retire BEFORE it publishes the downloaded binary",
+)
+require(
+ "& $DownloadedBinary --version" in installer
+ and "& $DownloadedBinary @InstallArgs" in installer,
+ "install.ps1 must verify and install through the downloaded binary",
)
-# Package-manager shims are intentionally one-shot portable instances on
-# Windows. Their downloaders validate both release executables adjacently in a
-# private temporary directory, cache the immutable pair for a later managed
-# install transition, and execute the launcher. They must not create or
-# interpret managed generation state themselves.
-portable_cache_contracts = {
+# ── 4. Package-manager shims resolve the single Windows binary ───────────────
+single_binary_contracts = {
"pkg/npm/install.js": (
- r"const\s+WINDOWS_PAYLOAD_NAME\s*=\s*['\"]codebase-memory-mcp\.payload\.exe['\"]",
- r"binName\s*=\s*platform\s*===\s*['\"]windows['\"]\s*\?\s*WINDOWS_PAYLOAD_NAME",
+ r"const\s+WINDOWS_BINARY_NAME\s*=\s*['\"]codebase-memory-mcp\.exe['\"]",
+ r"installWindowsBinaryAtomically\(",
+ r"windowsBinaryReady\(",
),
"pkg/npm/bin.js": (
- r"binName\s*=\s*isWindows\s*\?\s*['\"]codebase-memory-mcp\.payload\.exe['\"]",
+ r"binName\s*=\s*isWindows\s*\?\s*['\"]codebase-memory-mcp\.exe['\"]",
+ r"const\s+executionPath\s*=\s*binPath",
),
"pkg/pypi/src/codebase_memory_mcp/_cli.py": (
- r"_WINDOWS_PAYLOAD_NAME\s*=\s*['\"]codebase-memory-mcp\.payload\.exe['\"]",
- r"def\s+_bin_path[\s\S]{0,500}_WINDOWS_PAYLOAD_NAME\s+if\s+sys\.platform\s*==\s*['\"]win32['\"]",
- ),
- "pkg/go/cmd/codebase-memory-mcp/main.go": (
- r"windowsPayloadName\s*=\s*['\"]codebase-memory-mcp\.payload\.exe['\"]",
- r"if\s+runtime\.GOOS\s*==\s*['\"]windows['\"][\s\S]{0,300}name\s*=\s*windowsPayloadName",
+ r"_WINDOWS_BINARY_NAME\s*=\s*['\"]codebase-memory-mcp\.exe['\"]",
+ r"def\s+_windows_binary_ready\(",
),
}
-for relative, patterns in portable_cache_contracts.items():
+for relative, patterns in single_binary_contracts.items():
source = read(relative)
require(
- payload in source
- and all(re.search(pattern, source, re.DOTALL) for pattern in patterns),
- f"{relative} must retain {payload} as the Windows cache readiness path",
+ all(re.search(pattern, source, re.DOTALL) for pattern in patterns),
+ f"{relative} must resolve the single Windows binary",
)
require(
".cbm/generations" not in source and "current-v1" not in source,
f"{relative} must remain portable and not own managed launcher state",
)
-# Portable package shims keep an immutable, exact-version launcher/payload pair.
-# The launcher resolves its adjacent payload for every native command.
-# Concurrent first-run contenders publish launcher first and payload last;
-# payload is therefore the readiness signal. npm and Go serialize pair repair,
-# preserve any complete runnable winner, and roll back only bytes proven to
-# belong to their own transaction. PyPI uses identical-byte collision checks.
-immutable_pair_cache_contracts = {
- "pkg/npm/install.js": (
- "const cacheNames = platform === 'windows'",
- "const lock = acquireWindowsPairLock(destDir)",
- "publishedDigests.set(name, stagedDigests.get(name))",
- "if (digest && pathMatchesDigest(target, digest))",
- ),
- "pkg/pypi/src/codebase_memory_mcp/_cli.py": (
- "cache_names = extraction_names",
- "publish_names = (",
- "_files_equal_sha256",
- ),
- "pkg/go/cmd/codebase-memory-mcp/main.go": (
- "installWindowsPairAtomically(tmp, filepath.Dir(dest))",
- "lock, err := acquireWindowsPairLock(dstDir)",
- "publishedDigests[name] = stagedDigests[name]",
- "if ok && pathMatchesSHA256(target, digest)",
- ),
-}
-for relative, needles in immutable_pair_cache_contracts.items():
- source = read(relative)
- require(
- all(needle in source for needle in needles),
- f"{relative} must publish an immutable exact-version Windows pair with {payload} last",
- )
- require(
- "publishedPaths" not in source
- and "published_paths" not in source
- and "const published = []" not in source,
- f"{relative} must not roll back published destinations by pathname",
- )
-
-npm_installer = read("pkg/npm/install.js")
-require(
- "for (const name of [WINDOWS_LAUNCHER_NAME, WINDOWS_PAYLOAD_NAME])" in npm_installer
- and "windowsPairReady(destDir, verifier)" in npm_installer
- and "publishedDigests.set(name, stagedDigests.get(name))" in npm_installer
- and "if (digest && pathMatchesDigest(target, digest))" in npm_installer,
- "npm must publish launcher then payload, preserve a coherent winner, and "
- "roll back only transaction-owned bytes",
-)
-python_wrapper = read("pkg/pypi/src/codebase_memory_mcp/_cli.py")
-require(
- re.search(
- r"publish_names = \(\s*\(_WINDOWS_LAUNCHER_NAME, "
- r"_WINDOWS_PAYLOAD_NAME\)",
- python_wrapper,
- ) is not None
- and "_files_equal_sha256(staged_paths[name], target)" in python_wrapper,
- "PyPI must publish launcher then payload and only accept an identical collision",
-)
-go_wrapper = read("pkg/go/cmd/codebase-memory-mcp/main.go")
-require(
- "names := []string{windowsLauncherName, windowsPayloadName}" in go_wrapper
- and "windowsPairReady(dstDir, verifier)" in go_wrapper
- and "publishedDigests[name] = stagedDigests[name]" in go_wrapper
- and "if ok && pathMatchesSHA256(target, digest)" in go_wrapper,
- "Go must publish launcher then payload, preserve a coherent winner, and "
- "roll back only transaction-owned bytes",
-)
-
-npm_shim = read("pkg/npm/bin.js")
-require(
- "launcherPath" in npm_shim
- and "windowsLauncherName" in npm_shim
- and "fs.existsSync(launcherPath)" in npm_shim,
- "pkg/npm/bin.js readiness must require the adjacent launcher/payload pair",
-)
-require(
- "const executionPath = isWindows ? launcherPath : binPath" in npm_shim
- and "spawnSync(executionPath, process.argv.slice(2)" in npm_shim
- and "spawnSync(binPath, process.argv.slice(2)" not in npm_shim,
- "npm must execute Windows commands through the adjacent launcher",
-)
-require(
- "verifyCandidate(extractedPaths.get(WINDOWS_LAUNCHER_NAME))" in npm_installer
- and "if (platform === 'windows' && windowsPairReady(BIN_DIR)) return;" in npm_installer
- and "verifier(launcher)" in npm_installer,
- "npm must validate extracted and cached Windows pairs through the launcher",
-)
-require(
- "_windows_pair_ready" in python_wrapper,
- "PyPI readiness must require and validate the adjacent launcher/payload pair",
-)
-require(
- "return payload.with_name(_WINDOWS_LAUNCHER_NAME)" in python_wrapper
- and "execution_path = _execution_path(bin_path, sys.platform)" in python_wrapper
- and "args = [str(execution_path)] + sys.argv[1:]" in python_wrapper
- and "result = subprocess.run(args)" in python_wrapper
- and "args = [str(bin_path)] + sys.argv[1:]" not in python_wrapper,
- "PyPI must execute Windows commands through the adjacent launcher",
-)
-require(
- "windowsLauncherPath" in go_wrapper
- and "installWindowsPairAtomically" in go_wrapper,
- "Go readiness must require and validate the adjacent launcher/payload pair",
-)
-require(
- "return filepath.Join(filepath.Dir(payload), windowsLauncherName)" in go_wrapper
- and "return executionPathForOS(payload, runtime.GOOS), nil" in go_wrapper
- and "execBinary(executable, os.Args[1:])" in go_wrapper,
- "Go must execute Windows commands through the adjacent launcher",
-)
-
# All package downloaders parse the Windows archive against the exact official
-# five-root-file allowlist. Portable wrappers privately validate the executable
-# pair and cache that pair immutably; they may not silently ignore an
-# attacker-controlled sixth member.
+# four-root-file allowlist; they may not silently ignore an attacker-controlled
+# fifth member.
exact_archive_guards = {
"install.ps1": (
"$seen.Count -ne $WindowsArchiveNames.Count",
@@ -394,8 +234,7 @@ exact_archive_guards = {
),
"pkg/npm/install.js": (
"$seen.Count -ne $requiredNames.Count",
- "WINDOWS_LAUNCHER_NAME",
- "WINDOWS_PAYLOAD_NAME",
+ "WINDOWS_BINARY_NAME",
"'LICENSE'",
"'install.ps1'",
"THIRD_PARTY_NOTICES.md",
@@ -403,16 +242,7 @@ exact_archive_guards = {
"pkg/pypi/src/codebase_memory_mcp/_cli.py": (
"name not in required_set",
"len(seen) != len(required)",
- "_WINDOWS_LAUNCHER_NAME",
- "_WINDOWS_PAYLOAD_NAME",
- '"LICENSE"',
- '"install.ps1"',
- "THIRD_PARTY_NOTICES.md",
- ),
- "pkg/go/cmd/codebase-memory-mcp/main.go": (
- "len(seen) != len(archiveNames)",
- "windowsLauncherName",
- "windowsPayloadName",
+ "_WINDOWS_BINARY_NAME",
'"LICENSE"',
'"install.ps1"',
"THIRD_PARTY_NOTICES.md",
@@ -422,11 +252,11 @@ for relative, needles in exact_archive_guards.items():
source = read(relative)
require(
all(needle in source for needle in needles),
- f"{relative} must reject every Windows zip namespace except the official five-file allowlist",
+ f"{relative} must reject every Windows zip namespace except the official four-file "
+ "allowlist",
)
-# A portable mutation refusal must point to the owning package manager and to
-# the explicit one-time transition into managed mode.
+# A portable mutation refusal must point to the owning package manager.
guidance_contracts = {
"pkg/npm/bin.js": (
"npm install codebase-memory-mcp@latest",
@@ -438,11 +268,6 @@ guidance_contracts = {
"python -m pip uninstall codebase-memory-mcp",
"install --yes",
),
- "pkg/go/cmd/codebase-memory-mcp/main.go": (
- "go install github.com/DeusData/codebase-memory-mcp/pkg/go/cmd/codebase-memory-mcp@latest",
- "Remove-Item (Get-Command codebase-memory-mcp).Source",
- "codebase-memory-mcp install --yes",
- ),
}
for relative, needles in guidance_contracts.items():
source = read(relative)
@@ -451,39 +276,32 @@ for relative, needles in guidance_contracts.items():
f"{relative} must provide actionable package and managed-install guidance",
)
-# Native Windows regression coverage moves from the transient activation helper
-# to the permanent launcher suite.
+# ── 5. Native Windows guard coverage of the replacement contract ─────────────
windows_test_driver = read("scripts/test-windows.ps1")
require(
- "tests\\windows\\test_windows_launcher.py" in windows_test_driver
- or "tests/windows/test_windows_launcher.py" in windows_test_driver,
- "scripts/test-windows.ps1 must run tests/windows/test_windows_launcher.py",
+ "tests\\windows\\test_windows_update_handoff.py" in windows_test_driver
+ or "tests/windows/test_windows_update_handoff.py" in windows_test_driver,
+ "scripts/test-windows.ps1 must run tests/windows/test_windows_update_handoff.py",
)
require(
- "test_cli_activation_helper.py" not in windows_test_driver,
- "scripts/test-windows.ps1 must not run the legacy transient activation-helper test",
+ "test_windows_launcher.py" not in windows_test_driver
+ and "test_cli_activation_helper.py" not in windows_test_driver,
+ "scripts/test-windows.ps1 must not run the retired launcher guards",
)
require(
- all(
- needle in windows_test_driver
- for needle in (
- 'Copy-Item -LiteralPath $launcherBin -Destination $guardBin',
- 'Copy-Item -LiteralPath $bin -Destination $guardPayload',
- '& $py $t $guardBin',
- '& $py $t $guardBin $guardPayload $abiMismatchLauncher',
- )
- ),
- "ordinary native Windows guards must execute a staged launcher/payload release pair",
+ 'Copy-Item -LiteralPath $bin -Destination $guardBin' in windows_test_driver
+ and "$guardPayload" not in windows_test_driver,
+ "native Windows guards must stage exactly one executable",
)
require(
- windows_test_driver.count("| Out-Host") >= 3
- and windows_test_driver.count("$buildExit = $LASTEXITCODE") >= 3,
+ windows_test_driver.count("| Out-Host") >= 1
+ and windows_test_driver.count("$buildExit = $LASTEXITCODE") >= 1,
"Windows build helpers must not leak compiler output into returned artifact paths",
)
require(
- '$code -eq 1 -or $t -eq "tests\\windows\\test_windows_launcher.py"'
+ '$code -eq 1 -or $t -eq "tests\\windows\\test_windows_update_handoff.py"'
in windows_test_driver,
- "the permanent-launcher guard must fail instead of skip on driver/precondition errors",
+ "the update-handoff guard must fail instead of skip on driver/precondition errors",
)
require(
all(
@@ -498,8 +316,8 @@ require(
'Remove-Item -LiteralPath $guardRoot -Recurse -Force',
)
),
- "Windows launcher guards must keep staged and Python-created fixtures "
- "beneath the current account profile",
+ "Windows guards must keep staged and Python-created fixtures beneath the current "
+ "account profile",
)
require(
'$guardRoot = $null\ntry {\n $userProfile = '
@@ -507,297 +325,80 @@ require(
in windows_test_driver
and 'if ($guardRoot) {\n Remove-Item -LiteralPath $guardRoot -Recurse -Force'
in windows_test_driver,
- "Windows launcher guard setup must be covered by profile-fixture cleanup",
+ "Windows guard setup must be covered by profile-fixture cleanup",
)
# The hosted runner profile can itself be trusted while newly-created children
# still inherit mutation-capable principals. Require the guard root to replace
# that inherited DACL with a protected, current-account-owned ACL before any
-# launcher bundle or Python temporary descendants are created below it.
-guard_root_creation = (
- 'New-Item -ItemType Directory -Path $guardRoot | Out-Null'
-)
-guard_bundle_creation = '$guardBundle = Join-Path $guardRoot '
+# staged executable or Python temporary descendant is created below it.
+guard_root_creation = "New-Item -ItemType Directory -Path $guardRoot | Out-Null"
+guard_bundle_creation = "$guardBundle = Join-Path $guardRoot "
acl_start = windows_test_driver.find(guard_root_creation)
acl_end = windows_test_driver.find(guard_bundle_creation, acl_start + 1)
guard_acl_setup = (
- windows_test_driver[acl_start:acl_end]
- if acl_start >= 0 and acl_end > acl_start
- else ""
+ windows_test_driver[acl_start:acl_end] if acl_start >= 0 and acl_end > acl_start else ""
)
require(
all(
needle in guard_acl_setup
for needle in (
- '[System.Security.Principal.WindowsIdentity]::GetCurrent().User',
- '[System.Security.AccessControl.DirectorySecurity]::new()',
- '$guardAcl.SetOwner($currentSid)',
- '$guardAcl.SetAccessRuleProtection($true, $false)',
- '[System.Security.AccessControl.FileSystemRights]::FullControl',
- '[System.Security.AccessControl.InheritanceFlags]::ContainerInherit',
- '[System.Security.AccessControl.InheritanceFlags]::ObjectInherit',
- '[System.Security.AccessControl.PropagationFlags]::None',
- '[System.Security.AccessControl.AccessControlType]::Allow',
- 'Set-Acl -LiteralPath $guardRoot -AclObject $guardAcl',
- )
- ),
- "Windows launcher guards must protect the guard-root DACL and grant only "
- "the current account inheritable full control before creating descendants",
-)
-
-# Launcher supervision has two distinct failure directions: killing the
-# launcher must kill its payload job, and killing only the launcher's immediate
-# parent must terminate the launcher plus every descendant. Require the native
-# test to invoke both probes, not merely define helpers that never run.
-windows_launcher_test = read("tests/windows/test_windows_launcher.py")
-unsafe_acl_test = windows_launcher_test[
- windows_launcher_test.find("def assert_untrusted_ancestor_acl_rejected(") :
- windows_launcher_test.find("\ndef process_entries()")
-]
-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(") >= 2
- and "server.proc.kill()" in windows_launcher_test
- and "wait_for_process_exit(child_pid" in windows_launcher_test,
- "native Windows coverage must kill the launcher and reject an orphaned payload",
-)
-require(
- windows_launcher_test.count(
- "assert_immediate_parent_death_contains_launcher_tree("
- ) >= 2
- and '"--launcher-parent-probe"' in windows_launcher_test
- and "wrapper.kill()" in windows_launcher_test
- and "wait_for_process_exit(launcher_pid" in windows_launcher_test,
- "native Windows coverage must kill the immediate parent and reject a surviving launcher tree",
-)
-
-launcher_source = read("src/launcher/windows_launcher.c")
-require(
- "JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE" in launcher_source
- and "PROC_THREAD_ATTRIBUTE_JOB_LIST" in launcher_source
- and "launcher_parent_liveness_open" in launcher_source
- and "WaitForMultipleObjects" in launcher_source
- and "TerminateJobObject" in launcher_source,
- "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",
+ "[System.Security.Principal.WindowsIdentity]::GetCurrent().User",
+ "[System.Security.AccessControl.DirectorySecurity]::new()",
+ "$guardAcl.SetOwner($currentSid)",
+ "$guardAcl.SetAccessRuleProtection($true, $false)",
+ "[System.Security.AccessControl.FileSystemRights]::FullControl",
+ "[System.Security.AccessControl.InheritanceFlags]::ContainerInherit",
+ "[System.Security.AccessControl.InheritanceFlags]::ObjectInherit",
+ "[System.Security.AccessControl.PropagationFlags]::None",
+ "[System.Security.AccessControl.AccessControlType]::Allow",
+ "Set-Acl -LiteralPath $guardRoot -AclObject $guardAcl",
)
),
- "launcher-context consumption must bind PID/creation/file identity and diagnose each file-auth "
- "stage",
+ "Windows guards must protect the guard-root DACL and grant only the current account "
+ "inheritable full control before creating descendants",
)
-# 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.
+# The native guard must assert the REPLACEMENT contract, not merely exist.
+update_guard = read("tests/windows/test_windows_update_handoff.py")
require(
all(
- needle in launcher_state_source
+ needle in update_guard
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)",
+ '"install.ps1" in lowered',
+ "result.returncode == 0",
+ "sha256_file(binary) == before",
+ "codebase-memory-mcp.payload.exe",
)
),
- "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",
+ "the native update guard must assert exit 0, the printed install.ps1 command, an "
+ "unchanged own image, and the absence of a payload sibling",
)
+# ── 6. Native path-tree trust boundary (unchanged, launcher-independent) ─────
require(
all(
- needle in windows_launcher_test
+ needle in read("src/daemon/ipc.c")
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",
+ "win_directory_component_secure",
+ "win_file_security_secure(security, directory, false, mutation)",
+ "win_private_mutation_rights()",
+ "~((DWORD)FILE_ADD_SUBDIRECTORY)",
+ "FILE_ADD_FILE",
+ "FILE_DELETE_CHILD",
+ "final runtime",
+ "ACCESS_SYSTEM_SECURITY",
+ "956008885U",
+ "FILE_ATTRIBUTE_REPARSE_POINT",
)
),
- "native Windows coverage must exercise interrupted hard-link publication, unlink rollback, "
- "retired cleanup, and immediate reinstall isolation",
+ "src/daemon/ipc.c must enforce the shared cross-account ancestor trust policy",
)
-# 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].
+# 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(
@@ -815,96 +416,133 @@ require(
)
)
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",
+ "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")
-launcher_target = re.search(
- r"(?m)^\s*[^#\n]*codebase-memory-mcp-launcher(?:\.exe|\$\([A-Za-z0-9_]+\))?\s*:",
- makefile,
+# ── 7. Real-Windows local-CI drivers ─────────────────────────────────────────
+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(
- launcher_target is not None,
- "Makefile.cbm must expose a codebase-memory-mcp-launcher executable target",
+ "JOBS='$(nproc)'" in vm_driver,
+ "win.sh must defer nproc expansion to the remote MSYS shell without over-escaping it",
)
-
-# Every native path-tree trust boundary must validate opened ancestor handles,
-# reject reparse points, inspect mutation-capable allow ACEs, and recognize the
-# bounded privileged-principal set (current user, SYSTEM, Administrators, and
-# the fixed TrustedInstaller service SID). The normal C:\\Users ancestor grants
-# cross-account add-subdirectory, so each implementation permits only that
-# right on intermediate components while keeping its final private directory
-# strict. The native tests inject real ACLs; these static markers preserve the
-# narrow exception and its surrounding defenses on non-Windows presubmit hosts.
-ancestor_security_contracts = {
- "src/daemon/ipc.c": (
- "win_directory_component_secure",
- "win_file_security_secure(security, directory, false, mutation)",
- "win_private_mutation_rights()",
- "~((DWORD)FILE_ADD_SUBDIRECTORY)",
- "FILE_ADD_FILE",
- "FILE_DELETE_CHILD",
- "final runtime",
- "ACCESS_SYSTEM_SECURITY",
- "956008885U",
- "FILE_ATTRIBUTE_REPARSE_POINT",
- ),
- "src/cli/windows_launcher_state.c": (
- "windows_owner_secure(component, false)",
- "windows_acl_secure_for_mutation(component, mutation)",
- "windows_private_mutation_rights()",
- "if (index < directory_length)",
- "windows_private_mutation_rights() & ~((DWORD)FILE_ADD_SUBDIRECTORY)",
- "mutation &= ~((DWORD)FILE_ADD_SUBDIRECTORY)",
- "FILE_ADD_FILE",
- "FILE_DELETE_CHILD",
- "immediate parent remains fully private",
- "FILE_READ_ATTRIBUTES | READ_CONTROL",
- "ACCESS_SYSTEM_SECURITY",
- "956008885U",
- "FILE_FLAG_OPEN_REPARSE_POINT",
- ),
- "src/launcher/windows_launcher.c": (
- "launcher_security_is_safe(component, false, mutation)",
- "launcher_private_mutation_rights()",
- "if (index < directory_length)",
- "mutation &= ~((DWORD)FILE_ADD_SUBDIRECTORY)",
- "FILE_ADD_FILE",
- "FILE_DELETE_CHILD",
- "DLL or .exe.local",
- "ACCESS_SYSTEM_SECURITY",
- "956008885U",
- "FILE_FLAG_OPEN_REPARSE_POINT",
- "PIPE_REJECT_REMOTE_CLIENTS",
- ),
-}
-for relative, needles in ancestor_security_contracts.items():
- source = read(relative)
+for relative, source in (
+ ("test-infrastructure/vm/win.sh", vm_driver),
+ ("test-infrastructure/vm/provision-windows.sh", vm_provision),
+):
require(
- all(needle in source for needle in needles),
- f"{relative} must enforce the shared cross-account ancestor trust policy",
+ "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",
+)
+require(
+ "mac-vm)" not in read("test-infrastructure/run.sh")
+ and "CBM_WIN_VM_SSH" not in read("test-infrastructure/run.sh"),
+ "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",
+)
-# Release smoke must run the canonical launcher while preserving the payload it
-# resolves. Requiring both names in the Windows smoke job prevents a test from
-# accidentally continuing to exercise a renamed monolithic payload.
+# ── 8. Release smoke stays profile-rooted and single-binary ──────────────────
smoke_workflow = read(".github/workflows/_smoke.yml")
windows_match = re.search(
- r"(?ms)^ smoke-windows:\s*(.*?)(?=^ [A-Za-z0-9_-]+:\s*$|\Z)",
- smoke_workflow,
+ r"(?ms)^ smoke-windows:\s*(.*?)(?=^ [A-Za-z0-9_-]+:\s*$|\Z)", smoke_workflow
)
windows_smoke = windows_match.group(1) if windows_match else ""
require(bool(windows_smoke), "_smoke.yml must contain the smoke-windows job")
-# The staging/execution behavior lives in the canonical wrapper now; the
-# workflow only provisions the artifact and calls it (venue-parity contract).
vm_smoke = read("test-infrastructure/vm/vm-smoke.sh")
smoke_local = read("scripts/smoke-local.sh")
require(
'scripts/smoke-test.sh "$SMOKE_DIR/codebase-memory-mcp.exe"' in vm_smoke,
- f"Windows smoke wrapper must execute the canonical {launcher}",
+ f"Windows smoke wrapper must execute the canonical {binary}",
)
require(
"bash test-infrastructure/vm/vm-smoke.sh" in windows_smoke
@@ -912,13 +550,8 @@ require(
"Windows release smoke must call the canonical wrapper on the extracted artifact",
)
require(
- launcher in windows_smoke and payload in windows_smoke,
- f"Windows release smoke must retain both {launcher} and {payload}",
-)
-smoke_blocks = yaml_run_blocks(windows_smoke)
-require(
- any("zip" in block and launcher in block and payload in block for block in smoke_blocks),
- "Windows artifact-server smoke archive must contain launcher and payload",
+ f'test ! -e "$ARTIFACT_DIR/{payload}"' in windows_smoke,
+ "Windows release smoke must assert the published archive has no payload sibling",
)
require(
all(
@@ -926,14 +559,14 @@ require(
for needle in (
'PROFILE_ROOT="$(cygpath -u "$USERPROFILE")"',
'SMOKE_DIR="$(mktemp -d "$PROFILE_ROOT/cbm-vm-smoke.XXXXXX")"',
- 'cp "$LAUNCHER_SRC" "$SMOKE_DIR/codebase-memory-mcp.exe"',
- 'cp "$PAYLOAD_SRC" "$SMOKE_DIR/codebase-memory-mcp.payload.exe"',
+ 'cp "$BINARY_SRC" "$SMOKE_DIR/codebase-memory-mcp.exe"',
'CBM_CACHE_DIR="$(cygpath -m "$SMOKE_DIR/cache")"',
'SMOKE_TEMP_ROOT="$SMOKE_DIR"',
)
),
- "Windows smoke wrapper must keep every launcher fixture beneath the current account profile",
+ "Windows smoke wrapper must keep every fixture beneath the current account profile",
)
+smoke_blocks = yaml_run_blocks(windows_smoke)
windows_release_version_blocks = [
re.sub(r"\s+", " ", re.sub(r"\\\s*\n\s*", " ", block)).strip()
for block in smoke_blocks
@@ -945,31 +578,29 @@ require(
needle in windows_release_version_blocks[0]
for needle in (
'PROFILE_ROOT="$(cygpath -u "$USERPROFILE")"',
- 'cp "$ARTIFACT_DIR/codebase-memory-mcp.exe" "$ARTIFACT_DIR/codebase-memory-mcp.payload.exe" "$LAUNCH_DIR/"',
- '"$LAUNCH_DIR/codebase-memory-mcp.payload.exe" --version',
+ 'cp "$ARTIFACT_DIR/codebase-memory-mcp.exe" "$LAUNCH_DIR/"',
'"$LAUNCH_DIR/codebase-memory-mcp.exe" --version',
)
),
- "Windows release version checks must execute the pair beneath the current account profile",
+ "Windows release version checks must execute the single binary beneath the current "
+ "account profile",
)
# RUNNER_TEMP is legitimate ONLY for artifact provisioning/scanning; every
-# launcher fixture and execution must stay beneath the account profile.
+# executable fixture and execution must stay beneath the account profile.
runner_temp_allowed = (
re.compile(r'ARTIFACT_DIR="\$\(cygpath -u "\$RUNNER_TEMP"\)/cbm-artifact"'),
re.compile(r'Join-Path \$env:RUNNER_TEMP "cbm-artifact"'),
)
-runner_temp_lines = [
- line.strip() for line in windows_smoke.splitlines() if "RUNNER_TEMP" in line
-]
+runner_temp_lines = [line.strip() for line in windows_smoke.splitlines() if "RUNNER_TEMP" in line]
require(
bool(runner_temp_lines)
and all(
- any(pattern.search(line) for pattern in runner_temp_allowed)
- for line in runner_temp_lines
+ any(pattern.search(line) for pattern in runner_temp_allowed) for line in runner_temp_lines
)
and 'mktemp -d "$RUNNER_TEMP' not in windows_smoke
and re.search(r'"\$RUNNER_TEMP[^"\n]*\.exe"', windows_smoke) is None,
- "Windows release smoke may use RUNNER_TEMP only to provision/scan the artifact, never as a launcher root",
+ "Windows release smoke may use RUNNER_TEMP only to provision/scan the artifact, never as "
+ "an execution root",
)
windows_release_security_blocks = [
re.sub(r"\s+", " ", re.sub(r"\\\s*\n\s*", " ", block)).strip()
@@ -983,23 +614,21 @@ require(
for needle in (
'PROFILE_ROOT="$(cygpath -u "$USERPROFILE")"',
'SECURITY_DIR="$(mktemp -d "$PROFILE_ROOT/cbm-release-security.XXXXXX")"',
- 'cp "$ARTIFACT_DIR/codebase-memory-mcp.exe" "$ARTIFACT_DIR/codebase-memory-mcp.payload.exe" "$SECURITY_DIR/"',
+ 'cp "$ARTIFACT_DIR/codebase-memory-mcp.exe" "$SECURITY_DIR/"',
'TMPDIR="$SECURITY_DIR" '
'scripts/security-install.sh "$SECURITY_DIR/codebase-memory-mcp.exe"',
)
),
- "Windows release install audit must execute the pair beneath the current account profile",
+ "Windows release install audit must execute the single binary beneath the current "
+ "account profile",
)
-# Native update transport remains HTTPS-only in production. Release smoke may
-# 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.
+# ── 9. Update transport stays HTTPS-only in production ───────────────────────
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",
+ and 'copy_smoke_binary "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"' not in smoke_script,
+ "Windows smoke must leave canonical targets absent for an authenticated install",
)
require(
"smoke_mktemp_file" in smoke_script
@@ -1008,12 +637,17 @@ require(
"smoke-test.sh must route every temporary fixture through its private-root helpers",
)
require(
- 'SMOKE_UPDATE_FIXTURE_DIR' in smoke_script
+ "SMOKE_UPDATE_FIXTURE_DIR" in smoke_script
and 'UPDATE_DOWNLOAD_URL="file://$UPDATE_FIXTURE_DIR"' in smoke_script
and 'UPDATE_DOWNLOAD_URL="file:///$UPDATE_FIXTURE_DIR"' in smoke_script
and 'CBM_DOWNLOAD_URL="$UPDATE_DOWNLOAD_URL"' in smoke_script,
"Phase 14 native update must use an explicit file:// fixture override",
)
+require(
+ "FAIL 14a: Windows update replaced the binary in-process" in smoke_script
+ and 'grep -q "install.ps1" "$UPDATE_LOG"' in smoke_script,
+ "Phase 14 must assert the Windows update handoff instead of an in-process replacement",
+)
require(
'HOME="$WIN_HOME" TEMP="$WIN_HOME" TMP="$WIN_HOME"' in smoke_script
and "MSYS2_ARG_CONV_EXCL='*'" in smoke_script
@@ -1032,16 +666,15 @@ require(
and 'SMOKE_UPDATE_FIXTURE_DIR="$FIXTURE_DIR"' in smoke_local
and "scripts/smoke-local.sh" in smoke_workflow
and smoke_workflow.count("CBM_SMOKE_ARTIFACT_DIR") >= 2,
- "Unix and Windows release smoke must identify their local update fixture via the canonical wrappers",
+ "Unix and Windows release smoke must identify their local update fixture via the "
+ "canonical wrappers",
)
cli_source = read("src/cli/cli.c")
probe_start = cli_source.find("cbm_json_mcp_probe_windows_command_path(")
probe_end = cli_source.find("#endif", probe_start)
safe_command_probe = (
- cli_source[probe_start:probe_end]
- if probe_start >= 0 and probe_end > probe_start
- else ""
+ cli_source[probe_start:probe_end] if probe_start >= 0 and probe_end > probe_start else ""
)
require(
"HANDLE *component_handles" in safe_command_probe
@@ -1053,14 +686,10 @@ require(
"write/delete sharing until the complete local path has been classified",
)
file_override_match = re.search(
- r"static bool cli_download_is_explicit_file_override\(.*?\n}\n",
- cli_source,
- re.DOTALL,
+ r"static bool cli_download_is_explicit_file_override\(.*?\n}\n", cli_source, re.DOTALL
)
protocol_match = re.search(
- r"static const char \*cli_download_protocol\(.*?\n}\n",
- cli_source,
- re.DOTALL,
+ r"static const char \*cli_download_protocol\(.*?\n}\n", cli_source, re.DOTALL
)
file_override = file_override_match.group(0) if file_override_match else ""
protocol = protocol_match.group(0) if protocol_match else ""
@@ -1079,30 +708,39 @@ require(
"production native downloads must remain HTTPS-only",
)
download_helpers = cli_source[
- cli_source.find("static int cbm_download_to_file("):
- cli_source.find("/* ── macOS ad-hoc signing")
+ cli_source.find("static int cbm_download_to_file(") : cli_source.find("/* ── macOS ad-hoc signing")
]
require(
- download_helpers.count('"--proto"') >= 2
- and download_helpers.count('"--proto-redir"') >= 2,
+ download_helpers.count('"--proto"') >= 2 and download_helpers.count('"--proto-redir"') >= 2,
"native curl invocations must pin both initial and redirected protocols",
)
-# PR smoke builds artifacts in-place, then delegates all release-name staging,
-# fixture packaging, and full launcher smoke semantics to the maintained native
-# Windows harness. Keeping those mechanics out of workflow YAML prevents the PR
-# and local-VM paths from silently drifting apart.
-pr_workflow = read(".github/workflows/pr.yml")
-pr_smoke_match = re.search(
- r"(?ms)^ pr-smoke:\s*(.*?)(?=^ [A-Za-z0-9_-]+:\s*$|\Z)",
- pr_workflow,
+# The Windows `update` command must hand off to install.ps1 and must NOT carry
+# an in-process self-update path (which is what required the launcher stub).
+update_start = cli_source.find("int cbm_cmd_update(int argc, char **argv) {")
+update_end = cli_source.find("\n/* ── ", update_start)
+update_windows_block = (
+ cli_source[update_start : update_end if update_end > update_start else len(cli_source)]
)
+require(
+ update_start >= 0
+ and "install.ps1" in update_windows_block
+ and "powershell -ExecutionPolicy Bypass -File" in update_windows_block,
+ "cbm_cmd_update must print the install.ps1 command on Windows",
+)
+require(
+ "cbm_windows_launcher" not in cli_source
+ and "windows_launcher_state.h" not in cli_source,
+ "src/cli/cli.c must not retain any launcher-state API usage",
+)
+
+# ── 10. PR smoke delegates to the maintained native harness ──────────────────
+pr_workflow = read(".github/workflows/pr.yml")
+pr_smoke_match = re.search(r"(?ms)^ pr-smoke:\s*(.*?)(?=^ [A-Za-z0-9_-]+:\s*$|\Z)", pr_workflow)
pr_smoke = pr_smoke_match.group(1) if pr_smoke_match else ""
require(bool(pr_smoke), "pr.yml must contain the pr-smoke job")
pr_windows_blocks = [
- block
- for block in yaml_run_blocks(pr_smoke)
- if "scripts/build.sh CC=clang CXX=clang++" in block
+ block for block in yaml_run_blocks(pr_smoke) if "scripts/build.sh CC=clang CXX=clang++" in block
]
require(
len(pr_windows_blocks) == 1,
@@ -1112,21 +750,17 @@ if pr_windows_blocks:
pr_windows_block = re.sub(r"\\\s*\n\s*", " ", pr_windows_blocks[0])
pr_windows_block = re.sub(r"\s+", " ", pr_windows_block).strip()
require(
- "SMOKE_ARCH=amd64 bash test-infrastructure/vm/vm-smoke.sh"
- in pr_windows_block,
- "Windows PR smoke must invoke the maintained native harness with the "
- "authoritative amd64 artifact architecture",
+ "SMOKE_ARCH=amd64 bash test-infrastructure/vm/vm-smoke.sh" in pr_windows_block,
+ "Windows PR smoke must invoke the maintained native harness with the authoritative "
+ "amd64 artifact architecture",
)
require(
pr_windows_block.find("scripts/build.sh CC=clang CXX=clang++")
- < pr_windows_block.find(
- "SMOKE_ARCH=amd64 bash test-infrastructure/vm/vm-smoke.sh"
- ),
+ < pr_windows_block.find("SMOKE_ARCH=amd64 bash test-infrastructure/vm/vm-smoke.sh"),
"Windows PR smoke must build before invoking the maintained harness",
)
require(
- "scripts/smoke-test.sh" not in pr_windows_block
- and "codebase-memory-mcp.payload.exe" not in pr_windows_block,
+ "scripts/smoke-test.sh" not in pr_windows_block and payload not in pr_windows_block,
"Windows PR workflow must not duplicate vm-smoke staging or smoke-test logic",
)
require(
@@ -1135,10 +769,10 @@ if pr_windows_blocks:
)
if failures:
- print("Windows launcher bundle contract FAILED:", file=sys.stderr)
+ print("Windows single-binary bundle contract FAILED:", file=sys.stderr)
for failure in failures:
print(f" - {failure}", file=sys.stderr)
raise SystemExit(1)
-print("Windows launcher bundle contract passed")
+print("Windows single-binary bundle contract passed")
PY
diff --git a/tests/test_windows_launcher_state.c b/tests/test_windows_launcher_state.c
deleted file mode 100644
index b040c6427..000000000
--- a/tests/test_windows_launcher_state.c
+++ /dev/null
@@ -1,450 +0,0 @@
-/*
- * test_windows_launcher_state.c — Permanent Windows launcher state contract.
- *
- * This suite exercises the stable public byte contract for the managed Windows
- * layout: a tiny launcher reads one fixed current-v1 record and resolves the
- * immutable payload generation
- * relative to its own location. Keep these pure helpers platform-independent
- * so the record format and command policy are exercised on every CI host.
- */
-#include "test_framework.h"
-
-#include <cli/windows_launcher_state.h>
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <string.h>
-#include <wchar.h>
-
-static const char launcher_sha256[] = "0123456789abcdef0123456789abcdef"
- "0123456789abcdef0123456789abcdef";
-
-static cbm_windows_current_v1_t launcher_valid_state(void) {
- cbm_windows_current_v1_t state;
- memset(&state, 0, sizeof(state));
- state.launcher_abi_min = 1;
- state.launcher_abi_max = 3;
- state.payload_size = UINT64_C(0x0102030405060708);
- memcpy(state.payload_sha256, launcher_sha256, sizeof(launcher_sha256));
- return state;
-}
-
-static bool launcher_memory_is_zero(const void *memory, size_t size) {
- const uint8_t *bytes = memory;
- for (size_t index = 0; index < size; index++) {
- if (bytes[index] != 0) {
- return false;
- }
- }
- return true;
-}
-
-static void launcher_put_u32_le(uint8_t *out, uint32_t value) {
- out[0] = (uint8_t)value;
- out[1] = (uint8_t)(value >> 8);
- out[2] = (uint8_t)(value >> 16);
- out[3] = (uint8_t)(value >> 24);
-}
-
-static void launcher_put_u64_le(uint8_t *out, uint64_t value) {
- for (unsigned int index = 0; index < 8U; index++) {
- out[index] = (uint8_t)(value >> (index * 8U));
- }
-}
-
-static cbm_windows_release_descriptor_v1_t launcher_valid_descriptor(void) {
- cbm_windows_release_descriptor_v1_t descriptor;
- memset(&descriptor, 0, sizeof(descriptor));
- descriptor.launcher_abi = 2U;
- descriptor.payload_launcher_abi_min = 1U;
- descriptor.payload_launcher_abi_max = 3U;
- descriptor.payload_size = UINT64_C(0x0102030405060708);
- memcpy(descriptor.payload_sha256, launcher_sha256, sizeof(launcher_sha256));
- return descriptor;
-}
-
-TEST(windows_release_descriptor_v1_encoding_is_exact_and_round_trips) {
- cbm_windows_release_descriptor_v1_t descriptor = launcher_valid_descriptor();
- uint8_t actual[CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE];
- uint8_t expected[CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE];
- memset(expected, 0, sizeof(expected));
- memcpy(expected, "CBMWRD1\0", 8U);
- launcher_put_u32_le(expected + 8U, 1U);
- launcher_put_u32_le(expected + 12U, CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE);
- launcher_put_u32_le(expected + 16U, descriptor.launcher_abi);
- launcher_put_u32_le(expected + 20U, descriptor.payload_launcher_abi_min);
- launcher_put_u32_le(expected + 24U, descriptor.payload_launcher_abi_max);
- launcher_put_u64_le(expected + 32U, descriptor.payload_size);
- memcpy(expected + 40U, launcher_sha256, 64U);
- ASSERT_TRUE(cbm_windows_release_descriptor_v1_encode(&descriptor, actual));
- ASSERT_MEM_EQ(actual, expected, sizeof(actual));
-
- cbm_windows_release_descriptor_v1_t decoded;
- ASSERT_TRUE(cbm_windows_release_descriptor_v1_decode(actual, sizeof(actual), &decoded));
- ASSERT_EQ(decoded.launcher_abi, descriptor.launcher_abi);
- ASSERT_EQ(decoded.payload_launcher_abi_min, descriptor.payload_launcher_abi_min);
- ASSERT_EQ(decoded.payload_launcher_abi_max, descriptor.payload_launcher_abi_max);
- ASSERT_EQ(decoded.payload_size, descriptor.payload_size);
- ASSERT_STR_EQ(decoded.payload_sha256, descriptor.payload_sha256);
- PASS();
-}
-
-TEST(windows_release_descriptor_v1_rejects_noncanonical_or_incompatible) {
- cbm_windows_release_descriptor_v1_t descriptor = launcher_valid_descriptor();
- uint8_t record[CBM_WINDOWS_RELEASE_DESCRIPTOR_V1_SIZE];
- ASSERT_TRUE(cbm_windows_release_descriptor_v1_encode(&descriptor, record));
- record[28] = 1U;
- ASSERT_FALSE(cbm_windows_release_descriptor_v1_decode(record, sizeof(record), &descriptor));
- record[28] = 0U;
- record[104] = 1U;
- ASSERT_FALSE(cbm_windows_release_descriptor_v1_decode(record, sizeof(record), &descriptor));
-
- descriptor = launcher_valid_descriptor();
- descriptor.launcher_abi = 4U;
- ASSERT_FALSE(cbm_windows_release_descriptor_v1_encode(&descriptor, record));
- descriptor = launcher_valid_descriptor();
- descriptor.payload_launcher_abi_min = 0U;
- ASSERT_FALSE(cbm_windows_release_descriptor_v1_encode(&descriptor, record));
- PASS();
-}
-
-TEST(windows_transition_plan_requires_a_crash_safe_compatibility_bridge) {
- cbm_windows_current_v1_t current = launcher_valid_state();
- cbm_windows_release_descriptor_v1_t candidate = launcher_valid_descriptor();
-
- current.launcher_abi_min = 1U;
- current.launcher_abi_max = 1U;
- candidate.launcher_abi = 1U;
- candidate.payload_launcher_abi_min = 1U;
- candidate.payload_launcher_abi_max = 1U;
- ASSERT_EQ(cbm_windows_transition_plan(&current, &candidate),
- CBM_WINDOWS_TRANSITION_LAUNCHER_FIRST);
-
- candidate.launcher_abi = 2U;
- candidate.payload_launcher_abi_min = 1U;
- candidate.payload_launcher_abi_max = 2U;
- ASSERT_EQ(cbm_windows_transition_plan(&current, &candidate),
- CBM_WINDOWS_TRANSITION_CURRENT_FIRST);
-
- current.launcher_abi_min = 1U;
- current.launcher_abi_max = 2U;
- candidate.payload_launcher_abi_min = 2U;
- candidate.payload_launcher_abi_max = 2U;
- ASSERT_EQ(cbm_windows_transition_plan(&current, &candidate),
- CBM_WINDOWS_TRANSITION_LAUNCHER_FIRST);
-
- current.launcher_abi_min = 1U;
- current.launcher_abi_max = 1U;
- ASSERT_EQ(cbm_windows_transition_plan(&current, &candidate),
- CBM_WINDOWS_TRANSITION_INCOMPATIBLE);
-
- current.launcher_abi_min = 1U;
- current.launcher_abi_max = 3U;
- candidate.launcher_abi = 4U;
- candidate.payload_launcher_abi_min = 2U;
- candidate.payload_launcher_abi_max = 4U;
- ASSERT_EQ(cbm_windows_transition_plan(&current, &candidate),
- CBM_WINDOWS_TRANSITION_INCOMPATIBLE);
- ASSERT_EQ(cbm_windows_transition_plan(NULL, &candidate), CBM_WINDOWS_TRANSITION_INCOMPATIBLE);
- PASS();
-}
-
-TEST(windows_current_v1_encoding_is_exact_fixed_little_endian_record) {
- cbm_windows_current_v1_t state = launcher_valid_state();
- state.launcher_abi_min = UINT32_C(0x01020304);
- state.launcher_abi_max = UINT32_C(0x05060708);
-
- uint8_t actual[CBM_WINDOWS_CURRENT_V1_SIZE];
- memset(actual, 0xa5, sizeof(actual));
- ASSERT_TRUE(cbm_windows_current_v1_encode(&state, actual));
-
- uint8_t expected[128] = {0};
- const uint8_t magic[8] = {'C', 'B', 'M', 'C', 'U', 'R', '1', '\0'};
- memcpy(expected, magic, sizeof(magic));
- launcher_put_u32_le(expected + 8, 1);
- launcher_put_u32_le(expected + 12, 128);
- launcher_put_u32_le(expected + 16, state.launcher_abi_min);
- launcher_put_u32_le(expected + 20, state.launcher_abi_max);
- expected[24] = 0x08;
- expected[25] = 0x07;
- expected[26] = 0x06;
- expected[27] = 0x05;
- expected[28] = 0x04;
- expected[29] = 0x03;
- expected[30] = 0x02;
- expected[31] = 0x01;
- memcpy(expected + 32, launcher_sha256, 64);
-
- ASSERT_EQ(CBM_WINDOWS_CURRENT_V1_SIZE, 128);
- ASSERT_MEM_EQ(actual, expected, sizeof(expected));
- ASSERT_TRUE(launcher_memory_is_zero(actual + 96, 32));
- PASS();
-}
-
-TEST(windows_current_v1_round_trip_preserves_authenticated_payload_fields) {
- cbm_windows_current_v1_t input = launcher_valid_state();
- uint8_t record[CBM_WINDOWS_CURRENT_V1_SIZE];
- ASSERT_TRUE(cbm_windows_current_v1_encode(&input, record));
-
- cbm_windows_current_v1_t output;
- memset(&output, 0xa5, sizeof(output));
- ASSERT_TRUE(cbm_windows_current_v1_decode(record, sizeof(record), &output));
- ASSERT_EQ(output.launcher_abi_min, input.launcher_abi_min);
- ASSERT_EQ(output.launcher_abi_max, input.launcher_abi_max);
- ASSERT_EQ(output.payload_size, input.payload_size);
- ASSERT_STR_EQ(output.payload_sha256, input.payload_sha256);
- ASSERT_EQ(output.payload_sha256[64], '\0');
- PASS();
-}
-
-TEST(windows_current_v1_launcher_abi_range_is_inclusive_and_fail_closed) {
- cbm_windows_current_v1_t state = launcher_valid_state();
- ASSERT_FALSE(cbm_windows_current_v1_supports_launcher_abi(&state, 0));
- ASSERT_TRUE(cbm_windows_current_v1_supports_launcher_abi(&state, 1));
- ASSERT_TRUE(cbm_windows_current_v1_supports_launcher_abi(&state, 2));
- ASSERT_TRUE(cbm_windows_current_v1_supports_launcher_abi(&state, 3));
- ASSERT_FALSE(cbm_windows_current_v1_supports_launcher_abi(&state, 4));
- ASSERT_FALSE(cbm_windows_current_v1_supports_launcher_abi(NULL, 2));
- PASS();
-}
-
-TEST(windows_current_v1_encoder_rejects_noncanonical_state) {
- cbm_windows_current_v1_t state = launcher_valid_state();
- uint8_t record[CBM_WINDOWS_CURRENT_V1_SIZE];
-
- ASSERT_FALSE(cbm_windows_current_v1_encode(NULL, record));
- ASSERT_FALSE(cbm_windows_current_v1_encode(&state, NULL));
-
- state.launcher_abi_min = 0;
- ASSERT_FALSE(cbm_windows_current_v1_encode(&state, record));
- state = launcher_valid_state();
- state.launcher_abi_min = 4;
- state.launcher_abi_max = 3;
- ASSERT_FALSE(cbm_windows_current_v1_encode(&state, record));
- state = launcher_valid_state();
- state.payload_size = 0;
- ASSERT_FALSE(cbm_windows_current_v1_encode(&state, record));
- state = launcher_valid_state();
- state.payload_sha256[0] = 'A';
- ASSERT_FALSE(cbm_windows_current_v1_encode(&state, record));
- state = launcher_valid_state();
- state.payload_sha256[17] = 'g';
- ASSERT_FALSE(cbm_windows_current_v1_encode(&state, record));
- state = launcher_valid_state();
- memset(state.payload_sha256, 'a', sizeof(state.payload_sha256));
- ASSERT_FALSE(cbm_windows_current_v1_encode(&state, record));
- PASS();
-}
-
-static int launcher_assert_decode_rejected(const uint8_t *record, size_t size) {
- cbm_windows_current_v1_t output;
- memset(&output, 0xa5, sizeof(output));
- if (cbm_windows_current_v1_decode(record, size, &output)) {
- return 1;
- }
- /* A rejected attacker-controlled record must not leave partial state that
- * a caller could accidentally consume. */
- return launcher_memory_is_zero(&output, sizeof(output)) ? 0 : 1;
-}
-
-TEST(windows_current_v1_decoder_rejects_every_noncanonical_field) {
- cbm_windows_current_v1_t state = launcher_valid_state();
- uint8_t valid[CBM_WINDOWS_CURRENT_V1_SIZE + 1];
- memset(valid, 0, sizeof(valid));
- ASSERT_TRUE(cbm_windows_current_v1_encode(&state, valid));
-
- ASSERT_EQ(launcher_assert_decode_rejected(valid, 127), 0);
- ASSERT_EQ(launcher_assert_decode_rejected(valid, 129), 0);
- ASSERT_FALSE(cbm_windows_current_v1_decode(NULL, 128, &state));
- ASSERT_FALSE(cbm_windows_current_v1_decode(valid, 128, NULL));
-
- uint8_t damaged[CBM_WINDOWS_CURRENT_V1_SIZE];
- memcpy(damaged, valid, sizeof(damaged));
- damaged[0] ^= 1;
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
-
- memcpy(damaged, valid, sizeof(damaged));
- launcher_put_u32_le(damaged + 8, 2);
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
-
- memcpy(damaged, valid, sizeof(damaged));
- launcher_put_u32_le(damaged + 12, 127);
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
-
- memcpy(damaged, valid, sizeof(damaged));
- launcher_put_u32_le(damaged + 16, 0);
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
-
- memcpy(damaged, valid, sizeof(damaged));
- launcher_put_u32_le(damaged + 16, 4);
- launcher_put_u32_le(damaged + 20, 3);
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
-
- memcpy(damaged, valid, sizeof(damaged));
- memset(damaged + 24, 0, 8);
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
-
- memcpy(damaged, valid, sizeof(damaged));
- damaged[32] = 'A';
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
-
- memcpy(damaged, valid, sizeof(damaged));
- damaged[63] = 'g';
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
-
- memcpy(damaged, valid, sizeof(damaged));
- damaged[96] = 1;
- ASSERT_EQ(launcher_assert_decode_rejected(damaged, sizeof(damaged)), 0);
- PASS();
-}
-
-TEST(windows_generation_path_is_launcher_relative_for_custom_unicode_directory) {
- 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.payload.exe";
- wchar_t actual[512];
- ASSERT_TRUE(cbm_windows_generation_payload_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.payload.exe";
- ASSERT_TRUE(cbm_windows_generation_payload_path(root_launcher, launcher_sha256, actual,
- sizeof(actual) / sizeof(actual[0])));
- ASSERT_EQ(wcscmp(actual, root_expected), 0);
- 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));
- ASSERT_FALSE(cbm_windows_generation_payload_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_payload_path(L"C:\\codebase-memory-mcp.exe",
- launcher_sha256, output, 12));
- ASSERT_EQ(output[0], L'\0');
-
- char uppercase[65];
- memcpy(uppercase, launcher_sha256, sizeof(uppercase));
- uppercase[0] = 'A';
- 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();
-}
-
-TEST(windows_launcher_action_classifier_matches_top_level_dispatch) {
- const char *ordinary_mcp[] = {"codebase-memory-mcp.exe"};
- const char *ordinary_cli[] = {"codebase-memory-mcp.exe", "cli", "search_graph",
- "{\"query\":\"update\"}"};
- const char *ordinary_install[] = {"codebase-memory-mcp.exe", "install", "update"};
- const char *ordinary_help[] = {"codebase-memory-mcp.exe", "--help", "update"};
- const char *update[] = {"codebase-memory-mcp.exe", "--profile", "update", "--yes"};
- const char *uninstall[] = {"codebase-memory-mcp.exe", "ignored", "uninstall", "--yes"};
- const char *first_wins[] = {"codebase-memory-mcp.exe", "update", "uninstall"};
-
- ASSERT_EQ(cbm_windows_launcher_classify_action(1, ordinary_mcp),
- CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY);
- ASSERT_EQ(cbm_windows_launcher_classify_action(4, ordinary_cli),
- CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY);
- ASSERT_EQ(cbm_windows_launcher_classify_action(3, ordinary_install),
- CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY);
- ASSERT_EQ(cbm_windows_launcher_classify_action(3, ordinary_help),
- CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY);
- ASSERT_EQ(cbm_windows_launcher_classify_action(4, update), CBM_WINDOWS_LAUNCHER_ACTION_UPDATE);
- ASSERT_EQ(cbm_windows_launcher_classify_action(4, uninstall),
- CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL);
- ASSERT_EQ(cbm_windows_launcher_classify_action(3, first_wins),
- CBM_WINDOWS_LAUNCHER_ACTION_UPDATE);
- ASSERT_EQ(cbm_windows_launcher_classify_action(0, NULL), CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY);
- PASS();
-}
-
-TEST(windows_portable_payload_rejects_only_managed_mutations) {
- ASSERT_TRUE(cbm_windows_launcher_action_allowed(CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY, false));
- ASSERT_FALSE(cbm_windows_launcher_action_allowed(CBM_WINDOWS_LAUNCHER_ACTION_UPDATE, false));
- ASSERT_FALSE(cbm_windows_launcher_action_allowed(CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL, false));
-
- ASSERT_TRUE(cbm_windows_launcher_action_allowed(CBM_WINDOWS_LAUNCHER_ACTION_ORDINARY, true));
- ASSERT_TRUE(cbm_windows_launcher_action_allowed(CBM_WINDOWS_LAUNCHER_ACTION_UPDATE, true));
- ASSERT_TRUE(cbm_windows_launcher_action_allowed(CBM_WINDOWS_LAUNCHER_ACTION_UNINSTALL, true));
- ASSERT_FALSE(cbm_windows_launcher_action_allowed((cbm_windows_launcher_action_t)99, true));
- PASS();
-}
-
-SUITE(windows_launcher_state) {
- RUN_TEST(windows_release_descriptor_v1_encoding_is_exact_and_round_trips);
- RUN_TEST(windows_release_descriptor_v1_rejects_noncanonical_or_incompatible);
- RUN_TEST(windows_transition_plan_requires_a_crash_safe_compatibility_bridge);
- RUN_TEST(windows_current_v1_encoding_is_exact_fixed_little_endian_record);
- RUN_TEST(windows_current_v1_round_trip_preserves_authenticated_payload_fields);
- RUN_TEST(windows_current_v1_launcher_abi_range_is_inclusive_and_fail_closed);
- 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_windows_launcher.py b/tests/windows/test_windows_launcher.py
deleted file mode 100644
index 9183f5afb..000000000
--- a/tests/windows/test_windows_launcher.py
+++ /dev/null
@@ -1,1586 +0,0 @@
-"""GREEN native-Windows guard for the permanent launcher contract.
-
-The release contains two executables:
-
-* ``codebase-memory-mcp.exe`` is the small permanent launcher.
-* ``codebase-memory-mcp.payload.exe`` is the portable CBM payload.
-
-Only ``install`` turns that pair into a managed installation. A managed
-launcher resolves its payload from a strict, fixed-size current-v1 record
-relative to the launcher's own directory. Portable package-manager payloads
-remain useful for ordinary MCP/CLI commands, but must refuse self-update and
-self-uninstall before they disturb an active daemon generation.
-
-This guard deliberately crosses real CreateProcess/stdio/filesystem boundaries
-on native Windows. It also kills the launcher abruptly and inspects the
-process tree, because a waiting launcher must own its payload child strongly
-enough that killing the launcher cannot leave an orphaned MCP client.
-
-Exit code: 0 == contract honored, 1 == regression, 2 == precondition failure.
-
-Usage:
- python test_windows_launcher.py \
- <launcher.exe> <payload.exe> <abi-mismatch-launcher.exe>
-"""
-
-import ctypes
-from ctypes import wintypes
-import hashlib
-import os
-import pathlib
-import platform
-import re
-import shutil
-import struct
-import subprocess
-import sys
-import tempfile
-import time
-import zipfile
-
-if os.name == "nt":
- import winreg
-
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from mcp_stdio import McpError, McpServer # noqa: E402
-
-
-CURRENT_MAGIC = b"CBMCUR1\0"
-CURRENT_RECORD_SIZE = 128
-CURRENT_FORMAT_OFFSET = 8
-CURRENT_SIZE_OFFSET = 12
-CURRENT_ABI_MIN_OFFSET = 16
-CURRENT_ABI_MAX_OFFSET = 20
-CURRENT_PAYLOAD_SIZE_OFFSET = 24
-CURRENT_SHA256_OFFSET = 32
-CURRENT_SHA256_SIZE = 64
-CURRENT_RESERVED_OFFSET = 96
-
-DESCRIPTOR_MAGIC = b"CBMWRD1\0"
-DESCRIPTOR_RECORD_SIZE = 128
-DESCRIPTOR_FORMAT_OFFSET = 8
-DESCRIPTOR_SIZE_OFFSET = 12
-DESCRIPTOR_LAUNCHER_ABI_OFFSET = 16
-DESCRIPTOR_PAYLOAD_ABI_MIN_OFFSET = 20
-DESCRIPTOR_PAYLOAD_ABI_MAX_OFFSET = 24
-DESCRIPTOR_FLAGS_OFFSET = 28
-DESCRIPTOR_PAYLOAD_SIZE_OFFSET = 32
-DESCRIPTOR_SHA256_OFFSET = 40
-DESCRIPTOR_RESERVED_OFFSET = 104
-
-TH32CS_SNAPPROCESS = 0x00000002
-INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
-PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
-SYNCHRONIZE = 0x00100000
-WAIT_OBJECT_0 = 0x00000000
-WAIT_TIMEOUT = 0x00000102
-
-
-class GuardFailure(Exception):
- pass
-
-
-def sha256_file(path):
- """SHA-256 hex digest of a file's contents (payload/launcher digest checks)."""
- return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest()
-
-
-class PROCESSENTRY32W(ctypes.Structure):
- _fields_ = [
- ("dwSize", wintypes.DWORD),
- ("cntUsage", wintypes.DWORD),
- ("th32ProcessID", wintypes.DWORD),
- ("th32DefaultHeapID", ctypes.c_size_t),
- ("th32ModuleID", wintypes.DWORD),
- ("cntThreads", wintypes.DWORD),
- ("th32ParentProcessID", wintypes.DWORD),
- ("pcPriClassBase", wintypes.LONG),
- ("dwFlags", wintypes.DWORD),
- ("szExeFile", wintypes.WCHAR * 260),
- ]
-
-
-def require(condition, message):
- if not condition:
- raise GuardFailure(message)
-
-
-def output_text(result):
- return ((result.stdout or b"") + b"\n" + (result.stderr or b"")).decode(
- "utf-8", "replace"
- )
-
-
-def run(command, env, timeout=30):
- try:
- return subprocess.run(
- [str(part) for part in command],
- input=b"",
- capture_output=True,
- env=env,
- timeout=timeout,
- )
- except subprocess.TimeoutExpired as exc:
- raise GuardFailure(
- "command exceeded %ss: %s" % (timeout, " ".join(map(str, command)))
- ) from exc
-
-
-def isolated_environment(work):
- home = work / "home"
- cache = work / "cache"
- home.mkdir(parents=True)
- cache.mkdir(parents=True)
- env = dict(os.environ)
- env.update(
- {
- "HOME": str(home),
- "USERPROFILE": str(home),
- "APPDATA": str(home / "AppData" / "Roaming"),
- "LOCALAPPDATA": str(home / "AppData" / "Local"),
- "CBM_CACHE_DIR": str(cache),
- "PYTHONUTF8": "1",
- }
- )
- return env, cache
-
-
-def copy_portable_pair(source_launcher, source_payload, directory):
- directory.mkdir(parents=True, exist_ok=True)
- launcher = directory / "codebase-memory-mcp.exe"
- payload = directory / "codebase-memory-mcp.payload.exe"
- shutil.copy2(source_launcher, launcher)
- shutil.copy2(source_payload, payload)
- return launcher, payload
-
-
-def copy_portable_payload(source_payload, directory):
- directory.mkdir(parents=True, exist_ok=True)
- payload = directory / "codebase-memory-mcp.payload.exe"
- shutil.copy2(source_payload, payload)
- return payload
-
-
-def path_registry_snapshot():
- try:
- with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as key:
- value, kind = winreg.QueryValueEx(key, "Path")
- return True, value, kind
- except FileNotFoundError:
- return False, None, None
-
-
-def path_registry_restore(snapshot):
- existed, value, kind = snapshot
- with winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Environment") as key:
- if existed:
- winreg.SetValueEx(key, "Path", 0, kind, value)
- else:
- try:
- winreg.DeleteValue(key, "Path")
- except FileNotFoundError:
- pass
-
-
-def find_and_validate_current(managed_dir):
- matches = []
- for candidate in (managed_dir / ".cbm").rglob("*"):
- if not candidate.is_file():
- continue
- try:
- data = candidate.read_bytes()
- except OSError:
- continue
- if len(data) == CURRENT_RECORD_SIZE and data.startswith(CURRENT_MAGIC):
- matches.append((candidate, data))
- require(
- len(matches) == 1,
- "managed layout must contain exactly one 128-byte CBMCUR1 current record; got %d"
- % len(matches),
- )
- current, data = matches[0]
- version = struct.unpack_from("<I", data, CURRENT_FORMAT_OFFSET)[0]
- size = struct.unpack_from("<I", data, CURRENT_SIZE_OFFSET)[0]
- abi_min = struct.unpack_from("<I", data, CURRENT_ABI_MIN_OFFSET)[0]
- abi_max = struct.unpack_from("<I", data, CURRENT_ABI_MAX_OFFSET)[0]
- payload_size = struct.unpack_from("<Q", data, CURRENT_PAYLOAD_SIZE_OFFSET)[0]
- try:
- digest = data[
- CURRENT_SHA256_OFFSET : CURRENT_SHA256_OFFSET + CURRENT_SHA256_SIZE
- ].decode("ascii")
- except UnicodeDecodeError as exc:
- raise GuardFailure("current-v1 SHA-256 is not ASCII") from exc
-
- require(version == 1, "current record is not current-v1")
- require(size == CURRENT_RECORD_SIZE, "current-v1 record_size is not 128")
- require(abi_min > 0 and abi_min <= abi_max, "current-v1 ABI range is invalid")
- require(re.fullmatch(r"[0-9a-f]{64}", digest), "current-v1 digest is not lowercase SHA-256")
- require(
- data[CURRENT_RESERVED_OFFSET:] == bytes(CURRENT_RECORD_SIZE - CURRENT_RESERVED_OFFSET),
- "current-v1 reserved bytes must be zero",
- )
-
- payload = (
- managed_dir
- / ".cbm"
- / "generations"
- / 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")
- require(
- struct.unpack_from("<I", data, DESCRIPTOR_FORMAT_OFFSET)[0] == 1,
- "release descriptor format is not v1",
- )
- require(
- struct.unpack_from("<I", data, DESCRIPTOR_SIZE_OFFSET)[0]
- == DESCRIPTOR_RECORD_SIZE,
- "release descriptor record_size is invalid",
- )
- launcher_abi = struct.unpack_from("<I", data, DESCRIPTOR_LAUNCHER_ABI_OFFSET)[0]
- payload_min = struct.unpack_from("<I", data, DESCRIPTOR_PAYLOAD_ABI_MIN_OFFSET)[0]
- payload_max = struct.unpack_from("<I", data, DESCRIPTOR_PAYLOAD_ABI_MAX_OFFSET)[0]
- flags = struct.unpack_from("<I", data, DESCRIPTOR_FLAGS_OFFSET)[0]
- payload_size = struct.unpack_from("<Q", data, DESCRIPTOR_PAYLOAD_SIZE_OFFSET)[0]
- digest = data[DESCRIPTOR_SHA256_OFFSET:DESCRIPTOR_RESERVED_OFFSET].decode("ascii")
- require(flags == 0, "release descriptor flags are nonzero")
- require(
- payload_min > 0 and payload_min <= launcher_abi <= payload_max,
- "release descriptor launcher/payload ABI range is incompatible",
- )
- require(payload_size > 0, "release descriptor payload size is zero")
- require(re.fullmatch(r"[0-9a-f]{64}", digest), "release descriptor digest is invalid")
- require(
- data[DESCRIPTOR_RESERVED_OFFSET:] == bytes(
- DESCRIPTOR_RECORD_SIZE - DESCRIPTOR_RESERVED_OFFSET
- ),
- "release descriptor reserved bytes are nonzero",
- )
- return launcher_abi, payload_min, payload_max, payload_size, digest
-
-
-def assert_release_descriptor(source_launcher, source_payload, env, cache):
- cache_before = sorted(str(path.relative_to(cache)) for path in cache.rglob("*"))
- result = run(
- [source_launcher, "__cbm_windows_release_descriptor_v1"], env, timeout=30
- )
- require(
- result.returncode == 0,
- "release descriptor probe failed: %s" % output_text(result)[-800:],
- )
- _, _, _, payload_size, digest = parse_release_descriptor(result.stdout)
- require(payload_size == source_payload.stat().st_size, "descriptor payload size mismatch")
- require(digest == sha256_file(source_payload), "descriptor payload digest mismatch")
- cache_after = sorted(str(path.relative_to(cache)) for path in cache.rglob("*"))
- require(cache_after == cache_before, "release descriptor probe touched cache/daemon state")
- print("PASS: release pair self-described ABI and payload identity without side effects")
-
-
-def assert_portable_mutations_refuse(source_payload, env, cache, work):
- session_payload = copy_portable_payload(source_payload, work / "portable-session")
- with McpServer(str(session_payload), cache_dir=str(cache), extra_env=env) as server:
- server.initialize(timeout=30)
- require(server.tools_list(timeout=30), "portable MCP control session has no tools")
-
- for action, options in (
- ("update", ["--yes", "--standard"]),
- ("uninstall", ["--yes"]),
- ):
- command_payload = copy_portable_payload(
- source_payload, work / ("portable-" + action)
- )
- command_env = dict(env)
- # If the update guard regresses, keep its unintended network path
- # 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
- diagnostic = output_text(result).lower()
- require(result.returncode != 0, "portable %s unexpectedly succeeded" % action)
- require(elapsed < 8.0, "portable %s did not fail early" % action)
- require(
- "install" in diagnostic
- and any(
- word in diagnostic
- for word in ("package manager", "managed", "launcher")
- ),
- "portable %s did not explain package-manager/managed-install recovery"
- % action,
- )
- # The same already-open stdio session must still own the same live
- # daemon connection. A stop-and-transparent-restart is not enough:
- # the existing pipe itself has to remain usable.
- require(
- server.tools_list(timeout=10),
- "portable %s drained the active MCP/daemon session before refusing"
- % action,
- )
- print("PASS: portable %s refused early without draining the session" % action)
-
-
-def assert_untrusted_ancestor_acl_rejected(
- source_launcher, source_payload, env, work
-):
- unsafe_ancestor = work / "unsafe cross-account ACL ancestor"
- launcher, _ = copy_portable_pair(
- source_launcher, source_payload, unsafe_ancestor / "bundle"
- )
- require(
- run([launcher, "--version"], env).returncode == 0,
- "portable launcher ACL control failed before the unsafe ACE was added",
- )
- extended_launcher = "\\\\?\\" + str(launcher.resolve())
- extended_result = run([extended_launcher, "--version"], env)
- require(
- extended_result.returncode == 0,
- "launcher rejected its documented extended DOS module path: %s"
- % output_text(extended_result)[-600:],
- )
-
- grant = run(
- ["icacls", unsafe_ancestor, "/grant", "*S-1-1-0:(M)"], env
- )
- require(
- grant.returncode == 0,
- "could not install native Everyone-modify ancestor fixture: %s"
- % output_text(grant)[-600:],
- )
- try:
- for candidate, spelling in (
- (launcher, "normal"),
- (extended_launcher, "extended DOS"),
- ):
- result = run([candidate, "--version"], env)
- diagnostic = output_text(result).lower()
- require(
- result.returncode != 0,
- "%s launcher path accepted an ancestor granting cross-account modify access"
- % spelling,
- )
- require(
- any(
- word in diagnostic
- for word in (
- "unsafe",
- "security",
- "ownership",
- "access",
- "resolve",
- )
- ),
- "%s launcher path unsafe-ancestor refusal was not explicit"
- % spelling,
- )
- finally:
- remove = run(
- ["icacls", unsafe_ancestor, "/remove:g", "*S-1-1-0"], env
- )
- require(
- remove.returncode == 0,
- "could not remove native Everyone-modify ancestor fixture",
- )
- for candidate, spelling in (
- (launcher, "normal"),
- (extended_launcher, "extended DOS"),
- ):
- require(
- run([candidate, "--version"], env).returncode == 0,
- "%s launcher path did not recover after unsafe ancestor ACE removal"
- % spelling,
- )
- print("PASS: launcher rejected an untrusted mutation ACE on an ancestor")
-
-
-def assert_add_only_ancestor_acl_allowed(source_launcher, source_payload, env, work):
- ancestor = work / "cross-account add-only ancestor"
- launcher, 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,
- "could not install native Everyone-add-subdirectory ancestor fixture: %s"
- % output_text(grant)[-600:],
- )
- try:
- for candidate, spelling in (
- (launcher, "normal"),
- ("\\\\?\\" + str(launcher.resolve()), "extended DOS"),
- ):
- result = run([candidate, "--version"], env)
- require(
- result.returncode == 0,
- "%s launcher path treated sibling creation as replacement access: %s"
- % (spelling, output_text(result)[-600:]),
- )
-
- managed_dir = ancestor / "managed install under add-only ancestor"
- install = run(
- [
- portable_payload,
- "install",
- "--yes",
- "--force",
- "--skip-config",
- "--dir",
- managed_dir,
- ],
- env,
- timeout=60,
- )
- require(
- install.returncode == 0,
- "managed install rejected a standard add-subdirectory-only ancestor: %s"
- % output_text(install)[-800:],
- )
- 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=180)
- require(
- uninstall.returncode == 0,
- "add-only managed install could not be uninstalled: %s"
- % output_text(uninstall)[-800:],
- )
- finally:
- remove = run(["icacls", ancestor, "/remove:g", "*S-1-1-0"], env)
- require(
- remove.returncode == 0,
- "could not remove native Everyone-add-subdirectory ancestor fixture",
- )
- print(
- "PASS: launcher and managed install allowed add-only sibling creation "
- "without weakening path integrity"
- )
-
-
-def assert_targeted_ancestor_acl_rejected(path, launcher, right, description, env):
- grant = run(["icacls", path, "/grant", "*S-1-1-0:(%s)" % right], env)
- require(
- grant.returncode == 0,
- "could not install native Everyone-%s fixture: %s"
- % (description, output_text(grant)[-600:]),
- )
- try:
- for candidate, spelling in (
- (launcher, "normal"),
- ("\\\\?\\" + str(launcher.resolve()), "extended DOS"),
- ):
- result = run([candidate, "--version"], env)
- require(
- result.returncode != 0,
- "%s launcher accepted cross-account %s"
- % (spelling, description),
- )
- finally:
- remove = run(["icacls", path, "/remove:g", "*S-1-1-0"], env)
- require(
- remove.returncode == 0,
- "could not remove native Everyone-%s fixture" % description,
- )
- require(
- run([launcher, "--version"], env).returncode == 0,
- "launcher did not recover after the %s ACE was removed" % description,
- )
-
-
-def assert_file_add_and_executable_parent_acl_rejected(
- source_launcher, source_payload, env, work
-):
- file_add_ancestor = work / "cross-account file-add ancestor"
- launcher, _ = copy_portable_pair(
- source_launcher, source_payload, file_add_ancestor / "bundle"
- )
- assert_targeted_ancestor_acl_rejected(
- file_add_ancestor, launcher, "WD", "file creation on an intermediate ancestor", env
- )
-
- executable_parent = work / "cross-account executable parent"
- launcher, _ = copy_portable_pair(source_launcher, source_payload, executable_parent)
- assert_targeted_ancestor_acl_rejected(
- executable_parent,
- launcher,
- "AD",
- "subdirectory creation beside the executable",
- env,
- )
- print("PASS: launcher kept file-add and executable-parent ACL boundaries strict")
-
-
-def process_entries():
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
- kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
- kernel32.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]
- kernel32.Process32FirstW.restype = wintypes.BOOL
- kernel32.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]
- kernel32.Process32NextW.restype = wintypes.BOOL
- kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
- kernel32.CloseHandle.restype = wintypes.BOOL
-
- snapshot = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
- if snapshot == INVALID_HANDLE_VALUE:
- raise GuardFailure("CreateToolhelp32Snapshot failed")
- entries = []
- try:
- entry = PROCESSENTRY32W()
- entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)
- ok = kernel32.Process32FirstW(snapshot, ctypes.byref(entry))
- while ok:
- entries.append(
- (int(entry.th32ProcessID), int(entry.th32ParentProcessID), entry.szExeFile)
- )
- entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)
- ok = kernel32.Process32NextW(snapshot, ctypes.byref(entry))
- finally:
- kernel32.CloseHandle(snapshot)
- return entries
-
-
-def process_is_alive(pid):
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
- kernel32.OpenProcess.restype = wintypes.HANDLE
- kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
- kernel32.WaitForSingleObject.restype = wintypes.DWORD
- kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
- handle = kernel32.OpenProcess(
- SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, False, pid
- )
- if not handle:
- return False
- try:
- status = kernel32.WaitForSingleObject(handle, 0)
- return status == WAIT_TIMEOUT
- finally:
- kernel32.CloseHandle(handle)
-
-
-def wait_for_payload_child(launcher_pid, timeout=10):
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- children = [
- (pid, name)
- for pid, parent, name in process_entries()
- if parent == launcher_pid
- and name.lower().endswith("codebase-memory-mcp.payload.exe")
- ]
- if len(children) == 1:
- return children[0][0]
- if len(children) > 1:
- raise GuardFailure("launcher spawned more than one direct payload child")
- time.sleep(0.05)
- raise GuardFailure("launcher did not create its direct payload child")
-
-
-def wait_for_process_exit(pid, timeout=10):
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- if not process_is_alive(pid):
- return True
- time.sleep(0.05)
- return not process_is_alive(pid)
-
-
-def descendant_pids(root_pid):
- entries = process_entries()
- descendants = set()
- frontier = {root_pid}
- while frontier:
- next_frontier = {
- pid
- for pid, parent, _ in entries
- if parent in frontier and pid not in descendants
- }
- descendants.update(next_frontier)
- frontier = next_frontier
- return descendants
-
-
-def assert_launcher_death_contains_payload(launcher, env, cache):
- server = McpServer(str(launcher), cache_dir=str(cache), extra_env=env)
- try:
- server.start()
- server.initialize(timeout=30)
- child_pid = wait_for_payload_child(server.proc.pid)
- require(process_is_alive(child_pid), "payload child exited before crash probe")
- server.proc.kill()
- server.proc.wait(timeout=10)
- require(
- wait_for_process_exit(child_pid, timeout=10),
- "killing the permanent launcher orphaned payload pid %d" % child_pid,
- )
- print("PASS: abrupt launcher death contained its payload child")
- finally:
- server.close()
-
-
-def assert_immediate_parent_death_contains_launcher_tree(launcher, env, work):
- pid_file = work / "launcher-parent-probe.pid"
- wrapper = subprocess.Popen(
- [
- sys.executable,
- str(pathlib.Path(__file__).resolve()),
- "--launcher-parent-probe",
- str(launcher),
- str(pid_file),
- ],
- stdin=subprocess.PIPE,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- env=env,
- )
- try:
- deadline = time.monotonic() + 10
- while time.monotonic() < deadline and not pid_file.exists():
- if wrapper.poll() is not None:
- raise GuardFailure("parent-probe wrapper exited before publishing launcher PID")
- time.sleep(0.05)
- require(pid_file.exists(), "parent-probe wrapper did not publish launcher PID")
- launcher_pid = int(pid_file.read_text(encoding="ascii").strip())
- payload_pid = wait_for_payload_child(launcher_pid, timeout=10)
- tracked = {launcher_pid, payload_pid} | descendant_pids(launcher_pid)
- require(process_is_alive(launcher_pid), "launcher exited before parent-death probe")
- require(process_is_alive(payload_pid), "payload exited before parent-death probe")
-
- # Kill only the wrapper. The test process intentionally keeps the
- # wrapper stdin pipe open, so MCP EOF cannot explain child teardown.
- wrapper.kill()
- wrapper.wait(timeout=10)
- require(
- wait_for_process_exit(launcher_pid, timeout=10),
- "killing only the wrapper left launcher pid %d alive" % launcher_pid,
- )
- survivors = [pid for pid in tracked if process_is_alive(pid)]
- descendant_deadline = time.monotonic() + 10
- while survivors and time.monotonic() < descendant_deadline:
- time.sleep(0.05)
- survivors = [pid for pid in survivors if process_is_alive(pid)]
- require(not survivors, "wrapper death left launcher descendants alive: %s" % survivors)
- print("PASS: immediate parent death terminated launcher and payload session tree")
- finally:
- if wrapper.poll() is None:
- wrapper.kill()
- wrapper.wait(timeout=10)
- if wrapper.stdin:
- wrapper.stdin.close()
-
-
-def assert_launcher_relay(launcher, payload, env, cache):
- direct_version = run([payload, "--version"], env)
- launched_version = run([launcher, "--version"], env)
- require(direct_version.returncode == 0, "managed payload --version failed")
- require(
- launched_version.returncode == direct_version.returncode,
- "launcher did not propagate the payload's success exit status exactly",
- )
- require(
- launched_version.stdout == direct_version.stdout
- and launched_version.stderr == direct_version.stderr,
- "launcher did not relay --version stdout/stderr byte-for-byte",
- )
-
- # A missing CLI tool has a stable non-zero product exit. Compare it with
- # the same generation payload rather than baking the numeric code into the
- # launcher contract.
- direct_error = run([payload, "cli"], env)
- launched_error = run([launcher, "cli"], env)
- require(direct_error.returncode != 0, "CLI error control unexpectedly succeeded")
- require(
- launched_error.returncode == direct_error.returncode,
- "launcher changed the payload's non-zero exit status",
- )
- require(
- launched_error.stdout == direct_error.stdout
- and launched_error.stderr == direct_error.stderr,
- "launcher did not relay failing CLI stdout/stderr byte-for-byte",
- )
-
- with McpServer(str(launcher), cache_dir=str(cache), extra_env=env) as server:
- init = server.initialize(timeout=30)
- require("result" in init, "launcher did not relay MCP initialize response")
- require(server.tools_list(timeout=30), "launcher did not relay MCP tools/list")
- print("PASS: launcher relayed MCP stdio and exact child exit/status streams")
-
-
-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)
- result = run([launcher, "--version"], env)
- diagnostic = output_text(result).lower()
- require(result.returncode != 0, "launcher accepted an incompatible current-v1 ABI")
- require("abi" in diagnostic or "incompatible" in diagnostic, "ABI refusal was not explicit")
-
- corrupt = bytearray(original)
- corrupt[: len(CURRENT_MAGIC)] = b"\0" * len(CURRENT_MAGIC)
- current.write_bytes(corrupt)
- result = run([launcher, "--version"], env)
- diagnostic = output_text(result).lower()
- require(result.returncode != 0, "launcher accepted a corrupted current record")
- require(
- any(word in diagnostic for word in ("current", "corrupt", "invalid", "state")),
- "corrupted-current failure was not explicit",
- )
- current.write_bytes(original)
- require(run([launcher, "--version"], env).returncode == 0, "restored current-v1 stopped working")
- print("PASS: current-v1 compatibility succeeded and corrupt/incompatible state failed hard")
-
-
-def assert_managed_update(
- source_launcher, source_payload, launcher, managed_dir, env, work
-):
- 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" % arch
- asset = release / asset_name
- with zipfile.ZipFile(asset, "w", compression=zipfile.ZIP_STORED) as archive:
- archive.write(source_launcher, "codebase-memory-mcp.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")
- digest = hashlib.sha256(asset.read_bytes()).hexdigest()
- (release / "checksums.txt").write_text(
- "%s %s\n" % (digest, asset_name), encoding="ascii"
- )
-
- 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.parent
- orphan_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_digest
- orphan_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,
- timeout=90,
- )
- require(
- result.returncode == 0,
- "managed update failed: %s" % output_text(result)[-1200:],
- )
- require(launcher.is_file(), "managed update removed the canonical launcher")
- _, _, generation_payload = find_and_validate_current(managed_dir)
- require(
- run([launcher, "--version"], env).returncode == 0,
- "managed update returned with a non-runnable launcher/current pair",
- )
- require(
- 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 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 = [
- path
- for path in (managed_dir / ".cbm" / "generations").iterdir()
- if path.is_dir()
- ]
- require(
- len(generation_directories) == 1
- and generation_directories[0].name == generation_payload.parent.name,
- "successful update did not leave exactly the current generation",
- )
- print(
- "PASS: managed update retained mapped old backing, then pruned it on the next activation"
- )
-
-
-def assert_managed_update_rejects_unrunnable_launcher_before_drain(
- source_payload, launcher, managed_dir, env, cache, work
-):
- release = work / "release-unrunnable-launcher"
- release.mkdir()
- machine = platform.machine().lower()
- arch = "arm64" if machine in ("arm64", "aarch64") else "amd64"
- asset_name = "codebase-memory-mcp-windows-%s.zip" % arch
- asset = release / asset_name
- with zipfile.ZipFile(asset, "w", compression=zipfile.ZIP_STORED) as archive:
- archive.writestr("codebase-memory-mcp.exe", b"MZ-not-a-runnable-launcher")
- archive.write(source_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")
- digest = hashlib.sha256(asset.read_bytes()).hexdigest()
- (release / "checksums.txt").write_text(
- "%s %s\n" % (digest, asset_name), encoding="ascii"
- )
- update_env = dict(env)
- update_env["CBM_DOWNLOAD_URL"] = release.resolve().as_uri()
- current, current_before, _ = find_and_validate_current(managed_dir)
- launcher_before = sha256_file(launcher)
-
- with McpServer(str(launcher), cache_dir=str(cache), extra_env=env) as server:
- server.initialize(timeout=30)
- result = run(
- [launcher, "update", "--force", "--standard", "--yes"],
- update_env,
- timeout=60,
- )
- diagnostic = output_text(result).lower()
- require(result.returncode != 0, "unrunnable launcher update succeeded")
- require(
- any(word in diagnostic for word in ("launcher", "candidate", "runnable", "capability")),
- "unrunnable launcher rejection was not explicit",
- )
- require(
- server.tools_list(timeout=10),
- "unrunnable launcher candidate drained the active managed session",
- )
-
- require(sha256_file(launcher) == launcher_before, "failed update replaced the launcher")
- require(current.read_bytes() == current_before, "failed update changed current-v1")
- print("PASS: unrunnable update launcher failed before session drain")
-
-
-def assert_managed_update_rejects_cross_abi_pair_before_drain(
- abi_mismatch_launcher, source_payload, launcher, managed_dir, env, cache, work
-):
- release = work / "release-abi-mismatch"
- release.mkdir()
- machine = platform.machine().lower()
- arch = "arm64" if machine in ("arm64", "aarch64") else "amd64"
- asset_name = "codebase-memory-mcp-windows-%s.zip" % arch
- asset = release / asset_name
- with zipfile.ZipFile(asset, "w", compression=zipfile.ZIP_STORED) as archive:
- archive.write(abi_mismatch_launcher, "codebase-memory-mcp.exe")
- archive.write(source_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")
- digest = hashlib.sha256(asset.read_bytes()).hexdigest()
- (release / "checksums.txt").write_text(
- "%s %s\n" % (digest, asset_name), encoding="ascii"
- )
- update_env = dict(env)
- update_env["CBM_DOWNLOAD_URL"] = release.resolve().as_uri()
- current, current_before, _ = find_and_validate_current(managed_dir)
- launcher_before = sha256_file(launcher)
- generations_before = sorted(
- str(path.relative_to(managed_dir))
- for path in (managed_dir / ".cbm" / "generations").rglob("*")
- )
-
- with McpServer(str(launcher), cache_dir=str(cache), extra_env=env) as server:
- server.initialize(timeout=30)
- result = run(
- [launcher, "update", "--force", "--standard", "--yes"],
- update_env,
- timeout=60,
- )
- diagnostic = output_text(result).lower()
- require(result.returncode != 0, "cross-ABI launcher/payload update succeeded")
- require(
- any(word in diagnostic for word in ("abi", "descriptor", "bridge", "incompatible")),
- "cross-ABI update refusal did not explain compatibility failure",
- )
- require(
- server.tools_list(timeout=10),
- "cross-ABI candidate drained the active managed session",
- )
-
- generations_after = sorted(
- str(path.relative_to(managed_dir))
- for path in (managed_dir / ".cbm" / "generations").rglob("*")
- )
- require(sha256_file(launcher) == launcher_before, "cross-ABI update replaced launcher")
- require(current.read_bytes() == current_before, "cross-ABI update changed current-v1")
- require(generations_after == generations_before, "cross-ABI update published a generation")
- print("PASS: incompatible future launcher ABI failed hard before session drain")
-
-
-def assert_failed_update_rolls_back_new_generation(
- source_launcher, source_payload, launcher, managed_dir, env, work
-):
- release = work / "release-generation-rollback"
- release.mkdir()
- mutated_payload = release / "mutated.payload.exe"
- mutated_payload.write_bytes(
- source_payload.read_bytes() + b"\0CBM generation rollback fixture\n"
- )
- require(
- run([mutated_payload, "--version"], env).returncode == 0,
- "PE overlay payload fixture is not runnable",
- )
- mutated_digest = sha256_file(mutated_payload)
- machine = platform.machine().lower()
- arch = "arm64" if machine in ("arm64", "aarch64") else "amd64"
- asset_name = "codebase-memory-mcp-windows-%s.zip" % arch
- asset = release / asset_name
- with zipfile.ZipFile(asset, "w", compression=zipfile.ZIP_STORED) as archive:
- archive.write(source_launcher, "codebase-memory-mcp.exe")
- archive.write(mutated_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")
- digest = hashlib.sha256(asset.read_bytes()).hexdigest()
- (release / "checksums.txt").write_text(
- "%s %s\n" % (digest, asset_name), encoding="ascii"
- )
- update_env = dict(env)
- update_env["CBM_DOWNLOAD_URL"] = release.resolve().as_uri()
- current, current_before, _ = find_and_validate_current(managed_dir)
- launcher_before = sha256_file(launcher)
-
- 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 canonical launcher fixture")
- try:
- result = run(
- [launcher, "update", "--force", "--standard", "--yes"],
- update_env,
- timeout=90,
- )
- finally:
- kernel32.CloseHandle(held_launcher)
- require(result.returncode != 0, "forced post-publication launcher failure succeeded")
- require(sha256_file(launcher) == launcher_before, "failed update changed launcher")
- require(current.read_bytes() == current_before, "failed update changed current-v1")
- require(
- not (managed_dir / ".cbm" / "generations" / mutated_digest).exists(),
- "failed update orphaned its newly published generation",
- )
- print("PASS: post-publication update failure rolled back its new generation")
-
-
-def assert_managed_update_dry_run_skips_capability_probe(
- launcher, managed_dir, env
-):
- dry_env = dict(env)
- dry_env["CBM_TEST_WINDOWS_LAUNCHER_CAPABILITY_PROBE"] = "fail"
- current, current_before, _ = find_and_validate_current(managed_dir)
- launcher_before = sha256_file(launcher)
- result = run(
- [launcher, "update", "--dry-run", "--force", "--standard", "--yes"],
- dry_env,
- timeout=30,
- )
- require(
- result.returncode == 0,
- "managed update dry-run invoked the forced-failing capability probe: %s"
- % output_text(result)[-800:],
- )
- require(sha256_file(launcher) == launcher_before, "update dry-run changed launcher")
- require(current.read_bytes() == current_before, "update dry-run changed current-v1")
- leftovers = [
- path
- for path in managed_dir.iterdir()
- if path.name.startswith(".cbm-launcher-probe-")
- or path.name == ".cbm-probe-path-check"
- ]
- require(not leftovers, "update dry-run left capability-probe artifacts: %s" % leftovers)
- print("PASS: managed update dry-run skipped mapped-image capability mutation")
-
-
-def assert_capability_probe_fail_hard(
- source_launcher, source_payload, launcher, env, cache, work
-):
- _, probe_payload = copy_portable_pair(
- source_launcher, source_payload, work / "portable-probe"
- )
- rejected_dir = work / "probe-rejected_日本語"
- rejected_env = dict(env)
- # Deterministic native fault injection for the exact-volume launcher
- # capability probe. Production must treat this solely as a probe failure;
- # it must not bypass or weaken the real NTFS checks.
- rejected_env["CBM_TEST_WINDOWS_LAUNCHER_CAPABILITY_PROBE"] = "fail"
-
- with McpServer(str(launcher), cache_dir=str(cache), extra_env=env) as server:
- server.initialize(timeout=30)
- result = run(
- [
- probe_payload,
- "install",
- "--yes",
- "--force",
- "--skip-config",
- "--dir",
- rejected_dir,
- ],
- rejected_env,
- timeout=30,
- )
- diagnostic = output_text(result).lower()
- require(result.returncode != 0, "forced launcher capability-probe failure succeeded")
- require(
- any(word in diagnostic for word in ("capability", "ntfs", "atomic", "replace")),
- "launcher capability-probe failure was not explicit",
- )
- leftover_files = [p for p in rejected_dir.rglob("*") if p.is_file()]
- require(not leftover_files, "failed capability probe left managed-install files behind")
- require(
- server.tools_list(timeout=10),
- "capability-probe failure drained the already-active managed session",
- )
- 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, 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")
- 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():
- launcher = pathlib.Path(sys.argv[2]).resolve()
- pid_file = pathlib.Path(sys.argv[3]).resolve()
- child = subprocess.Popen(
- [str(launcher)],
- stdin=None,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- env=os.environ.copy(),
- )
- pid_file.write_text(str(child.pid), encoding="ascii")
- return child.wait()
-
-
-def main():
- if os.name != "nt":
- print("PRECONDITION: native Windows is required")
- return 2
- if len(sys.argv) == 4 and sys.argv[1] == "--launcher-parent-probe":
- return launcher_parent_probe_role()
- if len(sys.argv) != 4:
- print(
- "usage: python test_windows_launcher.py "
- "<launcher.exe> <payload.exe> <abi-mismatch-launcher.exe>"
- )
- return 2
-
- source_launcher = pathlib.Path(sys.argv[1]).resolve()
- source_payload = pathlib.Path(sys.argv[2]).resolve()
- abi_mismatch_launcher = pathlib.Path(sys.argv[3]).resolve()
- if not source_launcher.is_file():
- print("PRECONDITION: launcher not found: %s" % source_launcher)
- return 2
- if not source_payload.is_file():
- print("PRECONDITION: payload not found: %s" % source_payload)
- return 2
- if not abi_mismatch_launcher.is_file():
- print("PRECONDITION: ABI mismatch launcher not found: %s" % abi_mismatch_launcher)
- return 2
- if source_launcher.samefile(source_payload):
- print("PRECONDITION: launcher and payload must be distinct executables")
- return 2
-
- work = pathlib.Path(tempfile.mkdtemp(prefix="cbm_win_launcher_"))
- path_snapshot = path_registry_snapshot()
- try:
- env, cache = isolated_environment(work)
- assert_release_descriptor(source_launcher, source_payload, env, cache)
- assert_portable_mutations_refuse(source_payload, env, cache, work)
- assert_add_only_ancestor_acl_allowed(
- source_launcher, source_payload, env, work
- )
- assert_file_add_and_executable_parent_acl_rejected(
- source_launcher, source_payload, env, work
- )
- assert_untrusted_ancestor_acl_rejected(
- source_launcher, source_payload, env, work
- )
-
- _, portable_payload = copy_portable_pair(
- source_launcher, source_payload, work / "portable-install"
- )
- 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(
- payload_half.read_bytes() == payload_half_bytes and backing_half.is_file(),
- "payload-only repair replaced its valid half instead of adding the launcher",
- )
-
- 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: payload-only generation recovered into strict hardlink/current-v1 layout"
- )
-
- assert_launcher_relay(launcher, generation_payload, env, cache)
- assert_current_fail_closed(launcher, current, current_bytes, env)
- assert_managed_update_dry_run_skips_capability_probe(
- launcher, managed_dir, env
- )
- assert_managed_update_rejects_unrunnable_launcher_before_drain(
- source_payload, launcher, managed_dir, env, cache, work
- )
- assert_managed_update_rejects_cross_abi_pair_before_drain(
- abi_mismatch_launcher,
- source_payload,
- launcher,
- managed_dir,
- env,
- cache,
- work,
- )
- assert_failed_update_rolls_back_new_generation(
- source_launcher,
- source_payload,
- launcher,
- managed_dir,
- env,
- work,
- )
- assert_managed_update(
- source_launcher,
- source_payload,
- launcher,
- managed_dir,
- env,
- work,
- )
- assert_launcher_death_contains_payload(launcher, env, cache)
- assert_immediate_parent_death_contains_launcher_tree(
- launcher, env, work
- )
- assert_capability_probe_fail_hard(
- source_launcher, source_payload, launcher, env, cache, work
- )
- 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 0
- except (GuardFailure, McpError, OSError, subprocess.SubprocessError) as exc:
- print("\nRED: %s" % exc)
- return 1
- finally:
- try:
- path_registry_restore(path_snapshot)
- except OSError as exc:
- print("CLEANUP WARNING: could not restore HKCU Environment\\Path: %s" % exc)
- shutil.rmtree(work, ignore_errors=True)
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/tests/windows/test_windows_update_handoff.py b/tests/windows/test_windows_update_handoff.py
new file mode 100644
index 000000000..48155add3
--- /dev/null
+++ b/tests/windows/test_windows_update_handoff.py
@@ -0,0 +1,211 @@
+"""GREEN native-Windows guard for the `update` -> install.ps1 handoff.
+
+Windows ships ONE binary, exactly like Linux and macOS: ``codebase-memory-mcp.exe``.
+
+There used to be a second, permanently resident launcher stub whose only job
+was to swap the product binary out from under itself, because a running .exe
+cannot replace its own image on Windows. Defender's ML scored that stub
+Trojan:Win32/Wacatac.B!ml on x64 no matter what the build changed (bcrypt-free,
+stripped, versioned and resource-free variants were all flagged), while the
+product binary itself scans clean everywhere. So the swap moved OUT of the
+process into install.ps1, which runs while CBM is NOT running.
+
+This guard asserts the replacement contract on real native Windows:
+
+* ``update`` exits 0 and prints the exact install.ps1 command.
+* ``update`` NEVER replaces the running image in-process — the executable's
+ bytes are unchanged, and no launcher/payload sibling appears next to it.
+* ``update`` refuses to reach the network first: it hands off before it
+ consults CBM_DOWNLOAD_URL, so it stays fast even when that URL is a black
+ hole.
+* ``update`` does not disturb an already-open MCP/daemon session.
+
+A regression here means the in-process self-update — and therefore the
+AV-flagged launcher stub — came back.
+
+Exit code: 0 == contract honored, 1 == regression, 2 == precondition failure.
+
+Usage:
+ python test_windows_update_handoff.py <codebase-memory-mcp.exe>
+"""
+
+import hashlib
+import os
+import pathlib
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from mcp_stdio import McpError, McpServer # noqa: E402
+
+
+class GuardFailure(Exception):
+ pass
+
+
+def require(condition, message):
+ if not condition:
+ raise GuardFailure(message)
+
+
+def sha256_file(path):
+ return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest()
+
+
+def output_text(result):
+ return ((result.stdout or b"") + b"\n" + (result.stderr or b"")).decode(
+ "utf-8", "replace"
+ )
+
+
+def run(command, env, timeout=30):
+ try:
+ return subprocess.run(
+ [str(part) for part in command],
+ input=b"",
+ capture_output=True,
+ env=env,
+ timeout=timeout,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise GuardFailure(
+ "command exceeded %ss: %s" % (timeout, " ".join(map(str, command)))
+ ) from exc
+
+
+def isolated_environment(work):
+ home = work / "home"
+ cache = work / "cache"
+ home.mkdir(parents=True)
+ cache.mkdir(parents=True)
+ env = dict(os.environ)
+ env.update(
+ {
+ "HOME": str(home),
+ "USERPROFILE": str(home),
+ "APPDATA": str(home / "AppData" / "Roaming"),
+ "LOCALAPPDATA": str(home / "AppData" / "Local"),
+ "CBM_CACHE_DIR": str(cache),
+ "PYTHONUTF8": "1",
+ }
+ )
+ return env, cache
+
+
+def copy_binary(source, directory):
+ directory.mkdir(parents=True, exist_ok=True)
+ binary = directory / "codebase-memory-mcp.exe"
+ shutil.copy2(source, binary)
+ return binary
+
+
+def assert_update_hands_off_to_install_script(source, env, work):
+ binary = copy_binary(source, work / "update-handoff")
+ before = sha256_file(binary)
+ command_env = dict(env)
+ # If the handoff regresses into a real in-process update, keep its
+ # unintended network path deterministic and fast: a correct implementation
+ # never consults this URL.
+ 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 handoff
+ # itself is a fast STATELESS local print (no daemon IPC, no download) whose
+ # timing is what this guard measures. The warm-up behaves identically.
+ run([binary, "update", "--yes", "--standard"], command_env, timeout=20)
+ started = time.monotonic()
+ result = run([binary, "update", "--yes", "--standard"], command_env, timeout=20)
+ elapsed = time.monotonic() - started
+ diagnostic = output_text(result)
+ lowered = diagnostic.lower()
+
+ require(
+ result.returncode == 0,
+ "update exited %s; the Windows handoff must succeed: %s"
+ % (result.returncode, diagnostic[-800:]),
+ )
+ require(
+ "install.ps1" in lowered,
+ "update did not print the install.ps1 command: %s" % diagnostic[-800:],
+ )
+ require(
+ "powershell" in lowered,
+ "update did not print a runnable PowerShell command: %s" % diagnostic[-800:],
+ )
+ require(
+ elapsed < 8.0,
+ "update took %.1fs — it must hand off before any network I/O" % elapsed,
+ )
+ require(
+ sha256_file(binary) == before,
+ "update replaced the running image in-process (a running .exe cannot "
+ "replace itself; that is exactly what the removed launcher stub was for)",
+ )
+ require(
+ not (binary.parent / "codebase-memory-mcp.payload.exe").exists(),
+ "update recreated a launcher/payload pair beside the binary",
+ )
+ require(
+ not list(binary.parent.glob("*launcher*")),
+ "update produced a launcher artifact beside the binary",
+ )
+ print("PASS: update handed off to install.ps1 without touching its own image")
+
+
+def assert_update_does_not_drain_active_session(source, env, cache, work):
+ binary = copy_binary(source, work / "update-session")
+ with McpServer(str(binary), cache_dir=str(cache), extra_env=env) as server:
+ server.initialize(timeout=30)
+ require(server.tools_list(timeout=30), "MCP control session has no tools")
+
+ command = copy_binary(source, work / "update-session-command")
+ command_env = dict(env)
+ command_env["CBM_DOWNLOAD_URL"] = "https://127.0.0.1:1"
+ result = run([command, "update", "--yes", "--standard"], command_env, timeout=20)
+ require(
+ result.returncode == 0,
+ "update exited %s beside a live session: %s"
+ % (result.returncode, output_text(result)[-800:]),
+ )
+ # The same already-open stdio session must still own the same live
+ # daemon connection. A stop-and-transparent-restart is not enough: the
+ # existing pipe itself has to remain usable.
+ require(
+ server.tools_list(timeout=10),
+ "update drained the active MCP/daemon session",
+ )
+ print("PASS: update left the active MCP/daemon session untouched")
+
+
+def main():
+ if os.name != "nt":
+ print("PRECONDITION: native Windows is required")
+ return 2
+ if len(sys.argv) != 2:
+ print("usage: python test_windows_update_handoff.py <codebase-memory-mcp.exe>")
+ return 2
+
+ source = pathlib.Path(sys.argv[1]).resolve()
+ if not source.is_file():
+ print("PRECONDITION: binary not found: %s" % source)
+ return 2
+
+ work = pathlib.Path(tempfile.mkdtemp(prefix="cbm_win_update_"))
+ try:
+ env, cache = isolated_environment(work)
+ assert_update_hands_off_to_install_script(source, env, work)
+ assert_update_does_not_drain_active_session(source, env, cache, work)
+ print("\nGREEN: Windows update handoff contract honored.")
+ return 0
+ except (GuardFailure, McpError, OSError, subprocess.SubprocessError) as exc:
+ print("\nRED: %s" % exc)
+ return 1
+ finally:
+ shutil.rmtree(work, ignore_errors=True)
+
+
+if __name__ == "__main__":
+ sys.exit(main())