初始提交: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
+39
View File
@@ -0,0 +1,39 @@
# Mirrors the Ubuntu CI environment exactly:
# - Ubuntu 24.04 (same as GitHub Actions ubuntu-latest / ubuntu-24.04-arm)
# - GCC (system default) with ASan + UBSan + LeakSanitizer
# - libsqlite3-dev + zlib1g-dev (same as CI "Install deps" step)
#
# Build: docker build -t cbm-test test-infrastructure/
# Run: docker run --rm -v $(pwd):/src cbm-test
# Pinned by digest (supply-chain: no floating tags) — multi-arch manifest-list
# digest of ubuntu:noble as of 2026-07-23; bump deliberately, never to a tag.
FROM ubuntu:noble@sha256:4fbb8e6a8395de5a7550b33509421a2bafbc0aab6c06ba2cef9ebffbc7092d90
# Minimal: gcc + zlib only. sqlite3 is vendored (compiled from source with ASan).
# curl + zsh mirror the GitHub runner images: the self-update tests shell out
# to curl, and the shell-activation tests exercise zsh rc files.
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc g++ make \
zlib1g-dev \
pkg-config \
python3 \
git \
curl \
zsh \
ccache \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Verified compiler cache: content-keyed (compiler binary + preprocessed
# input), so a hit is provably the identical compilation — stale results are
# impossible by construction. The compose services mount a persistent volume
# at CCACHE_DIR and route compilers through the Debian masquerade dir.
ENV CCACHE_COMPILERCHECK=content
ENV PATH=/usr/lib/ccache:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
WORKDIR /src
# Default: run test.sh with GCC (mirrors CI exactly)
ENTRYPOINT ["scripts/test.sh"]
CMD ["CC=gcc", "CXX=g++"]
+27
View File
@@ -0,0 +1,27 @@
# Mirrors the Alpine CI environment for portable (musl static) builds.
# - Alpine 3.21 with musl libc
# - GCC + static zlib for fully static binaries
# - Produces portable Linux binaries that run on any distro
#
# Build: docker build -f test-infrastructure/Dockerfile.alpine -t cbm-alpine test-infrastructure/
# Run: docker run --rm -v $(pwd):/src cbm-alpine
FROM alpine:3.21@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c
RUN apk add --no-cache \
build-base \
linux-headers \
zlib-dev \
zlib-static \
bash \
curl \
git \
python3 \
nodejs \
npm \
ca-certificates
WORKDIR /src
ENTRYPOINT ["bash", "scripts/build.sh"]
CMD ["CC=gcc", "CXX=g++", "STATIC=1"]
+28
View File
@@ -0,0 +1,28 @@
# Dockerfile.glibc22 — the glibc-FLOOR venue (ubuntu-22.04, glibc 2.35).
#
# Mirrors CI's broad-matrix ubuntu-22.04 legs: the OLDEST userland we claim
# the portable (musl-static) binary runs on. Two assertions live here:
# 1. the portable binary passes the full canonical smoke on glibc 2.35;
# 2. the DYNAMIC binary refuses to start (its glibc 2.38+ floor is by
# design — old-glibc coverage is the portable binary's job, and a
# dynamic binary that silently ran here would mask a floor regression).
# Pinned by digest like every other venue image: a floating tag means the
# glibc-FLOOR assertion silently drifts to whatever ubuntu:22.04 points at, and
# a floor that moves is not a floor. (Scorecard PinnedDependenciesID #76 — this
# was the one image the pinning pass missed.)
FROM ubuntu:22.04@sha256:0e0a0fc6d18feda9db1590da249ac93e8d5abfea8f4c3c0c849ce512b5ef8982
RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
ca-certificates \
coreutils \
curl \
file \
git \
python3 \
tar \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /src
ENTRYPOINT ["bash"]
+34
View File
@@ -0,0 +1,34 @@
# Lint environment — mirrors CI lint job exactly:
# - clang-format-20 (from LLVM apt repo)
# - cppcheck 2.20.0 (built from source, same as CI)
#
# Build: docker build -t cbm-lint -f test-infrastructure/Dockerfile.lint test-infrastructure/
# Run: docker run --rm -v $(pwd):/src cbm-lint
# Pinned by digest (supply-chain: no floating tags) — multi-arch manifest-list
# digest of ubuntu:noble as of 2026-07-23; bump deliberately, never to a tag.
FROM ubuntu:noble@sha256:4fbb8e6a8395de5a7550b33509421a2bafbc0aab6c06ba2cef9ebffbc7092d90
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc g++ make cmake \
libsqlite3-dev zlib1g-dev \
pkg-config wget gnupg git ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# clang-format-20 (same version as CI)
RUN wget -qO- https://apt.llvm.org/llvm-snapshot.gpg.key | tee /etc/apt/trusted.gpg.d/apt.llvm.org.asc \
&& echo "deb http://apt.llvm.org/noble/ llvm-toolchain-noble-20 main" > /etc/apt/sources.list.d/llvm-20.list \
&& apt-get update && apt-get install -y --no-install-recommends clang-format-20 \
&& rm -rf /var/lib/apt/lists/*
# cppcheck 2.20.0 (same version as CI)
RUN git clone --depth 1 --branch 2.20.0 https://github.com/danmar/cppcheck.git /tmp/cppcheck \
&& cmake -S /tmp/cppcheck -B /tmp/cppcheck/build -DCMAKE_BUILD_TYPE=Release -DHAVE_RULES=OFF -DCMAKE_INSTALL_PREFIX=/usr/local \
&& cmake --build /tmp/cppcheck/build -j$(nproc) \
&& cmake --install /tmp/cppcheck/build \
&& rm -rf /tmp/cppcheck
WORKDIR /src
ENTRYPOINT ["scripts/lint.sh"]
CMD ["CLANG_FORMAT=clang-format-20"]
+66
View File
@@ -0,0 +1,66 @@
# Cross-compile AND run Windows tests locally using llvm-mingw + Wine.
#
# llvm-mingw: LLVM/Clang-based MinGW toolchain
# Wine: runs the resulting .exe for actual test execution
#
# Usage:
# docker compose -f test-infrastructure/docker-compose.yml run --rm build-windows
# docker compose -f test-infrastructure/docker-compose.yml run --rm test-windows
# Pinned by digest (supply-chain: no floating tags). This is the multi-arch
# manifest-list digest of mstorsjo/llvm-mingw:latest as of 2026-07-23; bump
# deliberately by re-resolving the digest, never back to a bare tag.
FROM mstorsjo/llvm-mingw:latest@sha256:5cbf421906f889e01c8d4005787474e302df6daa197286ebf212d419024966af
# curl+zstd are required (zlib sysroot fetch below). Wine is BEST-EFFORT: it
# only runs the .exe, and its i386 packages are unavailable on an arm64 Docker
# host (e.g. Colima on Apple Silicon), so a Wine failure must NOT abort the
# image build - the cross-COMPILE check still works without it.
RUN apt-get update && apt-get install -y --no-install-recommends curl zstd \
&& rm -rf /var/lib/apt/lists/*
RUN (dpkg --add-architecture i386 && apt-get update && \
apt-get install -y --no-install-recommends wine64 && rm -rf /var/lib/apt/lists/*) \
|| echo "WARN: Wine unavailable on this host arch -> compile-only mode"
# Install zlib into the llvm-mingw sysroot (from MSYS2 CLANG64 repo).
# The package is verified against its pinned sha256 before extraction —
# a bare curl|tar would execute whatever the mirror serves.
RUN mkdir -p /tmp/zlib-pkg && \
curl -sL "https://mirror.msys2.org/mingw/clang64/mingw-w64-clang-x86_64-zlib-1.3.1-1-any.pkg.tar.zst" \
-o /tmp/zlib.pkg.tar.zst && \
echo "b7f0c06e6d48128209a3a441f96b92351e565a0d031278c56a8db8a9b5ec291a /tmp/zlib.pkg.tar.zst" \
| sha256sum -c - && \
zstd -d < /tmp/zlib.pkg.tar.zst | tar xf - -C /tmp/zlib-pkg && \
rm /tmp/zlib.pkg.tar.zst && \
cp -rn /tmp/zlib-pkg/clang64/include/* /opt/llvm-mingw/x86_64-w64-mingw32/include/ && \
cp -rn /tmp/zlib-pkg/clang64/lib/* /opt/llvm-mingw/x86_64-w64-mingw32/lib/ && \
rm -rf /tmp/zlib-pkg
# Add Wine to PATH (Ubuntu noble puts it in /usr/lib/wine/)
ENV PATH="/usr/lib/wine:${PATH}"
# Verify all tools are installed
RUN echo "=== Tool check ===" && \
x86_64-w64-mingw32-clang --version | head -1 && \
x86_64-w64-mingw32-clang++ --version | head -1 && \
make --version | head -1 && \
ls /opt/llvm-mingw/x86_64-w64-mingw32/include/zlib.h && \
(wine64 --version 2>/dev/null || echo "WARN: wine64 not on PATH, checking alternatives...") && \
(which wine64 || which wine || find / -name "wine64" -type f 2>/dev/null | head -1 || echo "ERROR: wine not found") && \
echo "=== All tools OK ==="
# Pre-init Wine to avoid first-run prompts during test
RUN WINEDEBUG=-all wine64 wineboot --init 2>/dev/null || \
WINEDEBUG=-all wine wineboot --init 2>/dev/null || \
echo "WARN: Wine init skipped"
WORKDIR /src
ENTRYPOINT ["/bin/bash", "-c"]
# Default: cross-compile production build
CMD ["make -j4 -f Makefile.cbm clean-c && \
make -j4 -f Makefile.cbm cbm \
CC=x86_64-w64-mingw32-clang \
CXX=x86_64-w64-mingw32-clang++ \
&& echo '=== Windows cross-compile: OK ==='"]
+42
View File
@@ -0,0 +1,42 @@
# test-infrastructure/ — the local venues
The local half of the 3-OS CI ladder. **Every leg here runs the SAME canonical
scripts CI runs** (`scripts/test.sh`, `build.sh`, `smoke-local.sh`,
`soak-legs.sh`, `vm-smoke.sh` — see `scripts/README.md`); this directory only
provisions containers and the Windows VM. The venue-parity contract
(`tests/test_venue_parity_contract.sh`, Step 0j of every test leg) fails the
build if a venue grows its own harness logic — here or in the workflows.
## Entry points
| venue | entry | notes |
|---|---|---|
| Linux (arm64 + amd64) + cross-compile | `./run.sh <leg>` (`--help` for the leg list) | Colima only — Docker Desktop is broken on this machine. A clean-disk preflight (`scripts/ci/preflight-docker.sh`) runs before every leg: GitHub runners are ephemeral with a known-free 14 GB disk, so the long-lived VM is swept back to that shape first. |
| Real Windows (UTM ARM64 VM) | `vm/win.sh <command>` (`win.sh help`) | Same preflight idea (`scripts/ci/clean-test-residue.ps1`), plus CI's protected per-user TEMP root. Wine (`run.sh windows`) is a compile check only — never a substitute for the VM. |
| macOS | run the canonical scripts natively | `scripts/test.sh`, `scripts/build.sh`, `scripts/smoke-local.sh …` |
## The ladder (before any push)
1. `scripts/test.sh` — macOS native (or `--suites …` while iterating)
2. `./test-infrastructure/run.sh full` — Linux arm64 test/build/TSan/smoke/portable + mingw cross-compile (+ `amd64`, `soak-linux` as needed)
3. `vm/win.sh test-par` · `guards` · `smoke-install` · `soak` — the real-Windows legs
Infra unavailable = a run blocker to escalate — never a silent bypass.
## Fidelity guarantees (what makes local predictive of CI)
- **Same scripts, same sequence, same flags** — platform specifics (e.g. the
CLANGARM64 trap-UBSan default) live inside the canonical entries, applied
identically everywhere.
- **Same environment shape** — protected TEMP roots, sandboxed smoke, clean
builds with the content-verified ccache (a hit is byte-identical to a cold
compile; caches only accelerate, never change results).
- **Same starting disk** — preflights sweep residue and BLOCK below the
runner's 14 GB floor (a quietly full disk fails inside install paths and
masquerades as a product bug).
- **Known, deliberate residuals** — runner physics (4 vCPU vs local cores,
shared tenancy), Defender ON in the VM vs OFF on GitHub runners, no TSan on
Windows anywhere, no ASan runtime on native ARM64 Windows (trap-UBSan +
PageHeap stand in).
See `vm/README.md` for VM provisioning and day-to-day VM mechanics.
+301
View File
@@ -0,0 +1,301 @@
# Local test environment — mirrors GitHub Actions CI for ALL platforms.
#
# Coverage:
# Linux arm64: native test + build (mirrors CI ubuntu-24.04-arm)
# Linux amd64: QEMU test + build (mirrors CI ubuntu-latest)
# Windows: cross-compile with mingw-w64 (catches all compile errors)
# macOS: run natively — scripts/test.sh CC=cc && scripts/build.sh CC=cc
services:
# ── Linux test (ASan + UBSan + LeakSanitizer) ──────────────
# Always full-parallel: the suite is designed to be core-count-independent
# for correctness — timing/scheduling/subprocess suites assert invariants
# (ordering, bounded-return, RUNNING poll state), not wall-clock, so they
# pass at any parallelism. Artificial CPU starvation belongs to smoke/soak
# (CBM_LOCAL_CI_CPUS), not the regular suite.
test:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/arm64
volumes:
- ..:/src
- cbm-build:/src/build
- cbm-fixture-cache:/root/.cache/cbm-test-fixtures
- cbm-ccache-arm64:/root/.ccache
environment:
CCACHE_DIR: /root/.ccache
CCACHE_MAXSIZE: 1500M
command: ["CC=gcc", "CXX=g++", "BUILD_DIR=build/linux-arm64"]
test-amd64:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/amd64
volumes:
- ..:/src
- cbm-build:/src/build
- cbm-fixture-cache:/root/.cache/cbm-test-fixtures
- cbm-ccache-amd64:/root/.ccache
environment:
CCACHE_DIR: /root/.ccache
CCACHE_MAXSIZE: 1500M
command: ["CC=gcc", "CXX=g++", "BUILD_DIR=build/linux-amd64"]
# ── ThreadSanitizer (data-race gate) ───────────────────────────
# Overrides the default test.sh entrypoint to build + run the widened TSan
# suite set. /usr/lib/ccache is first on PATH in the image, so CC=gcc is
# ccache-masqueraded automatically (same as the ASan legs).
test-tsan:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/arm64
# make is PID 1 for this service. Give orphaned subprocess-test descendants
# a real reaper so killed zombies do not keep process groups appearing live.
init: true
volumes:
- ..:/src
- cbm-build:/src/build
- cbm-fixture-cache:/root/.cache/cbm-test-fixtures
- cbm-ccache-arm64:/root/.ccache
environment:
CCACHE_DIR: /root/.ccache
CCACHE_MAXSIZE: 1500M
# TSan's shadow memory needs a predictable address space; modern aarch64
# kernels' high-entropy mmap ASLR makes its runtime abort with "unexpected
# memory mapping" before any test runs. setarch -R (ADDR_NO_RANDOMIZE)
# fixes it, but the personality() syscall it uses is blocked by the default
# seccomp profile — unconfined is safe here (the container runs only our own
# test code). The no-randomize personality inherits to the make child.
security_opt: ["seccomp=unconfined"]
# The TSan leg lives in the canonical test entry (scripts/test.sh --tsan),
# same as CI's tsan jobs; the no-randomize personality inherits through it.
entrypoint: ["setarch", "-R", "bash", "scripts/test.sh", "--tsan"]
command: ["CC=gcc", "CXX=g++", "BUILD_DIR=build/linux-arm64-tsan"]
test-tsan-amd64:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/amd64
init: true
volumes:
- ..:/src
- cbm-build:/src/build
- cbm-fixture-cache:/root/.cache/cbm-test-fixtures
- cbm-ccache-amd64:/root/.ccache
environment:
CCACHE_DIR: /root/.ccache
CCACHE_MAXSIZE: 1500M
security_opt: ["seccomp=unconfined"]
# Canonical test entry, TSan mode — same file as CI's tsan jobs.
entrypoint: ["setarch", "-R", "bash", "scripts/test.sh", "--tsan"]
command: ["CC=gcc", "CXX=g++", "BUILD_DIR=build/linux-amd64-tsan"]
# ── Linux production build (-O2 -Werror) ───────────────────
build:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/arm64
volumes:
- ..:/src
entrypoint: ["scripts/build.sh"]
command: ["CC=gcc", "CXX=g++", "BUILD_DIR=build/linux-arm64"]
build-amd64:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/amd64
volumes:
- ..:/src
entrypoint: ["scripts/build.sh"]
command: ["CC=gcc", "CXX=g++", "BUILD_DIR=build/linux-amd64"]
# ── Windows cross-compile + test (llvm-mingw + Wine) ────────
build-windows:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile.mingw
platform: linux/amd64
volumes:
- ..:/src
test-windows:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile.mingw
platform: linux/amd64
volumes:
- ..:/src
command: >-
make -j4 -f Makefile.cbm clean-c BUILD_DIR=build/win-cross &&
make -j4 -f Makefile.cbm build/win-cross/test-runner
BUILD_DIR=build/win-cross
CC=x86_64-w64-mingw32-clang
CXX=x86_64-w64-mingw32-clang++ &&
echo '=== Running tests under Wine ===' &&
WINEDEBUG=-all wine64 build/win-cross/test-runner.exe &&
echo '=== Windows test: OK ==='
# ── Smoke test (build + run smoke-test.sh) ──────────────────
smoke:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/arm64
volumes:
- ..:/src
entrypoint: ["/bin/bash", "-c"]
command:
- |
scripts/build.sh CC=gcc CXX=g++ BUILD_DIR=build/linux-arm64 &&
scripts/smoke-local.sh ./build/linux-arm64/codebase-memory-mcp
smoke-amd64:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/amd64
volumes:
- ..:/src
entrypoint: ["/bin/bash", "-c"]
command:
- |
scripts/build.sh CC=gcc CXX=g++ BUILD_DIR=build/linux-amd64 &&
scripts/smoke-local.sh ./build/linux-amd64/codebase-memory-mcp
# ── Soak (both CI legs) ────────────────────────────────────
# The sequence (quick + #581 query-leak) lives in the canonical entry
# scripts/soak-legs.sh — the same file _soak.yml and the Windows VM run.
# The local ladder previously had NO unix soak at all. Duration follows
# CBM_SOAK_MINUTES (default 10, matching the dry run).
soak:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/arm64
volumes:
- ..:/src
entrypoint: ["/bin/bash", "-c"]
command:
- |
scripts/build.sh CC=gcc CXX=g++ BUILD_DIR=build/linux-arm64 &&
scripts/soak-legs.sh ./build/linux-arm64/codebase-memory-mcp ${CBM_SOAK_MINUTES:-10}
# ── Windows smoke (cross-compile + Wine) ──────────────────
smoke-windows:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile.mingw
platform: linux/amd64
volumes:
- ..:/src
entrypoint: ["/bin/bash", "-c"]
command:
- |
scripts/build.sh CC=x86_64-w64-mingw32-clang CXX=x86_64-w64-mingw32-clang++ BUILD_DIR=build/win-cross &&
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) ────────────────────
test-portable:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile.alpine
platform: linux/arm64
volumes:
- ..:/src
entrypoint: ["bash", "scripts/test.sh"]
command: ["CC=gcc", "CXX=g++", "BUILD_DIR=build/alpine"]
build-portable:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile.alpine
platform: linux/arm64
volumes:
- ..:/src
entrypoint: ["bash", "scripts/build.sh"]
command: ["CC=gcc", "CXX=g++", "STATIC=1", "BUILD_DIR=build/alpine"]
smoke-portable:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile.alpine
platform: linux/arm64
volumes:
- ..:/src
entrypoint: ["bash", "-c"]
command:
- |
scripts/build.sh CC=gcc CXX=g++ STATIC=1 BUILD_DIR=build/alpine &&
file build/alpine/codebase-memory-mcp | grep -q "statically linked" &&
echo "=== Verified: statically linked ===" &&
scripts/smoke-local.sh ./build/alpine/codebase-memory-mcp
# ── Artifact-flow smoke (package → extract → wrapper) ──────
# The release venue smokes the shipped archive; this lane reproduces that
# flow with local bytes via the canonical package-release.sh +
# smoke-local.sh artifact mode, so archive-layout bugs surface locally.
smoke-artifact:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile
platform: linux/arm64
volumes:
- ..:/src
entrypoint: ["/bin/bash", "-c"]
command:
- |
BUILD_DIR=build/linux-arm64 \
scripts/ci/smoke-artifact.sh linux arm64 CC=gcc CXX=g++
# ── glibc floor (ubuntu-22.04, glibc 2.35) ─────────────────
# Mirrors CI's broad-matrix 22.04 legs: the portable (musl-static) binary
# must pass the canonical smoke on the oldest supported userland, and the
# dynamic binary must REFUSE to start (glibc 2.38+ floor is by design).
smoke-glibc-floor:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile.glibc22
platform: linux/arm64
volumes:
- ..:/src
entrypoint: ["/bin/bash", "-c"]
command:
- |
set -e
file build/alpine/codebase-memory-mcp | grep -q "statically linked"
echo "=== glibc-floor: portable binary smoke on glibc 2.35 ==="
scripts/smoke-local.sh ./build/alpine/codebase-memory-mcp
echo "=== glibc-floor: dynamic binary must refuse (glibc 2.38+ floor) ==="
if build/linux-arm64/codebase-memory-mcp --version 2>/tmp/dynamic-floor.err; then
echo "ERROR: dynamic binary ran on glibc 2.35 — floor contract broken"
exit 1
fi
grep -qi 'GLIBC' /tmp/dynamic-floor.err
echo "=== Verified: dynamic binary refuses with a GLIBC floor error ==="
# ── Lint ────────────────────────────────────────────────────
lint:
build:
context: ..
dockerfile: test-infrastructure/Dockerfile.lint
volumes:
- ..:/src
command: ["--ci", "CLANG_FORMAT=clang-format-20"]
volumes:
cbm-ccache-arm64:
cbm-ccache-amd64:
# Build artifacts and the incremental-suite fixture cache stay on the VM's
# native filesystem: object writes over the virtiofs bind mount are the
# container legs' largest avoidable I/O cost, and the fixture cache makes
# the network clone once-per-volume instead of once-per-container.
cbm-build:
cbm-fixture-cache:
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# ladder.sh — the full local push gate, with all platform legs OVERLAPPED.
#
# The three platforms are separate scheduling domains (macOS native, the
# Colima container VM, the Windows UTM VM), so running their legs
# sequentially leaves most of the machine idle most of the time. This
# launches lint + the Linux container suite + the Windows VM suite in the
# background, runs the macOS full suite in the foreground, then joins and
# prints one verdict per leg. Each leg streams to its own log so a red leg
# can be inspected without rerunning anything.
#
# test-infrastructure/ladder.sh
#
# Prerequisites: Colima running (Linux/lint legs), the Windows VM
# provisioned and reachable (vm/provision-windows.sh). A missing
# prerequisite fails that leg loudly — never silently skips it.
set -uo pipefail
cd "$(dirname "$0")/.."
LOGS="${CBM_LADDER_LOGS:-${TMPDIR:-/tmp}/cbm-ladder-$$}"
mkdir -p "$LOGS"
echo "=== local ladder: lint + linux + windows in background, mac in foreground ==="
echo "=== logs: $LOGS ==="
./test-infrastructure/run.sh lint > "$LOGS/lint.log" 2>&1 &
LINT_PID=$!
./test-infrastructure/run.sh test > "$LOGS/linux.log" 2>&1 &
LINUX_PID=$!
(./test-infrastructure/vm/win.sh sync &&
./test-infrastructure/vm/win.sh test-par) > "$LOGS/windows.log" 2>&1 &
WIN_PID=$!
scripts/test.sh 2>&1 | tee "$LOGS/mac.log"
MAC_RC=${PIPESTATUS[0]}
wait "$LINT_PID"
LINT_RC=$?
wait "$LINUX_PID"
LINUX_RC=$?
wait "$WIN_PID"
WIN_RC=$?
echo ""
echo "=== ladder verdicts ==="
overall=0
report() {
local leg="$1" rc="$2" log="$3"
if [ "$rc" -eq 0 ]; then
echo " PASS $leg"
else
echo " FAIL $leg (rc=$rc) — $log"
echo " ── last 15 lines ──"
tail -15 "$log" | sed 's/^/ /'
overall=1
fi
}
report "macOS " "$MAC_RC" "$LOGS/mac.log"
report "lint " "$LINT_RC" "$LOGS/lint.log"
report "linux " "$LINUX_RC" "$LOGS/linux.log"
report "windows " "$WIN_RC" "$LOGS/windows.log"
exit "$overall"
+260
View File
@@ -0,0 +1,260 @@
#!/usr/bin/env bash
# Containerized local-CI legs. Before pushing, pair these with native macOS
# tests and the real-Windows VM gate documented below.
#
# Coverage:
# Linux arm64: test (ASan+LeakSan) + build (-O2) [native, fast]
# Linux amd64: test + build [QEMU, slower]
# Linux portable: Alpine musl static build + smoke [portable binary]
# Windows: cross-compile + Wine version check [fast check only; use
# vm/win.sh for mandatory real-Windows verification]
# macOS: run natively (not in Docker)
#
# Full power, always: the test containers run unconstrained — the suite is
# built to be core-count-independent for correctness (timing/scheduling/
# subprocess suites assert invariants — ordering, bounded-return, RUNNING poll
# state — not wall-clock), so it passes at any parallelism and there is no
# reason to throttle it. The CBM_LOCAL_CI_CPUS knob survives only for the
# smoke/soak services, where deliberate resource starvation is the point; it is
# NOT a pre-push gate for the regular suite. ccache persists in named volumes;
# entries are content-verified
# (stale hits impossible), so warm reruns skip unchanged compilation.
# Run this from the WORKTREE you want tested: the containers mount the repo
# this script resides in.
#
# Usage:
# ./test-infrastructure/run.sh # arm64 + portable + Windows cross-compile
# ./test-infrastructure/run.sh all # above + amd64 + Windows Wine smoke
# ./test-infrastructure/run.sh portable # Alpine portable build + smoke only
# ./test-infrastructure/run.sh windows # Windows cross-compile only
# ./test-infrastructure/run.sh soak-linux # arm64 soak: quick + query-leak
# ./test-infrastructure/run.sh soak-windows # native Windows VM, both legs
# ./test-infrastructure/run.sh test # Linux arm64 test only (no perf)
# ./test-infrastructure/run.sh perf # Linux arm64 perf/incremental only
# ./test-infrastructure/run.sh tsan # Linux arm64 ThreadSanitizer race gate
# ./test-infrastructure/run.sh tsan-amd64 # Linux amd64 ThreadSanitizer race gate
# ./test-infrastructure/run.sh build # Linux arm64 build only
# ./test-infrastructure/run.sh lint # clang-format + cppcheck
# ./test-infrastructure/run.sh shell # debug shell
# Runtime: any Docker-compatible daemon. On macOS we use Colima (free OSS):
# brew install colima docker docker-compose docker-buildx
# ln -sf /opt/homebrew/opt/docker-compose/bin/docker-compose ~/.docker/cli-plugins/docker-compose
# ln -sf /opt/homebrew/opt/docker-buildx/bin/docker-buildx ~/.docker/cli-plugins/docker-buildx
# colima start --vm-type vz --vz-rosetta --cpu "$(sysctl -n hw.ncpu)" --memory 32
# vCPUs are NOT a reservation: idle guest cores cost nothing and the macOS
# scheduler shares freely with everything else running. Exposing all cores
# just removes the artificial ceiling a smaller VM would impose on container
# runs — no session seizes anything. Memory is the only semi-reservation,
# hence 32 GB, leaving macOS ample headroom. --vz-rosetta is required for
# fast amd64 legs (QEMU otherwise). Autostart: brew services start colima.
#
# Monitoring a running leg: docker logs -f <container> (or tail the log you
# redirected to). Check in regularly instead of waiting blind — suite results
# stream as they finish, and failures print their FAIL sites immediately.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
COMPOSE="docker compose -f $ROOT/test-infrastructure/docker-compose.yml"
usage() {
cat <<'EOF'
Usage: test-infrastructure/run.sh [leg]
The Linux (and cross-compile) local-CI ladder, on Colima. Every leg runs the
SAME canonical scripts CI runs (scripts/test.sh, build.sh, smoke-local.sh,
soak-legs.sh) inside pinned containers; this wrapper only picks the container
and platform. A clean-disk preflight (scripts/ci/preflight-docker.sh) runs
first — CBM_SKIP_PREFLIGHT=1 skips it, CBM_PREFLIGHT_ARGS=--deep widens it.
Legs:
full (default) arm64: test + build + TSan + smoke + portable smoke
+ Windows mingw cross-compile check
all full + amd64 legs + Windows cross-compile/Wine check
test|build|smoke|tsan single arm64 legs
amd64|test-amd64|tsan-amd64 amd64 legs (tsan-amd64 needs real amd64 HW)
perf arm64 incremental-perf leg (CBM_SKIP_PERF unset)
shell|shell-alpine interactive debug shell inside the image
portable|portable-test Alpine musl static build legs
smoke-artifact arm64 artifact-flow smoke: package -> extract -> wrapper
glibc-floor ubuntu-22.04 (glibc 2.35): portable smoke + dynamic refusal
soak-linux both CI soak legs (quick + #581 query-leak) via
scripts/soak-legs.sh; CBM_SOAK_MINUTES per leg (default 10)
soak-windows delegates to the real-Windows VM (win.sh soak 10)
Environment:
CBM_SOAK_MINUTES soak-linux duration per leg (default 10)
CBM_LOCAL_CI_CPUS opt-in CPU cap for smoke/soak starvation checks only
(the regular suite always runs full-parallel)
CBM_SKIP_PREFLIGHT=1 / CBM_PREFLIGHT_ARGS=--deep preflight controls
windows|smoke-windows mingw cross-compile + Wine version check
lint containerized cppcheck + clang-format (CI image)
-h, --help This text.
Real-Windows legs (test/guards/smoke-install/soak) live in
test-infrastructure/vm/win.sh — Wine is a compile check only.
EOF
}
case "${1:-}" in -h|--help) usage; exit 0 ;; esac
print_real_windows_gate() {
echo "=== Container/cross-compile legs passed ==="
echo "=== Real-Windows gate remains: vm/win.sh sync, test, guards, smoke-install ==="
}
if [ "${1:-full}" = "soak-windows" ]; then
echo "=== Windows: native daemon soak (real Windows VM, 10 min) ==="
exec "$ROOT/test-infrastructure/vm/win.sh" soak 10
fi
if ! docker info >/dev/null 2>&1; then
echo "ERROR: no Docker daemon reachable." >&2
echo " Start one first — on macOS: colima start --vm-type vz --vz-rosetta --cpu 12 --memory 16" >&2
echo " (current context: $(docker context show 2>/dev/null || echo unknown))" >&2
exit 1
fi
if ! docker compose version >/dev/null 2>&1; then
echo "ERROR: docker compose plugin missing." >&2
echo " brew install docker-compose && ln -sf /opt/homebrew/opt/docker-compose/bin/docker-compose ~/.docker/cli-plugins/docker-compose" >&2
exit 1
fi
# A GitHub runner starts every job on a fresh image with a known-free disk;
# Colima is long-lived and accumulates exited containers and orphaned volumes.
# Sweep that back to the runner's shape and assert free space before any leg,
# so a disk that has quietly filled fails here rather than surfacing as a bogus
# product failure deep inside an install path. CBM_PREFLIGHT_ARGS=--deep also
# reclaims the build cache; CBM_SKIP_PREFLIGHT=1 opts out for a quick re-run.
if [ "${CBM_SKIP_PREFLIGHT:-0}" != "1" ]; then
# shellcheck disable=SC2086 # deliberate word-splitting of opt-in flags
"$ROOT/scripts/ci/preflight-docker.sh" ${CBM_PREFLIGHT_ARGS:-}
fi
case "${1:-full}" in
full)
echo "=== Linux arm64: test + build ==="
$COMPOSE run --rm -e CBM_SKIP_PERF=1 test
$COMPOSE run --rm build
echo "=== Linux arm64: ThreadSanitizer (data-race gate) ==="
$COMPOSE run --rm test-tsan
echo "=== Linux arm64: smoke test ==="
$COMPOSE run --rm smoke
echo "=== Linux portable: Alpine static build + smoke ==="
$COMPOSE run --rm smoke-portable
echo "=== Linux arm64: artifact-flow smoke ==="
$COMPOSE run --rm smoke-artifact
echo "=== Linux glibc-floor (ubuntu-22.04): portable smoke + dynamic refusal ==="
$COMPOSE run --rm smoke-glibc-floor
echo "=== Windows: cross-compile ==="
$COMPOSE run --rm build-windows
print_real_windows_gate
;;
test)
echo "=== Linux arm64: test (ASan + LeakSanitizer, no perf) ==="
$COMPOSE run --rm -e CBM_SKIP_PERF=1 test
;;
perf)
echo "=== Linux arm64: perf/incremental tests ==="
$COMPOSE run --rm test
;;
tsan)
echo "=== Linux arm64: ThreadSanitizer (data-race gate) ==="
$COMPOSE run --rm test-tsan
;;
tsan-amd64)
# NOTE: TSan's shadow memory is incompatible with x86_64-on-ARM
# translation (Rosetta/QEMU), so this FATALs ("unexpected memory
# mapping") on an Apple-Silicon host — it is a real-amd64-hardware /
# GitHub-CI gate, not a local-on-ARM one. ASan amd64 (test-amd64) runs
# fine under Rosetta; only TSan's mapping does not.
echo "=== Linux amd64: ThreadSanitizer (data-race gate; native amd64 only) ==="
$COMPOSE run --rm test-tsan-amd64
;;
build)
echo "=== Linux arm64: production build (-O2 -Werror) ==="
$COMPOSE run --rm build
;;
smoke)
echo "=== Linux arm64: smoke test (build + run all phases) ==="
$COMPOSE run --rm smoke
;;
soak-linux)
# Both CI legs (quick + #581 query-leak). Duration via CBM_SOAK_MINUTES,
# default 10 to match the dry run. Kept out of `full`/`all` for the same
# reason soak-windows is: it is a ~20-minute endurance gate, not part of
# the fast ladder.
echo "=== Linux arm64: soak (quick + query-leak, ${CBM_SOAK_MINUTES:-10}m each) ==="
$COMPOSE run --rm soak
;;
portable)
echo "=== Linux portable: Alpine static build + smoke ==="
$COMPOSE run --rm smoke-portable
;;
smoke-artifact)
echo "=== Linux arm64: artifact-flow smoke (package -> extract -> wrapper) ==="
$COMPOSE run --rm smoke-artifact
;;
glibc-floor)
echo "=== Linux glibc-floor (ubuntu-22.04): portable smoke + dynamic refusal ==="
$COMPOSE run --rm build
$COMPOSE run --rm build-portable
$COMPOSE run --rm smoke-glibc-floor
;;
portable-test)
echo "=== Linux portable: Alpine test (ASan + LeakSan) ==="
$COMPOSE run --rm -e CBM_SKIP_PERF=1 test-portable
;;
windows)
echo "=== Windows: cross-compile + binary version check (Wine) ==="
$COMPOSE run --rm smoke-windows
;;
smoke-windows)
echo "=== Windows: binary version check (cross-compile + Wine) ==="
$COMPOSE run --rm smoke-windows
;;
amd64)
echo "=== Linux amd64: test + build ==="
$COMPOSE run --rm -e CBM_SKIP_PERF=1 test-amd64
$COMPOSE run --rm build-amd64
;;
all)
echo "=== Linux arm64: test + build + smoke ==="
$COMPOSE run --rm -e CBM_SKIP_PERF=1 test
$COMPOSE run --rm build
$COMPOSE run --rm smoke
echo "=== Linux arm64: ThreadSanitizer (data-race gate) ==="
$COMPOSE run --rm test-tsan
# amd64 TSan is CI/native-amd64 only (Rosetta can't map TSan shadow);
# run it with `run.sh tsan-amd64` on real amd64. GitHub CI gates it.
echo "=== Linux portable: Alpine static build + smoke ==="
$COMPOSE run --rm smoke-portable
echo "=== Linux arm64: artifact-flow smoke ==="
$COMPOSE run --rm smoke-artifact
echo "=== Linux glibc-floor (ubuntu-22.04): portable smoke + dynamic refusal ==="
$COMPOSE run --rm smoke-glibc-floor
echo "=== Linux amd64: test + build + smoke ==="
$COMPOSE run --rm -e CBM_SKIP_PERF=1 test-amd64
$COMPOSE run --rm build-amd64
$COMPOSE run --rm smoke-amd64
echo "=== Windows: cross-compile + binary version check (Wine) ==="
$COMPOSE run --rm smoke-windows
print_real_windows_gate
;;
lint)
echo "=== Linters (clang-format-20 + cppcheck 2.20.0) ==="
$COMPOSE run --rm lint
;;
shell)
echo "=== Debug shell (Linux arm64) ==="
$COMPOSE run --rm --entrypoint bash test
;;
shell-alpine)
echo "=== Debug shell (Alpine) ==="
$COMPOSE run --rm --entrypoint bash test-portable
;;
*)
echo "run.sh: unknown leg '${1:-}'. Please consult --help." >&2
exit 2
;;
esac
+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"