初始提交:codebase-memory-mcp - Codebase Memory MCP Server

Fork from https://github.com/DeusData/codebase-memory-mcp
Go 实现,提供代码库记忆功能的 MCP 服务器
This commit is contained in:
xiaowei
2026-07-30 09:18:35 +08:00
commit f1e40eebb4
2049 changed files with 38420279 additions and 0 deletions
+134
View File
@@ -0,0 +1,134 @@
# Real-Windows local-CI leg
Windows kernel semantics cannot be reproduced by the container/Wine legs. The
UTM VM is a first-class part of the mandatory local-CI gate and is driven over
local ssh by the reproducible scripts in this directory. The canonical macOS
leg remains the native host; Linux runs through Colima.
## Windows VM — real ACL/token/owner semantics (script-driven)
Wine only compile-checks Windows. Kernel-real security semantics — object
ownership, DACLs, token identity, the Administrators-default-owner policy on
CI runners — need real Windows. The VM turns blind CI round-trips into a
seconds-fast local loop with full stderr/debugger visibility.
### Files
| File | Runs where | Purpose |
|---|---|---|
| `windows-bootstrap.ps1` | inside the VM, once | OpenSSH + host key + CI owner-policy mirror |
| `provision-windows.sh` | on the host | zero → fully-built, idempotent (disk-loss recovery) |
| `win.sh` | on the host | daily driver (`win.sh help`): routes every venue-grade command through the canonical leg scripts (`scripts/build.sh`, `scripts/test.sh`, `vm-smoke.sh`, `soak-legs.sh`) with clean-disk preflight |
| `vm-run-tests.sh` | inside the VM | provisioning wrapper (protected TEMP root + completion guard) around the canonical test/soak entries |
| `vm-smoke.sh` | inside the VM / CI msys2 | THE canonical Windows smoke (also run verbatim by PR CI and `_smoke.yml`) |
Host-local config (never committed): `~/.claude/cbm-vm/config` with
`CBM_VM_HOST=<ip>`, `CBM_VM_USER=<user>`, and the
`CBM_VM_HOST_KEY_SHA256=<SHA256:...>` fingerprint printed by the bootstrap.
`CBM_VM_BRANCH=<branch>` is optional; both drivers otherwise use the current
local Git branch, falling back to `main` only for a detached worktree.
The drivers verify that fingerprint before every connection. The ssh keypair is at
`~/.claude/cbm-vm/id_ed25519` (generate: `ssh-keygen -t ed25519 -N "" -C
claude-cbm-vm -f ~/.claude/cbm-vm/id_ed25519`; include the public half beside
`windows-bootstrap.ps1` on the setup ISO as documented in that script).
### One-time VM creation (~30 min interactive, do it once, snapshot it)
1. `brew install --cask utm` (free/open source).
2. Download the official **Windows 11 ARM64** ISO:
https://www.microsoft.com/software-download/windows11arm64
3. UTM → New VM → Virtualize → Windows → the ISO → **all host cores**,
12-16 GB RAM, 64+ GB disk. vCPUs are host-scheduled, not pinned: idle
guest cores cost nothing and nothing is seized from parallel work — no
artificial limits, speed first. RAM is the one bounded number (Windows
commits it eagerly).
4. Windows setup. At "Let's connect you to a network": Shift+Fn+F10 →
`start ms-cxh:localonly` → create a local account (no Microsoft account,
no network needed).
5. **⭐ Shut down and CLONE the VM in UTM now** ("Windows-CLEAN-backup").
Driver installs can brick the boot; the clone turns that into a 10-second
rollback instead of a reinstall. Boot the original afterwards.
6. Install the SPICE guest tools (network driver): download
https://github.com/utmapp/qemu/releases/download/v7.0.0-utm/spice-guest-tools-0.164.4.iso
on the host, mount via UTM's CD icon, run as administrator inside the VM,
restart. A brief "Display output is not active" during restart is normal.
7. Get `windows-bootstrap.ps1` into the VM via the ISO trick in its header
(clipboard and shared folders DO NOT work on Windows-ARM guests — the
SPICE vdagent/webdavd services don't exist there; don't chase them),
run it, note the printed ip/user, write `~/.claude/cbm-vm/config`,
reboot the VM once (owner policy).
8. From the host: `test-infrastructure/vm/provision-windows.sh` — installs
msys2 + both toolchains, clones the repo, builds everything, smoke-checks.
Re-run it any time; it is the single recovery command if the disk is lost.
### Daily loop
```
vm/win.sh update # sync VM repo to the pushed current branch + rebuild
vm/win.sh sync # mirror the uncommitted worktree and rebuild before local gates
vm/win.sh test cli daemon_ipc # run suites natively, seconds
vm/win.sh guards # the Windows guard scripts
vm/win.sh smoke-install # managed-install E2E, stderr VISIBLE
vm/win.sh soak 10 # native daemon endurance gate
vm/win.sh sh "cd /c/cbm && gdb ..." # anything, interactively
vm/win.sh push-file src/cli/cli.c /c/cbm/src/cli/cli.c # WIP iteration
```
`sync` requires the VM to already have the exact pushed base commit (`update`
does that); it then mirrors the host's uncommitted tracked and untracked changes,
cleans stale build outputs, and rebuilds.
### Toolchains & honest limits
- **CLANGARM64 (native, default)**: fast on all cores; OS-semantics bugs
(ACL/owner/paths/locks — the entire Windows tail class) reproduce
faithfully. Build with `SANITIZE=` (no ASan runtime exists for
aarch64-windows).
- **CLANG64 (x86_64 = CI's arch, emulated)**: arch-parity checks and
**UBSan, which WORKS under emulation** (validated: builds, runs, and
reports a planted signed-overflow with file:line) — `win.sh ubsan-build`
+ `ubsan-test <suites>`. UBSan needs no interceptors, which is why it
survives emulation.
- **ASan does NOT exist on this VM in either arch** — verified, don't
retry: the aarch64-windows compiler-rt ships no sanitizer runtimes at
all (MSVC's ARM64 ASan is a VS-2026 preview tied to the MSVC CRT), and
the x86_64 ASan runtime faults during process-init under x64-on-ARM
emulation. ASan coverage stays a CI-only leg; note the CI windows
failures have historically been logic failures, not ASan aborts.
- **PageHeap** (`win.sh pageheap on|off`): OS-level page-granular heap
overflow/UAF detection for the native ARM64 test-runner — a
toolchain-agnostic partial ASan substitute that works on real Windows.
- The bootstrap mirrors the GitHub-runner default-owner policy
(`NoDefaultAdminOwner=0`) so CI-only ownership refusals reproduce locally.
- Environment shape (runner temp paths, runneradmin profile) is
approximated, not identical — CI on the final SHA remains the proof.
## Honesty rules
- These legs never silently skip: absent tooling prints setup guidance and
exits with a distinct status.
- VM results complement, never replace, the CI matrix on the final SHA.
- Everything runs over the local UTM/host network only — nothing about the
VM loop touches the internet except the VM's own package/repo downloads.
## Ephemerality & Defender posture (venue parity)
A GitHub runner is ephemeral (fresh image, known-free disk, every job); this
VM is long-lived. The gap is closed by construction where possible and
documented honestly where not:
- **Preflight, every venue-grade command:** `clean-test-residue.ps1` sweeps
temp roots/staged binaries and asserts a runner-like free-disk floor, then
`scripts/ci/ensure-defender.ps1` enables + verifies Defender real-time
protection ON THIS VM (fail-closed: a drifted-off Defender goes red).
Hosted GitHub runners CANNOT match this posture — RTP is policy-locked off
on their images (verified 2026-07-27: WinDefend starts, Set-MpPreference
accepts, RTP stays off) — so AV-interaction coverage is a deliberate LOCAL
superset, and runner release scans stay on-demand (MpCmdRun, fail-soft).
- **Snapshot-revert is NOT scriptable via utmctl** (its verb set is
version/list/status/start/suspend/stop — no snapshot support), so per-run
revert-to-clean is not wired. The honest fallback is the sweep preflight
above. Opt-in alternative for a truly fresh start: shut the VM down and
manage qcow2 snapshots of the .utm disk offline (`qemu-img snapshot`) —
DESTRUCTIVE to VM state, so it is a deliberate manual step, never part of
the automated loop. `provision-windows.sh` remains the one-command rebuild.
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env bash
# provision-windows.sh — provision the Windows test VM from the macOS host.
#
# Idempotent: safe to re-run at any time; every step skips work already done.
# Recovers a fresh VM (or a lost disk) to fully-built state in one command.
#
# Prerequisites (one-time, manual — see README.md):
# 1. UTM VM with Windows 11 ARM64 installed, CLONED as a backup before
# drivers, SPICE guest tools installed (network), and
# windows-bootstrap.ps1 run inside the VM (OpenSSH + authorized key).
# 2. Host config in ~/.claude/cbm-vm/config (KEY=VALUE), values printed by
# windows-bootstrap.ps1 at the end of its run:
# CBM_VM_HOST=<vm ip>
# CBM_VM_USER=<vm user>
# CBM_VM_HOST_KEY_SHA256=<SHA256:... host-key fingerprint>
# Key at ~/.claude/cbm-vm/id_ed25519 (see README.md to generate your own;
# never commit keys or this config).
#
# Usage:
# test-infrastructure/vm/provision-windows.sh # full provision
# test-infrastructure/vm/provision-windows.sh --update # repo+build only
set -euo pipefail
CONFIG="${HOME}/.claude/cbm-vm/config"
KEY="${HOME}/.claude/cbm-vm/id_ed25519"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# The fixed host-local config is intentionally outside this repository.
# shellcheck source=/dev/null
[ -f "$CONFIG" ] && . "$CONFIG"
HOST="${CBM_VM_HOST:?set CBM_VM_HOST in ~/.claude/cbm-vm/config}"
USER_="${CBM_VM_USER:-test}"
HOST_KEY="${CBM_VM_HOST_KEY_SHA256:?set CBM_VM_HOST_KEY_SHA256 in ~/.claude/cbm-vm/config}"
LOCAL_BRANCH="$(git -C "$ROOT" branch --show-current)"
BRANCH="${CBM_VM_BRANCH:-${LOCAL_BRANCH:-main}}"
REPO_URL="${CBM_VM_REPO:-https://github.com/DeusData/codebase-memory-mcp.git}"
MSYS2_SFX_URL="https://github.com/msys2/msys2-installer/releases/download/2026-06-11/msys2-base-x86_64-20260611.sfx.exe"
MSYS2_SFX_SHA256="c105946e64e08f099ac0e4647461ce762b95333ad211777666476a9a41451d65"
# shellcheck source=test-infrastructure/vm/ssh-common.sh
source "$SCRIPT_DIR/ssh-common.sh"
cbm_vm_require_safe_branch "$BRANCH"
cbm_vm_prepare_known_hosts "$HOST" "$HOST_KEY"
trap cbm_vm_cleanup_known_hosts EXIT
SSH_OPTIONS=(-i "$KEY" -o IdentitiesOnly=yes -o HostKeyAlgorithms=ssh-ed25519 \
-o StrictHostKeyChecking=yes -o UserKnownHostsFile="$CBM_VM_KNOWN_HOSTS" \
-o ConnectTimeout=10 -o BatchMode=yes)
SSH=(ssh "${SSH_OPTIONS[@]}" "${USER_}@${HOST}")
# Expand inside the remote MSYS2 shell, not on the macOS host.
# shellcheck disable=SC2016
JOBS='$(nproc)'
# Run a command inside the given msys2 environment (clangarm64|clang64|msys).
vm() { # vm <env> <command...>
local env="$1"; shift
"${SSH[@]}" "C:\\msys64\\msys2_shell.cmd -defterm -no-start -${env} -c \"set -e -o pipefail; $*\""
}
vm_cmd() { "${SSH[@]}" "$@"; } # plain cmd.exe
vm_powershell() { cbm_vm_run_powershell "$1" "${SSH[@]}"; }
step() { printf '\n\033[1m== %s ==\033[0m\n' "$*"; }
step "0/6 reachability"
vm_cmd "echo VM_OK & ver" | grep -q VM_OK || {
echo "FATAL: cannot reach ${USER_}@${HOST} over ssh." >&2
echo "Run windows-bootstrap.ps1 inside the VM first (see README.md)." >&2
exit 1
}
cbm_vm_sync_windows_clock "${SSH[@]}"
if [ "${1:-}" != "--update" ]; then
step "1/6 msys2 base (skip if present)"
if ! vm_cmd "if exist C:\\msys64\\usr\\bin\\bash.exe echo MSYS2_PRESENT" | grep -q MSYS2_PRESENT; then
vm_powershell "\$ProgressPreference='SilentlyContinue'; [Net.ServicePointManager]::SecurityProtocol='Tls12'; Invoke-WebRequest -Uri '${MSYS2_SFX_URL}' -OutFile C:\\msys2.sfx.exe; \$actual=(Get-FileHash -LiteralPath C:\\msys2.sfx.exe -Algorithm SHA256).Hash.ToLowerInvariant(); if (\$actual -ne '${MSYS2_SFX_SHA256}') { Remove-Item -LiteralPath C:\\msys2.sfx.exe -Force; throw 'MSYS2 installer SHA-256 mismatch' }"
vm_cmd "C:\\msys2.sfx.exe -y -oC:\\" >/dev/null
vm_cmd "del C:\\msys2.sfx.exe"
vm "msys" "pacman-key --init && pacman-key --populate msys2"
fi
step "2/6 pacman full update (official two-pass sequence)"
vm "msys" "pacman --noconfirm --noprogressbar -Syuu"
vm "msys" "pacman --noconfirm --noprogressbar -Syuu"
step "3/6 toolchains: CLANGARM64 (native, fast) + CLANG64 (x86_64 = CI arch, ASan)"
vm "msys" "pacman -S --noconfirm --noprogressbar --needed \
git make coreutils curl zip unzip \
mingw-w64-clang-aarch64-clang mingw-w64-clang-aarch64-zlib \
mingw-w64-clang-aarch64-python mingw-w64-clang-aarch64-ccache \
mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-compiler-rt \
mingw-w64-clang-x86_64-zlib mingw-w64-clang-x86_64-ccache"
step "3b/6 official Node.js + VC++ runtime (guards UI build)"
# MSVC-built npm native modules (rollup) cannot resolve Node-API symbols
# against MSYS2's mingw node, and they need the VC++ runtime. Pinned
# official builds, hash/signature-verified.
NODE_VERSION="v22.23.1"
NODE_SHA256="b470fdfe3502c05151656e06d495e3f47544f2ee8b1d9c8705090f2dd5996bd0"
if ! vm_cmd "if exist C:\\node\\node.exe echo NODE_PRESENT" | grep -q NODE_PRESENT; then
vm_powershell "\$ProgressPreference='SilentlyContinue'; Invoke-WebRequest -Uri 'https://nodejs.org/dist/${NODE_VERSION}/node-${NODE_VERSION}-win-arm64.zip' -OutFile C:\\node.zip; \$actual=(Get-FileHash -LiteralPath C:\\node.zip -Algorithm SHA256).Hash.ToLowerInvariant(); if (\$actual -ne '${NODE_SHA256}') { Remove-Item C:\\node.zip; throw 'node SHA-256 mismatch' }; Expand-Archive -LiteralPath C:\\node.zip -DestinationPath C:\\; Move-Item C:\\node-${NODE_VERSION}-win-arm64 C:\\node; Remove-Item C:\\node.zip"
fi
if ! vm_cmd "if exist C:\\Windows\\System32\\vcruntime140.dll echo VCR_PRESENT" | grep -q VCR_PRESENT; then
vm_powershell "\$ProgressPreference='SilentlyContinue'; Invoke-WebRequest -Uri 'https://aka.ms/vs/17/release/vc_redist.arm64.exe' -OutFile C:\\vc_redist.arm64.exe; \$sig = Get-AuthenticodeSignature C:\\vc_redist.arm64.exe; if (\$sig.Status -ne 'Valid') { throw 'vc_redist unsigned' }; Start-Process C:\\vc_redist.arm64.exe -ArgumentList '/install','/quiet','/norestart' -Wait; Remove-Item C:\\vc_redist.arm64.exe"
fi
fi
step "4/6 repo clone/update -> /c/cbm @ ${BRANCH}"
if vm "clangarm64" "test -d /c/cbm/.git && echo REPO_PRESENT" | grep -q REPO_PRESENT; then
vm "clangarm64" "cd /c/cbm && git fetch origin ${BRANCH} && git reset --hard FETCH_HEAD && git clean -fdx && git log --oneline -1"
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 + 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"
vm "clangarm64" "cd /c/cbm && ./build/c/codebase-memory-mcp.exe --version && ./build/c/test-runner --list-suites | head -3"
printf '\n\033[1mPROVISION COMPLETE\033[0m — daily driving: test-infrastructure/vm/win.sh\n'
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env bash
# Shared pinned-host verification for the local Windows VM drivers.
cbm_vm_require_safe_branch() {
local branch="${1-}"
if [[ ! "$branch" =~ ^[A-Za-z0-9][A-Za-z0-9._/-]*$ ]] ||
! git check-ref-format --branch "$branch" >/dev/null 2>&1; then
echo "FATAL: CBM_VM_BRANCH is not a safe Git branch name: $branch" >&2
return 1
fi
}
cbm_vm_prepare_known_hosts() {
local host="$1"
local expected="$2"
local actual
if [[ ! "$expected" =~ ^SHA256:[A-Za-z0-9+/]{43}$ ]]; then
echo "FATAL: CBM_VM_HOST_KEY_SHA256 is missing or malformed." >&2
echo " Copy the SHA256:... Ed25519 fingerprint printed by windows-bootstrap.ps1." >&2
return 1
fi
CBM_VM_KNOWN_HOSTS="$(mktemp "${TMPDIR:-/tmp}/cbm-vm-known-hosts.XXXXXX")"
chmod 600 "$CBM_VM_KNOWN_HOSTS"
if ! ssh-keyscan -T 10 -t ed25519 "$host" >"$CBM_VM_KNOWN_HOSTS" 2>/dev/null; then
echo "FATAL: could not read the Windows VM Ed25519 host key at $host." >&2
cbm_vm_cleanup_known_hosts
return 1
fi
actual="$(ssh-keygen -lf "$CBM_VM_KNOWN_HOSTS" -E sha256 2>/dev/null | awk '{print $2}')"
if [ "$actual" != "$expected" ]; then
echo "FATAL: Windows VM SSH host-key mismatch." >&2
echo " expected: $expected" >&2
echo " observed: ${actual:-unreadable}" >&2
echo " Stop: verify the fingerprint from the VM console; do not accept it blindly." >&2
cbm_vm_cleanup_known_hosts
return 1
fi
}
cbm_vm_cleanup_known_hosts() {
if [ -n "${CBM_VM_KNOWN_HOSTS:-}" ]; then
rm -f -- "$CBM_VM_KNOWN_HOSTS"
CBM_VM_KNOWN_HOSTS=""
fi
}
# Send PowerShell source without exposing its metacharacters to the remote
# account shell. OpenSSH joins remote argv into one command string; raw
# parentheses, pipes, and semicolons can therefore be reinterpreted before
# PowerShell sees them. Windows PowerShell's encoded-command contract is
# UTF-16LE base64, produced locally from trusted repository-owned source.
# Usage: cbm_vm_run_powershell '<source>' "${SSH[@]}"
cbm_vm_run_powershell() {
local source="${1-}"
shift || true
if [ "$#" -eq 0 ]; then
echo "FATAL: encoded PowerShell requires an SSH command" >&2
return 1
fi
local encoded
if ! encoded="$(printf '%s' "$source" | iconv -f UTF-8 -t UTF-16LE | base64 | tr -d '\r\n')"; then
echo "FATAL: could not encode PowerShell source for the Windows VM." >&2
return 1
fi
"$@" "powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand $encoded"
}
# UTM guests can resume with their wall clock tens of minutes behind the host.
# Besides invalidating TLS and timeout evidence, that makes freshly mirrored
# source files appear "from the future", so make can repeatedly rebuild or
# incorrectly reason about dependencies. Set the dedicated test VM from the
# trusted local host clock, then fail unless the observed UTC epoch is close.
# Arguments are the complete pinned SSH command array.
cbm_vm_sync_windows_clock() {
if [ "$#" -eq 0 ]; then
echo "FATAL: Windows VM clock sync requires an SSH command" >&2
return 1
fi
local host_utc
local host_epoch
local guest_output
local guest_epoch
local skew
local powershell_source
local attempt
# A host sleep can pause QEMU after host_utc is captured but before the
# guest is set and validated. Retry from a fresh host timestamp instead of
# accepting the stale clock or requiring a manual VM restart.
for attempt in 1 2 3; do
host_utc="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
powershell_source="Set-Date -Date ([DateTimeOffset]::Parse('${host_utc}', [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::AssumeUniversal).LocalDateTime) | Out-Null; [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()"
if ! guest_output="$(cbm_vm_run_powershell "$powershell_source" "$@")"; then
echo "FATAL: could not synchronize the Windows VM clock from the host." >&2
return 1
fi
guest_epoch="$(printf '%s\n' "$guest_output" | tr -d '\r' | tail -n 1)"
case "$guest_epoch" in
'' | *[!0-9]*)
echo "FATAL: Windows VM clock sync returned an invalid epoch: $guest_epoch" >&2
return 1
;;
esac
host_epoch="$(date -u '+%s')"
skew=$((host_epoch - guest_epoch))
if [ "$skew" -lt 0 ]; then
skew=$((-skew))
fi
if [ "$skew" -le 15 ]; then
echo "WINDOWS_CLOCK_OK skew=${skew}s"
return 0
fi
done
echo "FATAL: Windows VM clock remains ${skew}s from the host after synchronization." >&2
return 1
}
cbm_vm_write_untracked_manifest() {
local root="$1"
local manifest="$2"
local symlinks
local entry
local mode
local relative
local link
local nested
symlinks="$(mktemp "${TMPDIR:-/tmp}/cbm-vm-symlinks.XXXXXX")"
: >"$manifest"
while IFS= read -r -d '' entry; do
mode="${entry%% *}"
relative="${entry#*$'\t'}"
if [ "$mode" = "120000" ]; then
printf '%s\0' "$relative" >>"$symlinks"
fi
done < <(git -C "$root" ls-files --stage -z)
while IFS= read -r -d '' relative; do
nested=false
while IFS= read -r -d '' link; do
case "$relative" in
"$link"/*) nested=true; break ;;
esac
done <"$symlinks"
if ! $nested && [ -L "$root/$relative" ]; then
echo "FATAL: untracked symlink cannot be mirrored to Windows: $relative" >&2
echo " Stage the symlink so the binary Git patch carries its platform semantics." >&2
rm -f -- "$symlinks"
return 1
fi
if ! $nested && [ -e "$root/$relative" ]; then
printf '%s\0' "$relative" >>"$manifest"
fi
done < <(git -C "$root" ls-files --others --exclude-standard -z)
rm -f -- "$symlinks"
}
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env bash
# vm-run-tests.sh — run C test suites on the Windows VM under a CI-shaped
# protected temp root. Runs ON the VM (MSYS2 shell), invoked by win.sh
# test / ubsan-test / trap-ubsan-test / soak.
#
# Why the temp root: the daemon/coordination suites fail closed on the
# MSYS-shared /tmp (C:\msys64\tmp), whose ancestry grants mutation rights to
# Authenticated Users — running them there produces security refusals, not
# test signal. CI gives the harness a per-user root under the profile with an
# owner-stamped, protected current-SID DACL (.github/workflows/_test.yml
# "Create protected per-user temp root"); this script mirrors that exactly so
# the VM leg validates what CI will see.
#
# Why the guard: this leg once piped through `tail -40`, and a suite that
# never validly ran looked green — 40 Windows failures reached CI unseen.
# Output now streams in full, and a run whose log lacks the runner's
# completion summary is a hard failure regardless of exit code.
set -uo pipefail
usage() {
cat <<'EOF'
Usage: bash test-infrastructure/vm/vm-run-tests.sh <suite...> | --par | --soak <minutes>
VM-side provisioning wrapper (runs ON the Windows VM, invoked by win.sh —
call `win.sh test|test-par|soak` from the host, not this file). Supplies the
CI-shaped protected per-user temp root (scripts/ci/new-protected-temp-root.ps1)
and full-output logging with a completion-summary guard, then routes into the
CANONICAL entries:
<suite...> scripts/test.sh --suites <list> (iteration mode)
--par scripts/test.sh (the full venue leg)
--soak <mins> scripts/soak-legs.sh (both CI soak legs)
Environment:
CBM_VM_RUNNER sanitizer-variant runner path (ubsan/trap-ubsan builds);
switches to direct-runner mode for those iteration tools.
CBM_VM_SOAK_BINARY product binary for --soak (default build/c/codebase-memory-mcp.exe)
CBM_VM_TEST_LOG VM-side log path (default /tmp/win-test.log)
Exit codes: 0 success · 2 usage · 90 = GUARD: no completion summary (a run
that died without its summary must never read as green) · else the leg's code.
EOF
}
case "${1:-}" in
-h | --help) usage; exit 0 ;;
esac
RUNNER="${CBM_VM_RUNNER:-}"
LOG="${CBM_VM_TEST_LOG:-/tmp/win-test.log}"
[ $# -ge 1 ] || { echo "vm-run-tests: missing arguments. Please consult --help." >&2; exit 2; }
if [ "$1" = "--soak" ]; then
[ $# -eq 2 ] || { echo "usage: vm-run-tests.sh --soak <positive-minutes>" >&2; exit 2; }
duration="$2"
case "$duration" in
''|*[!0-9]*) echo "usage: vm-run-tests.sh --soak <positive-minutes>" >&2; exit 2 ;;
esac
[ "$duration" -gt 0 ] ||
{ echo "usage: vm-run-tests.sh --soak <positive-minutes>" >&2; exit 2; }
binary="${CBM_VM_SOAK_BINARY:-build/c/codebase-memory-mcp.exe}"
[ -x "$binary" ] || { echo "ERROR: binary '$binary' missing — build first" >&2; exit 2; }
artifact="$binary"
elif [ -n "$RUNNER" ]; then
# Explicit CBM_VM_RUNNER = the sanitizer-variant iteration mode (ubsan /
# trap-ubsan runners built into their own BUILD_DIRs by win.sh). Those
# builds carry non-default flags, so they keep the direct-runner path.
[ -x "$RUNNER" ] || { echo "ERROR: runner '$RUNNER' missing — build first" >&2; exit 2; }
artifact="$RUNNER"
else
# Default path: suites run through the canonical scripts/test.sh (which
# builds its own runner, same as CI's test jobs). ACL-protect the build
# directory it will use.
artifact="build/c/test-runner"
fi
# Stale roots from earlier runs are removed up front; the current root is kept
# after the run for post-mortem inspection. The root itself is created by the
# same script CI uses (scripts/ci/new-protected-temp-root.ps1) so the two venues
# cannot drift apart on the ACL shape the daemon suites are validated against.
root_windows="$(MSYS2_ARG_CONV_EXCL='*' powershell.exe -NoProfile \
-ExecutionPolicy Bypass \
-File "$(cygpath -w scripts/ci/new-protected-temp-root.ps1)" \
-Prefix 'cbm-vm-tmp-' -PruneStale \
-ProtectDir "$(cygpath -w "$(dirname "$artifact")")" | tr -d '\r')"
[ -n "$root_windows" ] || { echo "ERROR: protected temp root creation failed" >&2; exit 2; }
TEMP="$(cygpath -m "$root_windows")"
TMP="$TEMP"
TMPDIR="$(cygpath -u "$root_windows")"
export TEMP TMP TMPDIR
# The runner's directory must look like a real user checkout: repos under a
# profile carry no Authenticated-Users ACE, but C:\cbm (like CI's workspace
# drive) inherits Modify for Authenticated Users from the drive root, which
# the activation transaction's source-directory policy correctly refuses —
# install-flow tests would then fail on the environment, not the code.
# Two steps, both idempotent: protect the DIRECTORY (inheritance flags are
# directory-only — a /T re-root leaves files with empty, deny-all DACLs),
# then /reset the children so they re-inherit the clean set from it.
runner_dir_w="$(cygpath -w "$(dirname "$artifact")")"
me="$(whoami | tr -d '\r')"
MSYS2_ARG_CONV_EXCL='*' icacls "$runner_dir_w" /inheritance:r \
/grant:r "${me}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' \
/Q >/dev/null 2>&1 || true
MSYS2_ARG_CONV_EXCL='*' icacls "${runner_dir_w}\\*" /reset /T /C /Q >/dev/null 2>&1 || true
echo "=== vm-run-tests: runner=$RUNNER temp=$TEMP suites: $* ==="
if [ "$1" = "--soak" ]; then
# The sequence (quick + #581 query-leak) and its completion guards live in
# the canonical entry scripts/soak-legs.sh — the same file _soak.yml and the
# compose soak service run. This wrapper only supplies the CI-shaped
# protected temp root (above) and the persistent VM-side log.
echo "=== vm-run-tests: soak binary=$binary temp=$TEMP ${duration}m/leg ==="
scripts/soak-legs.sh "$binary" "$duration" 2>&1 | tee "$LOG"
exit "${PIPESTATUS[0]}"
fi
# Both paths run the CANONICAL test entry scripts/test.sh under this protected
# environment — the same file every CI test leg runs:
# --par the full venue leg (clean build + contracts + parallel suites)
# <suite...> scripts/test.sh --suites — the documented iteration mode
# Only an explicit CBM_VM_RUNNER (sanitizer-variant builds) bypasses test.sh.
if [ -n "$RUNNER" ]; then
if [ "$1" = "--par" ]; then
bash scripts/run-tests-parallel.sh "$RUNNER" 2>&1 | tee "$LOG"
rc="${PIPESTATUS[0]}"
else
"$RUNNER" "$@" 2>&1 | tee "$LOG"
rc="${PIPESTATUS[0]}"
fi
elif [ "$1" = "--par" ]; then
scripts/test.sh CC=clang CXX=clang++ 2>&1 | tee "$LOG"
rc="${PIPESTATUS[0]}"
else
scripts/test.sh --suites "$*" CC=clang CXX=clang++ 2>&1 | tee "$LOG"
rc="${PIPESTATUS[0]}"
fi
if ! grep -Eq '[0-9]+ passed' "$LOG"; then
echo "GUARD: test runner produced no completion summary — the suites did" \
"not validly run; treating as failure (runner rc=$rc)" >&2
exit 90
fi
exit "$rc"
+255
View File
@@ -0,0 +1,255 @@
#!/usr/bin/env bash
# vm-smoke.sh — the ONE Windows smoke harness. Every venue calls this script:
# local CI (win.sh smoke-install), PR CI (pr.yml pr-smoke) and the release
# venues (_smoke.yml). They differ only in host specs, architecture, and which
# binaries they hand it — never in what the smoke does.
#
# Stages and serves a complete Windows release fixture from a profile-rooted
# directory. MSYS2 /tmp and the shared runner workspace are intentionally not
# valid install roots.
#
# Run inside the VM's CLANGARM64 shell from the repo root:
# bash test-infrastructure/vm/vm-smoke.sh
# Or from the host: test-infrastructure/vm/win.sh smoke-install
set -euo pipefail
usage() {
cat <<'EOF'
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 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).
Run inside the VM's CLANGARM64 shell (or a CI msys2 shell) from the repo root.
Environment:
SMOKE_ARCH arm64 (default) | amd64 — selects the served artifact name.
SMOKE_VARIANT standard (default) | ui. ui requires the embedded UI:
Phase 15's "no assets" SKIP becomes a FAILURE, so a standard
binary cannot pass a ui run.
CBM_SMOKE_ARTIFACT_DIR
Release mode: an EXTRACTED windows release artifact
(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
}
case "${1:-}" in
-h|--help) usage; exit 0 ;;
?*) echo "vm-smoke: unexpected argument '$1' (configuration is via environment). Please consult --help." >&2; exit 2 ;;
esac
cd "$(dirname "$0")/../.."
ROOT="$PWD"
# Two staging sources, one smoke. Unset (the local + PR default): stage the
# 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 \
LICENSE install.ps1 THIRD_PARTY_NOTICES.md; do
[ -s "$ARTIFACT_DIR/$required" ] ||
{ echo "vm-smoke: release artifact is missing $required" >&2; exit 2; }
done
BINARY_SRC="$ARTIFACT_DIR/codebase-memory-mcp.exe"
else
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}"
SMOKE_VARIANT="${SMOKE_VARIANT:-standard}"
case "$SMOKE_ARCH" in
arm64 | amd64) ;;
*) echo "vm-smoke: SMOKE_ARCH must be arm64 or amd64. Please consult --help." >&2; exit 2 ;;
esac
# A ui run must be handed a binary that actually carries the embedded assets;
# the suffix alone only renames the archive. SMOKE_REQUIRE_UI turns Phase 15's
# documented "no embedded assets" SKIP into a failure, so asking for ui and
# supplying a standard binary can no longer pass quietly.
case "$SMOKE_VARIANT" in
standard) SUFFIX="" ; REQUIRE_UI=0 ;;
ui) SUFFIX="-ui" ; REQUIRE_UI=1 ;;
*) echo "vm-smoke: SMOKE_VARIANT must be standard or ui. Please consult --help." >&2; exit 2 ;;
esac
PROFILE_ROOT="$(cygpath -u "$USERPROFILE")"
SMOKE_DIR="$(mktemp -d "$PROFILE_ROOT/cbm-vm-smoke.XXXXXX")"
FIXTURE_DIR="$SMOKE_DIR/artifacts"
SMOKE_HOME="$SMOKE_DIR/home"
SMOKE_XDG_CONFIG="$SMOKE_DIR/xdg-config"
SMOKE_APPDATA="$SMOKE_DIR/appdata"
SMOKE_LOCALAPPDATA="$SMOKE_DIR/localappdata"
SMOKE_TEMP_DIR="$SMOKE_DIR/temp"
PORT_FILE="$SMOKE_DIR/port"
SERVER_LOG="$SMOKE_DIR/server.log"
SERVER_PID=""
PATH_GUARD="$ROOT/test-infrastructure/vm/windows-user-path-guard.ps1"
PATH_SNAPSHOT="$SMOKE_DIR/user-path-snapshot.json"
PATH_RUN_ID=""
PATH_GUARD_READY=0
cleanup() {
local status=$?
trap - EXIT
if [ -n "$SERVER_PID" ]; then
kill "$SERVER_PID" 2>/dev/null || true
wait "$SERVER_PID" 2>/dev/null || true
fi
if [ "$PATH_GUARD_READY" -eq 1 ]; then
if ! MSYS2_ARG_CONV_EXCL='*' powershell.exe -NoProfile -ExecutionPolicy Bypass \
-File "$(cygpath -w "$PATH_GUARD")" \
-Mode cleanup \
-RunId "$PATH_RUN_ID" \
-SnapshotPath "$(cygpath -w "$PATH_SNAPSHOT")" \
-SmokeRoot "$(cygpath -w "$SMOKE_DIR")"; then
echo "vm-smoke: isolated registry cleanup failed" >&2
status=1
fi
fi
if [ "$status" -eq 0 ]; then
rm -rf "$SMOKE_DIR"
else
echo "vm-smoke: preserved failed smoke root at $SMOKE_DIR" >&2
fi
exit "$status"
}
trap cleanup EXIT
mkdir -p "$FIXTURE_DIR" "$SMOKE_HOME" "$SMOKE_XDG_CONFIG" "$SMOKE_APPDATA" \
"$SMOKE_LOCALAPPDATA" "$SMOKE_TEMP_DIR"
PATH_RUN_ID=$(
powershell.exe -NoProfile -Command \
"[Guid]::NewGuid().ToString('N')" | tr -d '\r\n'
)
if ! printf '%s' "$PATH_RUN_ID" | grep -qE '^[0-9A-Fa-f]{32}$'; then
echo "vm-smoke: could not generate an isolated registry run ID" >&2
exit 1
fi
PATH_GUARD_READY=1
MSYS2_ARG_CONV_EXCL='*' powershell.exe -NoProfile -ExecutionPolicy Bypass \
-File "$(cygpath -w "$PATH_GUARD")" \
-Mode prepare \
-RunId "$PATH_RUN_ID" \
-SnapshotPath "$(cygpath -w "$PATH_SNAPSHOT")" \
-SmokeRoot "$(cygpath -w "$SMOKE_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.
if [ -n "$ARTIFACT_DIR" ]; then
cp "$ARTIFACT_DIR/LICENSE" "$ARTIFACT_DIR/install.ps1" \
"$ARTIFACT_DIR/THIRD_PARTY_NOTICES.md" "$FIXTURE_DIR/"
else
cp LICENSE install.ps1 "$FIXTURE_DIR/"
scripts/gen-third-party-notices.sh "$FIXTURE_DIR/THIRD_PARTY_NOTICES.md"
fi
EXPECTED_ARTIFACT="codebase-memory-mcp${SUFFIX}-windows-${SMOKE_ARCH}.zip"
(
cd "$FIXTURE_DIR"
zip -q "$EXPECTED_ARTIFACT" \
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
sha256sum *.zip > checksums.txt
)
python3 "$ROOT/scripts/smoke-fixture-server.py" \
--directory "$FIXTURE_DIR" --port-file "$PORT_FILE" \
>"$SERVER_LOG" 2>&1 &
SERVER_PID=$!
PORT=""
READY=0
for _ in $(seq 1 100); do
if [ -s "$PORT_FILE" ]; then
PORT=$(tr -d '[:space:]' < "$PORT_FILE")
# Header-only readiness: a HEAD proves the server routes the artifact
# without transferring the archive body on every poll (hosted Windows
# runners reset mid-body full-GET polls — WinError 10054 on the server,
# 99 aborted transfers per job — while the same stack passes on the VM;
# the real download phases still exercise full transfers and report
# phase-precise if body transport is broken).
if curl --noproxy '*' -fsSI \
"http://127.0.0.1:$PORT/$EXPECTED_ARTIFACT" >/dev/null 2>&1; then
READY=1
break
fi
fi
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
break
fi
sleep 0.1
done
if [ "$READY" -ne 1 ]; then
echo "vm-smoke: fixture server did not serve $EXPECTED_ARTIFACT" >&2
echo "--- fixture server log ---" >&2
cat "$SERVER_LOG" >&2
exit 1
fi
# The release smoke performs real agent config mutations. Neutralize every
# supported destination override before entering it; individual phases may set
# an intentional override of their own beneath SMOKE_DIR.
env \
-u CLAUDE_CONFIG_DIR \
-u CODEX_HOME \
-u KIRO_HOME \
-u HERMES_HOME \
-u QWEN_HOME \
-u CLINE_DATA_DIR \
-u OPENCLAW_HOME \
-u OPENCLAW_STATE_DIR \
-u OPENCLAW_PROFILE \
-u OPENCLAW_CONFIG_PATH \
-u OPENCLAW_WORKSPACE_DIR \
-u OPENCODE_CONFIG \
-u OPENCODE_CONFIG_DIR \
-u COPILOT_HOME \
-u CRUSH_GLOBAL_CONFIG \
-u VIBE_HOME \
-u GLAB_CONFIG_DIR \
-u KIMI_CODE_HOME \
-u CBM_CONTINUE_CONFIG_PATH \
-u CBM_TRAE_CONFIG_PATH \
-u CBM_ROO_CONFIG_PATH \
-u CBM_CODY_CONFIG_PATH \
-u CBM_TEST_WINDOWS_USER_PATH_RUN_ID \
HOME="$(cygpath -m "$SMOKE_HOME")" \
USERPROFILE="$(cygpath -m "$SMOKE_HOME")" \
XDG_CONFIG_HOME="$(cygpath -m "$SMOKE_XDG_CONFIG")" \
APPDATA="$(cygpath -m "$SMOKE_APPDATA")" \
LOCALAPPDATA="$(cygpath -m "$SMOKE_LOCALAPPDATA")" \
TMPDIR="$SMOKE_TEMP_DIR" \
TEMP="$(cygpath -m "$SMOKE_TEMP_DIR")" \
TMP="$(cygpath -m "$SMOKE_TEMP_DIR")" \
SHELL="/usr/bin/bash" \
CBM_CACHE_DIR="$(cygpath -m "$SMOKE_DIR/cache")" \
CBM_TEST_WINDOWS_USER_PATH_RUN_ID="$PATH_RUN_ID" \
SMOKE_TEMP_ROOT="$SMOKE_DIR" \
SMOKE_DOWNLOAD_URL="http://127.0.0.1:$PORT" \
SMOKE_UPDATE_FIXTURE_DIR="$FIXTURE_DIR" \
SMOKE_ARCH="$SMOKE_ARCH" \
SMOKE_REQUIRE_UI="$REQUIRE_UI" \
scripts/smoke-test.sh "$SMOKE_DIR/codebase-memory-mcp.exe"
MSYS2_ARG_CONV_EXCL='*' powershell.exe -NoProfile -ExecutionPolicy Bypass \
-File "$(cygpath -w "$PATH_GUARD")" \
-Mode verify \
-RunId "$PATH_RUN_ID" \
-SnapshotPath "$(cygpath -w "$PATH_SNAPSHOT")" \
-SmokeRoot "$(cygpath -w "$SMOKE_DIR")"
+329
View File
@@ -0,0 +1,329 @@
#!/usr/bin/env bash
# win.sh — daily driver for the Windows test VM (real-Windows leg of local CI).
#
# All commands run over ssh (local UTM network only — nothing leaves the
# machine). Config: ~/.claude/cbm-vm/config (CBM_VM_HOST, CBM_VM_USER),
# key: ~/.claude/cbm-vm/id_ed25519. Provision first: provision-windows.sh.
#
# Usage:
# win.sh status # reachability + repo + build state
# win.sh update # fetch+reset repo to pushed branch, rebuild
# win.sh sync # mirror this uncommitted worktree + rebuild
# win.sh build # incremental native build (binary+runner)
# win.sh test <suite...> # run test-runner suites (native ARM64)
# win.sh guards # clean UI product build + Windows guards
# win.sh smoke-install # real managed-install E2E (Phase 8 class)
# win.sh smoke-artifact # release-archive flow (package+extract+smoke)
# win.sh soak [minutes] # both CI soak legs: quick + #581 query-leak
# win.sh sh <command...> # arbitrary command in CLANGARM64 env
# win.sh push-file <local> <vm> # scp one file into the VM (WIP iteration)
# win.sh test-par # full suite, parallel on all VM cores
# win.sh ubsan-build|ubsan-test # UBSan at CI's x86_64 arch (emulated; works)
# win.sh trap-ubsan-build|-test # NATIVE ARM64 UBSan (trap mode, no runtime)
# win.sh pageheap on|off # OS heap verification for native runs
set -euo pipefail
# help must not require a configured VM: agents discovering the tooling read
# --help before anything exists. Handled before config/ssh setup.
print_help() {
cat <<'EOF'
Usage: test-infrastructure/vm/win.sh <command> [args]
Daily driver for the real-Windows leg of local CI (UTM ARM64 VM over ssh).
Every venue-grade command routes through the CANONICAL leg scripts — the same
files CI runs (scripts/build.sh, scripts/test.sh, vm-smoke.sh, soak-legs.sh);
this wrapper only provisions (ssh, clock sync, clean-disk preflight, protected
temp root). Config: ~/.claude/cbm-vm/config (CBM_VM_HOST, CBM_VM_USER,
CBM_VM_HOST_KEY_SHA256); key: ~/.claude/cbm-vm/id_ed25519; first-time setup:
test-infrastructure/vm/provision-windows.sh.
Commands (venue-grade — canonical entries, preflight enforced):
update fetch+reset the VM repo to the pushed branch, rebuild
sync mirror this uncommitted worktree to the VM, rebuild
build scripts/build.sh (CLEAN + content-verified ccache)
test <suite...> scripts/test.sh --suites (iteration mode: incremental
rebuild, subset run, seconds; list suites with
`win.sh sh 'build/c/test-runner --list-suites'`)
test-par scripts/test.sh — THE full Windows ladder leg (clean
build + contracts + all suites + guards, as CI runs it)
guards clean UI product build + Windows guard suite (CI shape)
smoke-install scripts/build.sh + vm-smoke.sh — exactly PR CI's
windows smoke job
smoke-artifact package-release.sh → extract → vm-smoke.sh artifact
mode — the release archive flow with local bytes
soak [minutes] both CI soak legs via scripts/soak-legs.sh (default 10)
Sanitizer variants (documented iteration tools; direct-runner mode):
ubsan-build|ubsan-test <suite...> x86_64 UBSan under emulation (full
diagnostics; CI's exact x64 arch)
trap-ubsan-build|trap-ubsan-test <...> native ARM64 trap-mode UBSan (a UB
hit is a SIGILL trap; diagnose via
the emulated ubsan pair)
pageheap on|off OS heap verification for the native runner (IFEO)
Plumbing (no preflight):
status reachability + repo + build state
sh <command...> arbitrary command in the CLANGARM64 shell
push-file <src> <dst> scp one file into the VM (WIP iteration)
help this text
Environment:
CBM_VM_BRANCH branch for update (default: current local branch)
CBM_VM_MIN_FREE_GB preflight free-disk floor (default 14, runner spec)
CBM_VM_SKIP_PREFLIGHT=1 bootstrap-only escape (checkout predates the script)
Exit codes: 0 success · 2 usage error · other = the canonical leg's own code.
EOF
}
case "${1:-}" in
help | -h | --help) print_help; exit 0 ;;
esac
CONFIG="${HOME}/.claude/cbm-vm/config"
KEY="${HOME}/.claude/cbm-vm/id_ed25519"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# The fixed host-local config is intentionally outside this repository.
# shellcheck source=/dev/null
[ -f "$CONFIG" ] && . "$CONFIG"
HOST="${CBM_VM_HOST:?set CBM_VM_HOST in ~/.claude/cbm-vm/config}"
USER_="${CBM_VM_USER:-test}"
HOST_KEY="${CBM_VM_HOST_KEY_SHA256:?set CBM_VM_HOST_KEY_SHA256 in ~/.claude/cbm-vm/config}"
LOCAL_BRANCH="$(git -C "$ROOT" branch --show-current)"
BRANCH="${CBM_VM_BRANCH:-${LOCAL_BRANCH:-main}}"
# Expand inside the remote MSYS2 shell, not on the macOS host.
# shellcheck disable=SC2016
JOBS='$(nproc)'
# shellcheck source=test-infrastructure/vm/ssh-common.sh
source "$SCRIPT_DIR/ssh-common.sh"
cbm_vm_require_safe_branch "$BRANCH"
cbm_vm_prepare_known_hosts "$HOST" "$HOST_KEY"
WIN_MANIFEST=""
WIN_ARCHIVE=""
WIN_PATCH=""
win_cleanup() {
[ -z "$WIN_MANIFEST" ] || rm -f -- "$WIN_MANIFEST"
[ -z "$WIN_ARCHIVE" ] || rm -f -- "$WIN_ARCHIVE"
[ -z "$WIN_PATCH" ] || rm -f -- "$WIN_PATCH"
cbm_vm_cleanup_known_hosts
}
trap win_cleanup EXIT
SSH_OPTIONS=(-i "$KEY" -o IdentitiesOnly=yes -o HostKeyAlgorithms=ssh-ed25519 \
-o StrictHostKeyChecking=yes -o UserKnownHostsFile="$CBM_VM_KNOWN_HOSTS" \
-o ConnectTimeout=10 -o BatchMode=yes)
SSH=(ssh "${SSH_OPTIONS[@]}" "${USER_}@${HOST}")
SCP=(scp "${SSH_OPTIONS[@]}")
vm() { local env="$1"; shift
"${SSH[@]}" "C:\\msys64\\msys2_shell.cmd -defterm -no-start -${env} -c \"set -e -o pipefail; $*\""; }
vm_cmd() { "${SSH[@]}" "$@"; } # plain cmd.exe (CI-shaped environment)
# A GitHub runner is ephemeral: every job starts on a fresh image with a
# known-free disk. This VM is long-lived, so each run leaves temp roots and
# ~100 MB staged binary copies behind. Sweep them and assert runner-like free
# space BEFORE any build or run, so the local venue never tests a shape CI
# would not produce — and so a disk that has quietly filled fails here, loudly,
# instead of surfacing as a bogus ERROR_DISK_FULL inside the install path.
# CBM_VM_SKIP_PREFLIGHT=1 exists for ONE case: bootstrapping a VM whose
# checkout predates this script, where `update`/`sync` must run before the
# script can exist there. Sweep manually first — it is not a way to run on a
# disk that failed the gate.
vm_preflight() {
[ "${CBM_VM_SKIP_PREFLIGHT:-0}" = "1" ] && {
echo "=== win.sh: preflight SKIPPED (CBM_VM_SKIP_PREFLIGHT=1) ==="
return 0
}
vm_cmd "powershell -NoProfile -ExecutionPolicy Bypass -File \
C:\\cbm\\scripts\\ci\\clean-test-residue.ps1 -MinFreeGB ${CBM_VM_MIN_FREE_GB:-14}"
# Defender parity: every Windows venue (this VM and the GitHub runners)
# tests with real-time protection ACTIVE — the same canonical script the
# CI jobs run, so a drifted-off Defender fails loudly, never silently.
vm_cmd "powershell -NoProfile -ExecutionPolicy Bypass -File \
C:\\cbm\\scripts\\ci\\ensure-defender.ps1"
}
cmd="${1:-status}"; shift || true
case "$cmd" in
status | help | -h | --help) ;;
*) cbm_vm_sync_windows_clock "${SSH[@]}" ;;
esac
# Inspection and plumbing commands need no clean disk; anything that builds or
# runs on the VM does.
case "$cmd" in
status | sh | push-file | pageheap | help | -h | --help) ;;
*) vm_preflight ;;
esac
case "$cmd" in
status)
"${SSH[@]}" "echo VM_REACHABLE & ver"
vm clangarm64 "cd /c/cbm 2>/dev/null && git log --oneline -1 && ls -la build/c/codebase-memory-mcp.exe build/c/test-runner.exe 2>/dev/null || echo 'repo/build missing — run provision-windows.sh'"
;;
update)
vm clangarm64 "cd /c/cbm && git fetch origin ${BRANCH} && git reset --hard FETCH_HEAD && git clean -fdx && git log --oneline -1"
exec "$0" build
;;
sync)
local_head="$(git -C "$ROOT" rev-parse --verify HEAD)"
WIN_MANIFEST="$(mktemp "${TMPDIR:-/tmp}/cbm-vm-manifest.XXXXXX")"
WIN_ARCHIVE="$(mktemp "${TMPDIR:-/tmp}/cbm-vm-worktree.XXXXXX.tar")"
WIN_PATCH="$(mktemp "${TMPDIR:-/tmp}/cbm-vm-worktree.XXXXXX.patch")"
git -C "$ROOT" diff --binary --full-index HEAD -- >"$WIN_PATCH"
cbm_vm_write_untracked_manifest "$ROOT" "$WIN_MANIFEST"
COPYFILE_DISABLE=1 tar --no-xattrs --no-mac-metadata \
-C "$ROOT" --null -T "$WIN_MANIFEST" -cf "$WIN_ARCHIVE"
remote_head="$(vm clangarm64 "cd /c/cbm && git rev-parse --verify HEAD")"
remote_head="${remote_head//$'\r'/}"
if [ "$remote_head" != "$local_head" ]; then
echo "FATAL: Windows VM is at $remote_head, expected local HEAD $local_head; run win.sh update first." >&2
exit 1
fi
vm clangarm64 \
"cd /c/cbm && git reset --hard '$local_head' && git clean -fdx"
if [ -s "$WIN_PATCH" ]; then
"${SSH[@]}" \
'C:\msys64\msys2_shell.cmd -defterm -no-start -clangarm64 -c "cd /c/cbm && git apply --binary --whitespace=nowarn -"' \
<"$WIN_PATCH"
fi
if [ -s "$WIN_MANIFEST" ]; then
"${SSH[@]}" \
'C:\msys64\msys2_shell.cmd -defterm -no-start -clangarm64 -c "cd /c/cbm && tar -xf -"' \
<"$WIN_ARCHIVE"
fi
vm clangarm64 "cd /c/cbm && git status --short --branch"
win_cleanup
exec "$0" build
;;
build)
# The canonical build entry, exactly as CI runs it: a CLEAN scripts/build.sh
# (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)
# builds its own runner, same as CI's test jobs.
vm clangarm64 "cd /c/cbm && scripts/build.sh CC=clang CXX=clang++ > /tmp/win-build.log 2>&1 && echo BUILD_OK || (echo BUILD_FAIL; tail -20 /tmp/win-build.log; exit 1)"
;;
test)
[ $# -ge 1 ] || { echo "usage: win.sh test <suite...>" >&2; exit 2; }
# Suites run through the CANONICAL scripts/test.sh --suites (incremental
# rebuild, subset run — the documented iteration mode), under CI's
# protected per-user temp root via vm-run-tests.sh, which streams FULL
# output and refuses to report success without the runner's completion
# summary. A `| tail -40` here once hid 40 real Windows failures.
vm clangarm64 "cd /c/cbm && bash test-infrastructure/vm/vm-run-tests.sh $*"
;;
guards)
# 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 —
# taking the test-runner and every incremental object with it. The UI build
# needs the official MSVC Node.js (/c/node, from provision-windows.sh):
# MSVC-built npm native modules cannot resolve Node-API symbols against
# MSYS2's mingw node.
vm clangarm64 "export PATH=/c/node:\$PATH && cd /c/cbm && scripts/build.sh --with-ui CC=clang CXX=clang++ SANITIZE= BUILD_DIR=build/guards"
# The guards themselves run through plain cmd/PowerShell, exactly like the
# CI job: under the MSYS2 shell TMP is C:\msys64\tmp, whose ancestry
# grants mutation rights to Authenticated Users — the daemon's
# cache-private validation (correctly) refuses caches there, which is a
# different environment shape than CI's profile-rooted TEMP. Python must
# be PREPENDED: the Microsoft Store python.exe alias stub lives early in
# the profile PATH and otherwise shadows any appended interpreter.
vm_cmd "cd /d C:\\cbm && set PATH=C:\\msys64\\clangarm64\\bin;C:\\msys64\\usr\\bin;%PATH%&& powershell -NoProfile -ExecutionPolicy Bypass -File scripts\\test-windows.ps1 -GuardsOnly -Binary build\\guards\\codebase-memory-mcp.exe -Make C:\\msys64\\usr\\bin\\make.exe"
;;
smoke-install)
# EXACTLY the PR CI smoke job (pr.yml pr-smoke windows): a clean canonical
# build, then the canonical Windows smoke wrapper. The clean build wipes
# build/c (including any test-runner) just as CI's separate jobs imply;
# ccache keeps the rebuild to minutes — parity was the explicit user call
# over incremental speed here.
vm clangarm64 "cd /c/cbm && scripts/build.sh CC=clang CXX=clang++ && bash test-infrastructure/vm/vm-smoke.sh"
;;
smoke-artifact)
# The release-archive flow with local bytes: canonical build → the ONE
# package-release.sh → extract → vm-smoke.sh in artifact mode — the same
# sequence _build.yml + _smoke.yml run remotely, so archive-layout bugs
# surface here instead of in a release dry run.
vm clangarm64 "cd /c/cbm && bash scripts/ci/smoke-artifact.sh windows arm64 CC=clang CXX=clang++"
;;
soak)
duration="${1:-10}"
case "$duration" in
''|*[!0-9]*) echo "usage: win.sh soak [positive-minutes]" >&2; exit 2 ;;
esac
if [ "$duration" -le 0 ]; then
echo "usage: win.sh soak [positive-minutes]" >&2
exit 2
fi
vm clangarm64 "cd /c/cbm && CBM_VM_TEST_LOG=/tmp/win-soak.log bash \
test-infrastructure/vm/vm-run-tests.sh --soak '$duration'"
;;
sh)
vm clangarm64 "$*"
;;
push-file)
[ $# -eq 2 ] || { echo "usage: win.sh push-file <local-path> <vm-path>" >&2; exit 2; }
# Windows OpenSSH resolves scp targets natively: use C:/... not /c/...
dest="${2/#\/c\//C:\/}"
"${SCP[@]}" "$1" "${USER_}@${HOST}:${dest}"
;;
ubsan-build)
# x86_64 (CI's exact arch) with UBSan, runs under Windows-on-ARM emulation.
# Validated: UBSan needs no interceptors, so it builds, runs, AND reports
# correctly under emulation. (ASan does NOT: no aarch64 runtime exists and
# the x86_64 runtime faults in emulated process-init — ASan stays CI-only.)
vm clang64 "cd /c/cbm && make -j${JOBS} -f Makefile.cbm CC=clang CXX=clang++ SANITIZE='-fsanitize=undefined -fno-omit-frame-pointer' build/c/test-runner > /tmp/win-ubsan-build.log 2>&1 && echo UBSAN_BUILD_OK || (echo UBSAN_BUILD_FAIL; tail -20 /tmp/win-ubsan-build.log; exit 1)"
;;
ubsan-test)
[ $# -ge 1 ] || { echo "usage: win.sh ubsan-test <suite...>" >&2; exit 2; }
vm clang64 "cd /c/cbm && CBM_VM_TEST_LOG=/tmp/win-ubsan-test.log bash test-infrastructure/vm/vm-run-tests.sh $*"
;;
trap-ubsan-build)
# NATIVE ARM64 UBSan via trap mode. -fsanitize-trap=undefined needs NO
# runtime library (which is exactly what aarch64-w64-windows-gnu lacks), so
# unlike ASan this instruments and runs on native ARM64: a UB hit becomes a
# bare illegal-instruction trap (SIGILL) instead of a diagnostic. Paired
# with -fstack-protector-strong for stack-smash coverage the heap tools
# (PageHeap) miss. This is the native-arch UBSan gate; to see WHICH check
# fired, reproduce under the emulated `win.sh ubsan-build`/`ubsan-test`,
# which carries the full runtime + message. BUILD_DIR isolated so it never
# clobbers the plain test-runner.
vm clangarm64 "cd /c/cbm && make -j${JOBS} -f Makefile.cbm CC='ccache clang' CXX='ccache clang++' SANITIZE='-fsanitize=undefined -fsanitize-trap=undefined -fstack-protector-strong -fno-omit-frame-pointer' BUILD_DIR=build/trap-ubsan build/trap-ubsan/test-runner > /tmp/win-trap-ubsan-build.log 2>&1 && echo TRAP_UBSAN_BUILD_OK || (echo TRAP_UBSAN_BUILD_FAIL; tail -20 /tmp/win-trap-ubsan-build.log; exit 1)"
;;
trap-ubsan-test)
[ $# -ge 1 ] || { echo "usage: win.sh trap-ubsan-test <suite...>" >&2; exit 2; }
# A UB trap crashes the runner with SIGILL (exit 132); the harness reports
# the failing suite so the emulated diagnosis loop can name the check.
vm clangarm64 "cd /c/cbm && CBM_VM_RUNNER=build/trap-ubsan/test-runner CBM_VM_TEST_LOG=/tmp/win-trap-ubsan-test.log bash test-infrastructure/vm/vm-run-tests.sh $*"
;;
pageheap)
# OS-level heap verification (page-granular overflow/UAF detection) for the
# native ARM64 test-runner — toolchain-agnostic partial ASan substitute.
# 'on' enables full PageHeap for test-runner.exe via IFEO; 'off' removes it.
case "${1:-}" in
on)
"${SSH[@]}" "reg add \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\test-runner.exe\" /v GlobalFlag /t REG_DWORD /d 0x02000000 /f && reg add \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\test-runner.exe\" /v PageHeapFlags /t REG_DWORD /d 0x3 /f && echo PAGEHEAP_ON"
;;
off)
"${SSH[@]}" "reg delete \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\test-runner.exe\" /f && echo PAGEHEAP_OFF"
;;
*) echo "usage: win.sh pageheap on|off" >&2; exit 2 ;;
esac
;;
test-par)
# THE Windows ladder test leg: the full canonical scripts/test.sh (clean
# sanitizer build + contract steps 0a-0j + all suites via the parallel
# harness + prod-binary guards) — exactly what CI's windows test legs run —
# under the CI-shaped protected temp root with FULL output (this leg once
# ran under the MSYS-shared /tmp and piped through `tail -25` — the same
# truncated-blindness class that hid 40 Windows failures from `test`).
vm clangarm64 "cd /c/cbm && CBM_VM_TEST_LOG=/tmp/win-test-par.log bash test-infrastructure/vm/vm-run-tests.sh --par"
;;
help | -h | --help)
print_help
;;
*)
echo "win.sh: unknown command '$cmd'. Please consult --help." >&2; exit 2
;;
esac
@@ -0,0 +1,84 @@
# windows-bootstrap.ps1 — ONE-TIME setup inside the Windows test VM.
#
# Everything else (msys2, toolchains, repo, builds) is provisioned FROM THE
# HOST over ssh by provision-windows.sh — this script only opens that door.
#
# Getting this file into a fresh VM (clipboard/shared folders are unreliable
# on Windows-ARM guests — the SPICE agent services do not exist there): build
# a small ISO on the host and mount it via UTM's CD drive:
# mkdir /tmp/cbmiso
# cp windows-bootstrap.ps1 /tmp/cbmiso/
# cp ~/.claude/cbm-vm/id_ed25519.pub /tmp/cbmiso/host-key.pub
# printf '@echo off\r\npowershell -NoProfile -ExecutionPolicy Bypass -File "%%~dp0windows-bootstrap.ps1" -SshPublicKeyPath "%%~dp0host-key.pub"\r\n' > /tmp/cbmiso/RUN-ME.bat
# hdiutil makehybrid -iso -joliet -default-volume-name CBMSETUP -o ~/cbm-setup.iso /tmp/cbmiso
# Then in the VM: open the CD drive in Explorer and double-click RUN-ME.bat.
#
# Requires: SPICE guest tools already installed (network driver working).
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$SshPublicKeyPath
)
$resolvedPublicKeyPath = (Resolve-Path -LiteralPath $SshPublicKeyPath -ErrorAction Stop).Path
$publicKeyLines = @(
Get-Content -LiteralPath $resolvedPublicKeyPath -Encoding Ascii |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
)
if ($publicKeyLines.Count -ne 1 -or
$publicKeyLines[0] -notmatch '^ssh-ed25519 [A-Za-z0-9+/]+={0,3}(?: [^\r\n]+)?$') {
throw "SshPublicKeyPath must contain exactly one OpenSSH Ed25519 public key"
}
$drivingHostPublicKey = $publicKeyLines[0]
# Self-elevate so double-clicking RUN-ME.bat just works.
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
$elevationArguments = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -SshPublicKeyPath `"$resolvedPublicKeyPath`""
Start-Process powershell -Verb RunAs -ArgumentList $elevationArguments
exit
}
$ErrorActionPreference = "Stop"
Write-Host "=== 1/4: OpenSSH server ===" -ForegroundColor Cyan
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 | Out-Null
Start-Service sshd
Set-Service -Name sshd -StartupType Automatic
New-NetFirewallRule -Name cbm-sshd -DisplayName "OpenSSH (cbm test VM)" `
-Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 `
-ErrorAction SilentlyContinue | Out-Null
Write-Host "=== 2/4: authorize the driving host's key ===" -ForegroundColor Cyan
$f = 'C:\ProgramData\ssh\administrators_authorized_keys'
Set-Content -LiteralPath $f -Value $drivingHostPublicKey -Encoding Ascii
icacls $f /inheritance:r /grant 'Administrators:F' /grant 'SYSTEM:F' | Out-Null
Write-Host "=== 3/4: mirror the GitHub-runner default-owner policy ===" -ForegroundColor Cyan
# 'System objects: Default owner for objects created by members of the
# Administrators group' = Administrators. Windows CLIENT editions default new
# objects to the user SID; GitHub's SERVER runners default them to BUILTIN\
# Administrators — the class every exact-owner validation must survive.
# Mirroring it here makes CI-only ownership refusals reproduce in this VM.
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" `
-Name NoDefaultAdminOwner -Value 0 -Type DWord
Write-Host "=== 4/4: report ===" -ForegroundColor Cyan
$ip = (Get-NetIPAddress -AddressFamily IPv4 |
Where-Object { $_.IPAddress -notlike '127.*' -and $_.IPAddress -notlike '169.254.*' } |
Select-Object -First 1).IPAddress
Write-Host ""
Write-Host "==================== SSH READY ====================" -ForegroundColor Green
Write-Host (" user: " + $env:USERNAME) -ForegroundColor Yellow
Write-Host (" ip: " + $ip) -ForegroundColor Yellow
$hostKeyFingerprint = (& "$env:WINDIR\System32\OpenSSH\ssh-keygen.exe" -lf `
'C:\ProgramData\ssh\ssh_host_ed25519_key.pub' -E sha256) -join ' '
Write-Host (" host key: " + $hostKeyFingerprint) -ForegroundColor Yellow
Write-Host "===================================================" -ForegroundColor Green
Write-Host "On the host, write ~/.claude/cbm-vm/config with:"
Write-Host " CBM_VM_HOST=$ip"
Write-Host (" CBM_VM_USER=" + $env:USERNAME)
Write-Host " CBM_VM_HOST_KEY_SHA256=<copy the SHA256:... value above>"
Write-Host "Then run: test-infrastructure/vm/provision-windows.sh"
Write-Host "NOTE: reboot once so the default-owner policy applies."
Read-Host 'Press Enter to close'
@@ -0,0 +1,303 @@
param(
[Parameter(Mandatory = $true)]
[ValidateSet("prepare", "verify", "cleanup")]
[string]$Mode,
[Parameter(Mandatory = $true)]
[ValidatePattern("^[0-9A-Fa-f]{32}$")]
[string]$RunId,
[Parameter(Mandatory = $true)]
[string]$SnapshotPath,
[Parameter(Mandatory = $true)]
[string]$SmokeRoot
)
$ErrorActionPreference = "Stop"
$TestKeyPath = "Software\CodebaseMemoryMCP\Smoke\$RunId"
$SentinelName = "CbmSmokeRunId"
$RegistryView = [Microsoft.Win32.RegistryView]::Registry64
function Open-CurrentUser {
return [Microsoft.Win32.RegistryKey]::OpenBaseKey(
[Microsoft.Win32.RegistryHive]::CurrentUser,
$RegistryView
)
}
function Read-PathValue {
param([string]$KeyPath)
$base = Open-CurrentUser
try {
$key = $base.OpenSubKey($KeyPath, $false)
if ($null -eq $key) {
return [pscustomobject]@{ Exists = $false; Kind = $null; Value = $null }
}
try {
$pathName = @(
$key.GetValueNames() | Where-Object {
[string]::Equals(
$_,
"Path",
[System.StringComparison]::OrdinalIgnoreCase
)
}
) | Select-Object -First 1
if ($null -eq $pathName) {
return [pscustomobject]@{ Exists = $false; Kind = $null; Value = $null }
}
$kind = $key.GetValueKind($pathName)
if (
$kind -ne [Microsoft.Win32.RegistryValueKind]::String -and
$kind -ne [Microsoft.Win32.RegistryValueKind]::ExpandString
) {
throw "$KeyPath\Path has unsupported registry kind $kind"
}
$value = $key.GetValue(
$pathName,
$null,
[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
)
if ($null -eq $value) {
$value = ""
}
return [pscustomobject]@{
Exists = $true
Kind = $kind.ToString()
Value = [string]$value
}
}
finally {
$key.Dispose()
}
}
finally {
$base.Dispose()
}
}
function Get-StateHash {
param($State)
$serialized = (
[string][int][bool]$State.Exists + "`0" +
[string]$State.Kind + "`0" +
[string]$State.Value
)
$sha = [System.Security.Cryptography.SHA256]::Create()
try {
$digest = $sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($serialized))
return -join ($digest | ForEach-Object { $_.ToString("x2") })
}
finally {
$sha.Dispose()
}
}
function Assert-StateEqual {
param($Expected, $Actual)
if (
[bool]$Expected.Exists -ne [bool]$Actual.Exists -or
-not [string]::Equals(
[string]$Expected.Kind,
[string]$Actual.Kind,
[System.StringComparison]::Ordinal
) -or
-not [string]::Equals(
[string]$Expected.Value,
[string]$Actual.Value,
[System.StringComparison]::Ordinal
)
) {
throw (
"HKCU\Environment\Path changed while the isolated smoke ran; " +
"before=$(Get-StateHash $Expected), after=$(Get-StateHash $Actual)"
)
}
}
function Assert-SmokePathValue {
param($State)
if (-not $State.Exists) {
throw "isolated smoke registry Path was not written"
}
$canonicalRoot = [System.IO.Path]::GetFullPath($SmokeRoot).TrimEnd(
[char[]]@('\', '/')
)
$rootPrefix = $canonicalRoot + [System.IO.Path]::DirectorySeparatorChar
$segments = @(([string]$State.Value).Split(";"))
if ($segments.Count -eq 0) {
throw "isolated smoke registry Path is empty"
}
foreach ($segment in $segments) {
$trimmed = $segment.Trim()
if ($trimmed.Length -eq 0) {
throw "isolated smoke registry Path contains an empty segment"
}
$canonicalSegment = [System.IO.Path]::GetFullPath($trimmed).TrimEnd(
[char[]]@('\', '/')
)
if (
-not [string]::Equals(
$canonicalSegment,
$canonicalRoot,
[System.StringComparison]::OrdinalIgnoreCase
) -and
-not $canonicalSegment.StartsWith(
$rootPrefix,
[System.StringComparison]::OrdinalIgnoreCase
)
) {
throw "isolated smoke registry Path escaped the smoke root"
}
}
}
function Assert-TestKeySentinel {
$base = Open-CurrentUser
try {
$key = $base.OpenSubKey($TestKeyPath, $false)
if ($null -eq $key) {
throw "isolated smoke registry key is missing"
}
try {
$sentinel = $key.GetValue(
$SentinelName,
$null,
[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
)
if (
$key.GetValueKind($SentinelName) -ne
[Microsoft.Win32.RegistryValueKind]::String -or
-not [string]::Equals(
[string]$sentinel,
$RunId,
[System.StringComparison]::Ordinal
)
) {
throw "isolated smoke registry sentinel is invalid"
}
}
finally {
$key.Dispose()
}
}
finally {
$base.Dispose()
}
}
if ($Mode -eq "prepare") {
$base = Open-CurrentUser
try {
$existing = $base.OpenSubKey($TestKeyPath, $false)
if ($null -ne $existing) {
$existing.Dispose()
throw "isolated smoke registry key already exists"
}
$key = $base.CreateSubKey($TestKeyPath, $true)
if ($null -eq $key) {
throw "could not create isolated smoke registry key"
}
try {
$key.SetValue(
$SentinelName,
$RunId,
[Microsoft.Win32.RegistryValueKind]::String
)
}
finally {
$key.Dispose()
}
}
finally {
$base.Dispose()
}
$state = Read-PathValue "Environment"
$record = [pscustomobject]@{
Version = 2
RunId = $RunId
Exists = $state.Exists
Kind = $state.Kind
Value = $state.Value
}
$parent = Split-Path -Parent $SnapshotPath
[System.IO.Directory]::CreateDirectory($parent) | Out-Null
$temporary = "$SnapshotPath.new"
$json = $record | ConvertTo-Json -Compress
[System.IO.File]::WriteAllText(
$temporary,
$json,
(New-Object System.Text.UTF8Encoding($false))
)
Move-Item -LiteralPath $temporary -Destination $SnapshotPath -Force
Write-Host "Prepared isolated Windows PATH smoke (live PATH hash: $(Get-StateHash $state))"
exit 0
}
if ($Mode -eq "verify") {
if (-not [System.IO.File]::Exists($SnapshotPath)) {
throw "Windows user PATH snapshot is missing"
}
$json = [System.IO.File]::ReadAllText(
$SnapshotPath,
[System.Text.Encoding]::UTF8
)
$record = $json | ConvertFrom-Json
if (
$record.Version -ne 2 -or
$null -eq $record.Exists -or
-not [string]::Equals(
[string]$record.RunId,
$RunId,
[System.StringComparison]::Ordinal
)
) {
throw "Windows user PATH snapshot is invalid"
}
Assert-TestKeySentinel
$current = Read-PathValue "Environment"
Assert-StateEqual $record $current
Assert-SmokePathValue (Read-PathValue $TestKeyPath)
Write-Host "Verified isolated Windows PATH smoke; live user PATH was not mutated"
exit 0
}
$base = Open-CurrentUser
try {
$key = $base.OpenSubKey($TestKeyPath, $false)
if ($null -ne $key) {
try {
$sentinel = $key.GetValue(
$SentinelName,
$null,
[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
)
if (
$key.GetValueKind($SentinelName) -ne
[Microsoft.Win32.RegistryValueKind]::String -or
-not [string]::Equals(
[string]$sentinel,
$RunId,
[System.StringComparison]::Ordinal
)
) {
throw "refusing to delete an isolated registry key with the wrong sentinel"
}
}
finally {
$key.Dispose()
}
$base.DeleteSubKeyTree($TestKeyPath, $false)
}
}
finally {
$base.Dispose()
}
Write-Host "Removed isolated Windows PATH smoke registry key"